From 9ad63ea473a958506c041077f1d810c0c7c8c18d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ingy=20d=C3=B6t=20Net?= Date: Mon, 17 Feb 2020 23:21:07 -0800 Subject: [PATCH] Family Day update --- Lang/APL/Increment-a-numerical-string | 1 + Lang/AWK/Carmichael-3-strong-pseudoprimes | 1 + ...Circles-of-given-radius-through-two-points | 1 + Lang/AWK/Colour-bars-Display | 1 + Lang/AWK/Dynamic-variable-names | 1 + Lang/AWK/Gray-code | 1 + Lang/AWK/Greyscale-bars-Display | 1 + .../Keyboard-input-Flush-the-keyboard-buffer | 1 + Lang/AWK/Keyboard-input-Keypress-check | 1 + Lang/AWK/Left-factorials | 1 + Lang/AWK/Maximum-triangle-path-sum | 1 + Lang/AWK/Permutation-test | 1 + Lang/AWK/Permutations | 1 + Lang/AWK/Pythagorean-triples | 1 + Lang/AWK/Sudoku | 1 + Lang/Ada/AKS-test-for-primes | 1 + Lang/Ada/Brownian-tree | 1 + Lang/Ada/Colour-bars-Display | 1 + Lang/Ada/Colour-pinstripe-Display | 1 + Lang/Ada/Death-Star | 1 + Lang/Ada/Draw-a-clock | 1 + Lang/Ada/Fractal-tree | 1 + Lang/Ada/Gaussian-elimination | 1 + Lang/Ada/Hickerson-series-of-almost-integers | 1 + Lang/Ada/Honeycombs | 1 + Lang/Ada/Iterated-digits-squaring | 1 + Lang/Ada/Ludic-numbers | 1 + Lang/Ada/MD4 | 1 + Lang/Ada/Pinstripe-Display | 1 + Lang/Ada/RIPEMD-160 | 1 + Lang/Ada/SHA-256 | 1 + .../Sorting-algorithms-Pancake-sort | 1 + Lang/Binary-Lambda-Calculus/Quine | 1 + Lang/Bracmat/Function-composition | 1 + Lang/Bracmat/Quine | 1 + Lang/C++/00DESCRIPTION | 4 +- Lang/C++/K-d-tree | 1 + Lang/C++/Parse-an-IP-Address | 1 + Lang/C++/Truncatable-primes | 1 + Lang/C-sharp/Define-a-primitive-data-type | 1 + Lang/C-sharp/Enforced-immutability | 1 + Lang/C-sharp/Set-puzzle | 1 + Lang/C-sharp/Universal-Turing-machine | 1 + Lang/C-sharp/Y-combinator | 1 + Lang/C/00DESCRIPTION | 4 +- Lang/C/Balanced-ternary | 1 + Lang/C/Call-a-foreign-language-function | 1 + Lang/C/Call-an-object-method | 1 + Lang/C/Casting-out-nines | 1 + Lang/C/Inheritance-Multiple | 1 + Lang/C/RIPEMD-160 | 1 + Lang/C/Zeckendorf-arithmetic | 1 + Lang/COBOL/Count-the-coins | 1 + Lang/COBOL/Holidays-related-to-Easter | 1 + Lang/COBOL/Levenshtein-distance | 1 + Lang/COBOL/Parsing-RPN-calculator-algorithm | 1 + Lang/COBOL/Read-a-configuration-file | 1 + Lang/COBOL/Strip-comments-from-a-string | 1 + Lang/Cache-ObjectScript/Empty-string | 1 + Lang/Clojure/Rep-string | 1 + Lang/Clojure/Variables | 1 + Lang/Commodore-BASIC/00DESCRIPTION | 2 +- Lang/Commodore-BASIC/Count-the-coins | 1 + Lang/Commodore-BASIC/Joystick-position | 1 + Lang/Commodore-BASIC/Number-names | 1 + Lang/Crystal/Averages-Simple-moving-average | 1 + ...Catch-an-exception-thrown-in-a-nested-call | 1 + Lang/Crystal/Factorial | 1 + Lang/Crystal/Handle-a-signal | 1 + Lang/Crystal/Hash-from-two-arrays | 1 + Lang/Crystal/Hostname | 1 + Lang/Crystal/Include-a-file | 1 + Lang/Crystal/Knuth-shuffle | 1 + Lang/Crystal/Leap-year | 1 + Lang/Crystal/Loops-For | 1 + Lang/Crystal/Pangram-checker | 1 + Lang/Crystal/Remove-duplicate-elements | 1 + Lang/Crystal/Sorting-algorithms-Bogosort | 1 + .../Sorting-algorithms-Permutation-sort | 1 + .../Crystal/Sorting-algorithms-Selection-sort | 1 + Lang/Crystal/Stack | 1 + Lang/Crystal/Substring | 1 + Lang/Crystal/Synchronous-concurrency | 1 + Lang/Crystal/Test-a-function | 1 + Lang/Crystal/User-input-Text | 1 + Lang/Crystal/Zero-to-the-zero-power | 1 + .../Determine-if-only-one-instance-is-running | 1 + Lang/Dart/9-billion-names-of-God-the-integer | 1 + Lang/Dart/Comments | 1 + Lang/Delphi/Almost-prime | 1 + Lang/Delphi/CRC-32 | 1 + Lang/Delphi/Last-Friday-of-each-month | 1 + Lang/EDSAC-order-code/100-doors | 1 + Lang/EDSAC-order-code/Caesar-cipher | 1 + Lang/EDSAC-order-code/Catalan-numbers | 1 + ...-Arithmetic-Construct-from-rational-number | 1 + Lang/EDSAC-order-code/Factors-of-an-integer | 1 + Lang/EDSAC-order-code/Greatest-common-divisor | 1 + Lang/EDSAC-order-code/Hailstone-sequence | 1 + Lang/EDSAC-order-code/Pangram-checker | 1 + Lang/EDSAC-order-code/Pythagorean-triples | 1 + .../Sorting-algorithms-Bubble-sort | 1 + Lang/Elixir/Read-a-specific-line-from-a-file | 1 + Lang/Emacs-Lisp/Maze-generation | 1 + Lang/Emacs-Lisp/Maze-solving | 1 + Lang/Emacs-Lisp/Sorting-algorithms-Sleep-sort | 1 + Lang/F-Sharp/CRC-32 | 1 + .../Factor/9-billion-names-of-God-the-integer | 1 + Lang/Factor/Average-loop-length | 1 + Lang/Factor/Box-the-compass | 1 + Lang/Factor/Bulls-and-cows-Player | 1 + Lang/Factor/Carmichael-3-strong-pseudoprimes | 1 + Lang/Factor/Combinations-and-permutations | 1 + .../Constrained-random-points-on-a-circle | 1 + Lang/Factor/Deepcopy | 1 + .../Doubly-linked-list-Element-definition | 1 + Lang/Factor/Extensible-prime-generator | 1 + Lang/Factor/First-class-environments | 1 + .../Generate-Chess960-starting-position | 1 + .../Globally-replace-text-in-several-files | 1 + .../Factor/Hofstadter-Conway-$10,000-sequence | 1 + Lang/Factor/Holidays-related-to-Easter | 1 + Lang/Factor/Huffman-coding | 1 + Lang/Factor/Multiplicative-order | 1 + Lang/Factor/Numeric-error-propagation | 1 + Lang/Factor/Plot-coordinate-pairs | 1 + Lang/Factor/Queue-Definition | 1 + Lang/Factor/Ranking-methods | 1 + Lang/Factor/Roots-of-unity | 1 + Lang/Factor/Self-referential-sequence | 1 + Lang/Factor/Set-consolidation | 1 + Lang/Factor/Set-puzzle | 1 + Lang/Factor/Sierpinski-carpet | 1 + Lang/Factor/Sorting-algorithms-Cocktail-sort | 1 + Lang/Factor/Sorting-algorithms-Selection-sort | 1 + Lang/Factor/Topswops | 1 + Lang/Factor/Variable-size-Get | 1 + Lang/Forth/Maze-generation | 1 + Lang/Fortran/QR-decomposition | 1 + ...ficient-and-perfect-number-classifications | 1 + Lang/Frink/Check-that-file-exists | 1 + Lang/Frink/Conways-Game-of-Life | 1 + Lang/Frink/Copy-a-string | 1 + Lang/Frink/Fractal-tree | 1 + Lang/Frink/Generate-lower-case-ASCII-alphabet | 1 + Lang/Frink/Hostname | 1 + Lang/Frink/Josephus-problem | 1 + Lang/Frink/Look-and-say-sequence | 1 + .../Loop-over-multiple-arrays-simultaneously | 1 + Lang/Frink/Lucas-Lehmer-test | 1 + Lang/Frink/Mandelbrot-set | 1 + Lang/Frink/N-queens-problem | 1 + Lang/Frink/Pascals-triangle | 1 + Lang/Frink/Random-numbers | 1 + Lang/Frink/Roots-of-unity | 1 + Lang/Frink/SHA-256 | 1 + Lang/Frink/Sieve-of-Eratosthenes | 1 + Lang/Frink/String-length | 1 + Lang/Frink/Sum-multiples-of-3-and-5 | 1 + Lang/Frink/Sum-of-a-series | 1 + Lang/Frink/Towers-of-Hanoi | 1 + Lang/Gambas/Empty-program | 1 + Lang/Gambas/Quine | 1 + Lang/Go/Boolean-values | 1 + Lang/Go/Call-a-function-in-a-shared-library | 1 + Lang/Go/Catmull-Clark-subdivision-surface | 1 + Lang/Go/Executable-library | 1 + Lang/Go/Include-a-file | 1 + Lang/Go/Yahoo--search-interface | 1 + .../Arithmetic-geometric-mean-Calculate-Pi | 1 + Lang/Groovy/Kaprekar-numbers | 1 + Lang/Harbour/Bitwise-operations | 1 + Lang/Haxe/CRC-32 | 1 + Lang/Haxe/Factorial | 1 + Lang/Haxe/Loops-Break | 1 + Lang/Haxe/Loops-Continue | 1 + Lang/Haxe/Loops-Do-while | 1 + Lang/Haxe/Loops-Downward-for | 1 + Lang/Haxe/Loops-For-with-a-specified-step | 1 + Lang/Haxe/Loops-Infinite | 1 + Lang/Haxe/Loops-N-plus-one-half | 1 + Lang/Haxe/Loops-While | 1 + Lang/Haxe/MD5 | 1 + Lang/Haxe/SHA-1 | 1 + Lang/Haxe/SHA-256 | 1 + Lang/Haxe/Sorting-algorithms-Bubble-sort | 1 + Lang/Haxe/Sorting-algorithms-Cocktail-sort | 1 + Lang/Haxe/Sorting-algorithms-Comb-sort | 1 + Lang/Haxe/Sorting-algorithms-Counting-sort | 1 + Lang/Haxe/Sorting-algorithms-Gnome-sort | 1 + Lang/Haxe/Sorting-algorithms-Heapsort | 1 + Lang/Haxe/Sorting-algorithms-Insertion-sort | 1 + Lang/Haxe/Sorting-algorithms-Pancake-sort | 1 + Lang/Haxe/Sorting-algorithms-Shell-sort | 1 + Lang/Haxe/String-interpolation--included- | 1 + Lang/Haxe/Sum-of-a-series | 1 + Lang/Idris/Quaternion-type | 1 + Lang/J/00DESCRIPTION | 4 +- Lang/Java/00DESCRIPTION | 1 - Lang/Java/Bulls-and-cows-Player | 1 + Lang/Java/Check-Machin-like-formulas | 1 + Lang/Java/Combinations-and-permutations | 1 + Lang/Java/Doubly-linked-list-Definition | 1 + .../Java/Doubly-linked-list-Element-insertion | 1 + Lang/Java/Pascals-triangle-Puzzle | 1 + Lang/JavaScript/Benfords-law | 1 + Lang/JavaScript/Cholesky-decomposition | 1 + ...ical-integration-Gauss-Legendre-Quadrature | 1 + Lang/JavaScript/SHA-256 | 1 + Lang/JavaScript/Time-a-function | 1 + Lang/JavaScript/Variable-length-quantity | 1 + Lang/Julia/Catmull-Clark-subdivision-surface | 1 + Lang/Julia/SOAP | 1 + Lang/LOLCODE/Arrays | 1 + Lang/LOLCODE/Comments | 1 + Lang/LOLCODE/Even-or-odd | 1 + Lang/LOLCODE/User-input-Text | 1 + Lang/Lambdatalk/Matrix-multiplication | 1 + Lang/Lambdatalk/Mutual-recursion | 1 + Lang/Lambdatalk/Prime-decomposition | 1 + Lang/Liberty-BASIC/Calendar | 1 + Lang/Liberty-BASIC/Grayscale-image | 1 + Lang/Liberty-BASIC/Number-names | 1 + Lang/Liberty-BASIC/Zero-to-the-zero-power | 1 + Lang/Lobster/00DESCRIPTION | 5 +- Lang/Lobster/Chinese-remainder-theorem | 1 + Lang/Lobster/Cholesky-decomposition | 1 + Lang/Lobster/Combinations | 1 + Lang/Lobster/Combinations-with-repetitions | 1 + Lang/Lobster/Gray-code | 1 + Lang/Lobster/IBAN | 1 + Lang/Lobster/LU-decomposition | 1 + Lang/Lobster/Levenshtein-distance | 1 + Lang/Lobster/Long-multiplication | 1 + Lang/Lobster/Permutations | 1 + Lang/Lobster/Random-numbers | 1 + Lang/Lobster/Sorting-algorithms-Heapsort | 1 + Lang/Lua/00DESCRIPTION | 3 - Lang/Lua/Bernoulli-numbers | 1 + Lang/Lua/Continued-fraction | 1 + Lang/Lua/MD5-Implementation | 1 + Lang/Lua/Sierpinski-triangle | 1 + Lang/Lua/Tic-tac-toe | 1 + Lang/MAPPER/00DESCRIPTION | 2 +- Lang/MATLAB/Amicable-pairs | 1 + Lang/MATLAB/Universal-Turing-machine | 1 + Lang/MATLAB/XML-Input | 1 + Lang/MATLAB/XML-Output | 1 + Lang/MSX-Basic/00DESCRIPTION | 4 +- Lang/Maple/Generate-lower-case-ASCII-alphabet | 1 + Lang/Maple/Left-factorials | 1 + Lang/Maple/Pascals-triangle-Puzzle | 1 + Lang/Maple/Quaternion-type | 1 + Lang/Maple/Sequence-of-non-squares | 1 + Lang/Maple/Spiral-matrix | 1 + Lang/Maple/Visualize-a-tree | 1 + Lang/Nial/Fibonacci-sequence | 1 + Lang/Nim/Calendar | 1 + Lang/Nim/Carmichael-3-strong-pseudoprimes | 1 + Lang/Nim/Continued-fraction | 1 + Lang/Nim/Convert-decimal-number-to-rational | 1 + Lang/Nim/Deconvolution-1D | 1 + Lang/Nim/K-means++-clustering | 1 + Lang/Nim/Numeric-error-propagation | 1 + ...ical-integration-Gauss-Legendre-Quadrature | 1 + Lang/Nim/Permutation-test | 1 + Lang/Nim/Roots-of-a-function | 1 + Lang/Nim/Set-consolidation | 1 + Lang/Nim/Simulate-input-Keyboard | 1 + Lang/Nim/Thieles-interpolation-formula | 1 + Lang/Nim/Topswops | 1 + Lang/OCaml/String-prepend | 1 + Lang/OCaml/Voronoi-diagram | 1 + Lang/Objeck/24-game | 1 + Lang/Objeck/Sum-digits-of-an-integer | 1 + Lang/Objeck/Unix-ls | 1 + .../Arbitrary-precision-integers--included- | 1 + Lang/Ol/Binary-search | 1 + Lang/Ol/Currying | 1 + Lang/Ol/Empty-program | 1 + Lang/Ol/Enumerations | 1 + Lang/Ol/Even-or-odd | 1 + Lang/Ol/Extreme-floating-point-values | 1 + Lang/Ol/Hello-world-Text | 1 + Lang/Ol/Huffman-coding | 1 + Lang/Ol/Identity-matrix | 1 + Lang/Ol/Include-a-file | 1 + Lang/Ol/Interactive-programming | 1 + Lang/Ol/JSON | 1 + Lang/Ol/Langtons-ant | 1 + Lang/Ol/Loops-Foreach | 1 + Lang/Ol/MD5 | 1 + Lang/Ol/Metaprogramming | 1 + Lang/Ol/Primality-by-trial-division | 1 + Lang/Ol/Stack | 1 + Lang/Ol/Unicode-variable-names | 1 + .../Append-a-record-to-the-end-of-a-text-file | 1 + Lang/PHP/Currying | 1 + Lang/PHP/Entropy | 1 + Lang/PHP/Execute-a-Markov-algorithm | 1 + Lang/PHP/Fast-Fourier-transform | 1 + Lang/PHP/Hello-world-Newline-omission | 1 + Lang/PHP/Longest-string-challenge | 1 + Lang/PHP/Move-to-front-algorithm | 1 + Lang/PHP/Pythagorean-triples | 1 + Lang/PHP/Ray-casting-algorithm | 1 + Lang/PHP/Read-a-configuration-file | 1 + Lang/PHP/Read-a-specific-line-from-a-file | 1 + Lang/PHP/Sierpinski-carpet | 1 + Lang/PHP/Sierpinski-triangle | 1 + Lang/PHP/Speech-synthesis | 1 + Lang/PHP/Sum-multiples-of-3-and-5 | 1 + Lang/PHP/Terminal-control-Cursor-positioning | 1 + Lang/PHP/Update-a-configuration-file | 1 + Lang/PL-pgSQL/Fibonacci-sequence | 1 + Lang/Perl-6/00DESCRIPTION | 5 +- Lang/Perl-6/Bitmap-Flood-fill | 1 + Lang/Perl-6/Color-of-a-screen-pixel | 1 + Lang/Perl-6/Colour-pinstripe-Printer | 1 + Lang/Perl-6/Joystick-position | 1 + Lang/Perl-6/OpenGL | 1 + Lang/Perl-6/Pinstripe-Printer | 1 + Lang/Perl-6/Record-sound | 1 + .../Sutherland-Hodgman-polygon-clipping | 1 + .../Use-another-language-to-call-a-function | 1 + Lang/Perl-6/Vigen-re-cipher-Cryptanalysis | 1 + Lang/Perl-6/Write-to-Windows-event-log | 1 + Lang/Perl-6/Yahoo--search-interface | 1 + Lang/Perl/Binary-strings | 1 + Lang/Perl/Call-a-function-in-a-shared-library | 1 + Lang/Perl/Color-of-a-screen-pixel | 1 + Lang/Perl/Color-quantization | 1 + Lang/Perl/Image-convolution | 1 + Lang/Perl/Median-filter | 1 + Lang/Perl/QR-decomposition | 1 + Lang/Perl/Solve-the-no-connection-puzzle | 1 + Lang/Perl/Sutherland-Hodgman-polygon-clipping | 1 + Lang/Perl/Thieles-interpolation-formula | 1 + Lang/Perl/Vigen-re-cipher-Cryptanalysis | 1 + Lang/Phix/00DESCRIPTION | 2 +- Lang/Phix/Anonymous-recursion | 1 + Lang/Phix/Classes | 1 + Lang/Phix/Documentation | 1 + Lang/Phix/Hello-world-Web-server | 1 + Lang/Phix/Record-sound | 1 + Lang/Phix/SOAP | 1 + Lang/Phix/Send-email | 1 + Lang/Phix/Speech-synthesis | 1 + Lang/Phix/XML-Input | 1 + Lang/PicoLisp/Magic-squares-of-odd-order | 1 + Lang/Pike/Associative-array-Creation | 1 + Lang/Pike/Bitwise-operations | 1 + Lang/Pike/CRC-32 | 1 + Lang/Pike/Compound-data-type | 1 + Lang/Pike/Count-in-octal | 1 + Lang/Pike/Count-occurrences-of-a-substring | 1 + Lang/Pike/Environment-variables | 1 + Lang/Pike/File-input-output | 1 + Lang/Pike/Hash-from-two-arrays | 1 + Lang/Pike/Hello-world-Newline-omission | 1 + Lang/Pike/Hello-world-Standard-error | 1 + Lang/Pike/Hello-world-Web-server | 1 + Lang/Pike/Include-a-file | 1 + Lang/Pike/Integer-sequence | 1 + Lang/Pike/Letter-frequency | 1 + .../Loop-over-multiple-arrays-simultaneously | 1 + Lang/Pike/Loops-Nested | 1 + Lang/Pike/Reverse-a-string | 1 + Lang/Pike/Reverse-words-in-a-string | 1 + Lang/Pike/SHA-1 | 1 + Lang/Pike/SHA-256 | 1 + Lang/Pike/Show-the-epoch | 1 + Lang/Pike/Sorting-algorithms-Sleep-sort | 1 + Lang/Pike/Stack | 1 + Lang/Pike/String-append | 1 + Lang/Pike/String-case | 1 + Lang/Pike/String-concatenation | 1 + Lang/Pike/System-time | 1 + Lang/Pike/Time-a-function | 1 + Lang/Pike/Truncatable-primes | 1 + Lang/Pike/URL-decoding | 1 + Lang/Pike/URL-encoding | 1 + Lang/Pike/Unicode-strings | 1 + Lang/Pike/Unicode-variable-names | 1 + Lang/Pike/Unix-ls | 1 + Lang/Pike/Zero-to-the-zero-power | 1 + Lang/Pony/99-Bottles-of-Beer | 1 + .../Active-Directory-Search-for-a-user | 1 + .../PowerShell/Averages-Simple-moving-average | 1 + Lang/PowerShell/Polynomial-regression | 1 + Lang/PowerShell/QR-decomposition | 1 + Lang/PowerShell/RSA-code | 1 + Lang/Processing/Bitmap | 1 + Lang/Processing/Draw-a-clock | 1 + Lang/Processing/Draw-a-cuboid | 1 + Lang/Processing/Shell-one-liner | 1 + Lang/Processing/Start-from-a-main-routine | 1 + Lang/Prolog/Carmichael-3-strong-pseudoprimes | 1 + Lang/Prolog/Chinese-remainder-theorem | 1 + Lang/Prolog/Compile-time-calculation | 1 + Lang/Prolog/Count-in-octal | 1 + Lang/Prolog/Count-the-coins | 1 + Lang/Prolog/Detect-division-by-zero | 1 + Lang/Prolog/Empty-directory | 1 + Lang/Prolog/Enumerations | 1 + Lang/Prolog/Factors-of-a-Mersenne-number | 1 + Lang/Prolog/Fractran | 1 + Lang/Prolog/Hash-join | 1 + Lang/Prolog/Lucas-Lehmer-test | 1 + Lang/Prolog/Modular-inverse | 1 + Lang/Prolog/Multiplication-tables | 1 + Lang/Prolog/Nth-root | 1 + Lang/Prolog/Number-names | 1 + Lang/Prolog/Number-reversal-game | 1 + Lang/Prolog/Polymorphism | 1 + Lang/Prolog/Pythagorean-triples | 1 + Lang/Prolog/Roots-of-unity | 1 + Lang/Prolog/Set-puzzle | 1 + Lang/Prolog/Solve-a-Hopido-puzzle | 1 + Lang/Prolog/Solve-a-Numbrix-puzzle | 1 + Lang/Prolog/Sorting-algorithms-Bogosort | 1 + Lang/Prolog/Stair-climbing-puzzle | 1 + Lang/Prolog/Test-a-function | 1 + Lang/Pyret/Zero-to-the-zero-power | 1 + Lang/R/Address-of-a-variable | 1 + Lang/R/CSV-to-HTML-translation | 1 + Lang/R/Gaussian-elimination | 1 + Lang/R/Hello-world-Web-server | 1 + Lang/R/Hofstadter-Q-sequence | 1 + Lang/R/LU-decomposition | 1 + Lang/R/Left-factorials | 1 + Lang/R/Narcissistic-decimal-number | 1 + Lang/R/Number-names | 1 + Lang/R/Sockets | 1 + ...trip-whitespace-from-a-string-Top-and-tail | 1 + Lang/R/Unix-ls | 1 + Lang/REXX/00DESCRIPTION | 10 +- ...st-class-functions-Use-numbers-analogously | 1 + Lang/Red/Bitwise-IO | 1 + Lang/Red/Bitwise-operations | 1 + Lang/Red/Pascals-triangle | 1 + Lang/Red/Quaternion-type | 1 + Lang/Red/Voronoi-diagram | 1 + Lang/Robotic/Copy-a-string | 1 + Lang/Robotic/Empty-string | 1 + Lang/Robotic/Factorial | 1 + Lang/Robotic/Jump-anywhere | 1 + Lang/Robotic/Keyboard-input-Keypress-check | 1 + Lang/Robotic/Loops-Infinite | 1 + Lang/Robotic/String-append | 1 + Lang/Robotic/String-comparison | 1 + Lang/Ruby/Terminal-control-Inverse-video | 1 + Lang/Rust/Casting-out-nines | 1 + Lang/Rust/Exceptions | 1 + Lang/Rust/File-modification-time | 1 + Lang/Rust/Five-weekends | 1 + Lang/Rust/LZW-compression | 1 + Lang/Rust/Last-letter-first-letter | 1 + Lang/Rust/Matrix-exponentiation-operator | 1 + Lang/Rust/Optional-parameters | 1 + Lang/Rust/Phrase-reversals | 1 + Lang/Rust/Rep-string | 1 + ...Terminal-control-Ringing-the-terminal-bell | 1 + Lang/Rust/Vampire-number | 1 + Lang/Rust/XML-Input | 1 + Lang/Scala/Deal-cards-for-FreeCell | 1 + .../Verify-distribution-uniformity-Naive | 1 + Lang/Shen/Flatten-a-list | 1 + Lang/Shen/Permutations | 1 + Lang/Shen/Roman-numerals-Encode | 1 + Lang/Sidef/Average-loop-length | 1 + Lang/Smalltalk/00DESCRIPTION | 3 +- Lang/Smalltalk/Guess-the-number-With-feedback | 1 + Lang/Standard-ML/Day-of-the-week | 1 + Lang/Standard-ML/Factors-of-an-integer | 1 + Lang/Stata/Bitmap-Write-a-PPM-file | 1 + Lang/Stata/Conjugate-transpose | 1 + Lang/Stata/Write-float-arrays-to-a-text-file | 1 + Lang/Swift/Almost-prime | 1 + Lang/Swift/Arithmetic-Rational | 1 + Lang/Swift/Averages-Mean-angle | 1 + Lang/Swift/Averages-Mean-time-of-day | 1 + Lang/Swift/Averages-Root-mean-square | 1 + Lang/Swift/Averages-Simple-moving-average | 1 + Lang/Swift/Bernoulli-numbers | 1 + Lang/Swift/Carmichael-3-strong-pseudoprimes | 1 + Lang/Swift/Continued-fraction | 1 + Lang/Swift/Conways-Game-of-Life | 1 + Lang/Swift/Count-in-factors | 1 + Lang/Swift/Evaluate-binomial-coefficients | 1 + Lang/Swift/Fibonacci-word | 1 + Lang/Swift/Four-bit-adder | 1 + Lang/Swift/Gray-code | 1 + Lang/Swift/Knapsack-problem-Bounded | 1 + Lang/Swift/Knights-tour | 1 + Lang/Swift/Left-factorials | 1 + Lang/Swift/List-comprehensions | 1 + Lang/Swift/Matrix-multiplication | 1 + Lang/Swift/Matrix-transposition | 1 + Lang/Swift/Menu | 1 + Lang/Swift/Modular-exponentiation | 1 + Lang/Swift/Modular-inverse | 1 + Lang/Swift/Narcissistic-decimal-number | 1 + Lang/Swift/Nth-root | 1 + Lang/Swift/Parallel-calculations | 1 + Lang/Swift/Pernicious-numbers | 1 + Lang/Swift/Polynomial-long-division | 1 + Lang/Swift/Price-fraction | 1 + Lang/Swift/Self-describing-numbers | 1 + Lang/Swift/Semordnilap | 1 + .../Sort-an-array-of-composite-structures | 1 + Lang/Swift/Time-a-function | 1 + Lang/Swift/Vector-products | 1 + Lang/Swift/Vigen-re-cipher | 1 + Lang/UNIX-Shell/Execute-Brain---- | 1 + Lang/UNIX-Shell/Universal-Turing-machine | 1 + Lang/V/100-doors | 1 + Lang/VHDL/FizzBuzz | 1 + Lang/Vala/Abstract-type | 1 + ...ficient-and-perfect-number-classifications | 1 + Lang/Vala/Ackermann-function | 1 + Lang/Vala/Averages-Mean-angle | 1 + Lang/Vala/CRC-32 | 1 + Lang/Vala/Carmichael-3-strong-pseudoprimes | 1 + Lang/Vala/Catalan-numbers | 1 + Lang/Vala/Catalan-numbers-Pascals-triangle | 1 + Lang/Vala/Compound-data-type | 1 + Lang/Vala/Convert-decimal-number-to-rational | 1 + .../Loop-over-multiple-arrays-simultaneously | 1 + Lang/Vala/Loops-Continue | 1 + Lang/Vala/Loops-Do-while | 1 + Lang/Vala/Loops-Downward-for | 1 + Lang/Vala/Loops-For-with-a-specified-step | 1 + Lang/Vala/Loops-Foreach | 1 + Lang/Vala/Loops-N-plus-one-half | 1 + Lang/Vala/Loops-Nested | 1 + Lang/Vala/Loops-While | 1 + Lang/Vala/Map-range | 1 + Lang/Vala/Roman-numerals-Encode | 1 + Lang/Vala/Rot-13 | 1 + Lang/Vala/Sorting-algorithms-Bubble-sort | 1 + Lang/Vala/Sorting-algorithms-Cocktail-sort | 1 + Lang/Vala/Sorting-algorithms-Heapsort | 1 + Lang/Vala/Sorting-algorithms-Insertion-sort | 1 + Lang/Vala/String-append | 1 + Lang/Vala/String-comparison | 1 + Lang/Vala/String-concatenation | 1 + Lang/Vala/String-interpolation--included- | 1 + Lang/Vala/String-matching | 1 + .../Append-a-record-to-the-end-of-a-text-file | 1 + Lang/Visual-Basic-.NET/Balanced-ternary | 1 + .../Visual-Basic-.NET/Detect-division-by-zero | 1 + .../Execute-a-system-command | 1 + Lang/Visual-Basic-.NET/Filter | 1 + .../Generate-lower-case-ASCII-alphabet | 1 + Lang/Visual-Basic-.NET/Generic-swap | 1 + Lang/Visual-Basic-.NET/MD5 | 1 + .../Visual-Basic-.NET/Parametric-polymorphism | 1 + Lang/Visual-Basic-.NET/Zeckendorf-arithmetic | 1 + Lang/WebAssembly/Factorial | 1 + Lang/X86-Assembly/Ackermann-function | 1 + Lang/X86-Assembly/Copy-a-string | 1 + Lang/X86-Assembly/Factors-of-an-integer | 1 + Lang/X86-Assembly/Iterated-digits-squaring | 1 + .../Loop-over-multiple-arrays-simultaneously | 1 + Lang/X86-Assembly/Loops-Continue | 1 + Lang/X86-Assembly/Loops-Do-while | 1 + Lang/X86-Assembly/Pascals-triangle | 1 + Lang/XPL0/00DESCRIPTION | 14 +- Lang/XPL0/ABC-Problem | 1 + Lang/XPL0/Fibonacci-sequence | 1 + Lang/XPL0/Formatted-numeric-output | 1 + Lang/XPL0/Hello-world-Graphical | 1 + Lang/XPL0/Input-loop | 1 + Lang/XPL0/Read-a-file-line-by-line | 1 + Lang/XPL0/Zero-to-the-zero-power | 1 + Lang/XQuery/A+B | 1 + Lang/XQuery/JSON | 1 + Lang/XQuery/Longest-string-challenge | 1 + Lang/XQuery/XML-Output | 1 + Task/100-doors/C-sharp/100-doors-2.cs | 31 +- Task/100-doors/C-sharp/100-doors-3.cs | 14 +- Task/100-doors/C-sharp/100-doors-4.cs | 11 +- .../EDSAC-order-code/100-doors.edsac | 115 ++ Task/100-doors/Java/100-doors-2.java | 14 +- Task/100-doors/Java/100-doors-3.java | 12 +- Task/100-doors/Java/100-doors-4.java | 12 + Task/100-doors/Nim/100-doors-1.nim | 23 +- Task/100-doors/Nim/100-doors-2.nim | 20 +- Task/100-doors/Oforth/100-doors.oforth | 6 +- Task/100-doors/Perl-6/100-doors-3.pl6 | 2 +- Task/100-doors/Perl-6/100-doors-4.pl6 | 2 +- Task/100-doors/Perl-6/100-doors-5.pl6 | 27 +- Task/100-doors/Perl-6/100-doors-6.pl6 | 26 + Task/100-doors/Retro/100-doors.retro | 5 +- Task/100-doors/V/100-doors.v | 30 + Task/24-game/Elena/24-game.elena | 20 +- Task/24-game/Objeck/24-game.objeck | 101 ++ .../9-billion-names-of-god-the-integer-1.dart | 34 + .../9-billion-names-of-god-the-integer-2.dart | 6 + .../9-billion-names-of-god-the-integer.factor | 21 + .../Elena/99-bottles-of-beer.elena | 4 +- ...euphoria => 99-bottles-of-beer-1.euphoria} | 0 .../Euphoria/99-bottles-of-beer-2.euphoria | 17 + .../Phix/99-bottles-of-beer.phix | 18 +- .../Pony/99-bottles-of-beer-1.pony | 20 + .../Pony/99-bottles-of-beer-2.pony | 18 + .../Processing/99-bottles-of-beer | 3 - .../Processing/99-bottles-of-beer-1 | 5 + .../Processing/99-bottles-of-beer-2 | 18 + .../Python/99-bottles-of-beer-1.py | 34 +- .../Python/99-bottles-of-beer-2.py | 24 +- .../Python/99-bottles-of-beer-4.py | 143 ++- .../Python/99-bottles-of-beer-5.py | 256 ++++ Task/A+B/ARM-Assembly/a+b-1.arm | 3 +- Task/A+B/ARM-Assembly/a+b-2.arm | 534 +------- Task/A+B/ARM-Assembly/a+b-3.arm | 2 + Task/A+B/ARM-Assembly/a+b-4.arm | 513 ++++++++ Task/A+B/BASIC/a+b-4.basic | 2 +- .../{a+b.edsac => a+b-1.edsac} | 0 Task/A+B/EDSAC-order-code/a+b-2.edsac | 108 ++ Task/A+B/Elena/a+b-1.elena | 4 +- Task/A+B/Elena/a+b-2.elena | 2 +- Task/A+B/Java/a+b-1.java | 2 +- Task/A+B/XQuery/a+b.xquery | 15 + Task/ABC-Problem/Elena/abc-problem.elena | 4 +- Task/ABC-Problem/Julia/abc-problem.julia | 2 + Task/ABC-Problem/REXX/abc-problem-1.rexx | 14 +- Task/ABC-Problem/XPL0/abc-problem.xpl0 | 29 + .../Ada/aks-test-for-primes.ada | 88 ++ .../Julia/aks-test-for-primes-2.julia | 2 + .../Rust/aks-test-for-primes-1.rust | 8 +- Task/Abstract-type/00DESCRIPTION | 2 + .../{abstract-type.go => abstract-type-1.go} | 0 Task/Abstract-type/Go/abstract-type-2.go | 29 + Task/Abstract-type/Vala/abstract-type.vala | 29 + ...ent-and-perfect-number-classifications.ada | 21 +- ...t-and-perfect-number-classifications-1.erl | 16 +- ...t-and-perfect-number-classifications.frink | 11 + ...t-and-perfect-number-classifications-1.hs} | 0 ...nt-and-perfect-number-classifications-2.hs | 27 + ...t-and-perfect-number-classifications-1.py} | 0 ...nt-and-perfect-number-classifications-2.py | 109 ++ ...nt-and-perfect-number-classifications-3.py | 11 + ...nt-and-perfect-number-classifications-4.py | 13 + ...nt-and-perfect-number-classifications.vala | 35 + .../Retro/accumulator-factory.retro | 2 + Task/Ackermann-function/00DESCRIPTION | 4 +- ...nn-function.js => ackermann-function-1.js} | 0 .../JavaScript/ackermann-function-2.js | 6 + .../JavaScript/ackermann-function-3.js | 20 + .../JavaScript/ackermann-function-4.js | 26 + .../JavaScript/ackermann-function-5.js | 38 + ...-function.lua => ackermann-function-1.lua} | 0 .../Lua/ackermann-function-2.lua | 38 + .../Processing/ackermann-function | 26 +- .../Vala/ackermann-function.vala | 13 + .../X86-Assembly/ackermann-function.x86 | 29 + .../active-directory-search-for-a-user.psh | 7 + Task/Active-object/Phix/active-object-1.phix | 65 + ...ctive-object.phix => active-object-2.phix} | 0 .../Julia/address-of-a-variable-1.julia | 7 +- .../Perl/address-of-a-variable-1.pl | 2 +- .../Perl/address-of-a-variable-2.pl | 5 +- .../Perl/address-of-a-variable-3.pl | 8 +- .../Perl/address-of-a-variable-4.pl | 6 + .../R/address-of-a-variable-1.r | 9 + .../R/address-of-a-variable-2.r | 12 + Task/Align-columns/Python/align-columns-1.py | 50 +- Task/Align-columns/Python/align-columns-2.py | 53 +- Task/Align-columns/Python/align-columns-3.py | 29 +- Task/Align-columns/Python/align-columns-4.py | 82 +- Task/Align-columns/Python/align-columns-5.py | 75 ++ .../aliquot-sequence-classifications-3.julia | 2 + Task/Almost-prime/Delphi/almost-prime.delphi | 40 + Task/Almost-prime/Julia/almost-prime.julia | 17 + Task/Almost-prime/Swift/almost-prime.swift | 35 + Task/Amb/Elena/amb.elena | 3 +- Task/Amb/Haskell/amb-1.hs | 8 +- .../Elena/amicable-pairs-1.elena | 2 +- .../Haskell/amicable-pairs-2.hs | 40 +- .../JavaScript/amicable-pairs-3.js | 89 +- Task/Amicable-pairs/MATLAB/amicable-pairs.m | 35 + ...{amicable-pairs.py => amicable-pairs-1.py} | 0 .../Amicable-pairs/Python/amicable-pairs-2.py | 77 ++ Task/Amicable-pairs/Ruby/amicable-pairs.rb | 2 +- .../Julia/anagrams-deranged-anagrams.julia | 3 +- Task/Anagrams/8th/anagrams.8th | 2 +- Task/Anagrams/APL/anagrams-2.apl | 2 +- Task/Anagrams/COBOL/anagrams.cobol | 2 +- Task/Anagrams/Clojure/anagrams-2.clj | 2 +- Task/Anagrams/CoffeeScript/anagrams-1.coffee | 2 +- Task/Anagrams/Common-Lisp/anagrams-1.lisp | 2 +- Task/Anagrams/E/anagrams.e | 2 +- Task/Anagrams/Frink/anagrams.frink | 2 +- Task/Anagrams/Go/anagrams-1.go | 2 +- Task/Anagrams/Go/anagrams-2.go | 2 +- Task/Anagrams/Java/anagrams-1.java | 2 +- Task/Anagrams/Java/anagrams-2.java | 2 +- Task/Anagrams/Julia/anagrams.julia | 2 +- Task/Anagrams/Kotlin/anagrams.kotlin | 11 +- Task/Anagrams/Lasso/anagrams.lasso | 2 +- Task/Anagrams/LiveCode/anagrams.livecode | 2 +- Task/Anagrams/Maple/anagrams-1.maple | 2 +- Task/Anagrams/Mathematica/anagrams-1.math | 2 +- Task/Anagrams/Mathematica/anagrams-5.math | 2 +- Task/Anagrams/NetRexx/anagrams-1.netrexx | 2 +- Task/Anagrams/NetRexx/anagrams-2.netrexx | 2 +- Task/Anagrams/Objeck/anagrams.objeck | 2 +- Task/Anagrams/PHP/anagrams.php | 2 +- Task/Anagrams/Prolog/anagrams.pro | 2 +- Task/Anagrams/PureBasic/anagrams.purebasic | 2 +- Task/Anagrams/Python/anagrams-1.py | 2 +- Task/Anagrams/Python/anagrams-2.py | 2 +- Task/Anagrams/Python/anagrams-3.py | 2 +- Task/Anagrams/R/anagrams.r | 2 +- Task/Anagrams/Racket/anagrams.rkt | 2 +- Task/Anagrams/Rascal/anagrams-1.rascal | 2 +- Task/Anagrams/Red/anagrams.red | 2 +- Task/Anagrams/Ruby/anagrams-1.rb | 2 +- Task/Anagrams/Ruby/anagrams-2.rb | 2 +- Task/Anagrams/Run-BASIC/anagrams.run | 2 +- Task/Anagrams/Scala/anagrams-1.scala | 2 +- Task/Anagrams/Scala/anagrams-2.scala | 2 +- Task/Anagrams/Seed7/anagrams.seed7 | 2 +- Task/Anagrams/Smalltalk/anagrams-3.st | 2 +- Task/Anagrams/Stata/anagrams.stata | 2 +- Task/Anagrams/Swift/anagrams.swift | 2 +- Task/Anagrams/TUSCRIPT/anagrams.tu | 2 +- Task/Anagrams/Tcl/anagrams.tcl | 2 +- Task/Anagrams/UNIX-Shell/anagrams.sh | 2 +- .../Go/anonymous-recursion.go | 4 +- .../Phix/anonymous-recursion-1.phix | 18 + .../Phix/anonymous-recursion-2.phix | 10 + .../Python/anonymous-recursion-5.py | 4 + .../Python/anonymous-recursion-6.py | 3 + ...end-a-record-to-the-end-of-a-text-file.php | 19 + ...-a-record-to-the-end-of-a-text-file.visual | 54 + .../Elena/apply-a-callback-to-an-array.elena | 2 +- .../apply-a-callback-to-an-array-2.psh | 1 + ...arbitrary-precision-integers--included-.ol | 6 + .../Ruby/arithmetic-complex-1.rb | 6 +- .../ARM-Assembly/arithmetic-integer.arm | 160 +-- .../Retro/arithmetic-integer.retro | 16 +- .../Julia/arithmetic-rational.julia | 29 +- .../Swift/arithmetic-rational.swift | 156 +++ .../Phix/arithmetic-evaluation.phix | 1 + ...thmetic-geometric-mean-calculate-pi.groovy | 34 + ...ithmetic-geometric-mean-calculate-pi.julia | 36 +- ...rithmetic-geometric-mean-calculate-pi.math | 18 +- .../Haskell/arithmetic-geometric-mean.hs | 13 +- .../Julia/arithmetic-geometric-mean.julia | 15 +- .../Elena/array-concatenation.elena | 4 +- .../Retro/array-concatenation.retro | 4 +- Task/Arrays/C/arrays-10.c | 59 + Task/Arrays/Elena/arrays-1.elena | 2 +- Task/Arrays/LOLCODE/arrays.lol | 18 + Task/Assertions/Julia/assertions.julia | 9 +- .../{assertions.rexx => assertions-1.rexx} | 0 Task/Assertions/REXX/assertions-2.rexx | 15 + .../Ol/associative-array-creation.ol | 10 +- .../Pike/associative-array-creation-1.pike | 5 + .../Pike/associative-array-creation-2.pike | 4 + .../Factor/average-loop-length.factor | 25 + .../Julia/average-loop-length.julia | 3 +- .../Scala/average-loop-length.scala | 23 +- .../Sidef/average-loop-length.sidef | 22 + .../Elena/averages-arithmetic-mean.elena | 2 +- .../Julia/averages-arithmetic-mean.julia | 2 +- .../Julia/averages-mean-angle-1.julia | 1 + .../Swift/averages-mean-angle.swift | 21 + .../Vala/averages-mean-angle.vala | 21 + .../Julia/averages-mean-time-of-day.julia | 2 + .../Swift/averages-mean-time-of-day.swift | 57 + .../Elena/averages-median.elena | 4 +- .../Julia/averages-median.julia | 2 +- Task/Averages-Mode/Elena/averages-mode.elena | 6 +- .../Haskell/averages-pythagorean-means-2.hs | 8 +- .../Swift/averages-root-mean-square.swift | 8 + .../averages-simple-moving-average.crystal | 15 + .../averages-simple-moving-average-1.julia | 4 +- .../averages-simple-moving-average-2.julia | 28 +- .../averages-simple-moving-average.julia | 22 - .../averages-simple-moving-average.psh | 26 + .../REXX/averages-simple-moving-average.rexx | 1 - .../averages-simple-moving-average.swift | 28 + .../Haskell/balanced-brackets-1.hs | 20 +- .../Haskell/balanced-brackets-2.hs | 28 +- .../JavaScript/balanced-brackets-2.js | 112 +- .../JavaScript/balanced-brackets-3.js | 95 ++ .../Julia/balanced-brackets-1.julia | 2 + ...d-brackets.x86 => balanced-brackets-1.x86} | 0 .../X86-Assembly/balanced-brackets-2.x86 | 98 ++ Task/Balanced-ternary/C/balanced-ternary.c | 202 ++++ .../REXX/balanced-ternary.rexx | 47 +- .../Visual-Basic-.NET/balanced-ternary.visual | 188 +++ Task/Benfords-law/JavaScript/benfords-law.js | 3 + Task/Benfords-law/REXX/benfords-law.rexx | 43 +- .../Haskell/bernoulli-numbers-2.hs | 19 +- .../Julia/bernoulli-numbers.julia | 8 +- .../Lua/bernoulli-numbers.lua | 45 + Task/Bernoulli-numbers/R/bernoulli-numbers.r | 11 +- .../Rust/bernoulli-numbers.rust | 2 +- .../Sidef/bernoulli-numbers-1.sidef | 23 +- .../Sidef/bernoulli-numbers-2.sidef | 25 +- .../Sidef/bernoulli-numbers-3.sidef | 9 + .../Sidef/bernoulli-numbers-4.sidef | 15 + .../Sidef/bernoulli-numbers-5.sidef | 13 + .../Swift/bernoulli-numbers.swift | 29 + Task/Best-shuffle/Elena/best-shuffle.elena | 2 +- Task/Binary-digits/Ada/binary-digits.ada | 2 +- Task/Binary-digits/Elena/binary-digits.elena | 2 +- Task/Binary-digits/LOLCODE/binary-digits.lol | 29 +- Task/Binary-search/Ol/binary-search.ol | 15 + Task/Binary-strings/Perl/binary-strings.pl | 12 + .../C++/bitmap-bresenhams-line-algorithm.cpp | 4 +- .../Perl-6/bitmap-flood-fill.pl6 | 72 ++ .../REXX/bitmap-flood-fill.rexx | 20 +- .../Stata/bitmap-write-a-ppm-file.stata | 20 + Task/Bitmap/Processing/bitmap | 9 + Task/Bitmap/REXX/bitmap-1.rexx | 13 +- Task/Bitwise-IO/Red/bitwise-io.red | 58 + .../Harbour/bitwise-operations.harbour | 42 + .../Pike/bitwise-operations.pike | 18 + .../Red/bitwise-operations.red | 17 + Task/Boolean-values/Go/boolean-values.go | 26 + .../Factor/box-the-compass.factor | 27 + .../Julia/box-the-compass.julia | 34 +- Task/Box-the-compass/Nim/box-the-compass.nim | 42 +- .../UNIX-Shell/box-the-compass.sh | 11 +- Task/Break-OO-privacy/00DESCRIPTION | 1 + Task/Brownian-tree/Ada/brownian-tree.ada | 125 ++ .../Factor/bulls-and-cows-player.factor | 27 + .../Java/bulls-and-cows-player-1.java | 80 ++ .../Java/bulls-and-cows-player-2.java | 39 + .../Java/bulls-and-cows-player-3.java | 69 ++ .../Java/bulls-and-cows-player-4.java | 30 + .../Java/bulls-and-cows-player-5.java | 49 + .../BASIC/bulls-and-cows-3.basic | 38 + .../Bulls-and-cows/Elena/bulls-and-cows.elena | 4 +- .../Bulls-and-cows/REXX/bulls-and-cows-1.rexx | 49 +- Task/CRC-32/Delphi/crc-32.delphi | 15 + Task/CRC-32/F-Sharp/crc-32-1.fs | 39 + Task/CRC-32/F-Sharp/crc-32-2.fs | 2 + Task/CRC-32/Haxe/crc-32.haxe | 9 + Task/CRC-32/Pike/crc-32.pike | 2 + Task/CRC-32/REXX/crc-32.rexx | 41 +- Task/CRC-32/Vala/crc-32-1.vala | 6 + Task/CRC-32/Vala/crc-32-2.vala | 37 + .../C-sharp/csv-data-manipulation.cs | 111 +- .../Julia/csv-data-manipulation.julia | 16 +- ...nipulation.m => csv-data-manipulation-1.m} | 0 .../MATLAB/csv-data-manipulation-2.m | 4 + .../R/csv-data-manipulation-2.r | 10 +- .../R/csv-data-manipulation-3.r | 1 + .../Ruby/csv-data-manipulation.rb | 2 +- .../Julia/csv-to-html-translation-1.julia | 10 +- .../Julia/csv-to-html-translation-2.julia | 1 - .../R/csv-to-html-translation-1.r | 20 + .../R/csv-to-html-translation-2.r | 6 + .../EDSAC-order-code/caesar-cipher.edsac | 215 ++++ ...{caesar-cipher.php => caesar-cipher-1.php} | 0 Task/Caesar-cipher/PHP/caesar-cipher-2.php | 9 + .../00DESCRIPTION | 2 +- .../calendar---for-real-programmers.elena | 7 +- .../REXX/calendar---for-real-programmers.rexx | 7 +- Task/Calendar/Liberty-BASIC/calendar.liberty | 59 + Task/Calendar/Nim/calendar.nim | 38 + .../C/call-a-foreign-language-function-1.c | 24 + .../C/call-a-foreign-language-function-2.c | 16 + .../call-a-foreign-language-function-1.ocaml | 2 +- .../call-a-foreign-language-function-3.ocaml | 4 +- .../call-a-foreign-language-function-5.ocaml | 11 + .../call-a-function-in-a-shared-library-1.go | 8 + .../call-a-function-in-a-shared-library-2.go | 52 + .../call-a-function-in-a-shared-library-1.pl | 10 + .../call-a-function-in-a-shared-library-2.pl | 7 + .../Elena/call-a-function-1.elena | 2 +- Task/Call-a-function/Go/call-a-function-10.go | 2 + Task/Call-a-function/Go/call-a-function-11.go | 21 + Task/Call-a-function/Go/call-a-function-12.go | 27 + Task/Call-a-function/Go/call-a-function-5.go | 15 +- Task/Call-a-function/Go/call-a-function-6.go | 24 +- Task/Call-a-function/Go/call-a-function-7.go | 5 +- Task/Call-a-function/Go/call-a-function-8.go | 11 +- Task/Call-a-function/Go/call-a-function-9.go | 4 + Task/Call-a-function/Ol/call-a-function.ol | 6 +- .../Perl-6/call-a-function-11.pl6 | 91 ++ .../C/call-an-object-method.c | 27 + .../AWK/carmichael-3-strong-pseudoprimes.awk | 42 + .../carmichael-3-strong-pseudoprimes.factor | 23 + .../Nim/carmichael-3-strong-pseudoprimes.nim | 34 + .../carmichael-3-strong-pseudoprimes.pro | 31 + .../carmichael-3-strong-pseudoprimes.swift | 70 ++ .../carmichael-3-strong-pseudoprimes.vala | 33 + Task/Casting-out-nines/C/casting-out-nines.c | 21 + .../Rust/casting-out-nines.rust | 21 + .../catalan-numbers-pascals-triangle.vala | 11 + .../EDSAC-order-code/catalan-numbers.edsac | 99 ++ .../Scala/catalan-numbers.scala | 11 +- .../Catalan-numbers/Vala/catalan-numbers.vala | 77 ++ .../Go/catmull-clark-subdivision-surface.go | 286 +++++ .../catmull-clark-subdivision-surface.julia | 145 +++ .../catmull-clark-subdivision-surface.py | 12 +- Task/Character-codes/Go/character-codes-2.go | 23 +- Task/Character-codes/Go/character-codes-3.go | 24 +- Task/Character-codes/Go/character-codes-4.go | 6 +- Task/Character-codes/Go/character-codes-5.go | 3 + .../Perl-6/character-codes.pl6 | 29 +- .../Character-codes/Perl/character-codes-1.pl | 19 + .../Character-codes/Perl/character-codes-2.pl | 19 + Task/Character-codes/Perl/character-codes.pl | 2 - Task/Character-codes/Ruby/character-codes.rb | 4 + .../Perl/{chat-server.pl => chat-server-1.pl} | 0 Task/Chat-server/Perl/chat-server-2.pl | 80 ++ Task/Check-Machin-like-formulas/00DESCRIPTION | 2 +- .../Java/check-machin-like-formulas.java | 146 +++ .../REXX/check-machin-like-formulas.rexx | 15 +- .../Frink/check-that-file-exists.frink | 34 + ...le-exists.r => check-that-file-exists-1.r} | 0 .../R/check-that-file-exists-2.r | 1 + .../Stata/check-that-file-exists-4.stata | 1 + .../Julia/chinese-remainder-theorem.julia | 26 +- .../Lobster/chinese-remainder-theorem.lobster | 41 + .../Prolog/chinese-remainder-theorem.pro | 24 + .../Rust/chinese-remainder-theorem.rust | 70 +- .../JavaScript/cholesky-decomposition.js | 13 + .../Lobster/cholesky-decomposition.lobster | 79 ++ ...les-of-given-radius-through-two-points.awk | 29 + ...es-of-given-radius-through-two-points.rexx | 14 +- Task/Classes/Phix/classes.phix | 10 + .../Elena/closures-value-capture.elena | 2 +- Task/Collections/Elena/collections-1.elena | 2 +- .../BASIC/color-of-a-screen-pixel-1.basic | 3 + .../BASIC/color-of-a-screen-pixel-10.basic | 1 + .../BASIC/color-of-a-screen-pixel-11.basic | 3 + .../BASIC/color-of-a-screen-pixel-12.basic | 23 + .../BASIC/color-of-a-screen-pixel-13.basic | 4 + .../BASIC/color-of-a-screen-pixel-14.basic | 1 + .../BASIC/color-of-a-screen-pixel-15.basic | 10 + .../BASIC/color-of-a-screen-pixel-16.basic | 23 + .../BASIC/color-of-a-screen-pixel-17.basic | 14 + .../BASIC/color-of-a-screen-pixel-2.basic | 41 + .../BASIC/color-of-a-screen-pixel-3.basic | 2 + .../BASIC/color-of-a-screen-pixel-4.basic | 26 + .../BASIC/color-of-a-screen-pixel-5.basic | 6 + .../BASIC/color-of-a-screen-pixel-6.basic | 13 + ....basic => color-of-a-screen-pixel-7.basic} | 0 .../BASIC/color-of-a-screen-pixel-8.basic | 25 + .../BASIC/color-of-a-screen-pixel-9.basic | 3 + .../Perl-6/color-of-a-screen-pixel-1.pl6 | 18 + .../Perl-6/color-of-a-screen-pixel-2.pl6 | 55 + .../Perl/color-of-a-screen-pixel.pl | 14 + .../Perl/color-quantization.pl | 9 + .../AWK/colour-bars-display.awk | 13 + .../Ada/colour-bars-display.ada | 49 + Task/Colour-pinstripe-Display/00DESCRIPTION | 4 +- .../Ada/colour-pinstripe-display.ada | 74 ++ .../Perl-6/colour-pinstripe-printer.pl6 | 57 + .../combinations-and-permutations.factor | 4 + .../Java/combinations-and-permutations.java | 71 ++ .../combinations-with-repetitions.lobster | 25 + .../combinations-with-repetitions.purebasic | 2 +- Task/Combinations/J/combinations-4.j | 11 +- Task/Combinations/J/combinations-5.j | 4 +- Task/Combinations/J/combinations-6.j | 7 + Task/Combinations/J/combinations-7.j | 1 + .../Lobster/combinations-1.lobster | 21 + .../Lobster/combinations-2.lobster | 22 + ...{combinations.math => combinations-1.math} | 0 .../Mathematica/combinations-2.math | 1 + Task/Combinations/Python/combinations-5.py | 4 + Task/Combinations/REXX/combinations.rexx | 27 +- .../Julia/command-line-arguments.julia | 4 +- Task/Comments/Batch-File/comments-2.bat | 2 +- Task/Comments/Batch-File/comments-3.bat | 1 + Task/Comments/Dart/comments.dart | 12 + Task/Comments/LOLCODE/comments-1.lol | 3 + Task/Comments/LOLCODE/comments-2.lol | 1 + Task/Comments/Perl-6/comments-1.pl6 | 2 + Task/Comments/Perl-6/comments-2.pl6 | 6 + Task/Comments/Perl-6/comments-3.pl6 | 3 + Task/Comments/Perl-6/comments-4.pl6 | 3 + Task/Comments/Perl-6/comments-5.pl6 | 6 + Task/Comments/Perl-6/comments-6.pl6 | 9 + Task/Comments/Perl-6/comments.pl6 | 28 - .../Prolog/compile-time-calculation.pro | 9 + .../Pike/compound-data-type.pike | 14 + .../Vala/compound-data-type.vala | 4 + .../Ol/conditional-structures-5.ol | 14 +- .../Ol/conditional-structures-6.ol | 14 +- .../Julia/conjugate-transpose-3.julia | 1 + .../Stata/conjugate-transpose.stata | 31 + ...nstrained-random-points-on-a-circle.factor | 7 + ...nstrained-random-points-on-a-circle-1.rexx | 41 +- ...nstrained-random-points-on-a-circle-2.rexx | 66 +- ...nstrained-random-points-on-a-circle-3.rexx | 104 +- ...metic-construct-from-rational-number.edsac | 240 ++++ .../Lua/continued-fraction.lua | 66 + .../Nim/continued-fraction.nim | 27 + .../Swift/continued-fraction.swift | 106 ++ .../convert-decimal-number-to-rational.factor | 5 +- .../convert-decimal-number-to-rational-1.nim | 56 + .../convert-decimal-number-to-rational-2.nim | 11 + ...convert-decimal-number-to-rational-1.sidef | 6 +- ...convert-decimal-number-to-rational-2.sidef | 6 +- ...convert-decimal-number-to-rational-3.sidef | 2 + .../convert-decimal-number-to-rational.vala | 56 + .../Frink/conways-game-of-life.frink | 105 ++ .../JavaScript/conways-game-of-life-4.js | 70 ++ ...ife.julia => conways-game-of-life-1.julia} | 0 .../Julia/conways-game-of-life-2.julia | 43 + .../Perl/conways-game-of-life-3.pl | 17 + .../Retro/conways-game-of-life.retro | 134 +- .../Swift/conways-game-of-life.swift | 95 ++ Task/Copy-a-string/Frink/copy-a-string.frink | 2 + .../{copy-a-string.go => copy-a-string-1.go} | 0 Task/Copy-a-string/Go/copy-a-string-2.go | 22 + Task/Copy-a-string/Retro/copy-a-string.retro | 2 +- .../Robotic/copy-a-string.robotic | 3 + .../X86-Assembly/copy-a-string-1.x86 | 20 + .../X86-Assembly/copy-a-string-2.x86 | 22 + .../Factor/count-in-factors.factor | 10 +- .../Julia/count-in-factors.julia | 2 +- .../Scala/count-in-factors.scala | 36 +- .../Swift/count-in-factors.swift | 29 + Task/Count-in-octal/Perl/count-in-octal-3.pl | 4 + Task/Count-in-octal/Pike/count-in-octal.pike | 3 + Task/Count-in-octal/Prolog/count-in-octal.pro | 14 + .../count-occurrences-of-a-substring.pike | 3 + .../COBOL/count-the-coins.cobol | 31 + .../count-the-coins-1.commodore | 27 + .../count-the-coins-2.commodore | 2 + .../count-the-coins-3.commodore | 2 + .../Prolog/count-the-coins.pro | 10 + .../00DESCRIPTION | 2 + .../Create-a-file/BASIC/create-a-file-3.basic | 6 + Task/Create-a-file/Retro/create-a-file.retro | 5 +- ...a-two-dimensional-array-at-runtime-1.basic | 7 + ...-two-dimensional-array-at-runtime-10.basic | 14 + ...-two-dimensional-array-at-runtime-11.basic | 6 + ...-two-dimensional-array-at-runtime-12.basic | 6 + ...-two-dimensional-array-at-runtime-13.basic | 14 + ...a-two-dimensional-array-at-runtime-2.basic | 5 + ...a-two-dimensional-array-at-runtime-3.basic | 11 + ...a-two-dimensional-array-at-runtime-4.basic | 11 + ...a-two-dimensional-array-at-runtime-5.basic | 4 + ...a-two-dimensional-array-at-runtime-6.basic | 9 + ...a-two-dimensional-array-at-runtime-7.basic | 17 + ...-two-dimensional-array-at-runtime-8.basic} | 0 ...a-two-dimensional-array-at-runtime-9.basic | 9 + ...te-a-two-dimensional-array-at-runtime-1.py | 4 +- ...te-a-two-dimensional-array-at-runtime-2.py | 2 +- .../00DESCRIPTION | 1 - Task/Currying/Ol/currying.ol | 7 + Task/Currying/PHP/currying.php | 95 ++ .../Ada/{dns-query.ada => dns-query-1.ada} | 0 Task/DNS-query/Ada/dns-query-2.ada | 14 + .../{date-format.lisp => date-format-1.lisp} | 0 .../Common-Lisp/date-format-2.lisp | 4 + Task/Date-format/Pike/date-format.pike | 19 +- ...lation.julia => date-manipulation-1.julia} | 2 +- .../Julia/date-manipulation-2.julia | 14 + .../Julia/day-of-the-week.julia | 2 +- .../Day-of-the-week/Phix/day-of-the-week.phix | 3 +- Task/Day-of-the-week/SAS/day-of-the-week.sas | 4 +- .../Standard-ML/day-of-the-week.ml | 19 + .../Scala/deal-cards-for-freecell.scala | 33 + Task/Death-Star/Ada/death-star.ada | 143 +++ Task/Death-Star/Julia/death-star.julia | 4 +- .../Deconvolution-1D/Nim/deconvolution-1d.nim | 20 + Task/Deepcopy/Factor/deepcopy-1.factor | 26 + Task/Deepcopy/Factor/deepcopy-2.factor | 16 + .../C-sharp/define-a-primitive-data-type.cs | 115 ++ .../define-a-primitive-data-type.visual | 351 ++++-- .../define-a-primitive-data-type.visual | 2 +- Task/Delegates/Elena/delegates-1.elena | 2 +- Task/Delegates/Elena/delegates-2.elena | 2 +- .../{delete-a-file.f => delete-a-file-1.f} | 0 Task/Delete-a-file/Fortran/delete-a-file-2.f | 8 + Task/Delete-a-file/Java/delete-a-file.java | 25 +- Task/Delete-a-file/Retro/delete-a-file.retro | 5 +- .../Lua/detect-division-by-zero.lua | 7 +- .../Prolog/detect-division-by-zero.pro | 2 + .../detect-division-by-zero.visual | 15 + .../Go/determine-if-a-string-is-numeric-1.go | 19 + .../Go/determine-if-a-string-is-numeric-2.go | 28 + .../Go/determine-if-a-string-is-numeric.go | 6 - .../determine-if-a-string-is-numeric.julia | 4 +- .../determine-if-a-string-is-numeric.pl6 | 4 +- .../determine-if-a-string-is-numeric.phix | 14 + .../determine-if-a-string-is-numeric.retro | 2 +- ...etermine-if-only-one-instance-is-running.d | 20 + ...ine-if-only-one-instance-is-running-1.nim} | 0 ...mine-if-only-one-instance-is-running-2.nim | 35 + Task/Digital-root/Elena/digital-root.elena | 2 +- ...dinesmans-multiple-dwelling-problem.factor | 2 +- .../Julia/discordian-date.julia | 2 +- Task/Documentation/Phix/documentation.phix | 10 + Task/Documentation/Retro/documentation.retro | 37 +- Task/Dot-product/Elena/dot-product.elena | 2 +- .../Java/doubly-linked-list-definition.java | 25 + ...ubly-linked-list-element-definition.factor | 1 + .../doubly-linked-list-element-insertion.java | 40 + Task/Draw-a-clock/Ada/draw-a-clock.ada | 99 ++ Task/Draw-a-clock/Processing/draw-a-clock-1 | 19 + Task/Draw-a-clock/Processing/draw-a-clock-2 | 7 + Task/Draw-a-cuboid/Processing/draw-a-cuboid | 13 + .../Draw-a-sphere/BASIC/draw-a-sphere-1.basic | 6 +- .../Batch-File/draw-a-sphere.bat | 135 ++- ...w-a-sphere.julia => draw-a-sphere-1.julia} | 2 - .../Draw-a-sphere/Julia/draw-a-sphere-2.julia | 13 + Task/Draw-a-sphere/Processing/draw-a-sphere | 12 +- Task/Dynamic-variable-names/00DESCRIPTION | 25 - .../AWK/dynamic-variable-names.awk | 36 + .../Elena/dynamic-variable-names.elena | 6 +- .../Retro/dynamic-variable-names.retro | 3 + ...ty-directory.nim => empty-directory-1.nim} | 0 .../Empty-directory/Nim/empty-directory-2.nim | 7 + .../Prolog/empty-directory.pro | 6 + .../Futhark/empty-program.futhark | 2 +- .../Empty-program/Gambas/empty-program.gambas | 2 + Task/Empty-program/Ol/empty-program.ol | 1 + Task/Empty-string/C-sharp/empty-string-2.cs | 10 +- .../Cache-ObjectScript/empty-string.cos | 15 + .../Go/{empty-string.go => empty-string-1.go} | 0 Task/Empty-string/Go/empty-string-2.go | 23 + Task/Empty-string/Python/empty-string.py | 8 +- .../Empty-string/Robotic/empty-string.robotic | 8 + .../Visual-Basic-.NET/empty-string-1.visual | 2 +- .../Visual-Basic-.NET/empty-string-2.visual | 11 +- .../C-sharp/enforced-immutability-1.cs | 1 + .../C-sharp/enforced-immutability-2.cs | 1 + .../C-sharp/enforced-immutability-3.cs | 3 + .../C-sharp/enforced-immutability-4.cs | 4 + .../C-sharp/enforced-immutability-5.cs | 1 + .../C-sharp/enforced-immutability-6.cs | 7 + Task/Entropy/PHP/entropy.php | 27 + Task/Entropy/REXX/entropy-3.rexx | 40 +- Task/Enumerations/Ol/enumerations-1.ol | 16 + Task/Enumerations/Ol/enumerations-2.ol | 10 + Task/Enumerations/Prolog/enumerations.pro | 7 + Task/Enumerations/Retro/enumerations.retro | 3 + .../Pike/environment-variables.pike | 1 + .../Elena/equilibrium-index.elena | 2 +- .../Haskell/equilibrium-index-1.hs | 12 +- ...s.f => evaluate-binomial-coefficients-1.f} | 0 .../evaluate-binomial-coefficients-2.f | 43 + .../evaluate-binomial-coefficients-1.java | 79 +- .../evaluate-binomial-coefficients-2.java | 22 +- .../evaluate-binomial-coefficients-2.julia | 6 +- .../evaluate-binomial-coefficients-1.phix | 10 +- .../evaluate-binomial-coefficients-2.phix | 17 +- .../evaluate-binomial-coefficients-3.phix | 5 + ...ss => evaluate-binomial-coefficients-1.ss} | 0 .../evaluate-binomial-coefficients-2.ss | 12 + .../evaluate-binomial-coefficients.swift | 17 + Task/Even-or-odd/BASIC/even-or-odd-2.basic | 14 +- Task/Even-or-odd/BASIC/even-or-odd-3.basic | 7 + Task/Even-or-odd/LOLCODE/even-or-odd.lol | 12 + Task/Even-or-odd/Ol/even-or-odd.ol | 32 + Task/Events/Nim/{events.nim => events-1.nim} | 0 Task/Events/Nim/events-2.nim | 30 + .../Elena/evolutionary-algorithm.elena | 2 +- ...-exception-thrown-in-a-nested-call.crystal | 26 + ...an-exception-thrown-in-a-nested-call.elena | 2 +- Task/Exceptions/Elena/exceptions-1.elena | 2 +- Task/Exceptions/Elena/exceptions-3.elena | 2 +- Task/Exceptions/Rust/exceptions.rust | 51 + Task/Executable-library/00DESCRIPTION | 1 - .../Go/executable-library-1.go | 37 + .../Go/executable-library-2.go | 6 + .../Go/executable-library-3.go | 19 + .../Phix/executable-library-1.phix | 19 +- .../Scala/executable-library.scala | 7 +- .../UNIX-Shell/execute-brain----.sh | 49 + .../PHP/execute-a-markov-algorithm.php | 147 +++ .../execute-a-system-command.visual | 20 + .../Kotlin/exponentiation-operator.kotlin | 6 +- Task/Extend-your-language/00DESCRIPTION | 2 +- .../Factor/extensible-prime-generator.factor | 13 + .../Ol/extreme-floating-point-values.ol | 6 + Task/Factorial/BASIC/factorial-4.basic | 23 +- Task/Factorial/BASIC/factorial-5.basic | 13 +- Task/Factorial/BASIC/factorial-6.basic | 12 +- Task/Factorial/BASIC/factorial-7.basic | 10 + Task/Factorial/Crystal/factorial-1.crystal | 7 + Task/Factorial/Crystal/factorial-2.crystal | 6 + Task/Factorial/Emacs-Lisp/factorial-1.l | 15 +- Task/Factorial/Emacs-Lisp/factorial-2.l | 9 +- Task/Factorial/Fortran/factorial-2.f | 16 +- Task/Factorial/Fortran/factorial-3.f | 6 + Task/Factorial/Frink/factorial-1.frink | 7 +- Task/Factorial/Frink/factorial-2.frink | 2 + Task/Factorial/Frink/factorial-3.frink | 9 + 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/JavaScript/factorial-1.js | 6 +- Task/Factorial/Python/factorial-6.py | 7 +- Task/Factorial/Python/factorial-7.py | 30 +- Task/Factorial/Python/factorial-8.py | 2 + Task/Factorial/Python/factorial-9.py | 27 + Task/Factorial/R/factorial-1.r | 4 +- Task/Factorial/R/factorial-2.r | 4 +- Task/Factorial/REXX/factorial-1.rexx | 6 +- Task/Factorial/REXX/factorial-2.rexx | 18 +- Task/Factorial/REXX/factorial-3.rexx | 33 +- Task/Factorial/Robotic/factorial.robotic | 15 + Task/Factorial/Rust/factorial.rust | 2 +- .../WebAssembly/factorial.webassembly | 16 + .../Prolog/factors-of-a-mersenne-number.pro | 27 + .../Scala/factors-of-a-mersenne-number.scala | 54 +- Task/Factors-of-an-integer/00DESCRIPTION | 1 + .../factors-of-an-integer.edsac | 136 +++ .../Pascal/factors-of-an-integer-2.pascal | 312 ++++- .../REXX/factors-of-an-integer-1.rexx | 18 +- .../Sidef/factors-of-an-integer-1.sidef | 2 + ...er.sidef => factors-of-an-integer-2.sidef} | 6 +- .../Standard-ML/factors-of-an-integer-1.ml | 18 + .../Standard-ML/factors-of-an-integer-2.ml | 2 + .../X86-Assembly/factors-of-an-integer.x86 | 32 + .../Julia/fast-fourier-transform-1.julia | 2 + .../Julia/fast-fourier-transform-3.julia | 17 +- .../PHP/fast-fourier-transform-1.php | 40 + .../PHP/fast-fourier-transform-2.php | 101 ++ .../REXX/fast-fourier-transform.rexx | 66 +- .../fibonacci-n-step-number-sequences-1.scala | 15 +- .../fibonacci-n-step-number-sequences-2.scala | 19 +- .../fibonacci-n-step-number-sequences-3.scala | 21 +- ...fibonacci-n-step-number-sequences-1.sidef} | 6 +- .../fibonacci-n-step-number-sequences-2.sidef | 14 + .../fibonacci-n-step-number-sequences-3.sidef | 20 + .../APL/fibonacci-sequence-1.apl | 2 +- .../APL/fibonacci-sequence-2.apl | 2 +- .../APL/fibonacci-sequence-3.apl | 2 +- .../APL/fibonacci-sequence-4.apl | 1 + .../Elena/fibonacci-sequence.elena | 2 +- .../Nial/fibonacci-sequence-1.nial | 12 + .../Nial/fibonacci-sequence-2.nial | 1 + .../Nial/fibonacci-sequence-3.nial | 1 + .../Nial/fibonacci-sequence-4.nial | 1 + .../Nial/fibonacci-sequence-5.nial | 1 + .../Nial/fibonacci-sequence-6.nial | 1 + .../Nial/fibonacci-sequence-7.nial | 5 + .../Nial/fibonacci-sequence-8.nial | 1 + .../OCaml/fibonacci-sequence-2.ocaml | 28 +- .../OCaml/fibonacci-sequence-3.ocaml | 25 +- .../OCaml/fibonacci-sequence-4.ocaml | 16 + .../PL-pgSQL/fibonacci-sequence-1.sql | 8 + .../PL-pgSQL/fibonacci-sequence-2.sql | 5 + .../PL-pgSQL/fibonacci-sequence-3.sql | 17 + .../PL-pgSQL/fibonacci-sequence-4.sql | 9 + .../Rust/fibonacci-sequence-4.rust | 19 +- .../Rust/fibonacci-sequence-5.rust | 33 +- .../Rust/fibonacci-sequence-6.rust | 29 + .../XPL0/fibonacci-sequence.xpl0 | 23 + .../Fibonacci-word/Swift/fibonacci-word.swift | 42 + .../Julia/file-input-output-1.julia | 4 +- .../Julia/file-input-output-3.julia | 2 +- .../Julia/file-input-output-4.julia | 2 +- .../Pike/file-input-output.pike | 4 + .../Julia/file-modification-time.julia | 2 + .../Rust/file-modification-time.rust | 12 + Task/Filter/Elena/filter-1.elena | 2 +- Task/Filter/Elena/filter-2.elena | 2 +- Task/Filter/Visual-Basic-.NET/filter.visual | 41 + .../Haskell/find-common-directory-path-2.hs | 21 +- .../Nim/find-common-directory-path.nim | 6 +- .../find-common-directory-path-1.psh | 51 +- .../find-common-directory-path-2.psh | 3 +- ...ft-truncatable-prime-in-a-given-base.julia | 10 +- .../Python/find-limit-of-recursion-5.py | 7 + .../Python/find-limit-of-recursion-6.py | 2 + .../find-the-last-sunday-of-each-month.factor | 6 +- .../find-the-last-sunday-of-each-month-3.js | 103 +- .../find-the-last-sunday-of-each-month.phix | 2 +- .../find-the-missing-permutation-1.julia | 6 +- .../find-the-missing-permutation-2.julia | 5 - .../find-the-missing-permutation-3.julia | 16 + .../Factor/first-class-environments.factor | 21 + .../00DESCRIPTION | 1 + ...ss-functions-use-numbers-analogously.elena | 4 +- ...ass-functions-use-numbers-analogously.rexx | 13 + .../Elena/first-class-functions.elena | 14 +- Task/Five-weekends/Rust/five-weekends.rust | 45 + .../{fizzbuzz.crystal => fizzbuzz-1.crystal} | 0 Task/FizzBuzz/Crystal/fizzbuzz-2.crystal | 12 + Task/FizzBuzz/Erlang/fizzbuzz.erl | 3 +- Task/FizzBuzz/Java/fizzbuzz.java | 20 +- Task/FizzBuzz/Kotlin/fizzbuzz-1.kotlin | 16 +- Task/FizzBuzz/Kotlin/fizzbuzz-4.kotlin | 2 +- Task/FizzBuzz/Lua/fizzbuzz-5.lua | 20 + Task/FizzBuzz/Processing/fizzbuzz-4 | 17 +- Task/FizzBuzz/Python/fizzbuzz-10.py | 53 +- Task/FizzBuzz/Python/fizzbuzz-11.py | 1 + Task/FizzBuzz/Python/fizzbuzz-12.py | 12 + Task/FizzBuzz/Python/fizzbuzz-3.py | 10 +- Task/FizzBuzz/Python/fizzbuzz-4.py | 2 +- Task/FizzBuzz/Python/fizzbuzz-5.py | 4 +- Task/FizzBuzz/Python/fizzbuzz-6.py | 4 +- Task/FizzBuzz/Python/fizzbuzz-7.py | 2 +- Task/FizzBuzz/Python/fizzbuzz-8.py | 14 +- Task/FizzBuzz/Python/fizzbuzz-9.py | 59 +- Task/FizzBuzz/VHDL/fizzbuzz.vhdl | 29 + .../JavaScript/flatten-a-list-6.js | 7 +- .../Julia/flatten-a-list-1.julia | 4 +- .../Julia/flatten-a-list-2.julia | 5 +- .../Julia/flatten-a-list-3.julia | 11 + .../Flatten-a-list/Python/flatten-a-list-2.py | 83 +- .../Flatten-a-list/Python/flatten-a-list-3.py | 20 +- .../Flatten-a-list/Python/flatten-a-list-4.py | 90 +- .../Flatten-a-list/Python/flatten-a-list-5.py | 85 +- Task/Flatten-a-list/Shen/flatten-a-list.shen | 6 + .../Julia/flipping-bits-game.julia | 14 +- .../Julia/floyds-triangle.julia | 12 + Task/Forest-fire/Haskell/forest-fire.hs | 6 +- Task/Forest-fire/Julia/forest-fire.julia | 4 +- .../Perl/{forest-fire.pl => forest-fire-1.pl} | 0 Task/Forest-fire/Perl/forest-fire-2.pl | 23 + .../Julia/formal-power-series-1.julia | 93 +- .../Julia/formal-power-series-2.julia | 3 + .../Perl-6/formal-power-series.pl6 | 22 +- .../Perl/formal-power-series.pl | 2 +- .../Julia/formatted-numeric-output.julia | 1 + .../XPL0/formatted-numeric-output.xpl0 | 9 + .../Julia/four-bit-adder-1.julia | 2 + .../Four-bit-adder/Swift/four-bit-adder.swift | 26 + Task/Fractal-tree/Ada/fractal-tree.ada | 81 ++ Task/Fractal-tree/Frink/fractal-tree.frink | 27 + Task/Fractran/Prolog/fractran.pro | 50 + .../Bracmat/function-composition.bracmat | 20 + .../Python/function-composition-5.py | 23 + .../function-definition.applescript | 2 +- .../Julia/function-frequency.julia | 2 +- .../Stata/gamma-function-1.stata | 61 + .../Stata/gamma-function-2.stata | 31 + .../Gamma-function/Stata/gamma-function.stata | 42 - .../Ada/gaussian-elimination.ada | 119 ++ .../Haskell/gaussian-elimination-1.hs | 109 +- .../Haskell/gaussian-elimination-2.hs | 108 +- .../Haskell/gaussian-elimination-3.hs | 90 ++ .../R/gaussian-elimination.r | 35 + .../REXX/gaussian-elimination-2.rexx | 31 +- .../REXX/gaussian-elimination-3.rexx | 33 +- ...nerate-chess960-starting-position-1.factor | 28 + ...nerate-chess960-starting-position-2.factor | 3 + .../generate-lower-case-ascii-alphabet.elena | 2 +- ...generate-lower-case-ascii-alphabet-1.frink | 1 + ...generate-lower-case-ascii-alphabet-2.frink | 1 + ... generate-lower-case-ascii-alphabet-1.lua} | 0 .../generate-lower-case-ascii-alphabet-2.lua | 5 + .../generate-lower-case-ascii-alphabet.mumps | 8 +- .../generate-lower-case-ascii-alphabet.maple | 1 + .../generate-lower-case-ascii-alphabet.visual | 11 + Task/Generic-swap/Elena/generic-swap.elena | 13 +- .../Generic-swap/JavaScript/generic-swap-3.js | 8 + .../Visual-Basic-.NET/generic-swap-1.visual | 5 + .../Visual-Basic-.NET/generic-swap-2.visual | 2 + ...bally-replace-text-in-several-files.factor | 12 + ...ally-replace-text-in-several-files-1.java} | 0 ...bally-replace-text-in-several-files-2.java | 5 + Task/Gray-code/AWK/gray-code.awk | 37 + Task/Gray-code/Lobster/gray-code.lobster | 19 + Task/Gray-code/PureBasic/gray-code.purebasic | 2 +- Task/Gray-code/Swift/gray-code.swift | 22 + .../Liberty-BASIC/grayscale-image.liberty | 21 + .../greatest-common-divisor.edsac | 151 +++ .../Elena/greatest-element-of-a-list.elena | 2 +- .../Go/greatest-element-of-a-list-1.go | 3 +- .../Go/greatest-element-of-a-list-2.go | 51 +- .../Go/greatest-element-of-a-list-3.go | 60 +- .../Go/greatest-element-of-a-list-4.go | 64 + .../AWK/greyscale-bars-display.awk | 25 + .../Frink/greyscale-bars-display.frink | 1 + .../00DESCRIPTION | 2 +- .../guess-the-number-with-feedback.cos | 56 +- .../guess-the-number-with-feedback.st | 96 ++ .../BASIC/guess-the-number-2.basic | 16 +- .../BASIC/guess-the-number-3.basic | 44 +- .../BASIC/guess-the-number-4.basic | 42 +- .../BASIC/guess-the-number-5.basic | 49 + .../BASIC/guess-the-number-6.basic | 5 + .../Common-Lisp/guess-the-number.lisp | 24 +- Task/HTTP/Frink/http.frink | 2 +- .../Visual-Basic/https-authenticated.vb | 10 +- Task/HTTPS/Visual-Basic/https.vb | 8 +- .../EDSAC-order-code/hailstone-sequence.edsac | 260 ++++ .../REXX/hailstone-sequence-1.rexx | 21 +- .../REXX/hailstone-sequence-2.rexx | 49 +- Task/Hamming-numbers/00META.yaml | 3 +- .../Phix/hamming-numbers-1.phix | 16 +- .../Common-Lisp/handle-a-signal.lisp | 8 +- .../Crystal/handle-a-signal.crystal | 24 + .../Julia/handle-a-signal.julia | 24 +- ...{happy-numbers.apl => happy-numbers-1.apl} | 0 Task/Happy-numbers/APL/happy-numbers-2.apl | 14 + .../Pascal/happy-numbers-2.pascal | 248 ++-- Task/Happy-numbers/Sidef/happy-numbers.sidef | 4 +- Task/Harshad-or-Niven-series/00DESCRIPTION | 8 +- .../Haskell/harshad-or-niven-series-2.hs | 16 +- .../Python/harshad-or-niven-series-3.py | 80 +- .../REXX/harshad-or-niven-series-1.rexx | 26 +- .../REXX/harshad-or-niven-series-2.rexx | 24 +- .../REXX/harshad-or-niven-series-3.rexx | 31 +- .../REXX/harshad-or-niven-series-4.rexx | 28 +- .../C-sharp/hash-from-two-arrays-1.cs | 25 +- .../C-sharp/hash-from-two-arrays-2.cs | 4 +- .../C-sharp/hash-from-two-arrays-3.cs | 14 + .../Crystal/hash-from-two-arrays.crystal | 5 + .../Pike/hash-from-two-arrays.pike | 4 + Task/Hash-join/Prolog/hash-join.pro | 20 + .../Smalltalk/hello-world-graphical-2.st | 2 +- .../Smalltalk/hello-world-graphical-3.st | 1 + .../XPL0/hello-world-graphical.xpl0 | 1 + .../ARM-Assembly/hello-world-newbie.arm | 5 +- .../PHP/hello-world-newline-omission.php | 1 + .../Pike/hello-world-newline-omission.pike | 1 + .../Pike/hello-world-standard-error.pike | 1 + ...ld-text.cobol => hello-world-text-1.cobol} | 0 .../COBOL/hello-world-text-2.cobol | 1 + .../Kotlin/hello-world-text.kotlin | 2 +- Task/Hello-world-Text/Ol/hello-world-text.ol | 1 + ...-world-text.pl6 => hello-world-text-1.pl6} | 0 .../Perl-6/hello-world-text-2.pl6 | 1 + .../Phix/hello-world-web-server.phix | 45 + .../Pike/hello-world-web-server.pike | 11 + .../R/hello-world-web-server.r | 9 + Task/Here-document/00DESCRIPTION | 7 - Task/Here-document/00META.yaml | 4 +- Task/Here-document/Lua/here-document.lua | 2 + Task/Here-document/Rust/here-document.rust | 6 +- .../hickerson-series-of-almost-integers.ada | 62 + .../hickerson-series-of-almost-integers.f | 42 +- .../Elena/higher-order-functions.elena | 2 +- .../Elena/history-variables.elena | 2 +- .../hofstadter-conway-$10,000-sequence.factor | 19 + .../R/hofstadter-q-sequence.r | 27 + .../COBOL/holidays-related-to-easter.cobol | 123 ++ .../Factor/holidays-related-to-easter.factor | 34 + Task/Honeycombs/Ada/honeycombs.ada | 205 ++++ Task/Honeycombs/Go/honeycombs.go | 10 +- ...rners-rule-for-polynomial-evaluation.elena | 2 +- Task/Hostname/Crystal/hostname.crystal | 1 + Task/Hostname/Frink/hostname.frink | 1 + .../Factor/huffman-coding.factor | 132 ++ Task/Huffman-coding/Ol/huffman-coding-1.ol | 38 + Task/Huffman-coding/Ol/huffman-coding-2.ol | 10 + Task/IBAN/Kotlin/iban.kotlin | 40 +- Task/IBAN/Lobster/iban.lobster | 59 + .../Julia/identity-matrix-1.julia | 3 +- .../Julia/identity-matrix-2.julia | 2 +- Task/Identity-matrix/Ol/identity-matrix.ol | 7 + .../Perl-6/image-convolution-1.pl6 | 8 + ...onvolution.pl6 => image-convolution-2.pl6} | 3 +- .../Perl/image-convolution.pl | 11 + .../Crystal/include-a-file.crystal | 2 + Task/Include-a-file/Go/include-a-file-1.go | 13 + Task/Include-a-file/Go/include-a-file-2.go | 8 + Task/Include-a-file/Ol/include-a-file-1.ol | 1 + Task/Include-a-file/Ol/include-a-file-2.ol | 1 + Task/Include-a-file/Pike/include-a-file.pike | 1 + .../APL/increment-a-numerical-string.apl | 1 + .../Julia/increment-a-numerical-string.julia | 4 +- Task/Infinity/Julia/infinity.julia | 2 + .../C/inheritance-multiple.c | 16 + Task/Input-loop/Elena/input-loop-2.elena | 8 +- Task/Input-loop/XPL0/input-loop.xpl0 | 9 + .../Go/integer-comparison.go | 2 + .../Julia/integer-comparison.julia | 6 +- .../Julia/integer-overflow-1.julia | 1 + .../Rust/integer-overflow-2.rust | 28 +- ...eger-sequence.js => integer-sequence-1.js} | 0 .../JavaScript/integer-sequence-2.js | 4 + .../Pike/integer-sequence.pike | 3 + ...eger-sequence.rb => integer-sequence-1.rb} | 0 .../Ruby/integer-sequence-2.rb | 1 + .../Ol/interactive-programming.ol | 10 + Task/Introspection/Julia/introspection.julia | 2 +- .../Ada/iterated-digits-squaring.ada | 40 + .../X86-Assembly/iterated-digits-squaring.x86 | 52 + Task/JSON/Ol/json.ol | 46 + Task/JSON/XQuery/json.xquery | 28 + ...{jensens-device.py => jensens-device-1.py} | 0 .../Jensens-Device/Python/jensens-device-2.py | 5 + .../Jensens-Device/Python/jensens-device-3.py | 5 + Task/Jensens-Device/REXX/jensens-device.rexx | 16 +- .../Frink/josephus-problem.frink | 21 + .../REXX/josephus-problem-1.rexx | 2 + .../joystick-position-1.commodore | 24 + .../joystick-position-2.commodore | 24 + .../joystick-position-3.commodore | 27 + .../joystick-position-4.commodore | 27 + .../Perl-6/joystick-position.pl6 | 104 ++ .../{jump-anywhere.go => jump-anywhere-1.go} | 0 Task/Jump-anywhere/Go/jump-anywhere-2.go | 35 + Task/Jump-anywhere/Racket/jump-anywhere-3.rkt | 2 +- .../Robotic/jump-anywhere-1.robotic | 13 + .../Robotic/jump-anywhere-2.robotic | 14 + .../Robotic/jump-anywhere-3.robotic | 13 + .../Robotic/jump-anywhere-4.robotic | 29 + .../Robotic/jump-anywhere-5.robotic | 5 + .../Robotic/jump-anywhere-6.robotic | 22 + Task/K-d-tree/C++/k-d-tree.cpp | 299 +++++ Task/K-d-tree/Python/k-d-tree.py | 2 + .../Lua/k-means++-clustering.lua | 13 +- .../Nim/k-means++-clustering.nim | 193 +++ .../Groovy/kaprekar-numbers.groovy | 31 + .../Julia/kaprekar-numbers.julia | 10 +- ...yboard-input-flush-the-keyboard-buffer.awk | 7 + ...rd-input-flush-the-keyboard-buffer-2.basic | 12 +- ...rd-input-flush-the-keyboard-buffer-3.basic | 2 +- ...rd-input-flush-the-keyboard-buffer-4.basic | 1 + ...board-input-flush-the-keyboard-buffer-1.c} | 0 ...yboard-input-flush-the-keyboard-buffer-2.c | 23 + ...oard-input-flush-the-keyboard-buffer-1.go} | 0 ...board-input-flush-the-keyboard-buffer-2.go | 34 + .../AWK/keyboard-input-keypress-check.awk | 19 + ....go => keyboard-input-keypress-check-1.go} | 18 - .../Go/keyboard-input-keypress-check-2.go | 31 + .../keyboard-input-keypress-check.robotic | 8 + ...board-input-obtain-a-y-or-n-response-1.go} | 0 ...yboard-input-obtain-a-y-or-n-response-2.go | 27 + .../Python/knapsack-problem-0-1-3.py | 2 +- Task/Knapsack-problem-Bounded/00DESCRIPTION | 2 +- .../Swift/knapsack-problem-bounded.swift | 82 ++ .../Julia/knapsack-problem-continuous-1.julia | 2 + Task/Knights-tour/C++/knights-tour.cpp | 2 +- Task/Knights-tour/Haskell/knights-tour.hs | 62 +- ...{knights-tour.java => knights-tour-1.java} | 0 Task/Knights-tour/Java/knights-tour-2.java | 158 +++ Task/Knights-tour/Swift/knights-tour.swift | 130 ++ .../Crystal/knuth-shuffle.crystal | 9 + Task/Knuth-shuffle/Racket/knuth-shuffle.rkt | 2 +- .../Elena/knuths-algorithm-s.elena | 2 +- .../Julia/knuths-algorithm-s.julia | 2 + .../REXX/knuths-algorithm-s.rexx | 33 +- .../Lobster/lu-decomposition.lobster | 105 ++ Task/LU-decomposition/R/lu-decomposition.r | 4 + .../REXX/lu-decomposition.rexx | 88 +- Task/LZW-compression/Lua/lzw-compression.lua | 6 +- .../LZW-compression/Python/lzw-compression.py | 6 +- .../REXX/lzw-compression-2.rexx | 20 +- .../LZW-compression/Rust/lzw-compression.rust | 77 ++ .../Swift/lzw-compression.swift | 105 +- Task/Langtons-ant/Ol/langtons-ant.ol | 71 ++ .../Delphi/last-friday-of-each-month.delphi | 27 + .../Factor/last-friday-of-each-month.factor | 2 +- .../Julia/last-friday-of-each-month.julia | 2 +- .../Phix/last-friday-of-each-month.phix | 2 +- .../REXX/last-friday-of-each-month.rexx | 65 +- .../Rust/last-letter-first-letter.rust | 159 +++ Task/Leap-year/Crystal/leap-year.crystal | 3 + Task/Leap-year/Retro/leap-year.retro | 8 +- .../Icon/least-common-multiple-1.icon | 2 +- .../Kotlin/least-common-multiple.kotlin | 4 +- Task/Left-factorials/00DESCRIPTION | 6 +- Task/Left-factorials/AWK/left-factorials.awk | 23 + .../Maple/left-factorials.maple | 4 + Task/Left-factorials/R/left-factorials.r | 31 + .../Swift/left-factorials.swift | 37 + .../Julia/letter-frequency.julia | 4 +- .../Pike/letter-frequency.pike | 5 + .../REXX/letter-frequency-1.rexx | 84 +- .../COBOL/levenshtein-distance.cobol | 62 + .../Lobster/levenshtein-distance.lobster | 36 + .../REXX/levenshtein-distance-1.rexx | 40 +- .../Julia/linear-congruential-generator.julia | 2 + .../Swift/list-comprehensions.swift | 14 + ...erals-integer.go => literals-integer-1.go} | 0 .../Literals-Integer/Go/literals-integer-2.go | 23 + .../Liberty-BASIC/literals-string.liberty | 2 +- ...-operations.go => logical-operations-1.go} | 0 .../Go/logical-operations-2.go | 35 + .../Julia/logical-operations.julia | 2 + .../Lobster/long-multiplication.lobster | 113 ++ .../REXX/longest-common-subsequence.rexx | 52 +- .../Swift/longest-common-subsequence-1.swift | 27 +- .../Swift/longest-common-subsequence-2.swift | 32 +- .../PHP/longest-string-challenge.php | 24 + .../XQuery/longest-string-challenge.xquery | 6 + Task/Look-and-say-sequence/00DESCRIPTION | 3 + .../Frink/look-and-say-sequence.frink | 29 + .../Metafont/look-and-say-sequence.metafont | 23 + .../Oforth/look-and-say-sequence.oforth | 5 +- ...sequence.st => look-and-say-sequence-1.st} | 0 .../Smalltalk/look-and-say-sequence-2.st | 30 + ...over-multiple-arrays-simultaneously-3.lisp | 5 + ...ver-multiple-arrays-simultaneously-1.elena | 6 +- ...ver-multiple-arrays-simultaneously-2.elena | 6 +- ...-over-multiple-arrays-simultaneously.frink | 6 + ...p-over-multiple-arrays-simultaneously.pike | 6 + ...p-over-multiple-arrays-simultaneously.vala | 8 + ...op-over-multiple-arrays-simultaneously.x86 | 51 + .../{loops-break.lisp => loops-break-1.lisp} | 0 .../Common-Lisp/loops-break-2.lisp | 3 + Task/Loops-Break/Haxe/loops-break.haxe | 12 + Task/Loops-Continue/Haxe/loops-continue.haxe | 8 + Task/Loops-Continue/Vala/loops-continue.vala | 8 + .../X86-Assembly/loops-continue.x86 | 87 ++ .../BASIC/loops-do-while-3.basic | 10 +- .../BASIC/loops-do-while-4.basic | 9 +- .../BASIC/loops-do-while-5.basic | 4 + .../Common-Lisp/loops-do-while-3.lisp | 4 + ...{loops-do-while.go => loops-do-while-1.go} | 0 Task/Loops-Do-while/Go/loops-do-while-2.go | 11 + Task/Loops-Do-while/Go/loops-do-while-3.go | 27 + Task/Loops-Do-while/Haxe/loops-do-while.haxe | 6 + .../Loops-Do-while/MUMPS/loops-do-while.mumps | 14 +- Task/Loops-Do-while/Vala/loops-do-while.vala | 7 + .../X86-Assembly/loops-do-while.x86 | 25 + ...ard-for.lisp => loops-downward-for-1.lisp} | 0 .../Common-Lisp/loops-downward-for-2.lisp | 3 + .../Factor/loops-downward-for.factor | 2 +- ...ownward-for.go => loops-downward-for-1.go} | 0 .../Go/loops-downward-for-2.go | 14 + .../Haxe/loops-downward-for.haxe | 22 + .../Java/loops-downward-for.java | 4 +- .../Kotlin/loops-downward-for.kotlin | 6 +- .../UNIX-Shell/loops-downward-for-1.sh | 8 + .../UNIX-Shell/loops-downward-for-2.sh | 6 + .../Vala/loops-downward-for.vala | 2 + .../loops-for-with-a-specified-step-10.basic | 3 + .../loops-for-with-a-specified-step-11.basic | 4 + .../loops-for-with-a-specified-step-12.basic | 3 + .../loops-for-with-a-specified-step-13.basic | 4 + .../loops-for-with-a-specified-step-14.basic | 7 + .../loops-for-with-a-specified-step-15.basic | 15 + .../loops-for-with-a-specified-step-16.basic | 8 + .../loops-for-with-a-specified-step-17.basic | 5 + .../loops-for-with-a-specified-step-18.basic | 3 + .../loops-for-with-a-specified-step-19.basic | 3 + .../loops-for-with-a-specified-step-20.basic | 6 + .../loops-for-with-a-specified-step-21.basic | 9 + .../loops-for-with-a-specified-step-22.basic | 10 + .../loops-for-with-a-specified-step-7.basic | 3 + .../loops-for-with-a-specified-step-8.basic | 4 + .../loops-for-with-a-specified-step-9.basic | 10 + ...=> loops-for-with-a-specified-step-1.lisp} | 0 .../loops-for-with-a-specified-step-2.lisp | 3 + .../Haxe/loops-for-with-a-specified-step.haxe | 23 + .../Vala/loops-for-with-a-specified-step.vala | 2 + Task/Loops-For/Common-Lisp/loops-for-1.lisp | 2 +- Task/Loops-For/Common-Lisp/loops-for-4.lisp | 7 + Task/Loops-For/Crystal/loops-for-1.crystal | 6 + Task/Loops-For/Crystal/loops-for-2.crystal | 1 + .../Common-Lisp/loops-foreach-3.lisp | 1 + .../Common-Lisp/loops-foreach-4.lisp | 4 + .../Common-Lisp/loops-foreach-5.lisp | 4 + Task/Loops-Foreach/Elena/loops-foreach.elena | 2 +- Task/Loops-Foreach/Haxe/loops-foreach.haxe | 4 +- Task/Loops-Foreach/Ol/loops-foreach.ol | 6 + Task/Loops-Foreach/Vala/loops-foreach.vala | 9 + ...ps-infinite.lisp => loops-infinite-1.lisp} | 0 .../Common-Lisp/loops-infinite-2.lisp | 3 + Task/Loops-Infinite/Haxe/loops-infinite.haxe | 2 + Task/Loops-Infinite/Pike/loops-infinite.pike | 5 +- .../Robotic/loops-infinite.robotic | 3 + .../Common-Lisp/loops-n-plus-one-half-4.lisp | 6 + .../Common-Lisp/loops-n-plus-one-half-5.lisp | 5 + .../Haxe/loops-n-plus-one-half.haxe | 2 + ...half.pike => loops-n-plus-one-half-1.pike} | 0 .../Pike/loops-n-plus-one-half-2.pike | 4 + .../Pike/loops-n-plus-one-half-3.pike | 2 + .../Vala/loops-n-plus-one-half.vala | 7 + .../Loops-Nested/Factor/loops-nested-1.factor | 4 + .../Loops-Nested/Factor/loops-nested-2.factor | 7 + Task/Loops-Nested/Factor/loops-nested.factor | 10 - Task/Loops-Nested/Pike/loops-nested.pike | 24 + Task/Loops-Nested/Vala/loops-nested.vala | 20 + .../Cache-ObjectScript/loops-while.cos | 12 +- Task/Loops-While/Haxe/loops-while-1.haxe | 6 + Task/Loops-While/Haxe/loops-while-2.haxe | 6 + Task/Loops-While/Vala/loops-while.vala | 5 + .../Frink/lucas-lehmer-test.frink | 3 + .../Prolog/lucas-lehmer-test.pro | 37 + Task/Ludic-numbers/Ada/ludic-numbers.ada | 100 ++ .../R/luhn-test-of-credit-card-numbers.r | 7 +- Task/MD4/Ada/md4.ada | 34 + .../Lua/md5-implementation-1.lua | 122 ++ .../Lua/md5-implementation-2.lua | 7 + Task/MD5/Haxe/md5.haxe | 8 + Task/MD5/Ol/md5-1.ol | 3 + Task/MD5/Ol/md5-2.ol | 18 + Task/MD5/Visual-Basic-.NET/md5.visual | 25 + Task/Mad-Libs/Rust/mad-libs.rust | 8 +- .../PicoLisp/magic-squares-of-odd-order.l | 29 + .../JavaScript/main-step-of-gost-28147-89.js | 52 +- .../Rust/main-step-of-gost-28147-89.rust | 33 +- .../Elena/man-or-boy-test.elena | 7 +- .../Haskell/man-or-boy-test.hs | 3 +- .../Mandelbrot-set/Frink/mandelbrot-set.frink | 35 + Task/Mandelbrot-set/GLSL/mandelbrot-set.glsl | 73 +- ...delbrot-set.java => mandelbrot-set-1.java} | 0 .../Mandelbrot-set/Java/mandelbrot-set-2.java | 232 ++++ Task/Mandelbrot-set/Nim/mandelbrot-set.nim | 30 +- .../Mandelbrot-set/Python/mandelbrot-set-5.py | 30 + .../Mandelbrot-set/Python/mandelbrot-set-6.py | 22 + Task/Mandelbrot-set/Rust/mandelbrot-set.rust | 3 +- Task/Map-range/Vala/map-range.vala | 10 + .../00DESCRIPTION | 1 - .../Rust/matrix-exponentiation-operator.rust | 75 ++ .../Haskell/matrix-multiplication-3.hs | 34 +- .../Haskell/matrix-multiplication-4.hs | 12 + .../matrix-multiplication.lambdatalk | 23 + .../Swift/matrix-multiplication.swift | 59 + .../Swift/matrix-transposition.swift | 50 + .../AWK/maximum-triangle-path-sum.awk | 21 + .../Elena/maximum-triangle-path-sum.elena | 2 +- .../Python/maximum-triangle-path-sum-3.py | 13 +- .../Emacs-Lisp/maze-generation-1.l | 193 +++ .../Emacs-Lisp/maze-generation-2.l | 11 + .../Forth/maze-generation-1.fth | 111 ++ .../Forth/maze-generation-2.fth | 122 ++ .../Haskell/maze-generation.hs | 118 +- Task/Maze-solving/Emacs-Lisp/maze-solving-1.l | 193 +++ Task/Maze-solving/Emacs-Lisp/maze-solving-2.l | 9 + Task/Median-filter/Perl-6/median-filter.pl6 | 33 +- Task/Median-filter/Perl/median-filter.pl | 9 + .../00DESCRIPTION | 1 - Task/Menu/Factor/menu.factor | 15 +- Task/Menu/Gambas/menu.gambas | 54 +- Task/Menu/Julia/menu.julia | 2 + Task/Menu/Lua/menu.lua | 26 +- Task/Menu/PowerShell/menu.psh | 8 +- Task/Menu/Swift/menu.swift | 36 + Task/Metaprogramming/Ol/metaprogramming-1.ol | 12 + Task/Metaprogramming/Ol/metaprogramming-2.ol | 3 + .../Elena/middle-three-digits.elena | 2 +- .../Factor/middle-three-digits.factor | 25 +- .../Java/minesweeper-game.java | 1077 +++++++++-------- .../Swift/modular-exponentiation.swift | 31 + .../Prolog/modular-inverse.pro | 10 + .../Swift/modular-inverse.swift | 20 + .../Julia/monte-carlo-methods.julia | 2 + .../BASIC/monty-hall-problem-3.basic | 4 +- .../Julia/monty-hall-problem-1.julia | 2 + .../PHP/move-to-front-algorithm.php | 44 + .../Multifactorial/Julia/multifactorial.julia | 2 + .../R/multiple-regression-1.r | 2 - .../R/multiple-regression-3.r | 2 +- .../R/multiple-regression-4.r | 1 + .../Julia/multiplication-tables.julia | 2 + .../Prolog/multiplication-tables.pro | 33 + .../Factor/multiplicative-order.factor | 11 + .../Lambdatalk/mutual-recursion-1.lambdatalk | 7 + .../Lambdatalk/mutual-recursion-2.lambdatalk | 35 + .../REXX/mutual-recursion-1.rexx | 6 +- .../REXX/mutual-recursion-2.rexx | 10 +- .../REXX/mutual-recursion-3.rexx | 12 +- .../Factor/n-queens-problem.factor | 6 +- .../Frink/n-queens-problem.frink | 12 + .../Haskell/n-queens-problem-4.hs | 40 +- .../Haskell/n-queens-problem-5.hs | 14 +- .../Python/n-queens-problem-8.py | 9 +- Task/N-queens-problem/R/n-queens-problem-1.r | 28 + Task/N-queens-problem/R/n-queens-problem-2.r | 3 + Task/N-queens-problem/R/n-queens-problem-3.r | 1 + Task/N-queens-problem/R/n-queens-problem.r | 28 - Task/Narcissist/Julia/narcissist.julia | 5 +- .../Haskell/narcissistic-decimal-number-2.hs | 60 +- .../narcissistic-decimal-number-4.js | 153 ++- .../Python/narcissistic-decimal-number-3.py | 120 ++ .../R/narcissistic-decimal-number.r | 12 + .../Swift/narcissistic-decimal-number.swift | 23 + .../Julia/non-continuous-subsequences.julia | 26 +- .../Phix/non-decimal-radices-convert-1.phix | 3 + ...hix => non-decimal-radices-convert-2.phix} | 0 .../Python/non-decimal-radices-convert-2.py | 12 - .../Python/non-decimal-radices-convert-3.py | 10 + .../Julia/non-decimal-radices-output.julia | 3 +- .../Phix/non-decimal-radices-output.phix | 4 +- Task/Nth-root/Haskell/nth-root-2.hs | 6 +- Task/Nth-root/Prolog/nth-root.pro | 21 + Task/Nth-root/Python/nth-root-3.py | 111 ++ Task/Nth-root/Swift/nth-root.swift | 36 + Task/Nth/Elena/nth.elena | 4 +- Task/Nth/Julia/nth-1.julia | 13 +- Task/Nth/Julia/nth-2.julia | 27 +- Task/Nth/Julia/nth-3.julia | 17 + .../Commodore-BASIC/number-names.commodore | 48 + Task/Number-names/Julia/number-names-1.julia | 65 +- Task/Number-names/Julia/number-names-2.julia | 49 +- Task/Number-names/Kotlin/number-names.kotlin | 86 +- .../Liberty-BASIC/number-names.liberty | 109 ++ Task/Number-names/Phix/number-names.phix | 29 +- Task/Number-names/Prolog/number-names.pro | 61 + Task/Number-names/R/number-names.r | 51 + .../Prolog/number-reversal-game.pro | 27 + .../Factor/numeric-error-propagation-1.factor | 80 ++ .../Factor/numeric-error-propagation-2.factor | 47 + .../Nim/numeric-error-propagation.nim | 42 + ...l-integration-gauss-legendre-quadrature.js | 19 + ...-integration-gauss-legendre-quadrature.nim | 78 ++ ...tegration-gauss-legendre-quadrature-2.rexx | 10 +- ...tegration-gauss-legendre-quadrature-3.rexx | 16 +- .../Ol/object-serialization.ol | 10 +- .../Elena/old-lady-swallowed-a-fly.elena | 8 +- .../one-dimensional-cellular-automata-1.hs | 3 +- Task/OpenGL/Perl-6/opengl.pl6 | 88 ++ .../Rust/optional-parameters.rust | 139 +++ Task/Pangram-checker/00DESCRIPTION | 5 + .../Crystal/pangram-checker.crystal | 6 + .../EDSAC-order-code/pangram-checker.edsac | 132 ++ .../Retro/pangram-checker.retro | 12 +- .../Swift/parallel-calculations.swift | 74 ++ .../parametric-polymorphism.visual | 38 + .../Java/parametrized-sql-statement.java | 27 +- .../C++/parse-an-ip-address.cpp | 127 ++ .../Java/parse-an-ip-address.java | 110 ++ .../parsing-rpn-calculator-algorithm.cobol | 126 ++ .../parsing-rpn-to-infix-conversion.pl6 | 22 +- .../Elena/partial-function-application.elena | 4 +- .../Java/pascals-triangle-puzzle.java | 113 ++ .../Maple/pascals-triangle-puzzle.maple | 2 + .../Phix/pascals-triangle-puzzle.phix | 6 +- .../REXX/pascals-triangle-puzzle.rexx | 59 +- .../Frink/pascals-triangle.frink | 15 + .../Julia/pascals-triangle-1.julia | 8 + .../Julia/pascals-triangle-2.julia | 15 + .../Julia/pascals-triangle.julia | 8 - .../REXX/pascals-triangle.rexx | 24 +- .../Pascals-triangle/Red/pascals-triangle.red | 14 + .../X86-Assembly/pascals-triangle.x86 | 78 ++ Task/Pattern-matching/00DESCRIPTION | 2 - ...percentage-difference-between-images.julia | 2 +- .../Julia/percolation-bond-percolation.julia | 2 +- .../percolation-mean-cluster-density.julia | 2 +- .../Julia/percolation-mean-run-density.julia | 2 +- .../Julia/percolation-site-percolation.julia | 2 +- .../Prolog/perfect-numbers-2.pro | 7 +- .../Python/perfect-numbers-1.py | 4 +- .../Python/perfect-numbers-2.py | 26 +- .../Python/perfect-numbers-3.py | 39 +- .../Python/perfect-numbers-4.py | 35 + .../Permutation-test/AWK/permutation-test.awk | 25 + .../Permutation-test/Nim/permutation-test.nim | 28 + .../Julia/permutations-derangements.julia | 4 +- .../permutations-rank-of-a-permutation.julia | 2 + Task/Permutations/AWK/permutations.awk | 46 + .../AppleScript/permutations-2.applescript | 15 +- .../Common-Lisp/permutations-3.lisp | 14 + .../Permutations/Lobster/permutations.lobster | 132 ++ Task/Permutations/Lua/permutations-3.lua | 41 + Task/Permutations/Shen/permutations-1.shen | 18 + Task/Permutations/Shen/permutations-2.shen | 4 + .../Factor/pernicious-numbers.factor | 9 +- ...ous-numbers.py => pernicious-numbers-1.py} | 0 .../Python/pernicious-numbers-2.py | 133 ++ .../Sidef/pernicious-numbers.sidef | 21 +- .../Swift/pernicious-numbers.swift | 34 + .../Rust/phrase-reversals.rust | 51 + Task/Pi/JavaScript/pi-1.js | 34 +- .../Elena/pick-random-element.elena | 2 +- .../REXX/pick-random-element-1.rexx | 5 +- .../Ada/pinstripe-display.ada | 68 ++ .../Perl-6/pinstripe-printer.pl6 | 55 + .../Playing-cards/Kotlin/playing-cards.kotlin | 30 +- Task/Playing-cards/REXX/playing-cards-2.rexx | 60 +- .../Factor/plot-coordinate-pairs.factor | 7 + .../Perl-6/plot-coordinate-pairs.pl6 | 2 +- Task/Polymorphism/Prolog/polymorphism.pro | 43 + .../Java/polynomial-long-division.java | 649 ++++++++-- .../Phix/polynomial-long-division.phix | 1 + .../Swift/polynomial-long-division.swift | 130 ++ .../PowerShell/polynomial-regression.psh | 80 ++ Task/Power-set/D/power-set-3.d | 16 + Task/Power-set/Groovy/power-set-1.groovy | 16 +- Task/Power-set/Groovy/power-set-2.groovy | 4 +- Task/Power-set/R/power-set-2.r | 12 +- Task/Power-set/REXX/power-set.rexx | 23 +- ...-fraction.basic => price-fraction-1.basic} | 0 .../BASIC/price-fraction-2.basic | 22 + .../Price-fraction/Swift/price-fraction.swift | 32 + .../Ol/primality-by-trial-division-1.ol | 11 + .../Ol/primality-by-trial-division-2.ol | 19 + .../Rust/primality-by-trial-division.rust | 6 +- .../Lambdatalk/prime-decomposition.lambdatalk | 31 + .../Phix/prime-decomposition-2.phix | 1 + .../Phix/prime-decomposition-3.phix | 31 +- .../Prolog/prime-decomposition-4.pro | 35 + .../Python/prime-decomposition-2.py | 4 +- .../R/prime-decomposition-3.r | 19 + .../Sidef/prime-decomposition-1.sidef | 3 +- .../Julia/probabilistic-choice.julia | 2 + .../Julia/problem-of-apollonius-1.julia | 2 + .../Retro/program-termination.retro | 2 +- .../AWK/pythagorean-triples.awk | 23 + .../pythagorean-triples.edsac | 210 ++++ .../PHP/pythagorean-triples.php | 37 + .../Prolog/pythagorean-triples.pro | 37 + Task/QR-decomposition/00DESCRIPTION | 2 +- .../Fortran/qr-decomposition.f | 41 + .../Maxima/qr-decomposition-1.maxima | 2 +- .../QR-decomposition/Perl/qr-decomposition.pl | 16 + .../PowerShell/qr-decomposition.psh | 86 ++ .../Idris/quaternion-type-1.idris | 95 ++ .../Idris/quaternion-type-2.idris | 11 + .../Maple/quaternion-type.maple | 146 +++ Task/Quaternion-type/Red/quaternion-type.red | 59 + .../Factor/queue-definition.factor | 18 + .../Quine/Binary-Lambda-Calculus/quine.binary | 1 + Task/Quine/Bracmat/quine.bracmat | 1 + Task/Quine/Gambas/quine.gambas | 2 + Task/Quine/JavaScript/quine-10.js | 1 + Task/Quine/JavaScript/quine-9.js | 1 + Task/Quine/Swift/quine-3.swift | 1 + Task/RIPEMD-160/Ada/ripemd-160.ada | 34 + Task/RIPEMD-160/C/ripemd-160.c | 15 + Task/RSA-code/PowerShell/rsa-code.psh | 13 + Task/Random-numbers/00DESCRIPTION | 4 +- .../Random-numbers/Elena/random-numbers.elena | 8 +- .../Random-numbers/Frink/random-numbers.frink | 3 + .../Lobster/random-numbers.lobster | 29 + .../Scala/random-numbers-2.scala | 23 +- Task/Range-extraction/R/range-extraction.r | 18 +- .../Factor/ranking-methods.factor | 36 + .../Julia/ray-casting-algorithm-2.julia | 2 + .../PHP/ray-casting-algorithm.php | 86 ++ .../COBOL/read-a-configuration-file.cobol | 96 ++ .../PHP/read-a-configuration-file.php | 35 + .../XPL0/read-a-file-line-by-line.xpl0 | 6 + .../read-a-specific-line-from-a-file.elixir | 11 + .../Lua/read-a-specific-line-from-a-file.lua | 14 +- .../PHP/read-a-specific-line-from-a-file.php | 17 + ...tire-file.pike => read-entire-file-1.pike} | 0 .../Pike/read-entire-file-2.pike | 1 + .../Python/read-entire-file-4.py | 4 + .../OCaml/real-constants-and-functions.ocaml | 1 + Task/Record-sound/Perl-6/record-sound.pl6 | 69 ++ Task/Record-sound/Phix/record-sound.phix | 80 ++ .../Crystal/remove-duplicate-elements.crystal | 2 + .../Elena/remove-duplicate-elements.elena | 2 +- .../Rename-a-file/BASIC/rename-a-file-5.basic | 1 + .../Rename-a-file/BASIC/rename-a-file-6.basic | 1 + Task/Rep-string/Clojure/rep-string-1.clj | 6 + Task/Rep-string/Clojure/rep-string-2.clj | 13 + Task/Rep-string/Haskell/rep-string-2.hs | 5 +- Task/Rep-string/Rust/rep-string.rust | 81 ++ .../Resistor-mesh/Maxima/resistor-mesh.maxima | 2 +- .../Elena/return-multiple-values.elena | 2 +- .../Go/return-multiple-values-4.go | 64 + .../Forth/reverse-a-string-2.fth | 21 +- .../Pike/reverse-a-string-1.pike | 1 + .../Pike/reverse-a-string-2.pike | 6 + .../Retro/reverse-a-string.retro | 3 +- .../Elena/reverse-words-in-a-string.elena | 4 +- .../Pike/reverse-words-in-a-string.pike | 13 + .../Julia/roman-numerals-decode-2.julia | 2 + .../Julia/roman-numerals-encode.julia | 2 + .../Shen/roman-numerals-encode.shen | 9 + .../Vala/roman-numerals-encode.vala | 26 + .../Julia/roots-of-a-function-1.julia | 2 +- .../Nim/roots-of-a-function.nim | 22 + .../REXX/roots-of-a-function-1.rexx | 18 +- .../REXX/roots-of-a-function-2.rexx | 18 +- .../Julia/roots-of-a-quadratic-function.julia | 2 + .../R/roots-of-a-quadratic-function-1.r | 15 + .../R/roots-of-a-quadratic-function-2.r | 5 + .../R/roots-of-a-quadratic-function.r | 18 - .../Factor/roots-of-unity.factor | 3 + .../Roots-of-unity/Frink/roots-of-unity.frink | 12 + Task/Roots-of-unity/Prolog/roots-of-unity.pro | 16 + Task/Rot-13/Vala/rot-13.vala | 22 + .../JavaScript/run-length-encoding-4.js | 51 + .../Scala/run-length-encoding-3.scala | 4 + Task/S-Expressions/Haskell/s-expressions.hs | 50 +- Task/SHA-1/Haxe/sha-1.haxe | 8 + Task/SHA-1/Pike/sha-1.pike | 3 + Task/SHA-256/Ada/sha-256.ada | 34 + Task/SHA-256/Frink/sha-256.frink | 1 + Task/SHA-256/Haxe/sha-256.haxe | 8 + Task/SHA-256/JavaScript/sha-256.js | 6 + Task/SHA-256/Pike/sha-256.pike | 3 + Task/SOAP/Julia/soap.julia | 31 + Task/SOAP/Phix/soap.phix | 50 + .../Bracmat/scope-modifiers-2.bracmat | 2 +- Task/Search-a-list/Elena/search-a-list.elena | 4 +- .../Swift/self-describing-numbers.swift | 33 + .../Factor/self-referential-sequence.factor | 37 + Task/Semiprime/Factor/semiprime-1.factor | 1 + Task/Semiprime/Factor/semiprime-2.factor | 2 +- Task/Semiprime/Sidef/semiprime-1.sidef | 2 + Task/Semiprime/Sidef/semiprime-2.sidef | 11 + Task/Semiprime/Sidef/semiprime.sidef | 12 - Task/Semordnilap/Python/semordnilap-4.py | 53 +- Task/Semordnilap/Swift/semordnilap.swift | 11 + .../Elena/send-an-unknown-method-call.elena | 2 +- Task/Send-email/Phix/send-email.phix | 62 + .../Maple/sequence-of-non-squares.maple | 11 + ...quares.py => sequence-of-non-squares-1.py} | 0 .../Python/sequence-of-non-squares-2.py | 89 ++ .../REXX/sequence-of-non-squares.rexx | 16 +- .../Factor/set-consolidation.factor | 10 + .../Nim/set-consolidation.nim | 15 + Task/Set-puzzle/C-sharp/set-puzzle.cs | 85 ++ Task/Set-puzzle/Factor/set-puzzle.factor | 42 + Task/Set-puzzle/Prolog/set-puzzle.pro | 45 + .../Processing/shell-one-liner | 1 + .../Elena/short-circuit-evaluation.elena | 2 +- .../Show-the-epoch/Julia/show-the-epoch.julia | 2 +- Task/Show-the-epoch/Pike/show-the-epoch.pike | 2 + ...{show-the-epoch.rb => show-the-epoch-1.rb} | 0 Task/Show-the-epoch/Ruby/show-the-epoch-2.rb | 2 + .../Factor/sierpinski-carpet.factor | 7 + .../PHP/sierpinski-carpet.php | 28 + .../sierpinski-triangle-graphical-1.math | 12 +- .../sierpinski-triangle-graphical-2.math | 13 +- .../Haskell/sierpinski-triangle-5.hs | 11 + .../Java/sierpinski-triangle.java | 44 + .../JavaScript/sierpinski-triangle-3.js | 76 +- .../JavaScript/sierpinski-triangle-4.js | 100 +- .../JavaScript/sierpinski-triangle-5.js | 62 + .../Lua/sierpinski-triangle.lua | 17 + .../PHP/sierpinski-triangle.php | 24 + ...i-triangle.pl => sierpinski-triangle-1.pl} | 0 .../Perl/sierpinski-triangle-2.pl | 1 + .../Python/sierpinski-triangle-3.py | 13 +- .../BASIC/sieve-of-eratosthenes-5.basic | 20 +- .../F-Sharp/sieve-of-eratosthenes-15.fs | 205 +++- .../Frink/sieve-of-eratosthenes.frink | 18 + .../Java/sieve-of-eratosthenes-4.java | 66 +- .../Java/sieve-of-eratosthenes-5.java | 97 +- .../Java/sieve-of-eratosthenes-6.java | 101 +- .../Java/sieve-of-eratosthenes-7.java | 78 ++ .../PHP/sieve-of-eratosthenes.php | 6 + ...atosthenes.l => sieve-of-eratosthenes-1.l} | 0 .../PicoLisp/sieve-of-eratosthenes-2.l | 32 + .../PowerShell/sieve-of-eratosthenes-2.psh | 2 +- .../REXX/sieve-of-eratosthenes-3.rexx | 7 +- .../Swift/sieve-of-eratosthenes-1.swift | 50 +- .../Clojure/simulate-input-keyboard.clj | 2 +- .../Nim/simulate-input-keyboard.nim | 81 ++ .../C/simulate-input-mouse.c | 2 +- Task/Singleton/Python/singleton-3.py | 9 + Task/Singleton/Python/singleton-4.py | 2 + .../00DESCRIPTION | 1 + .../REXX/singly-linked-list-traversal.rexx | 2 +- Task/Sleep/Cache-ObjectScript/sleep.cos | 12 +- Task/Sockets/Elena/sockets.elena | 23 +- Task/Sockets/R/sockets.r | 3 + .../Prolog/solve-a-hopido-puzzle-1.pro | 24 + .../Prolog/solve-a-hopido-puzzle-2.pro | 14 + .../Prolog/solve-a-numbrix-puzzle.pro | 107 ++ .../REXX/solve-a-numbrix-puzzle.rexx | 90 +- .../Perl/solve-the-no-connection-puzzle.pl | 28 + ...ort-an-array-of-composite-structures.elena | 4 +- ...ort-an-array-of-composite-structures.swift | 21 + .../Elena/sort-an-integer-array.elena | 2 +- .../REXX/sort-an-integer-array-2.rexx | 32 +- .../Elena/sort-disjoint-sublist.elena | 6 +- .../Haskell/sort-disjoint-sublist-2.hs | 11 +- .../sort-using-a-custom-comparator.elena | 2 +- .../Nim/sort-using-a-custom-comparator.nim | 7 +- .../Prolog/sort-using-a-custom-comparator.pro | 4 +- .../sorting-algorithms-bogosort.crystal | 26 + .../Elena/sorting-algorithms-bogosort.elena | 2 +- .../Prolog/sorting-algorithms-bogosort.pro | 11 + .../sorting-algorithms-bubble-sort.edsac | 151 +++ .../sorting-algorithms-bubble-sort.elena | 2 +- .../Haxe/sorting-algorithms-bubble-sort.haxe | 39 + .../sorting-algorithms-bubble-sort-1.rexx | 12 +- .../sorting-algorithms-bubble-sort-2.rexx | 4 +- .../sorting-algorithms-bubble-sort-4.rexx | 6 +- .../sorting-algorithms-bubble-sort.swift | 7 +- .../Vala/sorting-algorithms-bubble-sort.vala | 29 + .../00DESCRIPTION | 6 +- .../sorting-algorithms-cocktail-sort.elena | 2 +- .../sorting-algorithms-cocktail-sort-1.factor | 18 + .../sorting-algorithms-cocktail-sort-2.factor | 21 + .../sorting-algorithms-cocktail-sort.haxe | 49 + .../sorting-algorithms-cocktail-sort-1.rexx | 127 +- .../sorting-algorithms-cocktail-sort-2.rexx | 29 +- .../sorting-algorithms-cocktail-sort.vala | 33 + .../Elena/sorting-algorithms-comb-sort.elena | 2 +- .../Haxe/sorting-algorithms-comb-sort.haxe | 43 + .../sorting-algorithms-counting-sort.haxe | 33 + .../Elena/sorting-algorithms-gnome-sort.elena | 2 +- .../Haxe/sorting-algorithms-gnome-sort.haxe | 39 + .../Haxe/sorting-algorithms-heapsort.haxe | 60 + .../sorting-algorithms-heapsort.lobster | 57 + .../Vala/sorting-algorithms-heapsort.vala | 53 + .../sorting-algorithms-insertion-sort.elena | 2 +- .../sorting-algorithms-insertion-sort-2.f | 1 - .../sorting-algorithms-insertion-sort.haxe | 33 + .../sorting-algorithms-insertion-sort.scala | 6 + .../sorting-algorithms-insertion-sort.vala | 19 + .../Scala/sorting-algorithms-merge-sort.scala | 21 + .../sorting-algorithms-pancake-sort.bat | 77 ++ .../sorting-algorithms-pancake-sort.elena | 2 +- .../Haxe/sorting-algorithms-pancake-sort.haxe | 48 + .../REXX/sorting-algorithms-pancake-sort.rexx | 12 +- ...orting-algorithms-permutation-sort.crystal | 18 + .../Elena/sorting-algorithms-quicksort.elena | 2 +- ...l => sorting-algorithms-quicksort-1.ocaml} | 0 .../sorting-algorithms-quicksort-2.ocaml | 31 + .../sorting-algorithms-quicksort-3.psh | 15 + .../sorting-algorithms-quicksort-2.ml | 4 +- .../Python/sorting-algorithms-radix-sort-2.py | 3 + .../sorting-algorithms-selection-sort.crystal | 13 + .../sorting-algorithms-selection-sort.elena | 2 +- ...sorting-algorithms-selection-sort-1.factor | 8 + ...sorting-algorithms-selection-sort-2.factor | 4 + .../sorting-algorithms-selection-sort.haxe | 54 +- .../Haxe/sorting-algorithms-shell-sort.haxe | 38 + .../sorting-algorithms-sleep-sort.l | 2 + .../Pike/sorting-algorithms-sleep-sort.pike | 21 + .../Ol/special-characters-2.ol | 2 +- .../PHP/speech-synthesis-1.php | 61 + .../PHP/speech-synthesis-2.php | 117 ++ .../Phix/speech-synthesis.phix | 27 + Task/Spiral-matrix/Maple/spiral-matrix.maple | 26 + .../Haskell/stable-marriage-problem-3.hs | 3 +- Task/Stack-traces/Nim/stack-traces.nim | 6 + Task/Stack/Crystal/stack.crystal | 8 + Task/Stack/Ol/stack-1.ol | 42 + Task/Stack/Ol/stack-2.ol | 37 + Task/Stack/Pike/stack.pike | 6 + .../Prolog/stair-climbing-puzzle-1.pro | 1 + .../Prolog/stair-climbing-puzzle-2.pro | 18 + .../Processing/start-from-a-main-routine-1 | 2 + .../Processing/start-from-a-main-routine-2 | 4 + .../Processing/start-from-a-main-routine-3 | 6 + .../Julia/statistics-basic.julia | 2 + .../Julia/stern-brocot-sequence.julia | 2 + .../{string-append.go => string-append-1.go} | 0 Task/String-append/Go/string-append-2.go | 13 + Task/String-append/Pike/string-append.pike | 3 + .../Robotic/string-append.robotic | 4 + ...tring-append.rust => string-append-1.rust} | 0 Task/String-append/Rust/string-append-2.rust | 5 + Task/String-append/Vala/string-append.vala | 5 + Task/String-case/Pike/string-case-1.pike | 9 + Task/String-case/Pike/string-case-2.pike | 8 + Task/String-case/Retro/string-case.retro | 5 +- .../Nim/string-comparison.nim | 2 + .../Robotic/string-comparison.robotic | 29 + .../Vala/string-comparison.vala | 10 + .../Pike/string-concatenation.pike | 4 + .../Retro/string-concatenation.retro | 3 +- .../Vala/string-concatenation.vala | 7 + .../Haxe/string-interpolation--included-.haxe | 7 + .../Vala/string-interpolation--included-.vala | 5 + .../String-length/BASIC/string-length-2.basic | 2 +- .../String-length/BASIC/string-length-3.basic | 10 +- .../String-length/BASIC/string-length-4.basic | 3 +- .../String-length/BASIC/string-length-5.basic | 5 + .../String-length/BASIC/string-length-6.basic | 2 + .../String-length/BASIC/string-length-7.basic | 2 + .../String-length/Frink/string-length-1.frink | 2 + .../String-length/Frink/string-length-2.frink | 2 + .../String-length/Frink/string-length-3.frink | 2 + .../String-length/Retro/string-length-1.retro | 2 +- Task/String-length/Ruby/string-length-1.rb | 5 +- Task/String-length/Ruby/string-length-2.rb | 8 +- Task/String-length/Ruby/string-length-3.rb | 5 +- Task/String-length/Ruby/string-length-4.rb | 2 +- Task/String-length/Ruby/string-length-5.rb | 2 +- Task/String-length/Ruby/string-length-6.rb | 14 +- Task/String-length/Ruby/string-length-7.rb | 12 + Task/String-length/Stata/string-length.stata | 4 + .../Perl-6/string-matching-4.pl6 | 1 + .../String-matching/Vala/string-matching.vala | 14 + .../BASIC/string-prepend-2.basic | 2 +- .../BASIC/string-prepend-3.basic | 3 + .../String-prepend/OCaml/string-prepend.ocaml | 4 + .../Nim/strip-block-comments.nim | 4 +- .../COBOL/strip-comments-from-a-string.cobol | 21 + .../Forth/strip-comments-from-a-string.fth | 25 + ...-and-extended-characters-from-a-string-1.c | 165 ++- ...-and-extended-characters-from-a-string-2.c | 67 +- ...-and-extended-characters-from-a-string-3.c | 3 + ...-and-extended-characters-from-a-string.nim | 9 +- ...itespace-from-a-string-top-and-tail.factor | 2 +- ...ip-whitespace-from-a-string-top-and-tail.r | 10 + ...hitespace-from-a-string-top-and-tail.retro | 6 +- .../Nim/substring-top-and-tail.nim | 15 +- Task/Substring/Crystal/substring.crystal | 17 + Task/Sudoku/00DESCRIPTION | 5 +- Task/Sudoku/AWK/sudoku.awk | 187 +++ Task/Sudoku/Lua/{sudoku.lua => sudoku-1.lua} | 0 Task/Sudoku/Lua/sudoku-2.lua | 69 ++ .../Elena/sum-and-product-of-an-array.elena | 2 +- .../Objeck/sum-digits-of-an-integer.objeck | 18 + .../Python/sum-digits-of-an-integer-1.py | 18 +- .../Python/sum-digits-of-an-integer-2.py | 16 +- .../Python/sum-digits-of-an-integer-3.py | 101 +- .../Python/sum-digits-of-an-integer-4.py | 111 ++ .../Emacs-Lisp/sum-multiples-of-3-and-5-1.l | 4 +- .../Emacs-Lisp/sum-multiples-of-3-and-5-2.l | 4 +- .../Emacs-Lisp/sum-multiples-of-3-and-5-3.l | 3 +- .../Factor/sum-multiples-of-3-and-5.factor | 27 +- .../Frink/sum-multiples-of-3-and-5.frink | 12 + ...5.java => sum-multiples-of-3-and-5-1.java} | 0 .../Java/sum-multiples-of-3-and-5-2.java | 40 + .../Maxima/sum-multiples-of-3-and-5.maxima | 13 +- .../PHP/sum-multiples-of-3-and-5-1.php | 8 + .../PHP/sum-multiples-of-3-and-5-2.php | 12 + .../PHP/sum-multiples-of-3-and-5-3.php | 19 + .../Phix/sum-multiples-of-3-and-5-1.phix | 16 + ...5.phix => sum-multiples-of-3-and-5-2.phix} | 0 .../PicoLisp/sum-multiples-of-3-and-5.l | 2 - .../PowerShell/sum-multiples-of-3-and-5-1.psh | 4 +- .../PowerShell/sum-multiples-of-3-and-5-2.psh | 4 +- .../Frink/sum-of-a-series.frink | 1 + .../Haxe/sum-of-a-series-1.haxe | 11 + .../Haxe/sum-of-a-series-2.haxe | 10 + .../Sum-of-a-series/Tcl/sum-of-a-series-1.tcl | 14 +- .../Sum-of-a-series/Tcl/sum-of-a-series-2.tcl | 12 +- .../Sum-of-a-series/Tcl/sum-of-a-series-3.tcl | 24 +- .../Sum-of-a-series/Tcl/sum-of-a-series-4.tcl | 16 + .../Sum-of-squares/Elena/sum-of-squares.elena | 4 +- Task/Sum-of-squares/Haskell/sum-of-squares.hs | 12 +- .../sutherland-hodgman-polygon-clipping.pl6 | 60 + .../sutherland-hodgman-polygon-clipping.pl | 50 + .../Perl-6/symmetric-difference.pl6 | 3 +- .../Crystal/synchronous-concurrency.crystal | 16 + Task/System-time/Pike/system-time.pike | 1 + .../Elena/temperature-conversion.elena | 2 +- .../Java/temperature-conversion.java | 2 +- ...terminal-control-clear-the-screen-10.basic | 1 + ...terminal-control-clear-the-screen-11.basic | 1 + .../terminal-control-clear-the-screen-3.basic | 2 +- .../terminal-control-clear-the-screen-4.basic | 2 +- .../terminal-control-clear-the-screen-5.basic | 2 +- .../terminal-control-clear-the-screen-6.basic | 2 +- .../terminal-control-clear-the-screen-7.basic | 2 +- .../terminal-control-clear-the-screen-8.basic | 2 +- .../terminal-control-clear-the-screen-9.basic | 1 + ...=> terminal-control-coloured-text-1.basic} | 0 .../terminal-control-coloured-text-2.basic | 5 + .../terminal-control-coloured-text-3.basic | 5 + .../terminal-control-coloured-text-4.basic | 9 + .../terminal-control-coloured-text-5.basic | 6 + .../terminal-control-cursor-positioning.php | 6 + ....tcl => terminal-control-dimensions-1.tcl} | 0 .../Tcl/terminal-control-dimensions-2.tcl | 2 + .../terminal-control-inverse-video-10.basic | 4 + .../terminal-control-inverse-video-4.basic | 11 +- .../terminal-control-inverse-video-5.basic | 11 +- .../terminal-control-inverse-video-6.basic | 15 +- .../terminal-control-inverse-video-7.basic | 9 +- .../terminal-control-inverse-video-8.basic | 9 +- .../terminal-control-inverse-video-9.basic | 12 +- .../Ruby/terminal-control-inverse-video.rb | 1 + ...nal-control-ringing-the-terminal-bell.rust | 3 + Task/Ternary-logic/Elena/ternary-logic.elena | 2 +- .../Crystal/test-a-function.crystal | 15 + .../Prolog/test-a-function.pro | 8 + Task/Textonyms/Julia/textonyms-1.julia | 2 + .../Elena/the-twelve-days-of-christmas.elena | 8 +- .../REXX/the-twelve-days-of-christmas.rexx | 23 +- .../Haskell/thieles-interpolation-formula.hs | 4 +- .../Nim/thieles-interpolation-formula.nim | 48 + .../Perl/thieles-interpolation-formula.pl | 45 + Task/Tic-tac-toe/Lua/tic-tac-toe.lua | 190 +++ .../JavaScript/time-a-function.js | 12 + .../Time-a-function/Phix/time-a-function.phix | 3 +- .../Time-a-function/Pike/time-a-function.pike | 12 + .../Time-a-function/Python/time-a-function.py | 4 +- .../Swift/time-a-function.swift | 56 + Task/Tokenize-a-string/00DESCRIPTION | 6 +- .../Ada/tokenize-a-string.ada | 32 +- .../Nim/tokenize-a-string.nim | 2 +- .../REXX/tokenize-a-string-1.rexx | 30 +- .../Elena/top-rank-per-group.elena | 34 +- Task/Topswops/Factor/topswops.factor | 26 + Task/Topswops/Nim/topswops.nim | 40 + Task/Topswops/Perl-6/topswops.pl6 | 2 +- Task/Total-circles-area/00DESCRIPTION | 54 +- .../Julia/total-circles-area.julia | 3 +- .../REXX/total-circles-area-2.rexx | 44 +- .../BASIC/towers-of-hanoi-3.basic | 8 + .../Clojure/towers-of-hanoi-1.clj | 5 + .../Clojure/towers-of-hanoi-2.clj | 5 + .../Clojure/towers-of-hanoi.clj | 7 - .../Frink/towers-of-hanoi.frink | 15 + ...ers-of-hanoi.lua => towers-of-hanoi-1.lua} | 0 .../Towers-of-Hanoi/Lua/towers-of-hanoi-2.lua | 40 + .../Towers-of-Hanoi/Lua/towers-of-hanoi-3.lua | 14 + Task/Towers-of-Hanoi/R/towers-of-hanoi.r | 10 +- .../REXX/towers-of-hanoi-2.rexx | 77 +- .../Towers-of-Hanoi/Scheme/towers-of-hanoi.ss | 25 +- .../AppleScript/tree-traversal.applescript | 414 ++++--- .../Tree-traversal/Elena/tree-traversal.elena | 10 +- .../JavaScript/tree-traversal-6.js | 248 ++-- .../Tree-traversal/Python/tree-traversal-1.py | 73 +- Task/Truncatable-primes/00DESCRIPTION | 5 +- .../C++/truncatable-primes.cpp | 66 + .../Pike/truncatable-primes.pike | 29 + .../REXX/truncatable-primes.rexx | 57 +- ...ncate-a-file.pl6 => truncate-a-file-1.pl6} | 0 .../Perl-6/truncate-a-file-2.pl6 | 1 + .../Elena/twelve-statements.elena | 6 +- .../Haskell/twelve-statements.hs | 59 +- .../Julia/twelve-statements.julia | 2 + Task/URL-decoding/Pike/url-decoding.pike | 13 + Task/URL-encoding/Pike/url-encoding.pike | 1 + .../Julia/unbias-a-random-generator.julia | 2 + .../Unicode-strings/Pike/unicode-strings.pike | 10 + .../Ol/unicode-variable-names.ol | 3 + .../Pike/unicode-variable-names.pike | 7 + .../Retro/unicode-variable-names.retro | 10 +- .../C-sharp/universal-turing-machine.cs | 200 +++ .../MATLAB/universal-turing-machine.m | 49 + .../Scala/universal-turing-machine.scala | 376 +++--- .../UNIX-Shell/universal-turing-machine.sh | 65 + Task/Unix-ls/Java/unix-ls-1.java | 12 + Task/Unix-ls/Java/unix-ls-2.java | 1 + Task/Unix-ls/Java/unix-ls.java | 22 - Task/Unix-ls/Nim/unix-ls.nim | 6 +- Task/Unix-ls/Objeck/unix-ls.objeck | 12 + Task/Unix-ls/Pike/unix-ls.pike | 2 + Task/Unix-ls/R/unix-ls.r | 2 + .../PHP/update-a-configuration-file.php | 21 + ...-another-language-to-call-a-function-1.pl6 | 6 + ...-another-language-to-call-a-function-2.pl6 | 15 + .../Ada/user-input-graphical.ada | 2 +- .../Crystal/user-input-text.crystal | 7 + .../LOLCODE/user-input-text.lol | 8 + .../Retro/user-input-text.retro | 10 +- .../Julia/vampire-number-2.julia | 2 + Task/Vampire-number/Rust/vampire-number.rust | 124 ++ .../Julia/van-der-corput-sequence.julia | 2 + .../JavaScript/variable-length-quantity.js | 31 + .../Julia/variable-length-quantity.julia | 2 + Task/Variable-size-Get/00DESCRIPTION | 17 - .../Factor/variable-size-get.factor | 11 + .../Phix/variable-size-set.phix | 7 +- Task/Variables/Clojure/variables-1.clj | 1 + Task/Variables/Clojure/variables-10.clj | 1 + Task/Variables/Clojure/variables-11.clj | 1 + Task/Variables/Clojure/variables-12.clj | 1 + Task/Variables/Clojure/variables-2.clj | 1 + Task/Variables/Clojure/variables-3.clj | 1 + Task/Variables/Clojure/variables-4.clj | 1 + Task/Variables/Clojure/variables-5.clj | 1 + Task/Variables/Clojure/variables-6.clj | 1 + Task/Variables/Clojure/variables-7.clj | 1 + Task/Variables/Clojure/variables-8.clj | 2 + Task/Variables/Clojure/variables-9.clj | 2 + Task/Variables/Elena/variables.elena | 4 +- .../Elena/variadic-function.elena | 4 +- Task/Vector-products/00DESCRIPTION | 6 +- .../Factor/vector-products.factor | 1 - ...ector-products.hs => vector-products-1.hs} | 0 .../Haskell/vector-products-2.hs | 56 + ...ector-products.js => vector-products-1.js} | 0 .../JavaScript/vector-products-2.js | 140 +++ .../Julia/vector-products.julia | 2 + .../Swift/vector-products.swift | 39 + ...verify-distribution-uniformity-naive.julia | 2 + ...rify-distribution-uniformity-naive-1.scala | 24 + ...rify-distribution-uniformity-naive-2.scala | 15 + .../Perl-6/vigen-re-cipher-cryptanalysis.pl6 | 93 ++ .../Perl/vigen-re-cipher-cryptanalysis.pl | 106 ++ Task/Vigen-re-cipher/Ada/vigen-re-cipher.ada | 2 +- .../Swift/vigen-re-cipher.swift | 125 ++ .../Common-Lisp/visualize-a-tree-3.lisp | 16 + .../Common-Lisp/visualize-a-tree-4.lisp | 27 + .../Elena/visualize-a-tree.elena | 14 +- .../Maple/visualize-a-tree.maple | 2 + .../Julia/vogels-approximation-method-3.julia | 2 + .../Delphi/voronoi-diagram.delphi | 2 + .../OCaml/voronoi-diagram.ocaml | 60 + Task/Voronoi-diagram/Red/voronoi-diagram.red | 62 + Task/Web-scraping/Julia/web-scraping-1.julia | 2 +- .../Window-creation/Nim/window-creation-7.nim | 18 + .../Elena/world-cup-group-stage.elena | 11 +- .../00DESCRIPTION | 2 +- .../write-float-arrays-to-a-text-file-1.f | 32 +- .../write-float-arrays-to-a-text-file-2.f | 34 +- .../Nim/write-float-arrays-to-a-text-file.nim | 10 +- .../write-float-arrays-to-a-text-file-1.pl6 | 8 +- .../write-float-arrays-to-a-text-file-2.pl6 | 11 +- .../write-float-arrays-to-a-text-file.psh | 2 +- .../R/write-float-arrays-to-a-text-file.r | 19 +- .../write-float-arrays-to-a-text-file.stata | 11 + .../Nim/write-language-name-in-3d-ascii.nim | 8 +- .../write-language-name-in-3d-ascii-3.rexx | 2 +- .../write-language-name-in-3d-ascii.sh | 9 +- .../Perl-6/write-to-windows-event-log.pl6 | 11 + Task/XML-Input/MATLAB/xml-input.m | 43 + Task/XML-Input/Phix/xml-input.phix | 27 + Task/XML-Input/Rust/xml-input-1.rust | 37 + Task/XML-Input/Rust/xml-input-2.rust | 27 + Task/XML-Output/MATLAB/xml-output.m | 14 + .../Nim/{xml-output.nim => xml-output-1.nim} | 4 +- Task/XML-Output/Nim/xml-output-2.nim | 5 + Task/XML-Output/XQuery/xml-output-1.xquery | 9 + Task/XML-Output/XQuery/xml-output-2.xquery | 8 + Task/XML-Output/XQuery/xml-output-3.xquery | 12 + Task/XML-Output/XQuery/xml-output-4.xquery | 11 + Task/XML-Output/XQuery/xml-output-5.xquery | 5 + Task/XML-XPath/00DESCRIPTION | 6 +- Task/XML-XPath/Scala/xml-xpath.scala | 42 +- .../Python/xiaolin-wus-line-algorithm.py | 7 +- Task/Y-combinator/C-sharp/y-combinator-1.cs | 22 + Task/Y-combinator/C-sharp/y-combinator-10.cs | 5 + Task/Y-combinator/C-sharp/y-combinator-11.cs | 23 + Task/Y-combinator/C-sharp/y-combinator-12.cs | 1 + Task/Y-combinator/C-sharp/y-combinator-13.cs | 49 + Task/Y-combinator/C-sharp/y-combinator-14.cs | 91 ++ Task/Y-combinator/C-sharp/y-combinator-15.cs | 97 ++ Task/Y-combinator/C-sharp/y-combinator-16.cs | 129 ++ Task/Y-combinator/C-sharp/y-combinator-17.cs | 21 + Task/Y-combinator/C-sharp/y-combinator-18.cs | 4 + Task/Y-combinator/C-sharp/y-combinator-19.cs | 3 + Task/Y-combinator/C-sharp/y-combinator-2.cs | 7 + Task/Y-combinator/C-sharp/y-combinator-3.cs | 5 + Task/Y-combinator/C-sharp/y-combinator-4.cs | 4 + Task/Y-combinator/C-sharp/y-combinator-5.cs | 41 + Task/Y-combinator/C-sharp/y-combinator-6.cs | 27 + Task/Y-combinator/C-sharp/y-combinator-7.cs | 48 + Task/Y-combinator/C-sharp/y-combinator-8.cs | 44 + Task/Y-combinator/C-sharp/y-combinator-9.cs | 43 + .../Go/yahoo--search-interface.go | 63 + .../Perl-6/yahoo--search-interface-1.pl6 | 55 + .../Perl-6/yahoo--search-interface-2.pl6 | 12 + .../C/zeckendorf-arithmetic.c | 189 +++ .../Elena/zeckendorf-arithmetic.elena | 4 +- .../Scala/zeckendorf-arithmetic.scala | 524 ++++---- .../zeckendorf-arithmetic.visual | 198 +++ Task/Zero-to-the-zero-power/00DESCRIPTION | 13 +- .../Crystal/zero-to-the-zero-power.crystal | 4 + .../Julia/zero-to-the-zero-power.julia | 2 + .../zero-to-the-zero-power.liberty | 3 + .../Nim/zero-to-the-zero-power.nim | 1 + .../Pike/zero-to-the-zero-power.pike | 1 + .../Pyret/zero-to-the-zero-power.pyret | 1 + .../XPL0/zero-to-the-zero-power.xpl0 | 1 + .../C/zhang-suen-thinning-algorithm.c | 4 +- Task/Zig-zag-matrix/00DESCRIPTION | 2 +- ...-matrix.factor => zig-zag-matrix-1.factor} | 0 .../Factor/zig-zag-matrix-2.factor | 11 + Task/Zig-zag-matrix/Nim/zig-zag-matrix-1.nim | 31 + Task/Zig-zag-matrix/Nim/zig-zag-matrix-2.nim | 22 + Task/Zig-zag-matrix/Nim/zig-zag-matrix.nim | 36 - .../Octave/zig-zag-matrix-3.octave | 57 + Task/Zig-zag-matrix/REXX/zig-zag-matrix.rexx | 41 +- 2442 files changed, 39761 insertions(+), 8255 deletions(-) create mode 120000 Lang/APL/Increment-a-numerical-string create mode 120000 Lang/AWK/Carmichael-3-strong-pseudoprimes create mode 120000 Lang/AWK/Circles-of-given-radius-through-two-points create mode 120000 Lang/AWK/Colour-bars-Display create mode 120000 Lang/AWK/Dynamic-variable-names create mode 120000 Lang/AWK/Gray-code create mode 120000 Lang/AWK/Greyscale-bars-Display create mode 120000 Lang/AWK/Keyboard-input-Flush-the-keyboard-buffer create mode 120000 Lang/AWK/Keyboard-input-Keypress-check create mode 120000 Lang/AWK/Left-factorials create mode 120000 Lang/AWK/Maximum-triangle-path-sum create mode 120000 Lang/AWK/Permutation-test create mode 120000 Lang/AWK/Permutations create mode 120000 Lang/AWK/Pythagorean-triples create mode 120000 Lang/AWK/Sudoku create mode 120000 Lang/Ada/AKS-test-for-primes create mode 120000 Lang/Ada/Brownian-tree create mode 120000 Lang/Ada/Colour-bars-Display create mode 120000 Lang/Ada/Colour-pinstripe-Display create mode 120000 Lang/Ada/Death-Star create mode 120000 Lang/Ada/Draw-a-clock create mode 120000 Lang/Ada/Fractal-tree create mode 120000 Lang/Ada/Gaussian-elimination create mode 120000 Lang/Ada/Hickerson-series-of-almost-integers create mode 120000 Lang/Ada/Honeycombs create mode 120000 Lang/Ada/Iterated-digits-squaring create mode 120000 Lang/Ada/Ludic-numbers create mode 120000 Lang/Ada/MD4 create mode 120000 Lang/Ada/Pinstripe-Display create mode 120000 Lang/Ada/RIPEMD-160 create mode 120000 Lang/Ada/SHA-256 create mode 120000 Lang/Batch-File/Sorting-algorithms-Pancake-sort create mode 120000 Lang/Binary-Lambda-Calculus/Quine create mode 120000 Lang/Bracmat/Function-composition create mode 120000 Lang/Bracmat/Quine create mode 120000 Lang/C++/K-d-tree create mode 120000 Lang/C++/Parse-an-IP-Address create mode 120000 Lang/C++/Truncatable-primes create mode 120000 Lang/C-sharp/Define-a-primitive-data-type create mode 120000 Lang/C-sharp/Enforced-immutability create mode 120000 Lang/C-sharp/Set-puzzle create mode 120000 Lang/C-sharp/Universal-Turing-machine create mode 120000 Lang/C-sharp/Y-combinator create mode 120000 Lang/C/Balanced-ternary create mode 120000 Lang/C/Call-a-foreign-language-function create mode 120000 Lang/C/Call-an-object-method create mode 120000 Lang/C/Casting-out-nines create mode 120000 Lang/C/Inheritance-Multiple create mode 120000 Lang/C/RIPEMD-160 create mode 120000 Lang/C/Zeckendorf-arithmetic create mode 120000 Lang/COBOL/Count-the-coins create mode 120000 Lang/COBOL/Holidays-related-to-Easter create mode 120000 Lang/COBOL/Levenshtein-distance create mode 120000 Lang/COBOL/Parsing-RPN-calculator-algorithm create mode 120000 Lang/COBOL/Read-a-configuration-file create mode 120000 Lang/COBOL/Strip-comments-from-a-string create mode 120000 Lang/Cache-ObjectScript/Empty-string create mode 120000 Lang/Clojure/Rep-string create mode 120000 Lang/Clojure/Variables create mode 120000 Lang/Commodore-BASIC/Count-the-coins create mode 120000 Lang/Commodore-BASIC/Joystick-position create mode 120000 Lang/Commodore-BASIC/Number-names create mode 120000 Lang/Crystal/Averages-Simple-moving-average create mode 120000 Lang/Crystal/Exceptions-Catch-an-exception-thrown-in-a-nested-call create mode 120000 Lang/Crystal/Factorial create mode 120000 Lang/Crystal/Handle-a-signal create mode 120000 Lang/Crystal/Hash-from-two-arrays create mode 120000 Lang/Crystal/Hostname create mode 120000 Lang/Crystal/Include-a-file create mode 120000 Lang/Crystal/Knuth-shuffle create mode 120000 Lang/Crystal/Leap-year create mode 120000 Lang/Crystal/Loops-For create mode 120000 Lang/Crystal/Pangram-checker create mode 120000 Lang/Crystal/Remove-duplicate-elements create mode 120000 Lang/Crystal/Sorting-algorithms-Bogosort create mode 120000 Lang/Crystal/Sorting-algorithms-Permutation-sort create mode 120000 Lang/Crystal/Sorting-algorithms-Selection-sort create mode 120000 Lang/Crystal/Stack create mode 120000 Lang/Crystal/Substring create mode 120000 Lang/Crystal/Synchronous-concurrency create mode 120000 Lang/Crystal/Test-a-function create mode 120000 Lang/Crystal/User-input-Text create mode 120000 Lang/Crystal/Zero-to-the-zero-power create mode 120000 Lang/D/Determine-if-only-one-instance-is-running create mode 120000 Lang/Dart/9-billion-names-of-God-the-integer create mode 120000 Lang/Dart/Comments create mode 120000 Lang/Delphi/Almost-prime create mode 120000 Lang/Delphi/CRC-32 create mode 120000 Lang/Delphi/Last-Friday-of-each-month create mode 120000 Lang/EDSAC-order-code/100-doors create mode 120000 Lang/EDSAC-order-code/Caesar-cipher create mode 120000 Lang/EDSAC-order-code/Catalan-numbers create mode 120000 Lang/EDSAC-order-code/Continued-fraction-Arithmetic-Construct-from-rational-number create mode 120000 Lang/EDSAC-order-code/Factors-of-an-integer create mode 120000 Lang/EDSAC-order-code/Greatest-common-divisor create mode 120000 Lang/EDSAC-order-code/Hailstone-sequence create mode 120000 Lang/EDSAC-order-code/Pangram-checker create mode 120000 Lang/EDSAC-order-code/Pythagorean-triples create mode 120000 Lang/EDSAC-order-code/Sorting-algorithms-Bubble-sort create mode 120000 Lang/Elixir/Read-a-specific-line-from-a-file create mode 120000 Lang/Emacs-Lisp/Maze-generation create mode 120000 Lang/Emacs-Lisp/Maze-solving create mode 120000 Lang/Emacs-Lisp/Sorting-algorithms-Sleep-sort create mode 120000 Lang/F-Sharp/CRC-32 create mode 120000 Lang/Factor/9-billion-names-of-God-the-integer create mode 120000 Lang/Factor/Average-loop-length create mode 120000 Lang/Factor/Box-the-compass create mode 120000 Lang/Factor/Bulls-and-cows-Player create mode 120000 Lang/Factor/Carmichael-3-strong-pseudoprimes create mode 120000 Lang/Factor/Combinations-and-permutations create mode 120000 Lang/Factor/Constrained-random-points-on-a-circle create mode 120000 Lang/Factor/Deepcopy create mode 120000 Lang/Factor/Doubly-linked-list-Element-definition create mode 120000 Lang/Factor/Extensible-prime-generator create mode 120000 Lang/Factor/First-class-environments create mode 120000 Lang/Factor/Generate-Chess960-starting-position create mode 120000 Lang/Factor/Globally-replace-text-in-several-files create mode 120000 Lang/Factor/Hofstadter-Conway-$10,000-sequence create mode 120000 Lang/Factor/Holidays-related-to-Easter create mode 120000 Lang/Factor/Huffman-coding create mode 120000 Lang/Factor/Multiplicative-order create mode 120000 Lang/Factor/Numeric-error-propagation create mode 120000 Lang/Factor/Plot-coordinate-pairs create mode 120000 Lang/Factor/Queue-Definition create mode 120000 Lang/Factor/Ranking-methods create mode 120000 Lang/Factor/Roots-of-unity create mode 120000 Lang/Factor/Self-referential-sequence create mode 120000 Lang/Factor/Set-consolidation create mode 120000 Lang/Factor/Set-puzzle create mode 120000 Lang/Factor/Sierpinski-carpet create mode 120000 Lang/Factor/Sorting-algorithms-Cocktail-sort create mode 120000 Lang/Factor/Sorting-algorithms-Selection-sort create mode 120000 Lang/Factor/Topswops create mode 120000 Lang/Factor/Variable-size-Get create mode 120000 Lang/Forth/Maze-generation create mode 120000 Lang/Fortran/QR-decomposition create mode 120000 Lang/Frink/Abundant,-deficient-and-perfect-number-classifications create mode 120000 Lang/Frink/Check-that-file-exists create mode 120000 Lang/Frink/Conways-Game-of-Life create mode 120000 Lang/Frink/Copy-a-string create mode 120000 Lang/Frink/Fractal-tree create mode 120000 Lang/Frink/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Frink/Hostname create mode 120000 Lang/Frink/Josephus-problem create mode 120000 Lang/Frink/Look-and-say-sequence create mode 120000 Lang/Frink/Loop-over-multiple-arrays-simultaneously create mode 120000 Lang/Frink/Lucas-Lehmer-test create mode 120000 Lang/Frink/Mandelbrot-set create mode 120000 Lang/Frink/N-queens-problem create mode 120000 Lang/Frink/Pascals-triangle create mode 120000 Lang/Frink/Random-numbers create mode 120000 Lang/Frink/Roots-of-unity create mode 120000 Lang/Frink/SHA-256 create mode 120000 Lang/Frink/Sieve-of-Eratosthenes create mode 120000 Lang/Frink/String-length create mode 120000 Lang/Frink/Sum-multiples-of-3-and-5 create mode 120000 Lang/Frink/Sum-of-a-series create mode 120000 Lang/Frink/Towers-of-Hanoi create mode 120000 Lang/Gambas/Empty-program create mode 120000 Lang/Gambas/Quine create mode 120000 Lang/Go/Boolean-values create mode 120000 Lang/Go/Call-a-function-in-a-shared-library create mode 120000 Lang/Go/Catmull-Clark-subdivision-surface create mode 120000 Lang/Go/Executable-library create mode 120000 Lang/Go/Include-a-file create mode 120000 Lang/Go/Yahoo--search-interface create mode 120000 Lang/Groovy/Arithmetic-geometric-mean-Calculate-Pi create mode 120000 Lang/Groovy/Kaprekar-numbers create mode 120000 Lang/Harbour/Bitwise-operations create mode 120000 Lang/Haxe/CRC-32 create mode 120000 Lang/Haxe/Factorial create mode 120000 Lang/Haxe/Loops-Break create mode 120000 Lang/Haxe/Loops-Continue create mode 120000 Lang/Haxe/Loops-Do-while create mode 120000 Lang/Haxe/Loops-Downward-for create mode 120000 Lang/Haxe/Loops-For-with-a-specified-step create mode 120000 Lang/Haxe/Loops-Infinite create mode 120000 Lang/Haxe/Loops-N-plus-one-half create mode 120000 Lang/Haxe/Loops-While create mode 120000 Lang/Haxe/MD5 create mode 120000 Lang/Haxe/SHA-1 create mode 120000 Lang/Haxe/SHA-256 create mode 120000 Lang/Haxe/Sorting-algorithms-Bubble-sort create mode 120000 Lang/Haxe/Sorting-algorithms-Cocktail-sort create mode 120000 Lang/Haxe/Sorting-algorithms-Comb-sort create mode 120000 Lang/Haxe/Sorting-algorithms-Counting-sort create mode 120000 Lang/Haxe/Sorting-algorithms-Gnome-sort create mode 120000 Lang/Haxe/Sorting-algorithms-Heapsort create mode 120000 Lang/Haxe/Sorting-algorithms-Insertion-sort create mode 120000 Lang/Haxe/Sorting-algorithms-Pancake-sort create mode 120000 Lang/Haxe/Sorting-algorithms-Shell-sort create mode 120000 Lang/Haxe/String-interpolation--included- create mode 120000 Lang/Haxe/Sum-of-a-series create mode 120000 Lang/Idris/Quaternion-type create mode 120000 Lang/Java/Bulls-and-cows-Player create mode 120000 Lang/Java/Check-Machin-like-formulas create mode 120000 Lang/Java/Combinations-and-permutations create mode 120000 Lang/Java/Doubly-linked-list-Definition create mode 120000 Lang/Java/Doubly-linked-list-Element-insertion create mode 120000 Lang/Java/Pascals-triangle-Puzzle create mode 120000 Lang/JavaScript/Benfords-law create mode 120000 Lang/JavaScript/Cholesky-decomposition create mode 120000 Lang/JavaScript/Numerical-integration-Gauss-Legendre-Quadrature create mode 120000 Lang/JavaScript/SHA-256 create mode 120000 Lang/JavaScript/Time-a-function create mode 120000 Lang/JavaScript/Variable-length-quantity create mode 120000 Lang/Julia/Catmull-Clark-subdivision-surface create mode 120000 Lang/Julia/SOAP create mode 120000 Lang/LOLCODE/Arrays create mode 120000 Lang/LOLCODE/Comments create mode 120000 Lang/LOLCODE/Even-or-odd create mode 120000 Lang/LOLCODE/User-input-Text create mode 120000 Lang/Lambdatalk/Matrix-multiplication create mode 120000 Lang/Lambdatalk/Mutual-recursion create mode 120000 Lang/Lambdatalk/Prime-decomposition create mode 120000 Lang/Liberty-BASIC/Calendar create mode 120000 Lang/Liberty-BASIC/Grayscale-image create mode 120000 Lang/Liberty-BASIC/Number-names create mode 120000 Lang/Liberty-BASIC/Zero-to-the-zero-power create mode 120000 Lang/Lobster/Chinese-remainder-theorem create mode 120000 Lang/Lobster/Cholesky-decomposition create mode 120000 Lang/Lobster/Combinations create mode 120000 Lang/Lobster/Combinations-with-repetitions create mode 120000 Lang/Lobster/Gray-code create mode 120000 Lang/Lobster/IBAN create mode 120000 Lang/Lobster/LU-decomposition create mode 120000 Lang/Lobster/Levenshtein-distance create mode 120000 Lang/Lobster/Long-multiplication create mode 120000 Lang/Lobster/Permutations create mode 120000 Lang/Lobster/Random-numbers create mode 120000 Lang/Lobster/Sorting-algorithms-Heapsort create mode 120000 Lang/Lua/Bernoulli-numbers create mode 120000 Lang/Lua/Continued-fraction create mode 120000 Lang/Lua/MD5-Implementation create mode 120000 Lang/Lua/Sierpinski-triangle create mode 120000 Lang/Lua/Tic-tac-toe create mode 120000 Lang/MATLAB/Amicable-pairs create mode 120000 Lang/MATLAB/Universal-Turing-machine create mode 120000 Lang/MATLAB/XML-Input create mode 120000 Lang/MATLAB/XML-Output create mode 120000 Lang/Maple/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Maple/Left-factorials create mode 120000 Lang/Maple/Pascals-triangle-Puzzle create mode 120000 Lang/Maple/Quaternion-type create mode 120000 Lang/Maple/Sequence-of-non-squares create mode 120000 Lang/Maple/Spiral-matrix create mode 120000 Lang/Maple/Visualize-a-tree create mode 120000 Lang/Nial/Fibonacci-sequence create mode 120000 Lang/Nim/Calendar create mode 120000 Lang/Nim/Carmichael-3-strong-pseudoprimes create mode 120000 Lang/Nim/Continued-fraction create mode 120000 Lang/Nim/Convert-decimal-number-to-rational create mode 120000 Lang/Nim/Deconvolution-1D create mode 120000 Lang/Nim/K-means++-clustering create mode 120000 Lang/Nim/Numeric-error-propagation create mode 120000 Lang/Nim/Numerical-integration-Gauss-Legendre-Quadrature create mode 120000 Lang/Nim/Permutation-test create mode 120000 Lang/Nim/Roots-of-a-function create mode 120000 Lang/Nim/Set-consolidation create mode 120000 Lang/Nim/Simulate-input-Keyboard create mode 120000 Lang/Nim/Thieles-interpolation-formula create mode 120000 Lang/Nim/Topswops create mode 120000 Lang/OCaml/String-prepend create mode 120000 Lang/OCaml/Voronoi-diagram create mode 120000 Lang/Objeck/24-game create mode 120000 Lang/Objeck/Sum-digits-of-an-integer create mode 120000 Lang/Objeck/Unix-ls create mode 120000 Lang/Ol/Arbitrary-precision-integers--included- create mode 120000 Lang/Ol/Binary-search create mode 120000 Lang/Ol/Currying create mode 120000 Lang/Ol/Empty-program create mode 120000 Lang/Ol/Enumerations create mode 120000 Lang/Ol/Even-or-odd create mode 120000 Lang/Ol/Extreme-floating-point-values create mode 120000 Lang/Ol/Hello-world-Text create mode 120000 Lang/Ol/Huffman-coding create mode 120000 Lang/Ol/Identity-matrix create mode 120000 Lang/Ol/Include-a-file create mode 120000 Lang/Ol/Interactive-programming create mode 120000 Lang/Ol/JSON create mode 120000 Lang/Ol/Langtons-ant create mode 120000 Lang/Ol/Loops-Foreach create mode 120000 Lang/Ol/MD5 create mode 120000 Lang/Ol/Metaprogramming create mode 120000 Lang/Ol/Primality-by-trial-division create mode 120000 Lang/Ol/Stack create mode 120000 Lang/Ol/Unicode-variable-names create mode 120000 Lang/PHP/Append-a-record-to-the-end-of-a-text-file create mode 120000 Lang/PHP/Currying create mode 120000 Lang/PHP/Entropy create mode 120000 Lang/PHP/Execute-a-Markov-algorithm create mode 120000 Lang/PHP/Fast-Fourier-transform create mode 120000 Lang/PHP/Hello-world-Newline-omission create mode 120000 Lang/PHP/Longest-string-challenge create mode 120000 Lang/PHP/Move-to-front-algorithm create mode 120000 Lang/PHP/Pythagorean-triples create mode 120000 Lang/PHP/Ray-casting-algorithm create mode 120000 Lang/PHP/Read-a-configuration-file create mode 120000 Lang/PHP/Read-a-specific-line-from-a-file create mode 120000 Lang/PHP/Sierpinski-carpet create mode 120000 Lang/PHP/Sierpinski-triangle create mode 120000 Lang/PHP/Speech-synthesis create mode 120000 Lang/PHP/Sum-multiples-of-3-and-5 create mode 120000 Lang/PHP/Terminal-control-Cursor-positioning create mode 120000 Lang/PHP/Update-a-configuration-file create mode 120000 Lang/PL-pgSQL/Fibonacci-sequence create mode 120000 Lang/Perl-6/Bitmap-Flood-fill create mode 120000 Lang/Perl-6/Color-of-a-screen-pixel create mode 120000 Lang/Perl-6/Colour-pinstripe-Printer create mode 120000 Lang/Perl-6/Joystick-position create mode 120000 Lang/Perl-6/OpenGL create mode 120000 Lang/Perl-6/Pinstripe-Printer create mode 120000 Lang/Perl-6/Record-sound create mode 120000 Lang/Perl-6/Sutherland-Hodgman-polygon-clipping create mode 120000 Lang/Perl-6/Use-another-language-to-call-a-function create mode 120000 Lang/Perl-6/Vigen-re-cipher-Cryptanalysis create mode 120000 Lang/Perl-6/Write-to-Windows-event-log create mode 120000 Lang/Perl-6/Yahoo--search-interface create mode 120000 Lang/Perl/Binary-strings create mode 120000 Lang/Perl/Call-a-function-in-a-shared-library create mode 120000 Lang/Perl/Color-of-a-screen-pixel create mode 120000 Lang/Perl/Color-quantization create mode 120000 Lang/Perl/Image-convolution create mode 120000 Lang/Perl/Median-filter create mode 120000 Lang/Perl/QR-decomposition create mode 120000 Lang/Perl/Solve-the-no-connection-puzzle create mode 120000 Lang/Perl/Sutherland-Hodgman-polygon-clipping create mode 120000 Lang/Perl/Thieles-interpolation-formula create mode 120000 Lang/Perl/Vigen-re-cipher-Cryptanalysis create mode 120000 Lang/Phix/Anonymous-recursion create mode 120000 Lang/Phix/Classes create mode 120000 Lang/Phix/Documentation create mode 120000 Lang/Phix/Hello-world-Web-server create mode 120000 Lang/Phix/Record-sound create mode 120000 Lang/Phix/SOAP create mode 120000 Lang/Phix/Send-email create mode 120000 Lang/Phix/Speech-synthesis create mode 120000 Lang/Phix/XML-Input create mode 120000 Lang/PicoLisp/Magic-squares-of-odd-order create mode 120000 Lang/Pike/Associative-array-Creation create mode 120000 Lang/Pike/Bitwise-operations create mode 120000 Lang/Pike/CRC-32 create mode 120000 Lang/Pike/Compound-data-type create mode 120000 Lang/Pike/Count-in-octal create mode 120000 Lang/Pike/Count-occurrences-of-a-substring create mode 120000 Lang/Pike/Environment-variables create mode 120000 Lang/Pike/File-input-output create mode 120000 Lang/Pike/Hash-from-two-arrays create mode 120000 Lang/Pike/Hello-world-Newline-omission create mode 120000 Lang/Pike/Hello-world-Standard-error create mode 120000 Lang/Pike/Hello-world-Web-server create mode 120000 Lang/Pike/Include-a-file create mode 120000 Lang/Pike/Integer-sequence create mode 120000 Lang/Pike/Letter-frequency create mode 120000 Lang/Pike/Loop-over-multiple-arrays-simultaneously create mode 120000 Lang/Pike/Loops-Nested create mode 120000 Lang/Pike/Reverse-a-string create mode 120000 Lang/Pike/Reverse-words-in-a-string create mode 120000 Lang/Pike/SHA-1 create mode 120000 Lang/Pike/SHA-256 create mode 120000 Lang/Pike/Show-the-epoch create mode 120000 Lang/Pike/Sorting-algorithms-Sleep-sort create mode 120000 Lang/Pike/Stack create mode 120000 Lang/Pike/String-append create mode 120000 Lang/Pike/String-case create mode 120000 Lang/Pike/String-concatenation create mode 120000 Lang/Pike/System-time create mode 120000 Lang/Pike/Time-a-function create mode 120000 Lang/Pike/Truncatable-primes create mode 120000 Lang/Pike/URL-decoding create mode 120000 Lang/Pike/URL-encoding create mode 120000 Lang/Pike/Unicode-strings create mode 120000 Lang/Pike/Unicode-variable-names create mode 120000 Lang/Pike/Unix-ls create mode 120000 Lang/Pike/Zero-to-the-zero-power create mode 120000 Lang/Pony/99-Bottles-of-Beer create mode 120000 Lang/PowerShell/Active-Directory-Search-for-a-user create mode 120000 Lang/PowerShell/Averages-Simple-moving-average create mode 120000 Lang/PowerShell/Polynomial-regression create mode 120000 Lang/PowerShell/QR-decomposition create mode 120000 Lang/PowerShell/RSA-code create mode 120000 Lang/Processing/Bitmap create mode 120000 Lang/Processing/Draw-a-clock create mode 120000 Lang/Processing/Draw-a-cuboid create mode 120000 Lang/Processing/Shell-one-liner create mode 120000 Lang/Processing/Start-from-a-main-routine create mode 120000 Lang/Prolog/Carmichael-3-strong-pseudoprimes create mode 120000 Lang/Prolog/Chinese-remainder-theorem create mode 120000 Lang/Prolog/Compile-time-calculation create mode 120000 Lang/Prolog/Count-in-octal create mode 120000 Lang/Prolog/Count-the-coins create mode 120000 Lang/Prolog/Detect-division-by-zero create mode 120000 Lang/Prolog/Empty-directory create mode 120000 Lang/Prolog/Enumerations create mode 120000 Lang/Prolog/Factors-of-a-Mersenne-number create mode 120000 Lang/Prolog/Fractran create mode 120000 Lang/Prolog/Hash-join create mode 120000 Lang/Prolog/Lucas-Lehmer-test create mode 120000 Lang/Prolog/Modular-inverse create mode 120000 Lang/Prolog/Multiplication-tables create mode 120000 Lang/Prolog/Nth-root create mode 120000 Lang/Prolog/Number-names create mode 120000 Lang/Prolog/Number-reversal-game create mode 120000 Lang/Prolog/Polymorphism create mode 120000 Lang/Prolog/Pythagorean-triples create mode 120000 Lang/Prolog/Roots-of-unity create mode 120000 Lang/Prolog/Set-puzzle create mode 120000 Lang/Prolog/Solve-a-Hopido-puzzle create mode 120000 Lang/Prolog/Solve-a-Numbrix-puzzle create mode 120000 Lang/Prolog/Sorting-algorithms-Bogosort create mode 120000 Lang/Prolog/Stair-climbing-puzzle create mode 120000 Lang/Prolog/Test-a-function create mode 120000 Lang/Pyret/Zero-to-the-zero-power create mode 120000 Lang/R/Address-of-a-variable create mode 120000 Lang/R/CSV-to-HTML-translation create mode 120000 Lang/R/Gaussian-elimination create mode 120000 Lang/R/Hello-world-Web-server create mode 120000 Lang/R/Hofstadter-Q-sequence create mode 120000 Lang/R/LU-decomposition create mode 120000 Lang/R/Left-factorials create mode 120000 Lang/R/Narcissistic-decimal-number create mode 120000 Lang/R/Number-names create mode 120000 Lang/R/Sockets create mode 120000 Lang/R/Strip-whitespace-from-a-string-Top-and-tail create mode 120000 Lang/R/Unix-ls create mode 120000 Lang/REXX/First-class-functions-Use-numbers-analogously create mode 120000 Lang/Red/Bitwise-IO create mode 120000 Lang/Red/Bitwise-operations create mode 120000 Lang/Red/Pascals-triangle create mode 120000 Lang/Red/Quaternion-type create mode 120000 Lang/Red/Voronoi-diagram create mode 120000 Lang/Robotic/Copy-a-string create mode 120000 Lang/Robotic/Empty-string create mode 120000 Lang/Robotic/Factorial create mode 120000 Lang/Robotic/Jump-anywhere create mode 120000 Lang/Robotic/Keyboard-input-Keypress-check create mode 120000 Lang/Robotic/Loops-Infinite create mode 120000 Lang/Robotic/String-append create mode 120000 Lang/Robotic/String-comparison create mode 120000 Lang/Ruby/Terminal-control-Inverse-video create mode 120000 Lang/Rust/Casting-out-nines create mode 120000 Lang/Rust/Exceptions create mode 120000 Lang/Rust/File-modification-time create mode 120000 Lang/Rust/Five-weekends create mode 120000 Lang/Rust/LZW-compression create mode 120000 Lang/Rust/Last-letter-first-letter create mode 120000 Lang/Rust/Matrix-exponentiation-operator create mode 120000 Lang/Rust/Optional-parameters create mode 120000 Lang/Rust/Phrase-reversals create mode 120000 Lang/Rust/Rep-string create mode 120000 Lang/Rust/Terminal-control-Ringing-the-terminal-bell create mode 120000 Lang/Rust/Vampire-number create mode 120000 Lang/Rust/XML-Input create mode 120000 Lang/Scala/Deal-cards-for-FreeCell create mode 120000 Lang/Scala/Verify-distribution-uniformity-Naive create mode 120000 Lang/Shen/Flatten-a-list create mode 120000 Lang/Shen/Permutations create mode 120000 Lang/Shen/Roman-numerals-Encode create mode 120000 Lang/Sidef/Average-loop-length create mode 120000 Lang/Smalltalk/Guess-the-number-With-feedback create mode 120000 Lang/Standard-ML/Day-of-the-week create mode 120000 Lang/Standard-ML/Factors-of-an-integer create mode 120000 Lang/Stata/Bitmap-Write-a-PPM-file create mode 120000 Lang/Stata/Conjugate-transpose create mode 120000 Lang/Stata/Write-float-arrays-to-a-text-file create mode 120000 Lang/Swift/Almost-prime create mode 120000 Lang/Swift/Arithmetic-Rational create mode 120000 Lang/Swift/Averages-Mean-angle create mode 120000 Lang/Swift/Averages-Mean-time-of-day create mode 120000 Lang/Swift/Averages-Root-mean-square create mode 120000 Lang/Swift/Averages-Simple-moving-average create mode 120000 Lang/Swift/Bernoulli-numbers create mode 120000 Lang/Swift/Carmichael-3-strong-pseudoprimes create mode 120000 Lang/Swift/Continued-fraction create mode 120000 Lang/Swift/Conways-Game-of-Life create mode 120000 Lang/Swift/Count-in-factors create mode 120000 Lang/Swift/Evaluate-binomial-coefficients create mode 120000 Lang/Swift/Fibonacci-word create mode 120000 Lang/Swift/Four-bit-adder create mode 120000 Lang/Swift/Gray-code create mode 120000 Lang/Swift/Knapsack-problem-Bounded create mode 120000 Lang/Swift/Knights-tour create mode 120000 Lang/Swift/Left-factorials create mode 120000 Lang/Swift/List-comprehensions create mode 120000 Lang/Swift/Matrix-multiplication create mode 120000 Lang/Swift/Matrix-transposition create mode 120000 Lang/Swift/Menu create mode 120000 Lang/Swift/Modular-exponentiation create mode 120000 Lang/Swift/Modular-inverse create mode 120000 Lang/Swift/Narcissistic-decimal-number create mode 120000 Lang/Swift/Nth-root create mode 120000 Lang/Swift/Parallel-calculations create mode 120000 Lang/Swift/Pernicious-numbers create mode 120000 Lang/Swift/Polynomial-long-division create mode 120000 Lang/Swift/Price-fraction create mode 120000 Lang/Swift/Self-describing-numbers create mode 120000 Lang/Swift/Semordnilap create mode 120000 Lang/Swift/Sort-an-array-of-composite-structures create mode 120000 Lang/Swift/Time-a-function create mode 120000 Lang/Swift/Vector-products create mode 120000 Lang/Swift/Vigen-re-cipher create mode 120000 Lang/UNIX-Shell/Execute-Brain---- create mode 120000 Lang/UNIX-Shell/Universal-Turing-machine create mode 120000 Lang/V/100-doors create mode 120000 Lang/VHDL/FizzBuzz create mode 120000 Lang/Vala/Abstract-type create mode 120000 Lang/Vala/Abundant,-deficient-and-perfect-number-classifications create mode 120000 Lang/Vala/Ackermann-function create mode 120000 Lang/Vala/Averages-Mean-angle create mode 120000 Lang/Vala/CRC-32 create mode 120000 Lang/Vala/Carmichael-3-strong-pseudoprimes create mode 120000 Lang/Vala/Catalan-numbers create mode 120000 Lang/Vala/Catalan-numbers-Pascals-triangle create mode 120000 Lang/Vala/Compound-data-type create mode 120000 Lang/Vala/Convert-decimal-number-to-rational create mode 120000 Lang/Vala/Loop-over-multiple-arrays-simultaneously create mode 120000 Lang/Vala/Loops-Continue create mode 120000 Lang/Vala/Loops-Do-while create mode 120000 Lang/Vala/Loops-Downward-for create mode 120000 Lang/Vala/Loops-For-with-a-specified-step create mode 120000 Lang/Vala/Loops-Foreach create mode 120000 Lang/Vala/Loops-N-plus-one-half create mode 120000 Lang/Vala/Loops-Nested create mode 120000 Lang/Vala/Loops-While create mode 120000 Lang/Vala/Map-range create mode 120000 Lang/Vala/Roman-numerals-Encode create mode 120000 Lang/Vala/Rot-13 create mode 120000 Lang/Vala/Sorting-algorithms-Bubble-sort create mode 120000 Lang/Vala/Sorting-algorithms-Cocktail-sort create mode 120000 Lang/Vala/Sorting-algorithms-Heapsort create mode 120000 Lang/Vala/Sorting-algorithms-Insertion-sort create mode 120000 Lang/Vala/String-append create mode 120000 Lang/Vala/String-comparison create mode 120000 Lang/Vala/String-concatenation create mode 120000 Lang/Vala/String-interpolation--included- create mode 120000 Lang/Vala/String-matching create mode 120000 Lang/Visual-Basic-.NET/Append-a-record-to-the-end-of-a-text-file create mode 120000 Lang/Visual-Basic-.NET/Balanced-ternary create mode 120000 Lang/Visual-Basic-.NET/Detect-division-by-zero create mode 120000 Lang/Visual-Basic-.NET/Execute-a-system-command create mode 120000 Lang/Visual-Basic-.NET/Filter create mode 120000 Lang/Visual-Basic-.NET/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Visual-Basic-.NET/Generic-swap create mode 120000 Lang/Visual-Basic-.NET/MD5 create mode 120000 Lang/Visual-Basic-.NET/Parametric-polymorphism create mode 120000 Lang/Visual-Basic-.NET/Zeckendorf-arithmetic create mode 120000 Lang/WebAssembly/Factorial create mode 120000 Lang/X86-Assembly/Ackermann-function create mode 120000 Lang/X86-Assembly/Copy-a-string create mode 120000 Lang/X86-Assembly/Factors-of-an-integer create mode 120000 Lang/X86-Assembly/Iterated-digits-squaring create mode 120000 Lang/X86-Assembly/Loop-over-multiple-arrays-simultaneously create mode 120000 Lang/X86-Assembly/Loops-Continue create mode 120000 Lang/X86-Assembly/Loops-Do-while create mode 120000 Lang/X86-Assembly/Pascals-triangle create mode 120000 Lang/XPL0/ABC-Problem create mode 120000 Lang/XPL0/Fibonacci-sequence create mode 120000 Lang/XPL0/Formatted-numeric-output create mode 120000 Lang/XPL0/Hello-world-Graphical create mode 120000 Lang/XPL0/Input-loop create mode 120000 Lang/XPL0/Read-a-file-line-by-line create mode 120000 Lang/XPL0/Zero-to-the-zero-power create mode 120000 Lang/XQuery/A+B create mode 120000 Lang/XQuery/JSON create mode 120000 Lang/XQuery/Longest-string-challenge create mode 120000 Lang/XQuery/XML-Output create mode 100644 Task/100-doors/EDSAC-order-code/100-doors.edsac create mode 100644 Task/100-doors/Java/100-doors-4.java create mode 100644 Task/100-doors/Perl-6/100-doors-6.pl6 create mode 100644 Task/100-doors/V/100-doors.v create mode 100644 Task/24-game/Objeck/24-game.objeck create mode 100644 Task/9-billion-names-of-God-the-integer/Dart/9-billion-names-of-god-the-integer-1.dart create mode 100644 Task/9-billion-names-of-God-the-integer/Dart/9-billion-names-of-god-the-integer-2.dart create mode 100644 Task/9-billion-names-of-God-the-integer/Factor/9-billion-names-of-god-the-integer.factor rename Task/99-Bottles-of-Beer/Euphoria/{99-bottles-of-beer.euphoria => 99-bottles-of-beer-1.euphoria} (100%) create mode 100644 Task/99-Bottles-of-Beer/Euphoria/99-bottles-of-beer-2.euphoria create mode 100644 Task/99-Bottles-of-Beer/Pony/99-bottles-of-beer-1.pony create mode 100644 Task/99-Bottles-of-Beer/Pony/99-bottles-of-beer-2.pony delete mode 100644 Task/99-Bottles-of-Beer/Processing/99-bottles-of-beer create mode 100644 Task/99-Bottles-of-Beer/Processing/99-bottles-of-beer-1 create mode 100644 Task/99-Bottles-of-Beer/Processing/99-bottles-of-beer-2 create mode 100644 Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-5.py create mode 100644 Task/A+B/ARM-Assembly/a+b-3.arm create mode 100644 Task/A+B/ARM-Assembly/a+b-4.arm rename Task/A+B/EDSAC-order-code/{a+b.edsac => a+b-1.edsac} (100%) create mode 100644 Task/A+B/EDSAC-order-code/a+b-2.edsac create mode 100644 Task/A+B/XQuery/a+b.xquery create mode 100644 Task/ABC-Problem/XPL0/abc-problem.xpl0 create mode 100644 Task/AKS-test-for-primes/Ada/aks-test-for-primes.ada rename Task/Abstract-type/Go/{abstract-type.go => abstract-type-1.go} (100%) create mode 100644 Task/Abstract-type/Go/abstract-type-2.go create mode 100644 Task/Abstract-type/Vala/abstract-type.vala create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/Frink/abundant,-deficient-and-perfect-number-classifications.frink rename Task/Abundant,-deficient-and-perfect-number-classifications/Haskell/{abundant,-deficient-and-perfect-number-classifications.hs => abundant,-deficient-and-perfect-number-classifications-1.hs} (100%) create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/Haskell/abundant,-deficient-and-perfect-number-classifications-2.hs rename Task/Abundant,-deficient-and-perfect-number-classifications/Python/{abundant,-deficient-and-perfect-number-classifications.py => abundant,-deficient-and-perfect-number-classifications-1.py} (100%) create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications-2.py create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications-3.py create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications-4.py create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/Vala/abundant,-deficient-and-perfect-number-classifications.vala create mode 100644 Task/Accumulator-factory/Retro/accumulator-factory.retro rename Task/Ackermann-function/JavaScript/{ackermann-function.js => ackermann-function-1.js} (100%) create mode 100644 Task/Ackermann-function/JavaScript/ackermann-function-2.js create mode 100644 Task/Ackermann-function/JavaScript/ackermann-function-3.js create mode 100644 Task/Ackermann-function/JavaScript/ackermann-function-4.js create mode 100644 Task/Ackermann-function/JavaScript/ackermann-function-5.js rename Task/Ackermann-function/Lua/{ackermann-function.lua => ackermann-function-1.lua} (100%) create mode 100644 Task/Ackermann-function/Lua/ackermann-function-2.lua create mode 100644 Task/Ackermann-function/Vala/ackermann-function.vala create mode 100644 Task/Ackermann-function/X86-Assembly/ackermann-function.x86 create mode 100644 Task/Active-Directory-Search-for-a-user/PowerShell/active-directory-search-for-a-user.psh create mode 100644 Task/Active-object/Phix/active-object-1.phix rename Task/Active-object/Phix/{active-object.phix => active-object-2.phix} (100%) create mode 100644 Task/Address-of-a-variable/Perl/address-of-a-variable-4.pl create mode 100644 Task/Address-of-a-variable/R/address-of-a-variable-1.r create mode 100644 Task/Address-of-a-variable/R/address-of-a-variable-2.r create mode 100644 Task/Align-columns/Python/align-columns-5.py create mode 100644 Task/Almost-prime/Delphi/almost-prime.delphi create mode 100644 Task/Almost-prime/Julia/almost-prime.julia create mode 100644 Task/Almost-prime/Swift/almost-prime.swift create mode 100644 Task/Amicable-pairs/MATLAB/amicable-pairs.m rename Task/Amicable-pairs/Python/{amicable-pairs.py => amicable-pairs-1.py} (100%) create mode 100644 Task/Amicable-pairs/Python/amicable-pairs-2.py create mode 100644 Task/Anonymous-recursion/Phix/anonymous-recursion-1.phix create mode 100644 Task/Anonymous-recursion/Phix/anonymous-recursion-2.phix create mode 100644 Task/Anonymous-recursion/Python/anonymous-recursion-5.py create mode 100644 Task/Anonymous-recursion/Python/anonymous-recursion-6.py create mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/PHP/append-a-record-to-the-end-of-a-text-file.php create mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/Visual-Basic-.NET/append-a-record-to-the-end-of-a-text-file.visual create mode 100644 Task/Arbitrary-precision-integers--included-/Ol/arbitrary-precision-integers--included-.ol create mode 100644 Task/Arithmetic-Rational/Swift/arithmetic-rational.swift create mode 100644 Task/Arithmetic-geometric-mean-Calculate-Pi/Groovy/arithmetic-geometric-mean-calculate-pi.groovy create mode 100644 Task/Arrays/C/arrays-10.c create mode 100644 Task/Arrays/LOLCODE/arrays.lol rename Task/Assertions/REXX/{assertions.rexx => assertions-1.rexx} (100%) create mode 100644 Task/Assertions/REXX/assertions-2.rexx create mode 100644 Task/Associative-array-Creation/Pike/associative-array-creation-1.pike create mode 100644 Task/Associative-array-Creation/Pike/associative-array-creation-2.pike create mode 100644 Task/Average-loop-length/Factor/average-loop-length.factor create mode 100644 Task/Average-loop-length/Sidef/average-loop-length.sidef create mode 100644 Task/Averages-Mean-angle/Swift/averages-mean-angle.swift create mode 100644 Task/Averages-Mean-angle/Vala/averages-mean-angle.vala create mode 100644 Task/Averages-Mean-time-of-day/Swift/averages-mean-time-of-day.swift create mode 100644 Task/Averages-Root-mean-square/Swift/averages-root-mean-square.swift create mode 100644 Task/Averages-Simple-moving-average/Crystal/averages-simple-moving-average.crystal delete mode 100644 Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average.julia create mode 100644 Task/Averages-Simple-moving-average/PowerShell/averages-simple-moving-average.psh create mode 100644 Task/Averages-Simple-moving-average/Swift/averages-simple-moving-average.swift create mode 100644 Task/Balanced-brackets/JavaScript/balanced-brackets-3.js rename Task/Balanced-brackets/X86-Assembly/{balanced-brackets.x86 => balanced-brackets-1.x86} (100%) create mode 100644 Task/Balanced-brackets/X86-Assembly/balanced-brackets-2.x86 create mode 100644 Task/Balanced-ternary/C/balanced-ternary.c create mode 100644 Task/Balanced-ternary/Visual-Basic-.NET/balanced-ternary.visual create mode 100644 Task/Benfords-law/JavaScript/benfords-law.js create mode 100644 Task/Bernoulli-numbers/Lua/bernoulli-numbers.lua create mode 100644 Task/Bernoulli-numbers/Sidef/bernoulli-numbers-3.sidef create mode 100644 Task/Bernoulli-numbers/Sidef/bernoulli-numbers-4.sidef create mode 100644 Task/Bernoulli-numbers/Sidef/bernoulli-numbers-5.sidef create mode 100644 Task/Bernoulli-numbers/Swift/bernoulli-numbers.swift create mode 100644 Task/Binary-search/Ol/binary-search.ol create mode 100644 Task/Binary-strings/Perl/binary-strings.pl create mode 100644 Task/Bitmap-Flood-fill/Perl-6/bitmap-flood-fill.pl6 create mode 100644 Task/Bitmap-Write-a-PPM-file/Stata/bitmap-write-a-ppm-file.stata create mode 100644 Task/Bitmap/Processing/bitmap create mode 100644 Task/Bitwise-IO/Red/bitwise-io.red create mode 100644 Task/Bitwise-operations/Harbour/bitwise-operations.harbour create mode 100644 Task/Bitwise-operations/Pike/bitwise-operations.pike create mode 100644 Task/Bitwise-operations/Red/bitwise-operations.red create mode 100644 Task/Boolean-values/Go/boolean-values.go create mode 100644 Task/Box-the-compass/Factor/box-the-compass.factor create mode 100644 Task/Brownian-tree/Ada/brownian-tree.ada create mode 100644 Task/Bulls-and-cows-Player/Factor/bulls-and-cows-player.factor create mode 100644 Task/Bulls-and-cows-Player/Java/bulls-and-cows-player-1.java create mode 100644 Task/Bulls-and-cows-Player/Java/bulls-and-cows-player-2.java create mode 100644 Task/Bulls-and-cows-Player/Java/bulls-and-cows-player-3.java create mode 100644 Task/Bulls-and-cows-Player/Java/bulls-and-cows-player-4.java create mode 100644 Task/Bulls-and-cows-Player/Java/bulls-and-cows-player-5.java create mode 100644 Task/Bulls-and-cows/BASIC/bulls-and-cows-3.basic create mode 100644 Task/CRC-32/Delphi/crc-32.delphi create mode 100644 Task/CRC-32/F-Sharp/crc-32-1.fs create mode 100644 Task/CRC-32/F-Sharp/crc-32-2.fs create mode 100644 Task/CRC-32/Haxe/crc-32.haxe create mode 100644 Task/CRC-32/Pike/crc-32.pike create mode 100644 Task/CRC-32/Vala/crc-32-1.vala create mode 100644 Task/CRC-32/Vala/crc-32-2.vala rename Task/CSV-data-manipulation/MATLAB/{csv-data-manipulation.m => csv-data-manipulation-1.m} (100%) create mode 100644 Task/CSV-data-manipulation/MATLAB/csv-data-manipulation-2.m create mode 100644 Task/CSV-data-manipulation/R/csv-data-manipulation-3.r create mode 100644 Task/CSV-to-HTML-translation/R/csv-to-html-translation-1.r create mode 100644 Task/CSV-to-HTML-translation/R/csv-to-html-translation-2.r create mode 100644 Task/Caesar-cipher/EDSAC-order-code/caesar-cipher.edsac rename Task/Caesar-cipher/PHP/{caesar-cipher.php => caesar-cipher-1.php} (100%) create mode 100644 Task/Caesar-cipher/PHP/caesar-cipher-2.php create mode 100644 Task/Calendar/Liberty-BASIC/calendar.liberty create mode 100644 Task/Calendar/Nim/calendar.nim create mode 100644 Task/Call-a-foreign-language-function/C/call-a-foreign-language-function-1.c create mode 100644 Task/Call-a-foreign-language-function/C/call-a-foreign-language-function-2.c create mode 100644 Task/Call-a-foreign-language-function/OCaml/call-a-foreign-language-function-5.ocaml create mode 100644 Task/Call-a-function-in-a-shared-library/Go/call-a-function-in-a-shared-library-1.go create mode 100644 Task/Call-a-function-in-a-shared-library/Go/call-a-function-in-a-shared-library-2.go create mode 100644 Task/Call-a-function-in-a-shared-library/Perl/call-a-function-in-a-shared-library-1.pl create mode 100644 Task/Call-a-function-in-a-shared-library/Perl/call-a-function-in-a-shared-library-2.pl create mode 100644 Task/Call-a-function/Go/call-a-function-10.go create mode 100644 Task/Call-a-function/Go/call-a-function-11.go create mode 100644 Task/Call-a-function/Go/call-a-function-12.go create mode 100644 Task/Call-a-function/Go/call-a-function-9.go create mode 100644 Task/Call-a-function/Perl-6/call-a-function-11.pl6 create mode 100644 Task/Call-an-object-method/C/call-an-object-method.c create mode 100644 Task/Carmichael-3-strong-pseudoprimes/AWK/carmichael-3-strong-pseudoprimes.awk create mode 100644 Task/Carmichael-3-strong-pseudoprimes/Factor/carmichael-3-strong-pseudoprimes.factor create mode 100644 Task/Carmichael-3-strong-pseudoprimes/Nim/carmichael-3-strong-pseudoprimes.nim create mode 100644 Task/Carmichael-3-strong-pseudoprimes/Prolog/carmichael-3-strong-pseudoprimes.pro create mode 100644 Task/Carmichael-3-strong-pseudoprimes/Swift/carmichael-3-strong-pseudoprimes.swift create mode 100644 Task/Carmichael-3-strong-pseudoprimes/Vala/carmichael-3-strong-pseudoprimes.vala create mode 100644 Task/Casting-out-nines/C/casting-out-nines.c create mode 100644 Task/Casting-out-nines/Rust/casting-out-nines.rust create mode 100644 Task/Catalan-numbers-Pascals-triangle/Vala/catalan-numbers-pascals-triangle.vala create mode 100644 Task/Catalan-numbers/EDSAC-order-code/catalan-numbers.edsac create mode 100644 Task/Catalan-numbers/Vala/catalan-numbers.vala create mode 100644 Task/Catmull-Clark-subdivision-surface/Go/catmull-clark-subdivision-surface.go create mode 100644 Task/Catmull-Clark-subdivision-surface/Julia/catmull-clark-subdivision-surface.julia create mode 100644 Task/Character-codes/Go/character-codes-5.go create mode 100644 Task/Character-codes/Perl/character-codes-1.pl create mode 100644 Task/Character-codes/Perl/character-codes-2.pl delete mode 100644 Task/Character-codes/Perl/character-codes.pl create mode 100644 Task/Character-codes/Ruby/character-codes.rb rename Task/Chat-server/Perl/{chat-server.pl => chat-server-1.pl} (100%) create mode 100644 Task/Chat-server/Perl/chat-server-2.pl create mode 100644 Task/Check-Machin-like-formulas/Java/check-machin-like-formulas.java create mode 100644 Task/Check-that-file-exists/Frink/check-that-file-exists.frink rename Task/Check-that-file-exists/R/{check-that-file-exists.r => check-that-file-exists-1.r} (100%) create mode 100644 Task/Check-that-file-exists/R/check-that-file-exists-2.r create mode 100644 Task/Check-that-file-exists/Stata/check-that-file-exists-4.stata create mode 100644 Task/Chinese-remainder-theorem/Lobster/chinese-remainder-theorem.lobster create mode 100644 Task/Chinese-remainder-theorem/Prolog/chinese-remainder-theorem.pro create mode 100644 Task/Cholesky-decomposition/JavaScript/cholesky-decomposition.js create mode 100644 Task/Cholesky-decomposition/Lobster/cholesky-decomposition.lobster create mode 100644 Task/Circles-of-given-radius-through-two-points/AWK/circles-of-given-radius-through-two-points.awk create mode 100644 Task/Classes/Phix/classes.phix create mode 100644 Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-1.basic create mode 100644 Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-10.basic create mode 100644 Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-11.basic create mode 100644 Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-12.basic create mode 100644 Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-13.basic create mode 100644 Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-14.basic create mode 100644 Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-15.basic create mode 100644 Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-16.basic create mode 100644 Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-17.basic create mode 100644 Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-2.basic create mode 100644 Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-3.basic create mode 100644 Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-4.basic create mode 100644 Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-5.basic create mode 100644 Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-6.basic rename Task/Color-of-a-screen-pixel/BASIC/{color-of-a-screen-pixel.basic => color-of-a-screen-pixel-7.basic} (100%) create mode 100644 Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-8.basic create mode 100644 Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-9.basic create mode 100644 Task/Color-of-a-screen-pixel/Perl-6/color-of-a-screen-pixel-1.pl6 create mode 100644 Task/Color-of-a-screen-pixel/Perl-6/color-of-a-screen-pixel-2.pl6 create mode 100644 Task/Color-of-a-screen-pixel/Perl/color-of-a-screen-pixel.pl create mode 100644 Task/Color-quantization/Perl/color-quantization.pl create mode 100644 Task/Colour-bars-Display/AWK/colour-bars-display.awk create mode 100644 Task/Colour-bars-Display/Ada/colour-bars-display.ada create mode 100644 Task/Colour-pinstripe-Display/Ada/colour-pinstripe-display.ada create mode 100644 Task/Colour-pinstripe-Printer/Perl-6/colour-pinstripe-printer.pl6 create mode 100644 Task/Combinations-and-permutations/Factor/combinations-and-permutations.factor create mode 100644 Task/Combinations-and-permutations/Java/combinations-and-permutations.java create mode 100644 Task/Combinations-with-repetitions/Lobster/combinations-with-repetitions.lobster create mode 100644 Task/Combinations/J/combinations-6.j create mode 100644 Task/Combinations/J/combinations-7.j create mode 100644 Task/Combinations/Lobster/combinations-1.lobster create mode 100644 Task/Combinations/Lobster/combinations-2.lobster rename Task/Combinations/Mathematica/{combinations.math => combinations-1.math} (100%) create mode 100644 Task/Combinations/Mathematica/combinations-2.math create mode 100644 Task/Combinations/Python/combinations-5.py create mode 100644 Task/Comments/Batch-File/comments-3.bat create mode 100644 Task/Comments/Dart/comments.dart create mode 100644 Task/Comments/LOLCODE/comments-1.lol create mode 100644 Task/Comments/LOLCODE/comments-2.lol create mode 100644 Task/Comments/Perl-6/comments-1.pl6 create mode 100644 Task/Comments/Perl-6/comments-2.pl6 create mode 100644 Task/Comments/Perl-6/comments-3.pl6 create mode 100644 Task/Comments/Perl-6/comments-4.pl6 create mode 100644 Task/Comments/Perl-6/comments-5.pl6 create mode 100644 Task/Comments/Perl-6/comments-6.pl6 delete mode 100644 Task/Comments/Perl-6/comments.pl6 create mode 100644 Task/Compile-time-calculation/Prolog/compile-time-calculation.pro create mode 100644 Task/Compound-data-type/Pike/compound-data-type.pike create mode 100644 Task/Compound-data-type/Vala/compound-data-type.vala create mode 100644 Task/Conjugate-transpose/Stata/conjugate-transpose.stata create mode 100644 Task/Constrained-random-points-on-a-circle/Factor/constrained-random-points-on-a-circle.factor create mode 100644 Task/Continued-fraction-Arithmetic-Construct-from-rational-number/EDSAC-order-code/continued-fraction-arithmetic-construct-from-rational-number.edsac create mode 100644 Task/Continued-fraction/Lua/continued-fraction.lua create mode 100644 Task/Continued-fraction/Nim/continued-fraction.nim create mode 100644 Task/Continued-fraction/Swift/continued-fraction.swift create mode 100644 Task/Convert-decimal-number-to-rational/Nim/convert-decimal-number-to-rational-1.nim create mode 100644 Task/Convert-decimal-number-to-rational/Nim/convert-decimal-number-to-rational-2.nim create mode 100644 Task/Convert-decimal-number-to-rational/Sidef/convert-decimal-number-to-rational-3.sidef create mode 100644 Task/Convert-decimal-number-to-rational/Vala/convert-decimal-number-to-rational.vala create mode 100644 Task/Conways-Game-of-Life/Frink/conways-game-of-life.frink create mode 100644 Task/Conways-Game-of-Life/JavaScript/conways-game-of-life-4.js rename Task/Conways-Game-of-Life/Julia/{conways-game-of-life.julia => conways-game-of-life-1.julia} (100%) create mode 100644 Task/Conways-Game-of-Life/Julia/conways-game-of-life-2.julia create mode 100644 Task/Conways-Game-of-Life/Perl/conways-game-of-life-3.pl create mode 100644 Task/Conways-Game-of-Life/Swift/conways-game-of-life.swift create mode 100644 Task/Copy-a-string/Frink/copy-a-string.frink rename Task/Copy-a-string/Go/{copy-a-string.go => copy-a-string-1.go} (100%) create mode 100644 Task/Copy-a-string/Go/copy-a-string-2.go create mode 100644 Task/Copy-a-string/Robotic/copy-a-string.robotic create mode 100644 Task/Copy-a-string/X86-Assembly/copy-a-string-1.x86 create mode 100644 Task/Copy-a-string/X86-Assembly/copy-a-string-2.x86 create mode 100644 Task/Count-in-factors/Swift/count-in-factors.swift create mode 100644 Task/Count-in-octal/Perl/count-in-octal-3.pl create mode 100644 Task/Count-in-octal/Pike/count-in-octal.pike create mode 100644 Task/Count-in-octal/Prolog/count-in-octal.pro create mode 100644 Task/Count-occurrences-of-a-substring/Pike/count-occurrences-of-a-substring.pike create mode 100644 Task/Count-the-coins/COBOL/count-the-coins.cobol create mode 100644 Task/Count-the-coins/Commodore-BASIC/count-the-coins-1.commodore create mode 100644 Task/Count-the-coins/Commodore-BASIC/count-the-coins-2.commodore create mode 100644 Task/Count-the-coins/Commodore-BASIC/count-the-coins-3.commodore create mode 100644 Task/Count-the-coins/Prolog/count-the-coins.pro create mode 100644 Task/Create-a-file/BASIC/create-a-file-3.basic create mode 100644 Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-1.basic create mode 100644 Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-10.basic create mode 100644 Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-11.basic create mode 100644 Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-12.basic create mode 100644 Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-13.basic create mode 100644 Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-2.basic create mode 100644 Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-3.basic create mode 100644 Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-4.basic create mode 100644 Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-5.basic create mode 100644 Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-6.basic create mode 100644 Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-7.basic rename Task/Create-a-two-dimensional-array-at-runtime/BASIC/{create-a-two-dimensional-array-at-runtime.basic => create-a-two-dimensional-array-at-runtime-8.basic} (100%) create mode 100644 Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-9.basic create mode 100644 Task/Currying/Ol/currying.ol create mode 100644 Task/Currying/PHP/currying.php rename Task/DNS-query/Ada/{dns-query.ada => dns-query-1.ada} (100%) create mode 100644 Task/DNS-query/Ada/dns-query-2.ada rename Task/Date-format/Common-Lisp/{date-format.lisp => date-format-1.lisp} (100%) create mode 100644 Task/Date-format/Common-Lisp/date-format-2.lisp rename Task/Date-manipulation/Julia/{date-manipulation.julia => date-manipulation-1.julia} (95%) create mode 100644 Task/Date-manipulation/Julia/date-manipulation-2.julia create mode 100644 Task/Day-of-the-week/Standard-ML/day-of-the-week.ml create mode 100644 Task/Deal-cards-for-FreeCell/Scala/deal-cards-for-freecell.scala create mode 100644 Task/Death-Star/Ada/death-star.ada create mode 100644 Task/Deconvolution-1D/Nim/deconvolution-1d.nim create mode 100644 Task/Deepcopy/Factor/deepcopy-1.factor create mode 100644 Task/Deepcopy/Factor/deepcopy-2.factor create mode 100644 Task/Define-a-primitive-data-type/C-sharp/define-a-primitive-data-type.cs rename Task/Delete-a-file/Fortran/{delete-a-file.f => delete-a-file-1.f} (100%) create mode 100644 Task/Delete-a-file/Fortran/delete-a-file-2.f create mode 100644 Task/Detect-division-by-zero/Prolog/detect-division-by-zero.pro create mode 100644 Task/Detect-division-by-zero/Visual-Basic-.NET/detect-division-by-zero.visual create mode 100644 Task/Determine-if-a-string-is-numeric/Go/determine-if-a-string-is-numeric-1.go create mode 100644 Task/Determine-if-a-string-is-numeric/Go/determine-if-a-string-is-numeric-2.go delete mode 100644 Task/Determine-if-a-string-is-numeric/Go/determine-if-a-string-is-numeric.go create mode 100644 Task/Determine-if-a-string-is-numeric/Phix/determine-if-a-string-is-numeric.phix create mode 100644 Task/Determine-if-only-one-instance-is-running/D/determine-if-only-one-instance-is-running.d rename Task/Determine-if-only-one-instance-is-running/Nim/{determine-if-only-one-instance-is-running.nim => determine-if-only-one-instance-is-running-1.nim} (100%) create mode 100644 Task/Determine-if-only-one-instance-is-running/Nim/determine-if-only-one-instance-is-running-2.nim create mode 100644 Task/Documentation/Phix/documentation.phix create mode 100644 Task/Doubly-linked-list-Definition/Java/doubly-linked-list-definition.java create mode 100644 Task/Doubly-linked-list-Element-definition/Factor/doubly-linked-list-element-definition.factor create mode 100644 Task/Doubly-linked-list-Element-insertion/Java/doubly-linked-list-element-insertion.java create mode 100644 Task/Draw-a-clock/Ada/draw-a-clock.ada create mode 100644 Task/Draw-a-clock/Processing/draw-a-clock-1 create mode 100644 Task/Draw-a-clock/Processing/draw-a-clock-2 create mode 100644 Task/Draw-a-cuboid/Processing/draw-a-cuboid rename Task/Draw-a-sphere/Julia/{draw-a-sphere.julia => draw-a-sphere-1.julia} (99%) create mode 100644 Task/Draw-a-sphere/Julia/draw-a-sphere-2.julia create mode 100644 Task/Dynamic-variable-names/AWK/dynamic-variable-names.awk create mode 100644 Task/Dynamic-variable-names/Retro/dynamic-variable-names.retro rename Task/Empty-directory/Nim/{empty-directory.nim => empty-directory-1.nim} (100%) create mode 100644 Task/Empty-directory/Nim/empty-directory-2.nim create mode 100644 Task/Empty-directory/Prolog/empty-directory.pro create mode 100644 Task/Empty-program/Gambas/empty-program.gambas create mode 100644 Task/Empty-program/Ol/empty-program.ol create mode 100644 Task/Empty-string/Cache-ObjectScript/empty-string.cos rename Task/Empty-string/Go/{empty-string.go => empty-string-1.go} (100%) create mode 100644 Task/Empty-string/Go/empty-string-2.go create mode 100644 Task/Empty-string/Robotic/empty-string.robotic create mode 100644 Task/Enforced-immutability/C-sharp/enforced-immutability-1.cs create mode 100644 Task/Enforced-immutability/C-sharp/enforced-immutability-2.cs create mode 100644 Task/Enforced-immutability/C-sharp/enforced-immutability-3.cs create mode 100644 Task/Enforced-immutability/C-sharp/enforced-immutability-4.cs create mode 100644 Task/Enforced-immutability/C-sharp/enforced-immutability-5.cs create mode 100644 Task/Enforced-immutability/C-sharp/enforced-immutability-6.cs create mode 100644 Task/Entropy/PHP/entropy.php create mode 100644 Task/Enumerations/Ol/enumerations-1.ol create mode 100644 Task/Enumerations/Ol/enumerations-2.ol create mode 100644 Task/Enumerations/Prolog/enumerations.pro create mode 100644 Task/Enumerations/Retro/enumerations.retro create mode 100644 Task/Environment-variables/Pike/environment-variables.pike rename Task/Evaluate-binomial-coefficients/Fortran/{evaluate-binomial-coefficients.f => evaluate-binomial-coefficients-1.f} (100%) create mode 100644 Task/Evaluate-binomial-coefficients/Fortran/evaluate-binomial-coefficients-2.f create mode 100644 Task/Evaluate-binomial-coefficients/Phix/evaluate-binomial-coefficients-3.phix rename Task/Evaluate-binomial-coefficients/Scheme/{evaluate-binomial-coefficients.ss => evaluate-binomial-coefficients-1.ss} (100%) create mode 100644 Task/Evaluate-binomial-coefficients/Scheme/evaluate-binomial-coefficients-2.ss create mode 100644 Task/Evaluate-binomial-coefficients/Swift/evaluate-binomial-coefficients.swift create mode 100644 Task/Even-or-odd/BASIC/even-or-odd-3.basic create mode 100644 Task/Even-or-odd/LOLCODE/even-or-odd.lol create mode 100644 Task/Even-or-odd/Ol/even-or-odd.ol rename Task/Events/Nim/{events.nim => events-1.nim} (100%) create mode 100644 Task/Events/Nim/events-2.nim create mode 100644 Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Crystal/exceptions-catch-an-exception-thrown-in-a-nested-call.crystal create mode 100644 Task/Exceptions/Rust/exceptions.rust create mode 100644 Task/Executable-library/Go/executable-library-1.go create mode 100644 Task/Executable-library/Go/executable-library-2.go create mode 100644 Task/Executable-library/Go/executable-library-3.go create mode 100644 Task/Execute-Brain----/UNIX-Shell/execute-brain----.sh create mode 100644 Task/Execute-a-Markov-algorithm/PHP/execute-a-markov-algorithm.php create mode 100644 Task/Execute-a-system-command/Visual-Basic-.NET/execute-a-system-command.visual create mode 100644 Task/Extensible-prime-generator/Factor/extensible-prime-generator.factor create mode 100644 Task/Extreme-floating-point-values/Ol/extreme-floating-point-values.ol create mode 100644 Task/Factorial/BASIC/factorial-7.basic create mode 100644 Task/Factorial/Crystal/factorial-1.crystal create mode 100644 Task/Factorial/Crystal/factorial-2.crystal create mode 100644 Task/Factorial/Fortran/factorial-3.f create mode 100644 Task/Factorial/Frink/factorial-3.frink create mode 100644 Task/Factorial/Haxe/factorial-1.haxe create mode 100644 Task/Factorial/Haxe/factorial-2.haxe create mode 100644 Task/Factorial/Haxe/factorial-3.haxe create mode 100644 Task/Factorial/Haxe/factorial-4.haxe create mode 100644 Task/Factorial/Haxe/factorial-5.haxe create mode 100644 Task/Factorial/Python/factorial-8.py create mode 100644 Task/Factorial/Python/factorial-9.py create mode 100644 Task/Factorial/Robotic/factorial.robotic create mode 100644 Task/Factorial/WebAssembly/factorial.webassembly create mode 100644 Task/Factors-of-a-Mersenne-number/Prolog/factors-of-a-mersenne-number.pro create mode 100644 Task/Factors-of-an-integer/EDSAC-order-code/factors-of-an-integer.edsac create mode 100644 Task/Factors-of-an-integer/Sidef/factors-of-an-integer-1.sidef rename Task/Factors-of-an-integer/Sidef/{factors-of-an-integer.sidef => factors-of-an-integer-2.sidef} (53%) create mode 100644 Task/Factors-of-an-integer/Standard-ML/factors-of-an-integer-1.ml create mode 100644 Task/Factors-of-an-integer/Standard-ML/factors-of-an-integer-2.ml create mode 100644 Task/Factors-of-an-integer/X86-Assembly/factors-of-an-integer.x86 create mode 100644 Task/Fast-Fourier-transform/PHP/fast-fourier-transform-1.php create mode 100644 Task/Fast-Fourier-transform/PHP/fast-fourier-transform-2.php rename Task/Fibonacci-n-step-number-sequences/Sidef/{fibonacci-n-step-number-sequences.sidef => fibonacci-n-step-number-sequences-1.sidef} (58%) create mode 100644 Task/Fibonacci-n-step-number-sequences/Sidef/fibonacci-n-step-number-sequences-2.sidef create mode 100644 Task/Fibonacci-n-step-number-sequences/Sidef/fibonacci-n-step-number-sequences-3.sidef create mode 100644 Task/Fibonacci-sequence/APL/fibonacci-sequence-4.apl create mode 100644 Task/Fibonacci-sequence/Nial/fibonacci-sequence-1.nial create mode 100644 Task/Fibonacci-sequence/Nial/fibonacci-sequence-2.nial create mode 100644 Task/Fibonacci-sequence/Nial/fibonacci-sequence-3.nial create mode 100644 Task/Fibonacci-sequence/Nial/fibonacci-sequence-4.nial create mode 100644 Task/Fibonacci-sequence/Nial/fibonacci-sequence-5.nial create mode 100644 Task/Fibonacci-sequence/Nial/fibonacci-sequence-6.nial create mode 100644 Task/Fibonacci-sequence/Nial/fibonacci-sequence-7.nial create mode 100644 Task/Fibonacci-sequence/Nial/fibonacci-sequence-8.nial create mode 100644 Task/Fibonacci-sequence/OCaml/fibonacci-sequence-4.ocaml create mode 100644 Task/Fibonacci-sequence/PL-pgSQL/fibonacci-sequence-1.sql create mode 100644 Task/Fibonacci-sequence/PL-pgSQL/fibonacci-sequence-2.sql create mode 100644 Task/Fibonacci-sequence/PL-pgSQL/fibonacci-sequence-3.sql create mode 100644 Task/Fibonacci-sequence/PL-pgSQL/fibonacci-sequence-4.sql create mode 100644 Task/Fibonacci-sequence/Rust/fibonacci-sequence-6.rust create mode 100644 Task/Fibonacci-sequence/XPL0/fibonacci-sequence.xpl0 create mode 100644 Task/Fibonacci-word/Swift/fibonacci-word.swift create mode 100644 Task/File-input-output/Pike/file-input-output.pike create mode 100644 Task/File-modification-time/Rust/file-modification-time.rust create mode 100644 Task/Filter/Visual-Basic-.NET/filter.visual create mode 100644 Task/Find-limit-of-recursion/Python/find-limit-of-recursion-5.py create mode 100644 Task/Find-limit-of-recursion/Python/find-limit-of-recursion-6.py create mode 100644 Task/Find-the-missing-permutation/Julia/find-the-missing-permutation-3.julia create mode 100644 Task/First-class-environments/Factor/first-class-environments.factor create mode 100644 Task/First-class-functions-Use-numbers-analogously/REXX/first-class-functions-use-numbers-analogously.rexx create mode 100644 Task/Five-weekends/Rust/five-weekends.rust rename Task/FizzBuzz/Crystal/{fizzbuzz.crystal => fizzbuzz-1.crystal} (100%) create mode 100644 Task/FizzBuzz/Crystal/fizzbuzz-2.crystal create mode 100644 Task/FizzBuzz/Lua/fizzbuzz-5.lua create mode 100644 Task/FizzBuzz/Python/fizzbuzz-11.py create mode 100644 Task/FizzBuzz/Python/fizzbuzz-12.py create mode 100644 Task/FizzBuzz/VHDL/fizzbuzz.vhdl create mode 100644 Task/Flatten-a-list/Julia/flatten-a-list-3.julia create mode 100644 Task/Flatten-a-list/Shen/flatten-a-list.shen rename Task/Forest-fire/Perl/{forest-fire.pl => forest-fire-1.pl} (100%) create mode 100644 Task/Forest-fire/Perl/forest-fire-2.pl create mode 100644 Task/Formatted-numeric-output/XPL0/formatted-numeric-output.xpl0 create mode 100644 Task/Four-bit-adder/Swift/four-bit-adder.swift create mode 100644 Task/Fractal-tree/Ada/fractal-tree.ada create mode 100644 Task/Fractal-tree/Frink/fractal-tree.frink create mode 100644 Task/Fractran/Prolog/fractran.pro create mode 100644 Task/Function-composition/Bracmat/function-composition.bracmat create mode 100644 Task/Function-composition/Python/function-composition-5.py create mode 100644 Task/Gamma-function/Stata/gamma-function-1.stata create mode 100644 Task/Gamma-function/Stata/gamma-function-2.stata delete mode 100644 Task/Gamma-function/Stata/gamma-function.stata create mode 100644 Task/Gaussian-elimination/Ada/gaussian-elimination.ada create mode 100644 Task/Gaussian-elimination/Haskell/gaussian-elimination-3.hs create mode 100644 Task/Gaussian-elimination/R/gaussian-elimination.r create mode 100644 Task/Generate-Chess960-starting-position/Factor/generate-chess960-starting-position-1.factor create mode 100644 Task/Generate-Chess960-starting-position/Factor/generate-chess960-starting-position-2.factor create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Frink/generate-lower-case-ascii-alphabet-1.frink create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Frink/generate-lower-case-ascii-alphabet-2.frink rename Task/Generate-lower-case-ASCII-alphabet/Lua/{generate-lower-case-ascii-alphabet.lua => generate-lower-case-ascii-alphabet-1.lua} (100%) create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Lua/generate-lower-case-ascii-alphabet-2.lua create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Maple/generate-lower-case-ascii-alphabet.maple create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Visual-Basic-.NET/generate-lower-case-ascii-alphabet.visual create mode 100644 Task/Generic-swap/JavaScript/generic-swap-3.js create mode 100644 Task/Generic-swap/Visual-Basic-.NET/generic-swap-1.visual create mode 100644 Task/Generic-swap/Visual-Basic-.NET/generic-swap-2.visual create mode 100644 Task/Globally-replace-text-in-several-files/Factor/globally-replace-text-in-several-files.factor rename Task/Globally-replace-text-in-several-files/Java/{globally-replace-text-in-several-files.java => globally-replace-text-in-several-files-1.java} (100%) create mode 100644 Task/Globally-replace-text-in-several-files/Java/globally-replace-text-in-several-files-2.java create mode 100644 Task/Gray-code/AWK/gray-code.awk create mode 100644 Task/Gray-code/Lobster/gray-code.lobster create mode 100644 Task/Gray-code/Swift/gray-code.swift create mode 100644 Task/Grayscale-image/Liberty-BASIC/grayscale-image.liberty create mode 100644 Task/Greatest-common-divisor/EDSAC-order-code/greatest-common-divisor.edsac create mode 100644 Task/Greatest-element-of-a-list/Go/greatest-element-of-a-list-4.go create mode 100644 Task/Greyscale-bars-Display/AWK/greyscale-bars-display.awk create mode 100644 Task/Guess-the-number-With-feedback/Smalltalk/guess-the-number-with-feedback.st create mode 100644 Task/Guess-the-number/BASIC/guess-the-number-5.basic create mode 100644 Task/Guess-the-number/BASIC/guess-the-number-6.basic create mode 100644 Task/Hailstone-sequence/EDSAC-order-code/hailstone-sequence.edsac create mode 100644 Task/Handle-a-signal/Crystal/handle-a-signal.crystal rename Task/Happy-numbers/APL/{happy-numbers.apl => happy-numbers-1.apl} (100%) create mode 100644 Task/Happy-numbers/APL/happy-numbers-2.apl create mode 100644 Task/Hash-from-two-arrays/C-sharp/hash-from-two-arrays-3.cs create mode 100644 Task/Hash-from-two-arrays/Crystal/hash-from-two-arrays.crystal create mode 100644 Task/Hash-from-two-arrays/Pike/hash-from-two-arrays.pike create mode 100644 Task/Hash-join/Prolog/hash-join.pro create mode 100644 Task/Hello-world-Graphical/Smalltalk/hello-world-graphical-3.st create mode 100644 Task/Hello-world-Graphical/XPL0/hello-world-graphical.xpl0 create mode 100644 Task/Hello-world-Newline-omission/PHP/hello-world-newline-omission.php create mode 100644 Task/Hello-world-Newline-omission/Pike/hello-world-newline-omission.pike create mode 100644 Task/Hello-world-Standard-error/Pike/hello-world-standard-error.pike rename Task/Hello-world-Text/COBOL/{hello-world-text.cobol => hello-world-text-1.cobol} (100%) create mode 100644 Task/Hello-world-Text/COBOL/hello-world-text-2.cobol create mode 100644 Task/Hello-world-Text/Ol/hello-world-text.ol rename Task/Hello-world-Text/Perl-6/{hello-world-text.pl6 => hello-world-text-1.pl6} (100%) create mode 100644 Task/Hello-world-Text/Perl-6/hello-world-text-2.pl6 create mode 100644 Task/Hello-world-Web-server/Phix/hello-world-web-server.phix create mode 100644 Task/Hello-world-Web-server/Pike/hello-world-web-server.pike create mode 100644 Task/Hello-world-Web-server/R/hello-world-web-server.r create mode 100644 Task/Hickerson-series-of-almost-integers/Ada/hickerson-series-of-almost-integers.ada create mode 100644 Task/Hofstadter-Conway-$10,000-sequence/Factor/hofstadter-conway-$10,000-sequence.factor create mode 100644 Task/Hofstadter-Q-sequence/R/hofstadter-q-sequence.r create mode 100644 Task/Holidays-related-to-Easter/COBOL/holidays-related-to-easter.cobol create mode 100644 Task/Holidays-related-to-Easter/Factor/holidays-related-to-easter.factor create mode 100644 Task/Honeycombs/Ada/honeycombs.ada create mode 100644 Task/Hostname/Crystal/hostname.crystal create mode 100644 Task/Hostname/Frink/hostname.frink create mode 100644 Task/Huffman-coding/Factor/huffman-coding.factor create mode 100644 Task/Huffman-coding/Ol/huffman-coding-1.ol create mode 100644 Task/Huffman-coding/Ol/huffman-coding-2.ol create mode 100644 Task/IBAN/Lobster/iban.lobster create mode 100644 Task/Identity-matrix/Ol/identity-matrix.ol create mode 100644 Task/Image-convolution/Perl-6/image-convolution-1.pl6 rename Task/Image-convolution/Perl-6/{image-convolution.pl6 => image-convolution-2.pl6} (86%) create mode 100644 Task/Image-convolution/Perl/image-convolution.pl create mode 100644 Task/Include-a-file/Crystal/include-a-file.crystal create mode 100644 Task/Include-a-file/Go/include-a-file-1.go create mode 100644 Task/Include-a-file/Go/include-a-file-2.go create mode 100644 Task/Include-a-file/Ol/include-a-file-1.ol create mode 100644 Task/Include-a-file/Ol/include-a-file-2.ol create mode 100644 Task/Include-a-file/Pike/include-a-file.pike create mode 100644 Task/Increment-a-numerical-string/APL/increment-a-numerical-string.apl create mode 100644 Task/Infinity/Julia/infinity.julia create mode 100644 Task/Inheritance-Multiple/C/inheritance-multiple.c create mode 100644 Task/Input-loop/XPL0/input-loop.xpl0 rename Task/Integer-sequence/JavaScript/{integer-sequence.js => integer-sequence-1.js} (100%) create mode 100644 Task/Integer-sequence/JavaScript/integer-sequence-2.js create mode 100644 Task/Integer-sequence/Pike/integer-sequence.pike rename Task/Integer-sequence/Ruby/{integer-sequence.rb => integer-sequence-1.rb} (100%) create mode 100644 Task/Integer-sequence/Ruby/integer-sequence-2.rb create mode 100644 Task/Interactive-programming/Ol/interactive-programming.ol create mode 100644 Task/Iterated-digits-squaring/Ada/iterated-digits-squaring.ada create mode 100644 Task/Iterated-digits-squaring/X86-Assembly/iterated-digits-squaring.x86 create mode 100644 Task/JSON/Ol/json.ol create mode 100644 Task/JSON/XQuery/json.xquery rename Task/Jensens-Device/Python/{jensens-device.py => jensens-device-1.py} (100%) create mode 100644 Task/Jensens-Device/Python/jensens-device-2.py create mode 100644 Task/Jensens-Device/Python/jensens-device-3.py create mode 100644 Task/Josephus-problem/Frink/josephus-problem.frink create mode 100644 Task/Joystick-position/Commodore-BASIC/joystick-position-1.commodore create mode 100644 Task/Joystick-position/Commodore-BASIC/joystick-position-2.commodore create mode 100644 Task/Joystick-position/Commodore-BASIC/joystick-position-3.commodore create mode 100644 Task/Joystick-position/Commodore-BASIC/joystick-position-4.commodore create mode 100644 Task/Joystick-position/Perl-6/joystick-position.pl6 rename Task/Jump-anywhere/Go/{jump-anywhere.go => jump-anywhere-1.go} (100%) create mode 100644 Task/Jump-anywhere/Go/jump-anywhere-2.go create mode 100644 Task/Jump-anywhere/Robotic/jump-anywhere-1.robotic create mode 100644 Task/Jump-anywhere/Robotic/jump-anywhere-2.robotic create mode 100644 Task/Jump-anywhere/Robotic/jump-anywhere-3.robotic create mode 100644 Task/Jump-anywhere/Robotic/jump-anywhere-4.robotic create mode 100644 Task/Jump-anywhere/Robotic/jump-anywhere-5.robotic create mode 100644 Task/Jump-anywhere/Robotic/jump-anywhere-6.robotic create mode 100644 Task/K-d-tree/C++/k-d-tree.cpp create mode 100644 Task/K-means++-clustering/Nim/k-means++-clustering.nim create mode 100644 Task/Kaprekar-numbers/Groovy/kaprekar-numbers.groovy create mode 100644 Task/Keyboard-input-Flush-the-keyboard-buffer/AWK/keyboard-input-flush-the-keyboard-buffer.awk create mode 100644 Task/Keyboard-input-Flush-the-keyboard-buffer/BASIC/keyboard-input-flush-the-keyboard-buffer-4.basic rename Task/Keyboard-input-Flush-the-keyboard-buffer/C/{keyboard-input-flush-the-keyboard-buffer.c => keyboard-input-flush-the-keyboard-buffer-1.c} (100%) create mode 100644 Task/Keyboard-input-Flush-the-keyboard-buffer/C/keyboard-input-flush-the-keyboard-buffer-2.c rename Task/Keyboard-input-Flush-the-keyboard-buffer/Go/{keyboard-input-flush-the-keyboard-buffer.go => keyboard-input-flush-the-keyboard-buffer-1.go} (100%) create mode 100644 Task/Keyboard-input-Flush-the-keyboard-buffer/Go/keyboard-input-flush-the-keyboard-buffer-2.go create mode 100644 Task/Keyboard-input-Keypress-check/AWK/keyboard-input-keypress-check.awk rename Task/Keyboard-input-Keypress-check/Go/{keyboard-input-keypress-check.go => keyboard-input-keypress-check-1.go} (54%) create mode 100644 Task/Keyboard-input-Keypress-check/Go/keyboard-input-keypress-check-2.go create mode 100644 Task/Keyboard-input-Keypress-check/Robotic/keyboard-input-keypress-check.robotic rename Task/Keyboard-input-Obtain-a-Y-or-N-response/Go/{keyboard-input-obtain-a-y-or-n-response.go => keyboard-input-obtain-a-y-or-n-response-1.go} (100%) create mode 100644 Task/Keyboard-input-Obtain-a-Y-or-N-response/Go/keyboard-input-obtain-a-y-or-n-response-2.go create mode 100644 Task/Knapsack-problem-Bounded/Swift/knapsack-problem-bounded.swift rename Task/Knights-tour/Java/{knights-tour.java => knights-tour-1.java} (100%) create mode 100644 Task/Knights-tour/Java/knights-tour-2.java create mode 100644 Task/Knights-tour/Swift/knights-tour.swift create mode 100644 Task/Knuth-shuffle/Crystal/knuth-shuffle.crystal create mode 100644 Task/LU-decomposition/Lobster/lu-decomposition.lobster create mode 100644 Task/LU-decomposition/R/lu-decomposition.r create mode 100644 Task/LZW-compression/Rust/lzw-compression.rust create mode 100644 Task/Langtons-ant/Ol/langtons-ant.ol create mode 100644 Task/Last-Friday-of-each-month/Delphi/last-friday-of-each-month.delphi create mode 100644 Task/Last-letter-first-letter/Rust/last-letter-first-letter.rust create mode 100644 Task/Leap-year/Crystal/leap-year.crystal create mode 100644 Task/Left-factorials/AWK/left-factorials.awk create mode 100644 Task/Left-factorials/Maple/left-factorials.maple create mode 100644 Task/Left-factorials/R/left-factorials.r create mode 100644 Task/Left-factorials/Swift/left-factorials.swift create mode 100644 Task/Letter-frequency/Pike/letter-frequency.pike create mode 100644 Task/Levenshtein-distance/COBOL/levenshtein-distance.cobol create mode 100644 Task/Levenshtein-distance/Lobster/levenshtein-distance.lobster create mode 100644 Task/List-comprehensions/Swift/list-comprehensions.swift rename Task/Literals-Integer/Go/{literals-integer.go => literals-integer-1.go} (100%) create mode 100644 Task/Literals-Integer/Go/literals-integer-2.go rename Task/Logical-operations/Go/{logical-operations.go => logical-operations-1.go} (100%) create mode 100644 Task/Logical-operations/Go/logical-operations-2.go create mode 100644 Task/Long-multiplication/Lobster/long-multiplication.lobster create mode 100644 Task/Longest-string-challenge/PHP/longest-string-challenge.php create mode 100644 Task/Longest-string-challenge/XQuery/longest-string-challenge.xquery create mode 100644 Task/Look-and-say-sequence/Frink/look-and-say-sequence.frink create mode 100644 Task/Look-and-say-sequence/Metafont/look-and-say-sequence.metafont rename Task/Look-and-say-sequence/Smalltalk/{look-and-say-sequence.st => look-and-say-sequence-1.st} (100%) create mode 100644 Task/Look-and-say-sequence/Smalltalk/look-and-say-sequence-2.st create mode 100644 Task/Loop-over-multiple-arrays-simultaneously/Common-Lisp/loop-over-multiple-arrays-simultaneously-3.lisp create mode 100644 Task/Loop-over-multiple-arrays-simultaneously/Frink/loop-over-multiple-arrays-simultaneously.frink create mode 100644 Task/Loop-over-multiple-arrays-simultaneously/Pike/loop-over-multiple-arrays-simultaneously.pike create mode 100644 Task/Loop-over-multiple-arrays-simultaneously/Vala/loop-over-multiple-arrays-simultaneously.vala create mode 100644 Task/Loop-over-multiple-arrays-simultaneously/X86-Assembly/loop-over-multiple-arrays-simultaneously.x86 rename Task/Loops-Break/Common-Lisp/{loops-break.lisp => loops-break-1.lisp} (100%) create mode 100644 Task/Loops-Break/Common-Lisp/loops-break-2.lisp create mode 100644 Task/Loops-Break/Haxe/loops-break.haxe create mode 100644 Task/Loops-Continue/Haxe/loops-continue.haxe create mode 100644 Task/Loops-Continue/Vala/loops-continue.vala create mode 100644 Task/Loops-Continue/X86-Assembly/loops-continue.x86 create mode 100644 Task/Loops-Do-while/BASIC/loops-do-while-5.basic create mode 100644 Task/Loops-Do-while/Common-Lisp/loops-do-while-3.lisp rename Task/Loops-Do-while/Go/{loops-do-while.go => loops-do-while-1.go} (100%) create mode 100644 Task/Loops-Do-while/Go/loops-do-while-2.go create mode 100644 Task/Loops-Do-while/Go/loops-do-while-3.go create mode 100644 Task/Loops-Do-while/Haxe/loops-do-while.haxe create mode 100644 Task/Loops-Do-while/Vala/loops-do-while.vala create mode 100644 Task/Loops-Do-while/X86-Assembly/loops-do-while.x86 rename Task/Loops-Downward-for/Common-Lisp/{loops-downward-for.lisp => loops-downward-for-1.lisp} (100%) create mode 100644 Task/Loops-Downward-for/Common-Lisp/loops-downward-for-2.lisp rename Task/Loops-Downward-for/Go/{loops-downward-for.go => loops-downward-for-1.go} (100%) create mode 100644 Task/Loops-Downward-for/Go/loops-downward-for-2.go create mode 100644 Task/Loops-Downward-for/Haxe/loops-downward-for.haxe create mode 100644 Task/Loops-Downward-for/Vala/loops-downward-for.vala create mode 100644 Task/Loops-For-with-a-specified-step/BASIC/loops-for-with-a-specified-step-10.basic create mode 100644 Task/Loops-For-with-a-specified-step/BASIC/loops-for-with-a-specified-step-11.basic create mode 100644 Task/Loops-For-with-a-specified-step/BASIC/loops-for-with-a-specified-step-12.basic create mode 100644 Task/Loops-For-with-a-specified-step/BASIC/loops-for-with-a-specified-step-13.basic create mode 100644 Task/Loops-For-with-a-specified-step/BASIC/loops-for-with-a-specified-step-14.basic create mode 100644 Task/Loops-For-with-a-specified-step/BASIC/loops-for-with-a-specified-step-15.basic create mode 100644 Task/Loops-For-with-a-specified-step/BASIC/loops-for-with-a-specified-step-16.basic create mode 100644 Task/Loops-For-with-a-specified-step/BASIC/loops-for-with-a-specified-step-17.basic create mode 100644 Task/Loops-For-with-a-specified-step/BASIC/loops-for-with-a-specified-step-18.basic create mode 100644 Task/Loops-For-with-a-specified-step/BASIC/loops-for-with-a-specified-step-19.basic create mode 100644 Task/Loops-For-with-a-specified-step/BASIC/loops-for-with-a-specified-step-20.basic create mode 100644 Task/Loops-For-with-a-specified-step/BASIC/loops-for-with-a-specified-step-21.basic create mode 100644 Task/Loops-For-with-a-specified-step/BASIC/loops-for-with-a-specified-step-22.basic create mode 100644 Task/Loops-For-with-a-specified-step/BASIC/loops-for-with-a-specified-step-7.basic create mode 100644 Task/Loops-For-with-a-specified-step/BASIC/loops-for-with-a-specified-step-8.basic create mode 100644 Task/Loops-For-with-a-specified-step/BASIC/loops-for-with-a-specified-step-9.basic rename Task/Loops-For-with-a-specified-step/Common-Lisp/{loops-for-with-a-specified-step.lisp => loops-for-with-a-specified-step-1.lisp} (100%) create mode 100644 Task/Loops-For-with-a-specified-step/Common-Lisp/loops-for-with-a-specified-step-2.lisp create mode 100644 Task/Loops-For-with-a-specified-step/Haxe/loops-for-with-a-specified-step.haxe create mode 100644 Task/Loops-For-with-a-specified-step/Vala/loops-for-with-a-specified-step.vala create mode 100644 Task/Loops-For/Common-Lisp/loops-for-4.lisp create mode 100644 Task/Loops-For/Crystal/loops-for-1.crystal create mode 100644 Task/Loops-For/Crystal/loops-for-2.crystal create mode 100644 Task/Loops-Foreach/Common-Lisp/loops-foreach-3.lisp create mode 100644 Task/Loops-Foreach/Common-Lisp/loops-foreach-4.lisp create mode 100644 Task/Loops-Foreach/Common-Lisp/loops-foreach-5.lisp create mode 100644 Task/Loops-Foreach/Ol/loops-foreach.ol create mode 100644 Task/Loops-Foreach/Vala/loops-foreach.vala rename Task/Loops-Infinite/Common-Lisp/{loops-infinite.lisp => loops-infinite-1.lisp} (100%) create mode 100644 Task/Loops-Infinite/Common-Lisp/loops-infinite-2.lisp create mode 100644 Task/Loops-Infinite/Haxe/loops-infinite.haxe create mode 100644 Task/Loops-Infinite/Robotic/loops-infinite.robotic create mode 100644 Task/Loops-N-plus-one-half/Common-Lisp/loops-n-plus-one-half-4.lisp create mode 100644 Task/Loops-N-plus-one-half/Common-Lisp/loops-n-plus-one-half-5.lisp create mode 100644 Task/Loops-N-plus-one-half/Haxe/loops-n-plus-one-half.haxe rename Task/Loops-N-plus-one-half/Pike/{loops-n-plus-one-half.pike => loops-n-plus-one-half-1.pike} (100%) create mode 100644 Task/Loops-N-plus-one-half/Pike/loops-n-plus-one-half-2.pike create mode 100644 Task/Loops-N-plus-one-half/Pike/loops-n-plus-one-half-3.pike create mode 100644 Task/Loops-N-plus-one-half/Vala/loops-n-plus-one-half.vala create mode 100644 Task/Loops-Nested/Factor/loops-nested-1.factor create mode 100644 Task/Loops-Nested/Factor/loops-nested-2.factor delete mode 100644 Task/Loops-Nested/Factor/loops-nested.factor create mode 100644 Task/Loops-Nested/Pike/loops-nested.pike create mode 100644 Task/Loops-Nested/Vala/loops-nested.vala create mode 100644 Task/Loops-While/Haxe/loops-while-1.haxe create mode 100644 Task/Loops-While/Haxe/loops-while-2.haxe create mode 100644 Task/Loops-While/Vala/loops-while.vala create mode 100644 Task/Lucas-Lehmer-test/Frink/lucas-lehmer-test.frink create mode 100644 Task/Lucas-Lehmer-test/Prolog/lucas-lehmer-test.pro create mode 100644 Task/Ludic-numbers/Ada/ludic-numbers.ada create mode 100644 Task/MD4/Ada/md4.ada create mode 100644 Task/MD5-Implementation/Lua/md5-implementation-1.lua create mode 100644 Task/MD5-Implementation/Lua/md5-implementation-2.lua create mode 100644 Task/MD5/Haxe/md5.haxe create mode 100644 Task/MD5/Ol/md5-1.ol create mode 100644 Task/MD5/Ol/md5-2.ol create mode 100644 Task/MD5/Visual-Basic-.NET/md5.visual create mode 100644 Task/Magic-squares-of-odd-order/PicoLisp/magic-squares-of-odd-order.l create mode 100644 Task/Mandelbrot-set/Frink/mandelbrot-set.frink rename Task/Mandelbrot-set/Java/{mandelbrot-set.java => mandelbrot-set-1.java} (100%) create mode 100644 Task/Mandelbrot-set/Java/mandelbrot-set-2.java create mode 100644 Task/Mandelbrot-set/Python/mandelbrot-set-5.py create mode 100644 Task/Mandelbrot-set/Python/mandelbrot-set-6.py create mode 100644 Task/Map-range/Vala/map-range.vala create mode 100644 Task/Matrix-exponentiation-operator/Rust/matrix-exponentiation-operator.rust create mode 100644 Task/Matrix-multiplication/Haskell/matrix-multiplication-4.hs create mode 100644 Task/Matrix-multiplication/Lambdatalk/matrix-multiplication.lambdatalk create mode 100644 Task/Matrix-multiplication/Swift/matrix-multiplication.swift create mode 100644 Task/Matrix-transposition/Swift/matrix-transposition.swift create mode 100644 Task/Maximum-triangle-path-sum/AWK/maximum-triangle-path-sum.awk create mode 100644 Task/Maze-generation/Emacs-Lisp/maze-generation-1.l create mode 100644 Task/Maze-generation/Emacs-Lisp/maze-generation-2.l create mode 100644 Task/Maze-generation/Forth/maze-generation-1.fth create mode 100644 Task/Maze-generation/Forth/maze-generation-2.fth create mode 100644 Task/Maze-solving/Emacs-Lisp/maze-solving-1.l create mode 100644 Task/Maze-solving/Emacs-Lisp/maze-solving-2.l create mode 100644 Task/Median-filter/Perl/median-filter.pl create mode 100644 Task/Menu/Swift/menu.swift create mode 100644 Task/Metaprogramming/Ol/metaprogramming-1.ol create mode 100644 Task/Metaprogramming/Ol/metaprogramming-2.ol create mode 100644 Task/Modular-exponentiation/Swift/modular-exponentiation.swift create mode 100644 Task/Modular-inverse/Prolog/modular-inverse.pro create mode 100644 Task/Modular-inverse/Swift/modular-inverse.swift create mode 100644 Task/Move-to-front-algorithm/PHP/move-to-front-algorithm.php create mode 100644 Task/Multiple-regression/R/multiple-regression-4.r create mode 100644 Task/Multiplication-tables/Prolog/multiplication-tables.pro create mode 100644 Task/Multiplicative-order/Factor/multiplicative-order.factor create mode 100644 Task/Mutual-recursion/Lambdatalk/mutual-recursion-1.lambdatalk create mode 100644 Task/Mutual-recursion/Lambdatalk/mutual-recursion-2.lambdatalk create mode 100644 Task/N-queens-problem/Frink/n-queens-problem.frink create mode 100644 Task/N-queens-problem/R/n-queens-problem-1.r create mode 100644 Task/N-queens-problem/R/n-queens-problem-2.r create mode 100644 Task/N-queens-problem/R/n-queens-problem-3.r delete mode 100644 Task/N-queens-problem/R/n-queens-problem.r create mode 100644 Task/Narcissistic-decimal-number/Python/narcissistic-decimal-number-3.py create mode 100644 Task/Narcissistic-decimal-number/R/narcissistic-decimal-number.r create mode 100644 Task/Narcissistic-decimal-number/Swift/narcissistic-decimal-number.swift create mode 100644 Task/Non-decimal-radices-Convert/Phix/non-decimal-radices-convert-1.phix rename Task/Non-decimal-radices-Convert/Phix/{non-decimal-radices-convert.phix => non-decimal-radices-convert-2.phix} (100%) create mode 100644 Task/Non-decimal-radices-Convert/Python/non-decimal-radices-convert-3.py create mode 100644 Task/Nth-root/Prolog/nth-root.pro create mode 100644 Task/Nth-root/Python/nth-root-3.py create mode 100644 Task/Nth-root/Swift/nth-root.swift create mode 100644 Task/Nth/Julia/nth-3.julia create mode 100644 Task/Number-names/Commodore-BASIC/number-names.commodore create mode 100644 Task/Number-names/Liberty-BASIC/number-names.liberty create mode 100644 Task/Number-names/Prolog/number-names.pro create mode 100644 Task/Number-names/R/number-names.r create mode 100644 Task/Number-reversal-game/Prolog/number-reversal-game.pro create mode 100644 Task/Numeric-error-propagation/Factor/numeric-error-propagation-1.factor create mode 100644 Task/Numeric-error-propagation/Factor/numeric-error-propagation-2.factor create mode 100644 Task/Numeric-error-propagation/Nim/numeric-error-propagation.nim create mode 100644 Task/Numerical-integration-Gauss-Legendre-Quadrature/JavaScript/numerical-integration-gauss-legendre-quadrature.js create mode 100644 Task/Numerical-integration-Gauss-Legendre-Quadrature/Nim/numerical-integration-gauss-legendre-quadrature.nim create mode 100644 Task/OpenGL/Perl-6/opengl.pl6 create mode 100644 Task/Optional-parameters/Rust/optional-parameters.rust create mode 100644 Task/Pangram-checker/Crystal/pangram-checker.crystal create mode 100644 Task/Pangram-checker/EDSAC-order-code/pangram-checker.edsac create mode 100644 Task/Parallel-calculations/Swift/parallel-calculations.swift create mode 100644 Task/Parametric-polymorphism/Visual-Basic-.NET/parametric-polymorphism.visual create mode 100644 Task/Parse-an-IP-Address/C++/parse-an-ip-address.cpp create mode 100644 Task/Parse-an-IP-Address/Java/parse-an-ip-address.java create mode 100644 Task/Parsing-RPN-calculator-algorithm/COBOL/parsing-rpn-calculator-algorithm.cobol create mode 100644 Task/Pascals-triangle-Puzzle/Java/pascals-triangle-puzzle.java create mode 100644 Task/Pascals-triangle-Puzzle/Maple/pascals-triangle-puzzle.maple create mode 100644 Task/Pascals-triangle/Frink/pascals-triangle.frink create mode 100644 Task/Pascals-triangle/Julia/pascals-triangle-1.julia create mode 100644 Task/Pascals-triangle/Julia/pascals-triangle-2.julia delete mode 100644 Task/Pascals-triangle/Julia/pascals-triangle.julia create mode 100644 Task/Pascals-triangle/Red/pascals-triangle.red create mode 100644 Task/Pascals-triangle/X86-Assembly/pascals-triangle.x86 create mode 100644 Task/Perfect-numbers/Python/perfect-numbers-4.py create mode 100644 Task/Permutation-test/AWK/permutation-test.awk create mode 100644 Task/Permutation-test/Nim/permutation-test.nim create mode 100644 Task/Permutations/AWK/permutations.awk create mode 100644 Task/Permutations/Common-Lisp/permutations-3.lisp create mode 100644 Task/Permutations/Lobster/permutations.lobster create mode 100644 Task/Permutations/Lua/permutations-3.lua create mode 100644 Task/Permutations/Shen/permutations-1.shen create mode 100644 Task/Permutations/Shen/permutations-2.shen rename Task/Pernicious-numbers/Python/{pernicious-numbers.py => pernicious-numbers-1.py} (100%) create mode 100644 Task/Pernicious-numbers/Python/pernicious-numbers-2.py create mode 100644 Task/Pernicious-numbers/Swift/pernicious-numbers.swift create mode 100644 Task/Phrase-reversals/Rust/phrase-reversals.rust create mode 100644 Task/Pinstripe-Display/Ada/pinstripe-display.ada create mode 100644 Task/Pinstripe-Printer/Perl-6/pinstripe-printer.pl6 create mode 100644 Task/Plot-coordinate-pairs/Factor/plot-coordinate-pairs.factor create mode 100644 Task/Polymorphism/Prolog/polymorphism.pro create mode 100644 Task/Polynomial-long-division/Swift/polynomial-long-division.swift create mode 100644 Task/Polynomial-regression/PowerShell/polynomial-regression.psh create mode 100644 Task/Power-set/D/power-set-3.d rename Task/Price-fraction/BASIC/{price-fraction.basic => price-fraction-1.basic} (100%) create mode 100644 Task/Price-fraction/BASIC/price-fraction-2.basic create mode 100644 Task/Price-fraction/Swift/price-fraction.swift create mode 100644 Task/Primality-by-trial-division/Ol/primality-by-trial-division-1.ol create mode 100644 Task/Primality-by-trial-division/Ol/primality-by-trial-division-2.ol create mode 100644 Task/Prime-decomposition/Lambdatalk/prime-decomposition.lambdatalk create mode 100644 Task/Prime-decomposition/Prolog/prime-decomposition-4.pro create mode 100644 Task/Prime-decomposition/R/prime-decomposition-3.r create mode 100644 Task/Pythagorean-triples/AWK/pythagorean-triples.awk create mode 100644 Task/Pythagorean-triples/EDSAC-order-code/pythagorean-triples.edsac create mode 100644 Task/Pythagorean-triples/PHP/pythagorean-triples.php create mode 100644 Task/Pythagorean-triples/Prolog/pythagorean-triples.pro create mode 100644 Task/QR-decomposition/Fortran/qr-decomposition.f create mode 100644 Task/QR-decomposition/Perl/qr-decomposition.pl create mode 100644 Task/QR-decomposition/PowerShell/qr-decomposition.psh create mode 100644 Task/Quaternion-type/Idris/quaternion-type-1.idris create mode 100644 Task/Quaternion-type/Idris/quaternion-type-2.idris create mode 100644 Task/Quaternion-type/Maple/quaternion-type.maple create mode 100644 Task/Quaternion-type/Red/quaternion-type.red create mode 100644 Task/Queue-Definition/Factor/queue-definition.factor create mode 100644 Task/Quine/Binary-Lambda-Calculus/quine.binary create mode 100644 Task/Quine/Bracmat/quine.bracmat create mode 100644 Task/Quine/Gambas/quine.gambas create mode 100644 Task/Quine/JavaScript/quine-10.js create mode 100644 Task/Quine/JavaScript/quine-9.js create mode 100644 Task/Quine/Swift/quine-3.swift create mode 100644 Task/RIPEMD-160/Ada/ripemd-160.ada create mode 100644 Task/RIPEMD-160/C/ripemd-160.c create mode 100644 Task/RSA-code/PowerShell/rsa-code.psh create mode 100644 Task/Random-numbers/Frink/random-numbers.frink create mode 100644 Task/Random-numbers/Lobster/random-numbers.lobster create mode 100644 Task/Ranking-methods/Factor/ranking-methods.factor create mode 100644 Task/Ray-casting-algorithm/PHP/ray-casting-algorithm.php create mode 100644 Task/Read-a-configuration-file/COBOL/read-a-configuration-file.cobol create mode 100644 Task/Read-a-configuration-file/PHP/read-a-configuration-file.php create mode 100644 Task/Read-a-file-line-by-line/XPL0/read-a-file-line-by-line.xpl0 create mode 100644 Task/Read-a-specific-line-from-a-file/Elixir/read-a-specific-line-from-a-file.elixir create mode 100644 Task/Read-a-specific-line-from-a-file/PHP/read-a-specific-line-from-a-file.php rename Task/Read-entire-file/Pike/{read-entire-file.pike => read-entire-file-1.pike} (100%) create mode 100644 Task/Read-entire-file/Pike/read-entire-file-2.pike create mode 100644 Task/Read-entire-file/Python/read-entire-file-4.py create mode 100644 Task/Record-sound/Perl-6/record-sound.pl6 create mode 100644 Task/Record-sound/Phix/record-sound.phix create mode 100644 Task/Remove-duplicate-elements/Crystal/remove-duplicate-elements.crystal create mode 100644 Task/Rename-a-file/BASIC/rename-a-file-5.basic create mode 100644 Task/Rename-a-file/BASIC/rename-a-file-6.basic create mode 100644 Task/Rep-string/Clojure/rep-string-1.clj create mode 100644 Task/Rep-string/Clojure/rep-string-2.clj create mode 100644 Task/Rep-string/Rust/rep-string.rust create mode 100644 Task/Return-multiple-values/Go/return-multiple-values-4.go create mode 100644 Task/Reverse-a-string/Pike/reverse-a-string-1.pike create mode 100644 Task/Reverse-a-string/Pike/reverse-a-string-2.pike create mode 100644 Task/Reverse-words-in-a-string/Pike/reverse-words-in-a-string.pike create mode 100644 Task/Roman-numerals-Encode/Shen/roman-numerals-encode.shen create mode 100644 Task/Roman-numerals-Encode/Vala/roman-numerals-encode.vala create mode 100644 Task/Roots-of-a-function/Nim/roots-of-a-function.nim create mode 100644 Task/Roots-of-a-quadratic-function/R/roots-of-a-quadratic-function-1.r create mode 100644 Task/Roots-of-a-quadratic-function/R/roots-of-a-quadratic-function-2.r delete mode 100644 Task/Roots-of-a-quadratic-function/R/roots-of-a-quadratic-function.r create mode 100644 Task/Roots-of-unity/Factor/roots-of-unity.factor create mode 100644 Task/Roots-of-unity/Frink/roots-of-unity.frink create mode 100644 Task/Roots-of-unity/Prolog/roots-of-unity.pro create mode 100644 Task/Rot-13/Vala/rot-13.vala create mode 100644 Task/Run-length-encoding/JavaScript/run-length-encoding-4.js create mode 100644 Task/Run-length-encoding/Scala/run-length-encoding-3.scala create mode 100644 Task/SHA-1/Haxe/sha-1.haxe create mode 100644 Task/SHA-1/Pike/sha-1.pike create mode 100644 Task/SHA-256/Ada/sha-256.ada create mode 100644 Task/SHA-256/Frink/sha-256.frink create mode 100644 Task/SHA-256/Haxe/sha-256.haxe create mode 100644 Task/SHA-256/JavaScript/sha-256.js create mode 100644 Task/SHA-256/Pike/sha-256.pike create mode 100644 Task/SOAP/Julia/soap.julia create mode 100644 Task/SOAP/Phix/soap.phix create mode 100644 Task/Self-describing-numbers/Swift/self-describing-numbers.swift create mode 100644 Task/Self-referential-sequence/Factor/self-referential-sequence.factor create mode 100644 Task/Semiprime/Sidef/semiprime-1.sidef create mode 100644 Task/Semiprime/Sidef/semiprime-2.sidef delete mode 100644 Task/Semiprime/Sidef/semiprime.sidef create mode 100644 Task/Semordnilap/Swift/semordnilap.swift create mode 100644 Task/Send-email/Phix/send-email.phix create mode 100644 Task/Sequence-of-non-squares/Maple/sequence-of-non-squares.maple rename Task/Sequence-of-non-squares/Python/{sequence-of-non-squares.py => sequence-of-non-squares-1.py} (100%) create mode 100644 Task/Sequence-of-non-squares/Python/sequence-of-non-squares-2.py create mode 100644 Task/Set-consolidation/Factor/set-consolidation.factor create mode 100644 Task/Set-consolidation/Nim/set-consolidation.nim create mode 100644 Task/Set-puzzle/C-sharp/set-puzzle.cs create mode 100644 Task/Set-puzzle/Factor/set-puzzle.factor create mode 100644 Task/Set-puzzle/Prolog/set-puzzle.pro create mode 100644 Task/Shell-one-liner/Processing/shell-one-liner create mode 100644 Task/Show-the-epoch/Pike/show-the-epoch.pike rename Task/Show-the-epoch/Ruby/{show-the-epoch.rb => show-the-epoch-1.rb} (100%) create mode 100644 Task/Show-the-epoch/Ruby/show-the-epoch-2.rb create mode 100644 Task/Sierpinski-carpet/Factor/sierpinski-carpet.factor create mode 100644 Task/Sierpinski-carpet/PHP/sierpinski-carpet.php create mode 100644 Task/Sierpinski-triangle/Haskell/sierpinski-triangle-5.hs create mode 100644 Task/Sierpinski-triangle/Java/sierpinski-triangle.java create mode 100644 Task/Sierpinski-triangle/JavaScript/sierpinski-triangle-5.js create mode 100644 Task/Sierpinski-triangle/Lua/sierpinski-triangle.lua create mode 100644 Task/Sierpinski-triangle/PHP/sierpinski-triangle.php rename Task/Sierpinski-triangle/Perl/{sierpinski-triangle.pl => sierpinski-triangle-1.pl} (100%) create mode 100644 Task/Sierpinski-triangle/Perl/sierpinski-triangle-2.pl create mode 100644 Task/Sieve-of-Eratosthenes/Frink/sieve-of-eratosthenes.frink create mode 100644 Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-7.java rename Task/Sieve-of-Eratosthenes/PicoLisp/{sieve-of-eratosthenes.l => sieve-of-eratosthenes-1.l} (100%) create mode 100644 Task/Sieve-of-Eratosthenes/PicoLisp/sieve-of-eratosthenes-2.l create mode 100644 Task/Simulate-input-Keyboard/Nim/simulate-input-keyboard.nim create mode 100644 Task/Singleton/Python/singleton-3.py create mode 100644 Task/Singleton/Python/singleton-4.py create mode 100644 Task/Sockets/R/sockets.r create mode 100644 Task/Solve-a-Hopido-puzzle/Prolog/solve-a-hopido-puzzle-1.pro create mode 100644 Task/Solve-a-Hopido-puzzle/Prolog/solve-a-hopido-puzzle-2.pro create mode 100644 Task/Solve-a-Numbrix-puzzle/Prolog/solve-a-numbrix-puzzle.pro create mode 100644 Task/Solve-the-no-connection-puzzle/Perl/solve-the-no-connection-puzzle.pl create mode 100644 Task/Sort-an-array-of-composite-structures/Swift/sort-an-array-of-composite-structures.swift create mode 100644 Task/Sorting-algorithms-Bogosort/Crystal/sorting-algorithms-bogosort.crystal create mode 100644 Task/Sorting-algorithms-Bogosort/Prolog/sorting-algorithms-bogosort.pro create mode 100644 Task/Sorting-algorithms-Bubble-sort/EDSAC-order-code/sorting-algorithms-bubble-sort.edsac create mode 100644 Task/Sorting-algorithms-Bubble-sort/Haxe/sorting-algorithms-bubble-sort.haxe create mode 100644 Task/Sorting-algorithms-Bubble-sort/Vala/sorting-algorithms-bubble-sort.vala create mode 100644 Task/Sorting-algorithms-Cocktail-sort/Factor/sorting-algorithms-cocktail-sort-1.factor create mode 100644 Task/Sorting-algorithms-Cocktail-sort/Factor/sorting-algorithms-cocktail-sort-2.factor create mode 100644 Task/Sorting-algorithms-Cocktail-sort/Haxe/sorting-algorithms-cocktail-sort.haxe create mode 100644 Task/Sorting-algorithms-Cocktail-sort/Vala/sorting-algorithms-cocktail-sort.vala create mode 100644 Task/Sorting-algorithms-Comb-sort/Haxe/sorting-algorithms-comb-sort.haxe create mode 100644 Task/Sorting-algorithms-Counting-sort/Haxe/sorting-algorithms-counting-sort.haxe create mode 100644 Task/Sorting-algorithms-Gnome-sort/Haxe/sorting-algorithms-gnome-sort.haxe create mode 100644 Task/Sorting-algorithms-Heapsort/Haxe/sorting-algorithms-heapsort.haxe create mode 100644 Task/Sorting-algorithms-Heapsort/Lobster/sorting-algorithms-heapsort.lobster create mode 100644 Task/Sorting-algorithms-Heapsort/Vala/sorting-algorithms-heapsort.vala create mode 100644 Task/Sorting-algorithms-Insertion-sort/Haxe/sorting-algorithms-insertion-sort.haxe create mode 100644 Task/Sorting-algorithms-Insertion-sort/Scala/sorting-algorithms-insertion-sort.scala create mode 100644 Task/Sorting-algorithms-Insertion-sort/Vala/sorting-algorithms-insertion-sort.vala create mode 100644 Task/Sorting-algorithms-Merge-sort/Scala/sorting-algorithms-merge-sort.scala create mode 100644 Task/Sorting-algorithms-Pancake-sort/Batch-File/sorting-algorithms-pancake-sort.bat create mode 100644 Task/Sorting-algorithms-Pancake-sort/Haxe/sorting-algorithms-pancake-sort.haxe create mode 100644 Task/Sorting-algorithms-Permutation-sort/Crystal/sorting-algorithms-permutation-sort.crystal rename Task/Sorting-algorithms-Quicksort/OCaml/{sorting-algorithms-quicksort.ocaml => sorting-algorithms-quicksort-1.ocaml} (100%) create mode 100644 Task/Sorting-algorithms-Quicksort/OCaml/sorting-algorithms-quicksort-2.ocaml create mode 100644 Task/Sorting-algorithms-Quicksort/PowerShell/sorting-algorithms-quicksort-3.psh create mode 100644 Task/Sorting-algorithms-Selection-sort/Crystal/sorting-algorithms-selection-sort.crystal create mode 100644 Task/Sorting-algorithms-Selection-sort/Factor/sorting-algorithms-selection-sort-1.factor create mode 100644 Task/Sorting-algorithms-Selection-sort/Factor/sorting-algorithms-selection-sort-2.factor create mode 100644 Task/Sorting-algorithms-Shell-sort/Haxe/sorting-algorithms-shell-sort.haxe create mode 100644 Task/Sorting-algorithms-Sleep-sort/Emacs-Lisp/sorting-algorithms-sleep-sort.l create mode 100644 Task/Sorting-algorithms-Sleep-sort/Pike/sorting-algorithms-sleep-sort.pike create mode 100644 Task/Speech-synthesis/PHP/speech-synthesis-1.php create mode 100644 Task/Speech-synthesis/PHP/speech-synthesis-2.php create mode 100644 Task/Speech-synthesis/Phix/speech-synthesis.phix create mode 100644 Task/Spiral-matrix/Maple/spiral-matrix.maple create mode 100644 Task/Stack/Crystal/stack.crystal create mode 100644 Task/Stack/Ol/stack-1.ol create mode 100644 Task/Stack/Ol/stack-2.ol create mode 100644 Task/Stack/Pike/stack.pike create mode 100644 Task/Stair-climbing-puzzle/Prolog/stair-climbing-puzzle-1.pro create mode 100644 Task/Stair-climbing-puzzle/Prolog/stair-climbing-puzzle-2.pro create mode 100644 Task/Start-from-a-main-routine/Processing/start-from-a-main-routine-1 create mode 100644 Task/Start-from-a-main-routine/Processing/start-from-a-main-routine-2 create mode 100644 Task/Start-from-a-main-routine/Processing/start-from-a-main-routine-3 rename Task/String-append/Go/{string-append.go => string-append-1.go} (100%) create mode 100644 Task/String-append/Go/string-append-2.go create mode 100644 Task/String-append/Pike/string-append.pike create mode 100644 Task/String-append/Robotic/string-append.robotic rename Task/String-append/Rust/{string-append.rust => string-append-1.rust} (100%) create mode 100644 Task/String-append/Rust/string-append-2.rust create mode 100644 Task/String-append/Vala/string-append.vala create mode 100644 Task/String-case/Pike/string-case-1.pike create mode 100644 Task/String-case/Pike/string-case-2.pike create mode 100644 Task/String-comparison/Robotic/string-comparison.robotic create mode 100644 Task/String-comparison/Vala/string-comparison.vala create mode 100644 Task/String-concatenation/Pike/string-concatenation.pike create mode 100644 Task/String-concatenation/Vala/string-concatenation.vala create mode 100644 Task/String-interpolation--included-/Haxe/string-interpolation--included-.haxe create mode 100644 Task/String-interpolation--included-/Vala/string-interpolation--included-.vala create mode 100644 Task/String-length/BASIC/string-length-5.basic create mode 100644 Task/String-length/BASIC/string-length-6.basic create mode 100644 Task/String-length/BASIC/string-length-7.basic create mode 100644 Task/String-length/Frink/string-length-1.frink create mode 100644 Task/String-length/Frink/string-length-2.frink create mode 100644 Task/String-length/Frink/string-length-3.frink create mode 100644 Task/String-length/Ruby/string-length-7.rb create mode 100644 Task/String-matching/Vala/string-matching.vala create mode 100644 Task/String-prepend/BASIC/string-prepend-3.basic create mode 100644 Task/String-prepend/OCaml/string-prepend.ocaml create mode 100644 Task/Strip-comments-from-a-string/COBOL/strip-comments-from-a-string.cobol create mode 100644 Task/Strip-comments-from-a-string/Forth/strip-comments-from-a-string.fth create mode 100644 Task/Strip-control-codes-and-extended-characters-from-a-string/C/strip-control-codes-and-extended-characters-from-a-string-3.c create mode 100644 Task/Strip-whitespace-from-a-string-Top-and-tail/R/strip-whitespace-from-a-string-top-and-tail.r create mode 100644 Task/Substring/Crystal/substring.crystal create mode 100644 Task/Sudoku/AWK/sudoku.awk rename Task/Sudoku/Lua/{sudoku.lua => sudoku-1.lua} (100%) create mode 100644 Task/Sudoku/Lua/sudoku-2.lua create mode 100644 Task/Sum-digits-of-an-integer/Objeck/sum-digits-of-an-integer.objeck create mode 100644 Task/Sum-digits-of-an-integer/Python/sum-digits-of-an-integer-4.py create mode 100644 Task/Sum-multiples-of-3-and-5/Frink/sum-multiples-of-3-and-5.frink rename Task/Sum-multiples-of-3-and-5/Java/{sum-multiples-of-3-and-5.java => sum-multiples-of-3-and-5-1.java} (100%) create mode 100644 Task/Sum-multiples-of-3-and-5/Java/sum-multiples-of-3-and-5-2.java create mode 100644 Task/Sum-multiples-of-3-and-5/PHP/sum-multiples-of-3-and-5-1.php create mode 100644 Task/Sum-multiples-of-3-and-5/PHP/sum-multiples-of-3-and-5-2.php create mode 100644 Task/Sum-multiples-of-3-and-5/PHP/sum-multiples-of-3-and-5-3.php create mode 100644 Task/Sum-multiples-of-3-and-5/Phix/sum-multiples-of-3-and-5-1.phix rename Task/Sum-multiples-of-3-and-5/Phix/{sum-multiples-of-3-and-5.phix => sum-multiples-of-3-and-5-2.phix} (100%) create mode 100644 Task/Sum-of-a-series/Frink/sum-of-a-series.frink create mode 100644 Task/Sum-of-a-series/Haxe/sum-of-a-series-1.haxe create mode 100644 Task/Sum-of-a-series/Haxe/sum-of-a-series-2.haxe create mode 100644 Task/Sum-of-a-series/Tcl/sum-of-a-series-4.tcl create mode 100644 Task/Sutherland-Hodgman-polygon-clipping/Perl-6/sutherland-hodgman-polygon-clipping.pl6 create mode 100644 Task/Sutherland-Hodgman-polygon-clipping/Perl/sutherland-hodgman-polygon-clipping.pl create mode 100644 Task/Synchronous-concurrency/Crystal/synchronous-concurrency.crystal create mode 100644 Task/System-time/Pike/system-time.pike create mode 100644 Task/Terminal-control-Clear-the-screen/BASIC/terminal-control-clear-the-screen-10.basic create mode 100644 Task/Terminal-control-Clear-the-screen/BASIC/terminal-control-clear-the-screen-11.basic create mode 100644 Task/Terminal-control-Clear-the-screen/BASIC/terminal-control-clear-the-screen-9.basic rename Task/Terminal-control-Coloured-text/BASIC/{terminal-control-coloured-text.basic => terminal-control-coloured-text-1.basic} (100%) create mode 100644 Task/Terminal-control-Coloured-text/BASIC/terminal-control-coloured-text-2.basic create mode 100644 Task/Terminal-control-Coloured-text/BASIC/terminal-control-coloured-text-3.basic create mode 100644 Task/Terminal-control-Coloured-text/BASIC/terminal-control-coloured-text-4.basic create mode 100644 Task/Terminal-control-Coloured-text/BASIC/terminal-control-coloured-text-5.basic create mode 100644 Task/Terminal-control-Cursor-positioning/PHP/terminal-control-cursor-positioning.php rename Task/Terminal-control-Dimensions/Tcl/{terminal-control-dimensions.tcl => terminal-control-dimensions-1.tcl} (100%) create mode 100644 Task/Terminal-control-Dimensions/Tcl/terminal-control-dimensions-2.tcl create mode 100644 Task/Terminal-control-Inverse-video/BASIC/terminal-control-inverse-video-10.basic create mode 100644 Task/Terminal-control-Inverse-video/Ruby/terminal-control-inverse-video.rb create mode 100644 Task/Terminal-control-Ringing-the-terminal-bell/Rust/terminal-control-ringing-the-terminal-bell.rust create mode 100644 Task/Test-a-function/Crystal/test-a-function.crystal create mode 100644 Task/Test-a-function/Prolog/test-a-function.pro create mode 100644 Task/Thieles-interpolation-formula/Nim/thieles-interpolation-formula.nim create mode 100644 Task/Thieles-interpolation-formula/Perl/thieles-interpolation-formula.pl create mode 100644 Task/Tic-tac-toe/Lua/tic-tac-toe.lua create mode 100644 Task/Time-a-function/JavaScript/time-a-function.js create mode 100644 Task/Time-a-function/Pike/time-a-function.pike create mode 100644 Task/Time-a-function/Swift/time-a-function.swift create mode 100644 Task/Topswops/Factor/topswops.factor create mode 100644 Task/Topswops/Nim/topswops.nim create mode 100644 Task/Towers-of-Hanoi/BASIC/towers-of-hanoi-3.basic create mode 100644 Task/Towers-of-Hanoi/Clojure/towers-of-hanoi-1.clj create mode 100644 Task/Towers-of-Hanoi/Clojure/towers-of-hanoi-2.clj delete mode 100644 Task/Towers-of-Hanoi/Clojure/towers-of-hanoi.clj create mode 100644 Task/Towers-of-Hanoi/Frink/towers-of-hanoi.frink rename Task/Towers-of-Hanoi/Lua/{towers-of-hanoi.lua => towers-of-hanoi-1.lua} (100%) create mode 100644 Task/Towers-of-Hanoi/Lua/towers-of-hanoi-2.lua create mode 100644 Task/Towers-of-Hanoi/Lua/towers-of-hanoi-3.lua create mode 100644 Task/Truncatable-primes/C++/truncatable-primes.cpp create mode 100644 Task/Truncatable-primes/Pike/truncatable-primes.pike rename Task/Truncate-a-file/Perl-6/{truncate-a-file.pl6 => truncate-a-file-1.pl6} (100%) create mode 100644 Task/Truncate-a-file/Perl-6/truncate-a-file-2.pl6 create mode 100644 Task/URL-decoding/Pike/url-decoding.pike create mode 100644 Task/URL-encoding/Pike/url-encoding.pike create mode 100644 Task/Unicode-strings/Pike/unicode-strings.pike create mode 100644 Task/Unicode-variable-names/Ol/unicode-variable-names.ol create mode 100644 Task/Unicode-variable-names/Pike/unicode-variable-names.pike create mode 100644 Task/Universal-Turing-machine/C-sharp/universal-turing-machine.cs create mode 100644 Task/Universal-Turing-machine/MATLAB/universal-turing-machine.m create mode 100644 Task/Universal-Turing-machine/UNIX-Shell/universal-turing-machine.sh create mode 100644 Task/Unix-ls/Java/unix-ls-1.java create mode 100644 Task/Unix-ls/Java/unix-ls-2.java delete mode 100644 Task/Unix-ls/Java/unix-ls.java create mode 100644 Task/Unix-ls/Objeck/unix-ls.objeck create mode 100644 Task/Unix-ls/Pike/unix-ls.pike create mode 100644 Task/Unix-ls/R/unix-ls.r create mode 100644 Task/Update-a-configuration-file/PHP/update-a-configuration-file.php create mode 100644 Task/Use-another-language-to-call-a-function/Perl-6/use-another-language-to-call-a-function-1.pl6 create mode 100644 Task/Use-another-language-to-call-a-function/Perl-6/use-another-language-to-call-a-function-2.pl6 create mode 100644 Task/User-input-Text/Crystal/user-input-text.crystal create mode 100644 Task/User-input-Text/LOLCODE/user-input-text.lol create mode 100644 Task/Vampire-number/Rust/vampire-number.rust create mode 100644 Task/Variable-length-quantity/JavaScript/variable-length-quantity.js create mode 100644 Task/Variable-size-Get/Factor/variable-size-get.factor create mode 100644 Task/Variables/Clojure/variables-1.clj create mode 100644 Task/Variables/Clojure/variables-10.clj create mode 100644 Task/Variables/Clojure/variables-11.clj create mode 100644 Task/Variables/Clojure/variables-12.clj create mode 100644 Task/Variables/Clojure/variables-2.clj create mode 100644 Task/Variables/Clojure/variables-3.clj create mode 100644 Task/Variables/Clojure/variables-4.clj create mode 100644 Task/Variables/Clojure/variables-5.clj create mode 100644 Task/Variables/Clojure/variables-6.clj create mode 100644 Task/Variables/Clojure/variables-7.clj create mode 100644 Task/Variables/Clojure/variables-8.clj create mode 100644 Task/Variables/Clojure/variables-9.clj rename Task/Vector-products/Haskell/{vector-products.hs => vector-products-1.hs} (100%) create mode 100644 Task/Vector-products/Haskell/vector-products-2.hs rename Task/Vector-products/JavaScript/{vector-products.js => vector-products-1.js} (100%) create mode 100644 Task/Vector-products/JavaScript/vector-products-2.js create mode 100644 Task/Vector-products/Swift/vector-products.swift create mode 100644 Task/Verify-distribution-uniformity-Naive/Scala/verify-distribution-uniformity-naive-1.scala create mode 100644 Task/Verify-distribution-uniformity-Naive/Scala/verify-distribution-uniformity-naive-2.scala create mode 100644 Task/Vigen-re-cipher-Cryptanalysis/Perl-6/vigen-re-cipher-cryptanalysis.pl6 create mode 100644 Task/Vigen-re-cipher-Cryptanalysis/Perl/vigen-re-cipher-cryptanalysis.pl create mode 100644 Task/Vigen-re-cipher/Swift/vigen-re-cipher.swift create mode 100644 Task/Visualize-a-tree/Common-Lisp/visualize-a-tree-3.lisp create mode 100644 Task/Visualize-a-tree/Common-Lisp/visualize-a-tree-4.lisp create mode 100644 Task/Visualize-a-tree/Maple/visualize-a-tree.maple create mode 100644 Task/Voronoi-diagram/OCaml/voronoi-diagram.ocaml create mode 100644 Task/Voronoi-diagram/Red/voronoi-diagram.red create mode 100644 Task/Window-creation/Nim/window-creation-7.nim create mode 100644 Task/Write-float-arrays-to-a-text-file/Stata/write-float-arrays-to-a-text-file.stata create mode 100644 Task/Write-to-Windows-event-log/Perl-6/write-to-windows-event-log.pl6 create mode 100644 Task/XML-Input/MATLAB/xml-input.m create mode 100644 Task/XML-Input/Phix/xml-input.phix create mode 100644 Task/XML-Input/Rust/xml-input-1.rust create mode 100644 Task/XML-Input/Rust/xml-input-2.rust create mode 100644 Task/XML-Output/MATLAB/xml-output.m rename Task/XML-Output/Nim/{xml-output.nim => xml-output-1.nim} (72%) create mode 100644 Task/XML-Output/Nim/xml-output-2.nim create mode 100644 Task/XML-Output/XQuery/xml-output-1.xquery create mode 100644 Task/XML-Output/XQuery/xml-output-2.xquery create mode 100644 Task/XML-Output/XQuery/xml-output-3.xquery create mode 100644 Task/XML-Output/XQuery/xml-output-4.xquery create mode 100644 Task/XML-Output/XQuery/xml-output-5.xquery create mode 100644 Task/Y-combinator/C-sharp/y-combinator-1.cs create mode 100644 Task/Y-combinator/C-sharp/y-combinator-10.cs create mode 100644 Task/Y-combinator/C-sharp/y-combinator-11.cs create mode 100644 Task/Y-combinator/C-sharp/y-combinator-12.cs create mode 100644 Task/Y-combinator/C-sharp/y-combinator-13.cs create mode 100644 Task/Y-combinator/C-sharp/y-combinator-14.cs create mode 100644 Task/Y-combinator/C-sharp/y-combinator-15.cs create mode 100644 Task/Y-combinator/C-sharp/y-combinator-16.cs create mode 100644 Task/Y-combinator/C-sharp/y-combinator-17.cs create mode 100644 Task/Y-combinator/C-sharp/y-combinator-18.cs create mode 100644 Task/Y-combinator/C-sharp/y-combinator-19.cs create mode 100644 Task/Y-combinator/C-sharp/y-combinator-2.cs create mode 100644 Task/Y-combinator/C-sharp/y-combinator-3.cs create mode 100644 Task/Y-combinator/C-sharp/y-combinator-4.cs create mode 100644 Task/Y-combinator/C-sharp/y-combinator-5.cs create mode 100644 Task/Y-combinator/C-sharp/y-combinator-6.cs create mode 100644 Task/Y-combinator/C-sharp/y-combinator-7.cs create mode 100644 Task/Y-combinator/C-sharp/y-combinator-8.cs create mode 100644 Task/Y-combinator/C-sharp/y-combinator-9.cs create mode 100644 Task/Yahoo--search-interface/Go/yahoo--search-interface.go create mode 100644 Task/Yahoo--search-interface/Perl-6/yahoo--search-interface-1.pl6 create mode 100644 Task/Yahoo--search-interface/Perl-6/yahoo--search-interface-2.pl6 create mode 100644 Task/Zeckendorf-arithmetic/C/zeckendorf-arithmetic.c create mode 100644 Task/Zeckendorf-arithmetic/Visual-Basic-.NET/zeckendorf-arithmetic.visual create mode 100644 Task/Zero-to-the-zero-power/Crystal/zero-to-the-zero-power.crystal create mode 100644 Task/Zero-to-the-zero-power/Liberty-BASIC/zero-to-the-zero-power.liberty create mode 100644 Task/Zero-to-the-zero-power/Pike/zero-to-the-zero-power.pike create mode 100644 Task/Zero-to-the-zero-power/Pyret/zero-to-the-zero-power.pyret create mode 100644 Task/Zero-to-the-zero-power/XPL0/zero-to-the-zero-power.xpl0 rename Task/Zig-zag-matrix/Factor/{zig-zag-matrix.factor => zig-zag-matrix-1.factor} (100%) create mode 100644 Task/Zig-zag-matrix/Factor/zig-zag-matrix-2.factor create mode 100644 Task/Zig-zag-matrix/Nim/zig-zag-matrix-1.nim create mode 100644 Task/Zig-zag-matrix/Nim/zig-zag-matrix-2.nim delete mode 100644 Task/Zig-zag-matrix/Nim/zig-zag-matrix.nim create mode 100644 Task/Zig-zag-matrix/Octave/zig-zag-matrix-3.octave diff --git a/Lang/APL/Increment-a-numerical-string b/Lang/APL/Increment-a-numerical-string new file mode 120000 index 0000000000..f47b332237 --- /dev/null +++ b/Lang/APL/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/APL \ No newline at end of file diff --git a/Lang/AWK/Carmichael-3-strong-pseudoprimes b/Lang/AWK/Carmichael-3-strong-pseudoprimes new file mode 120000 index 0000000000..cf873d813f --- /dev/null +++ b/Lang/AWK/Carmichael-3-strong-pseudoprimes @@ -0,0 +1 @@ +../../Task/Carmichael-3-strong-pseudoprimes/AWK \ No newline at end of file diff --git a/Lang/AWK/Circles-of-given-radius-through-two-points b/Lang/AWK/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..8fb4e4c864 --- /dev/null +++ b/Lang/AWK/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/AWK \ No newline at end of file diff --git a/Lang/AWK/Colour-bars-Display b/Lang/AWK/Colour-bars-Display new file mode 120000 index 0000000000..96edb40710 --- /dev/null +++ b/Lang/AWK/Colour-bars-Display @@ -0,0 +1 @@ +../../Task/Colour-bars-Display/AWK \ No newline at end of file diff --git a/Lang/AWK/Dynamic-variable-names b/Lang/AWK/Dynamic-variable-names new file mode 120000 index 0000000000..dec8341181 --- /dev/null +++ b/Lang/AWK/Dynamic-variable-names @@ -0,0 +1 @@ +../../Task/Dynamic-variable-names/AWK \ No newline at end of file diff --git a/Lang/AWK/Gray-code b/Lang/AWK/Gray-code new file mode 120000 index 0000000000..b6f2cc2fa0 --- /dev/null +++ b/Lang/AWK/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/AWK \ No newline at end of file diff --git a/Lang/AWK/Greyscale-bars-Display b/Lang/AWK/Greyscale-bars-Display new file mode 120000 index 0000000000..24fef049b7 --- /dev/null +++ b/Lang/AWK/Greyscale-bars-Display @@ -0,0 +1 @@ +../../Task/Greyscale-bars-Display/AWK \ No newline at end of file diff --git a/Lang/AWK/Keyboard-input-Flush-the-keyboard-buffer b/Lang/AWK/Keyboard-input-Flush-the-keyboard-buffer new file mode 120000 index 0000000000..ad94510007 --- /dev/null +++ b/Lang/AWK/Keyboard-input-Flush-the-keyboard-buffer @@ -0,0 +1 @@ +../../Task/Keyboard-input-Flush-the-keyboard-buffer/AWK \ No newline at end of file diff --git a/Lang/AWK/Keyboard-input-Keypress-check b/Lang/AWK/Keyboard-input-Keypress-check new file mode 120000 index 0000000000..5ddf65e6c1 --- /dev/null +++ b/Lang/AWK/Keyboard-input-Keypress-check @@ -0,0 +1 @@ +../../Task/Keyboard-input-Keypress-check/AWK \ No newline at end of file diff --git a/Lang/AWK/Left-factorials b/Lang/AWK/Left-factorials new file mode 120000 index 0000000000..81afc1f039 --- /dev/null +++ b/Lang/AWK/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/AWK \ No newline at end of file diff --git a/Lang/AWK/Maximum-triangle-path-sum b/Lang/AWK/Maximum-triangle-path-sum new file mode 120000 index 0000000000..c6370c73fc --- /dev/null +++ b/Lang/AWK/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/AWK \ No newline at end of file diff --git a/Lang/AWK/Permutation-test b/Lang/AWK/Permutation-test new file mode 120000 index 0000000000..e59136514f --- /dev/null +++ b/Lang/AWK/Permutation-test @@ -0,0 +1 @@ +../../Task/Permutation-test/AWK \ No newline at end of file diff --git a/Lang/AWK/Permutations b/Lang/AWK/Permutations new file mode 120000 index 0000000000..f09db84aba --- /dev/null +++ b/Lang/AWK/Permutations @@ -0,0 +1 @@ +../../Task/Permutations/AWK \ No newline at end of file diff --git a/Lang/AWK/Pythagorean-triples b/Lang/AWK/Pythagorean-triples new file mode 120000 index 0000000000..d9e3ac1598 --- /dev/null +++ b/Lang/AWK/Pythagorean-triples @@ -0,0 +1 @@ +../../Task/Pythagorean-triples/AWK \ No newline at end of file diff --git a/Lang/AWK/Sudoku b/Lang/AWK/Sudoku new file mode 120000 index 0000000000..20df7af4f4 --- /dev/null +++ b/Lang/AWK/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/AWK \ No newline at end of file diff --git a/Lang/Ada/AKS-test-for-primes b/Lang/Ada/AKS-test-for-primes new file mode 120000 index 0000000000..d6c69a7010 --- /dev/null +++ b/Lang/Ada/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Ada \ No newline at end of file diff --git a/Lang/Ada/Brownian-tree b/Lang/Ada/Brownian-tree new file mode 120000 index 0000000000..1adc5afe8a --- /dev/null +++ b/Lang/Ada/Brownian-tree @@ -0,0 +1 @@ +../../Task/Brownian-tree/Ada \ No newline at end of file diff --git a/Lang/Ada/Colour-bars-Display b/Lang/Ada/Colour-bars-Display new file mode 120000 index 0000000000..e953957383 --- /dev/null +++ b/Lang/Ada/Colour-bars-Display @@ -0,0 +1 @@ +../../Task/Colour-bars-Display/Ada \ No newline at end of file diff --git a/Lang/Ada/Colour-pinstripe-Display b/Lang/Ada/Colour-pinstripe-Display new file mode 120000 index 0000000000..5d109a84af --- /dev/null +++ b/Lang/Ada/Colour-pinstripe-Display @@ -0,0 +1 @@ +../../Task/Colour-pinstripe-Display/Ada \ No newline at end of file diff --git a/Lang/Ada/Death-Star b/Lang/Ada/Death-Star new file mode 120000 index 0000000000..652f2e85e5 --- /dev/null +++ b/Lang/Ada/Death-Star @@ -0,0 +1 @@ +../../Task/Death-Star/Ada \ No newline at end of file diff --git a/Lang/Ada/Draw-a-clock b/Lang/Ada/Draw-a-clock new file mode 120000 index 0000000000..3ffd72ec37 --- /dev/null +++ b/Lang/Ada/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/Ada \ No newline at end of file diff --git a/Lang/Ada/Fractal-tree b/Lang/Ada/Fractal-tree new file mode 120000 index 0000000000..abaec23fc2 --- /dev/null +++ b/Lang/Ada/Fractal-tree @@ -0,0 +1 @@ +../../Task/Fractal-tree/Ada \ No newline at end of file diff --git a/Lang/Ada/Gaussian-elimination b/Lang/Ada/Gaussian-elimination new file mode 120000 index 0000000000..00285d005d --- /dev/null +++ b/Lang/Ada/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/Ada \ No newline at end of file diff --git a/Lang/Ada/Hickerson-series-of-almost-integers b/Lang/Ada/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..4569913cb4 --- /dev/null +++ b/Lang/Ada/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/Ada \ No newline at end of file diff --git a/Lang/Ada/Honeycombs b/Lang/Ada/Honeycombs new file mode 120000 index 0000000000..b514713b52 --- /dev/null +++ b/Lang/Ada/Honeycombs @@ -0,0 +1 @@ +../../Task/Honeycombs/Ada \ No newline at end of file diff --git a/Lang/Ada/Iterated-digits-squaring b/Lang/Ada/Iterated-digits-squaring new file mode 120000 index 0000000000..57898a1765 --- /dev/null +++ b/Lang/Ada/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Ada \ No newline at end of file diff --git a/Lang/Ada/Ludic-numbers b/Lang/Ada/Ludic-numbers new file mode 120000 index 0000000000..395f9ef6e5 --- /dev/null +++ b/Lang/Ada/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/Ada \ No newline at end of file diff --git a/Lang/Ada/MD4 b/Lang/Ada/MD4 new file mode 120000 index 0000000000..57aeb4ab8e --- /dev/null +++ b/Lang/Ada/MD4 @@ -0,0 +1 @@ +../../Task/MD4/Ada \ No newline at end of file diff --git a/Lang/Ada/Pinstripe-Display b/Lang/Ada/Pinstripe-Display new file mode 120000 index 0000000000..85b18093e0 --- /dev/null +++ b/Lang/Ada/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/Ada \ No newline at end of file diff --git a/Lang/Ada/RIPEMD-160 b/Lang/Ada/RIPEMD-160 new file mode 120000 index 0000000000..50bf341036 --- /dev/null +++ b/Lang/Ada/RIPEMD-160 @@ -0,0 +1 @@ +../../Task/RIPEMD-160/Ada \ No newline at end of file diff --git a/Lang/Ada/SHA-256 b/Lang/Ada/SHA-256 new file mode 120000 index 0000000000..c9aea14904 --- /dev/null +++ b/Lang/Ada/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Ada \ No newline at end of file diff --git a/Lang/Batch-File/Sorting-algorithms-Pancake-sort b/Lang/Batch-File/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..89658edde2 --- /dev/null +++ b/Lang/Batch-File/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Batch-File \ No newline at end of file diff --git a/Lang/Binary-Lambda-Calculus/Quine b/Lang/Binary-Lambda-Calculus/Quine new file mode 120000 index 0000000000..2c1595a394 --- /dev/null +++ b/Lang/Binary-Lambda-Calculus/Quine @@ -0,0 +1 @@ +../../Task/Quine/Binary-Lambda-Calculus \ No newline at end of file diff --git a/Lang/Bracmat/Function-composition b/Lang/Bracmat/Function-composition new file mode 120000 index 0000000000..094a7f93c1 --- /dev/null +++ b/Lang/Bracmat/Function-composition @@ -0,0 +1 @@ +../../Task/Function-composition/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Quine b/Lang/Bracmat/Quine new file mode 120000 index 0000000000..406793e6de --- /dev/null +++ b/Lang/Bracmat/Quine @@ -0,0 +1 @@ +../../Task/Quine/Bracmat \ No newline at end of file diff --git a/Lang/C++/00DESCRIPTION b/Lang/C++/00DESCRIPTION index 98b9c95c62..879e1a18cf 100644 --- a/Lang/C++/00DESCRIPTION +++ b/Lang/C++/00DESCRIPTION @@ -24,8 +24,8 @@ If you can't find an implementation for your task in the C++ category below, ple * '''TR1''' (Technical Report 1) is a proposal for extensions to the C++ standard library. It was published in 2007. Many of its proposals made it into C++11. Many compilers support it, but put its headers in a different directory. * '''C++11''' (formerly called '''C++0x''' and sometimes '''C++1x''') is a significant improvement, adding many new language features and libraries. It was standardized by ISO in 2011. Most of its features are available in [[GCC]] [http://gcc.gnu.org/projects/cxx0x.html] and [[Clang]] [http://clang.llvm.org/cxx_status.html]. * '''C++14''' (formerly called '''C++1y''') is a minor improvement to C++11, standardized by ISO in 2014. Most of its features are available in [[Clang]] [http://clang.llvm.org/cxx_status.html] and [[GCC]] [http://gcc.gnu.org/projects/cxx1y.html]. -* '''C++17''' (formerly called '''C++1z''') is a minor improvement to C++14, standardized by ISO in 2017. Most of its features are already available in [[Clang]] [http://clang.llvm.org/cxx_status.html] and [[GCC]] [https://gcc.gnu.org/projects/cxx-status.html#cxx17]. -* '''C++2a''' ('''C++20 ''' unofficially) is a major upcoming improvement to C++17 first drafted in July 2017. What proposed features it will have is currently partially implemented by [[Clang]] [http://clang.llvm.org/cxx_status.html] and [[GCC]] [https://gcc.gnu.org/projects/cxx-status.html#tses] +* '''C++17''' (formerly called '''C++1z''') is a minor improvement to C++14, standardized by ISO in 2017. Most of its features are available in [[Clang]] [http://clang.llvm.org/cxx_status.html] and [[GCC]] [https://gcc.gnu.org/projects/cxx-status.html#cxx17]. +* '''C++20''' (formerly called '''C++2a''') is a major upcoming improvement to C++17 first drafted in July 2017. What proposed features it will have is currently partially implemented by [[Clang]] [http://clang.llvm.org/cxx_status.html] and [[GCC]] [https://gcc.gnu.org/projects/cxx-status.html#tses] {{language programming paradigm|Imperative}} {{language programming paradigm|Object-oriented}} diff --git a/Lang/C++/K-d-tree b/Lang/C++/K-d-tree new file mode 120000 index 0000000000..97e750358e --- /dev/null +++ b/Lang/C++/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/C++ \ No newline at end of file diff --git a/Lang/C++/Parse-an-IP-Address b/Lang/C++/Parse-an-IP-Address new file mode 120000 index 0000000000..37d5d793bf --- /dev/null +++ b/Lang/C++/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/C++ \ No newline at end of file diff --git a/Lang/C++/Truncatable-primes b/Lang/C++/Truncatable-primes new file mode 120000 index 0000000000..2248c7c0fb --- /dev/null +++ b/Lang/C++/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/C++ \ No newline at end of file diff --git a/Lang/C-sharp/Define-a-primitive-data-type b/Lang/C-sharp/Define-a-primitive-data-type new file mode 120000 index 0000000000..01d6a8738c --- /dev/null +++ b/Lang/C-sharp/Define-a-primitive-data-type @@ -0,0 +1 @@ +../../Task/Define-a-primitive-data-type/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Enforced-immutability b/Lang/C-sharp/Enforced-immutability new file mode 120000 index 0000000000..382c1c44f4 --- /dev/null +++ b/Lang/C-sharp/Enforced-immutability @@ -0,0 +1 @@ +../../Task/Enforced-immutability/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Set-puzzle b/Lang/C-sharp/Set-puzzle new file mode 120000 index 0000000000..1d3a3cd12c --- /dev/null +++ b/Lang/C-sharp/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Universal-Turing-machine b/Lang/C-sharp/Universal-Turing-machine new file mode 120000 index 0000000000..913eb04ec7 --- /dev/null +++ b/Lang/C-sharp/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Y-combinator b/Lang/C-sharp/Y-combinator new file mode 120000 index 0000000000..e8f7c25fca --- /dev/null +++ b/Lang/C-sharp/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/C-sharp \ No newline at end of file diff --git a/Lang/C/00DESCRIPTION b/Lang/C/00DESCRIPTION index 5e993cdf2a..de57315be1 100644 --- a/Lang/C/00DESCRIPTION +++ b/Lang/C/00DESCRIPTION @@ -22,7 +22,9 @@ C has since spread to many other [[:Category:Platforms|platforms]], and is now o * '''C89''' (often called '''[[ANSI]] C''') is the version of C standardized by ANSI in 1989. It is the most commonly used and supported version of the language. * '''C90''' (often called '''[[ISO]] C''') is identical to C89, republished by ISO in 1990. * '''C99''' is a significant improvement, adopting many features of [[C++]] and standardizing common compiler extensions. It was standardized by ISO in 1999, and by ANSI in 2000. It is primarily supported by commercial C compilers, but most of its features are available in [[Clang]] [[GCC]]. [http://gcc.gnu.org/c99status.html] -* '''C11''' is the current standard, published in December 2011. It is the default for [[GCC]] as of version 5.1. +* '''C11''' is the previous standard, published in December 2011. It is the default for [[GCC]] as of version 5.1. +* '''C18''' is the current standard, published in June 2018. It is the default for [[GCC]] as of version 8.1. +* '''C2x''' is the upcoming standard, planned for a 2021 publication. [[GCC]] 9 and [[Clang]] 9 have preliminary support for it. ==Citation== *[[wp:C_%28programming_language%29|Wikipedia:C (programming language)]] diff --git a/Lang/C/Balanced-ternary b/Lang/C/Balanced-ternary new file mode 120000 index 0000000000..ab1ab242c0 --- /dev/null +++ b/Lang/C/Balanced-ternary @@ -0,0 +1 @@ +../../Task/Balanced-ternary/C \ No newline at end of file diff --git a/Lang/C/Call-a-foreign-language-function b/Lang/C/Call-a-foreign-language-function new file mode 120000 index 0000000000..f1fc741722 --- /dev/null +++ b/Lang/C/Call-a-foreign-language-function @@ -0,0 +1 @@ +../../Task/Call-a-foreign-language-function/C \ No newline at end of file diff --git a/Lang/C/Call-an-object-method b/Lang/C/Call-an-object-method new file mode 120000 index 0000000000..ace53a3d9c --- /dev/null +++ b/Lang/C/Call-an-object-method @@ -0,0 +1 @@ +../../Task/Call-an-object-method/C \ No newline at end of file diff --git a/Lang/C/Casting-out-nines b/Lang/C/Casting-out-nines new file mode 120000 index 0000000000..eaeeff1ae5 --- /dev/null +++ b/Lang/C/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/C \ No newline at end of file diff --git a/Lang/C/Inheritance-Multiple b/Lang/C/Inheritance-Multiple new file mode 120000 index 0000000000..f2cfc901e7 --- /dev/null +++ b/Lang/C/Inheritance-Multiple @@ -0,0 +1 @@ +../../Task/Inheritance-Multiple/C \ No newline at end of file diff --git a/Lang/C/RIPEMD-160 b/Lang/C/RIPEMD-160 new file mode 120000 index 0000000000..f4ac355a0a --- /dev/null +++ b/Lang/C/RIPEMD-160 @@ -0,0 +1 @@ +../../Task/RIPEMD-160/C \ No newline at end of file diff --git a/Lang/C/Zeckendorf-arithmetic b/Lang/C/Zeckendorf-arithmetic new file mode 120000 index 0000000000..f632e7de64 --- /dev/null +++ b/Lang/C/Zeckendorf-arithmetic @@ -0,0 +1 @@ +../../Task/Zeckendorf-arithmetic/C \ No newline at end of file diff --git a/Lang/COBOL/Count-the-coins b/Lang/COBOL/Count-the-coins new file mode 120000 index 0000000000..acf06817a2 --- /dev/null +++ b/Lang/COBOL/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Holidays-related-to-Easter b/Lang/COBOL/Holidays-related-to-Easter new file mode 120000 index 0000000000..35a02d6351 --- /dev/null +++ b/Lang/COBOL/Holidays-related-to-Easter @@ -0,0 +1 @@ +../../Task/Holidays-related-to-Easter/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Levenshtein-distance b/Lang/COBOL/Levenshtein-distance new file mode 120000 index 0000000000..07e5498b4f --- /dev/null +++ b/Lang/COBOL/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Parsing-RPN-calculator-algorithm b/Lang/COBOL/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..ae21d6e418 --- /dev/null +++ b/Lang/COBOL/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Read-a-configuration-file b/Lang/COBOL/Read-a-configuration-file new file mode 120000 index 0000000000..55c0e65280 --- /dev/null +++ b/Lang/COBOL/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Strip-comments-from-a-string b/Lang/COBOL/Strip-comments-from-a-string new file mode 120000 index 0000000000..0598bc1f7a --- /dev/null +++ b/Lang/COBOL/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/COBOL \ No newline at end of file diff --git a/Lang/Cache-ObjectScript/Empty-string b/Lang/Cache-ObjectScript/Empty-string new file mode 120000 index 0000000000..7d9975969d --- /dev/null +++ b/Lang/Cache-ObjectScript/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Cache-ObjectScript \ No newline at end of file diff --git a/Lang/Clojure/Rep-string b/Lang/Clojure/Rep-string new file mode 120000 index 0000000000..2ad1996e09 --- /dev/null +++ b/Lang/Clojure/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Variables b/Lang/Clojure/Variables new file mode 120000 index 0000000000..1e5eab462a --- /dev/null +++ b/Lang/Clojure/Variables @@ -0,0 +1 @@ +../../Task/Variables/Clojure \ No newline at end of file diff --git a/Lang/Commodore-BASIC/00DESCRIPTION b/Lang/Commodore-BASIC/00DESCRIPTION index f0149d0a1a..902e621b25 100644 --- a/Lang/Commodore-BASIC/00DESCRIPTION +++ b/Lang/Commodore-BASIC/00DESCRIPTION @@ -10,6 +10,6 @@ Commodore BASIC is notable for its lack of integer arithmetic; all operations we Programs were tokenized into [[wp:bytecode|bytecode]], although many characters were left intact to facilitate printing the source code back out in original form; it's one of the few BASICs of the time that preserved whitespace (though not leading whitespace). Unlike some contemporary BASICs, it supported arrays of strings, and arrays could have thousands of elements as long as there was sufficient memory for them (but strings were limited to 255 bytes). -The most well-known version is 2.0, which came with the [[wp:Commodore VIC-20|VIC-20]] and [[wp:Commodore 64|Commodore 64]]. Despite the impressive sound and graphics capabilities of the machines, the language had no support for them; machine code was required to take advantage of those features. Later BASIC versions added support, but the later machines that came with those versions never came close to the popularity of the 64. +The most well-known version is 2.0, which came with the [[wp:Commodore VIC-20|VIC-20]] and [[wp:Commodore 64|Commodore 64]]. Despite the impressive sound and graphics capabilities of the machines, the language had no unique commands for them. Instead, programmers had to directly manipulate or read the hardware registers with POKE and PEEK commands to take advantage of those features. Later BASIC versions added support, but the later machines that came with those versions never came close to the popularity of the 64. In addition to the sound and graphic statements, the later versions also introduced structured programming constructs: DO...LOOP, which supported both pre- and post-evaluated conditions (DO WHILE/UNTIL ... LOOP and DO ... LOOP WHILE/UNTIL) as well as unconditional loop exit (EXIT) and BEGIN...BEND code blocks, which allowed multi-line conditional clauses. However, other limitations remained: variables were still all global and limited to 2-letter names, user-defined functions were restricted to a single expression with a single argument, etc. \ No newline at end of file diff --git a/Lang/Commodore-BASIC/Count-the-coins b/Lang/Commodore-BASIC/Count-the-coins new file mode 120000 index 0000000000..9bd60d095e --- /dev/null +++ b/Lang/Commodore-BASIC/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/Commodore-BASIC \ No newline at end of file diff --git a/Lang/Commodore-BASIC/Joystick-position b/Lang/Commodore-BASIC/Joystick-position new file mode 120000 index 0000000000..2b8b032bdd --- /dev/null +++ b/Lang/Commodore-BASIC/Joystick-position @@ -0,0 +1 @@ +../../Task/Joystick-position/Commodore-BASIC \ No newline at end of file diff --git a/Lang/Commodore-BASIC/Number-names b/Lang/Commodore-BASIC/Number-names new file mode 120000 index 0000000000..0b0ce89716 --- /dev/null +++ b/Lang/Commodore-BASIC/Number-names @@ -0,0 +1 @@ +../../Task/Number-names/Commodore-BASIC \ No newline at end of file diff --git a/Lang/Crystal/Averages-Simple-moving-average b/Lang/Crystal/Averages-Simple-moving-average new file mode 120000 index 0000000000..5391145f0c --- /dev/null +++ b/Lang/Crystal/Averages-Simple-moving-average @@ -0,0 +1 @@ +../../Task/Averages-Simple-moving-average/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Exceptions-Catch-an-exception-thrown-in-a-nested-call b/Lang/Crystal/Exceptions-Catch-an-exception-thrown-in-a-nested-call new file mode 120000 index 0000000000..3a086b9beb --- /dev/null +++ b/Lang/Crystal/Exceptions-Catch-an-exception-thrown-in-a-nested-call @@ -0,0 +1 @@ +../../Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Factorial b/Lang/Crystal/Factorial new file mode 120000 index 0000000000..3fbcd8cc80 --- /dev/null +++ b/Lang/Crystal/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Handle-a-signal b/Lang/Crystal/Handle-a-signal new file mode 120000 index 0000000000..a590aeea1f --- /dev/null +++ b/Lang/Crystal/Handle-a-signal @@ -0,0 +1 @@ +../../Task/Handle-a-signal/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Hash-from-two-arrays b/Lang/Crystal/Hash-from-two-arrays new file mode 120000 index 0000000000..3e20da695f --- /dev/null +++ b/Lang/Crystal/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Hostname b/Lang/Crystal/Hostname new file mode 120000 index 0000000000..3063037f5c --- /dev/null +++ b/Lang/Crystal/Hostname @@ -0,0 +1 @@ +../../Task/Hostname/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Include-a-file b/Lang/Crystal/Include-a-file new file mode 120000 index 0000000000..79e1daf87c --- /dev/null +++ b/Lang/Crystal/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Knuth-shuffle b/Lang/Crystal/Knuth-shuffle new file mode 120000 index 0000000000..c5f8142b8c --- /dev/null +++ b/Lang/Crystal/Knuth-shuffle @@ -0,0 +1 @@ +../../Task/Knuth-shuffle/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Leap-year b/Lang/Crystal/Leap-year new file mode 120000 index 0000000000..305a9724a5 --- /dev/null +++ b/Lang/Crystal/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Loops-For b/Lang/Crystal/Loops-For new file mode 120000 index 0000000000..4d84d1b85a --- /dev/null +++ b/Lang/Crystal/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Pangram-checker b/Lang/Crystal/Pangram-checker new file mode 120000 index 0000000000..d4bf87640d --- /dev/null +++ b/Lang/Crystal/Pangram-checker @@ -0,0 +1 @@ +../../Task/Pangram-checker/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Remove-duplicate-elements b/Lang/Crystal/Remove-duplicate-elements new file mode 120000 index 0000000000..781fa7c46c --- /dev/null +++ b/Lang/Crystal/Remove-duplicate-elements @@ -0,0 +1 @@ +../../Task/Remove-duplicate-elements/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Sorting-algorithms-Bogosort b/Lang/Crystal/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..bd48ca550e --- /dev/null +++ b/Lang/Crystal/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Sorting-algorithms-Permutation-sort b/Lang/Crystal/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..d1149332b2 --- /dev/null +++ b/Lang/Crystal/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Sorting-algorithms-Selection-sort b/Lang/Crystal/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..30c9b05792 --- /dev/null +++ b/Lang/Crystal/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Stack b/Lang/Crystal/Stack new file mode 120000 index 0000000000..c7f400eb81 --- /dev/null +++ b/Lang/Crystal/Stack @@ -0,0 +1 @@ +../../Task/Stack/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Substring b/Lang/Crystal/Substring new file mode 120000 index 0000000000..b32da0c925 --- /dev/null +++ b/Lang/Crystal/Substring @@ -0,0 +1 @@ +../../Task/Substring/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Synchronous-concurrency b/Lang/Crystal/Synchronous-concurrency new file mode 120000 index 0000000000..25d801b8d6 --- /dev/null +++ b/Lang/Crystal/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Test-a-function b/Lang/Crystal/Test-a-function new file mode 120000 index 0000000000..d64483b318 --- /dev/null +++ b/Lang/Crystal/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Crystal \ No newline at end of file diff --git a/Lang/Crystal/User-input-Text b/Lang/Crystal/User-input-Text new file mode 120000 index 0000000000..56aca0437b --- /dev/null +++ b/Lang/Crystal/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Zero-to-the-zero-power b/Lang/Crystal/Zero-to-the-zero-power new file mode 120000 index 0000000000..6048a9bf1b --- /dev/null +++ b/Lang/Crystal/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Crystal \ No newline at end of file diff --git a/Lang/D/Determine-if-only-one-instance-is-running b/Lang/D/Determine-if-only-one-instance-is-running new file mode 120000 index 0000000000..0b96c0c8bc --- /dev/null +++ b/Lang/D/Determine-if-only-one-instance-is-running @@ -0,0 +1 @@ +../../Task/Determine-if-only-one-instance-is-running/D \ No newline at end of file diff --git a/Lang/Dart/9-billion-names-of-God-the-integer b/Lang/Dart/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..e437ba2e09 --- /dev/null +++ b/Lang/Dart/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/Dart \ No newline at end of file diff --git a/Lang/Dart/Comments b/Lang/Dart/Comments new file mode 120000 index 0000000000..b1406496d8 --- /dev/null +++ b/Lang/Dart/Comments @@ -0,0 +1 @@ +../../Task/Comments/Dart \ No newline at end of file diff --git a/Lang/Delphi/Almost-prime b/Lang/Delphi/Almost-prime new file mode 120000 index 0000000000..8a9a9466fd --- /dev/null +++ b/Lang/Delphi/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Delphi \ No newline at end of file diff --git a/Lang/Delphi/CRC-32 b/Lang/Delphi/CRC-32 new file mode 120000 index 0000000000..164ae1544c --- /dev/null +++ b/Lang/Delphi/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Last-Friday-of-each-month b/Lang/Delphi/Last-Friday-of-each-month new file mode 120000 index 0000000000..55022f7bc6 --- /dev/null +++ b/Lang/Delphi/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/Delphi \ No newline at end of file diff --git a/Lang/EDSAC-order-code/100-doors b/Lang/EDSAC-order-code/100-doors new file mode 120000 index 0000000000..8ee909163d --- /dev/null +++ b/Lang/EDSAC-order-code/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/EDSAC-order-code \ No newline at end of file diff --git a/Lang/EDSAC-order-code/Caesar-cipher b/Lang/EDSAC-order-code/Caesar-cipher new file mode 120000 index 0000000000..54bf923a06 --- /dev/null +++ b/Lang/EDSAC-order-code/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/EDSAC-order-code \ No newline at end of file diff --git a/Lang/EDSAC-order-code/Catalan-numbers b/Lang/EDSAC-order-code/Catalan-numbers new file mode 120000 index 0000000000..b0880fe690 --- /dev/null +++ b/Lang/EDSAC-order-code/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/EDSAC-order-code \ No newline at end of file diff --git a/Lang/EDSAC-order-code/Continued-fraction-Arithmetic-Construct-from-rational-number b/Lang/EDSAC-order-code/Continued-fraction-Arithmetic-Construct-from-rational-number new file mode 120000 index 0000000000..93599ba09c --- /dev/null +++ b/Lang/EDSAC-order-code/Continued-fraction-Arithmetic-Construct-from-rational-number @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-Construct-from-rational-number/EDSAC-order-code \ No newline at end of file diff --git a/Lang/EDSAC-order-code/Factors-of-an-integer b/Lang/EDSAC-order-code/Factors-of-an-integer new file mode 120000 index 0000000000..0d07ca870a --- /dev/null +++ b/Lang/EDSAC-order-code/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/EDSAC-order-code \ No newline at end of file diff --git a/Lang/EDSAC-order-code/Greatest-common-divisor b/Lang/EDSAC-order-code/Greatest-common-divisor new file mode 120000 index 0000000000..5a4bcefe57 --- /dev/null +++ b/Lang/EDSAC-order-code/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/EDSAC-order-code \ No newline at end of file diff --git a/Lang/EDSAC-order-code/Hailstone-sequence b/Lang/EDSAC-order-code/Hailstone-sequence new file mode 120000 index 0000000000..8e960ac7a2 --- /dev/null +++ b/Lang/EDSAC-order-code/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/EDSAC-order-code \ No newline at end of file diff --git a/Lang/EDSAC-order-code/Pangram-checker b/Lang/EDSAC-order-code/Pangram-checker new file mode 120000 index 0000000000..bbbfaf2fd3 --- /dev/null +++ b/Lang/EDSAC-order-code/Pangram-checker @@ -0,0 +1 @@ +../../Task/Pangram-checker/EDSAC-order-code \ No newline at end of file diff --git a/Lang/EDSAC-order-code/Pythagorean-triples b/Lang/EDSAC-order-code/Pythagorean-triples new file mode 120000 index 0000000000..898457e662 --- /dev/null +++ b/Lang/EDSAC-order-code/Pythagorean-triples @@ -0,0 +1 @@ +../../Task/Pythagorean-triples/EDSAC-order-code \ No newline at end of file diff --git a/Lang/EDSAC-order-code/Sorting-algorithms-Bubble-sort b/Lang/EDSAC-order-code/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..73bf8c67e3 --- /dev/null +++ b/Lang/EDSAC-order-code/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/EDSAC-order-code \ No newline at end of file diff --git a/Lang/Elixir/Read-a-specific-line-from-a-file b/Lang/Elixir/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..c9b4a188bb --- /dev/null +++ b/Lang/Elixir/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/Elixir \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Maze-generation b/Lang/Emacs-Lisp/Maze-generation new file mode 120000 index 0000000000..f85d21405f --- /dev/null +++ b/Lang/Emacs-Lisp/Maze-generation @@ -0,0 +1 @@ +../../Task/Maze-generation/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Maze-solving b/Lang/Emacs-Lisp/Maze-solving new file mode 120000 index 0000000000..134bcdd3d2 --- /dev/null +++ b/Lang/Emacs-Lisp/Maze-solving @@ -0,0 +1 @@ +../../Task/Maze-solving/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Sorting-algorithms-Sleep-sort b/Lang/Emacs-Lisp/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..f1fc52f852 --- /dev/null +++ b/Lang/Emacs-Lisp/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Emacs-Lisp \ No newline at end of file diff --git a/Lang/F-Sharp/CRC-32 b/Lang/F-Sharp/CRC-32 new file mode 120000 index 0000000000..340a74f8e4 --- /dev/null +++ b/Lang/F-Sharp/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/F-Sharp \ No newline at end of file diff --git a/Lang/Factor/9-billion-names-of-God-the-integer b/Lang/Factor/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..5a06b344d0 --- /dev/null +++ b/Lang/Factor/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/Factor \ No newline at end of file diff --git a/Lang/Factor/Average-loop-length b/Lang/Factor/Average-loop-length new file mode 120000 index 0000000000..67400e8828 --- /dev/null +++ b/Lang/Factor/Average-loop-length @@ -0,0 +1 @@ +../../Task/Average-loop-length/Factor \ No newline at end of file diff --git a/Lang/Factor/Box-the-compass b/Lang/Factor/Box-the-compass new file mode 120000 index 0000000000..e269ea4183 --- /dev/null +++ b/Lang/Factor/Box-the-compass @@ -0,0 +1 @@ +../../Task/Box-the-compass/Factor \ No newline at end of file diff --git a/Lang/Factor/Bulls-and-cows-Player b/Lang/Factor/Bulls-and-cows-Player new file mode 120000 index 0000000000..a8e9a4d9b9 --- /dev/null +++ b/Lang/Factor/Bulls-and-cows-Player @@ -0,0 +1 @@ +../../Task/Bulls-and-cows-Player/Factor \ No newline at end of file diff --git a/Lang/Factor/Carmichael-3-strong-pseudoprimes b/Lang/Factor/Carmichael-3-strong-pseudoprimes new file mode 120000 index 0000000000..93eaa8dde3 --- /dev/null +++ b/Lang/Factor/Carmichael-3-strong-pseudoprimes @@ -0,0 +1 @@ +../../Task/Carmichael-3-strong-pseudoprimes/Factor \ No newline at end of file diff --git a/Lang/Factor/Combinations-and-permutations b/Lang/Factor/Combinations-and-permutations new file mode 120000 index 0000000000..b23e151071 --- /dev/null +++ b/Lang/Factor/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/Factor \ No newline at end of file diff --git a/Lang/Factor/Constrained-random-points-on-a-circle b/Lang/Factor/Constrained-random-points-on-a-circle new file mode 120000 index 0000000000..4d633f691e --- /dev/null +++ b/Lang/Factor/Constrained-random-points-on-a-circle @@ -0,0 +1 @@ +../../Task/Constrained-random-points-on-a-circle/Factor \ No newline at end of file diff --git a/Lang/Factor/Deepcopy b/Lang/Factor/Deepcopy new file mode 120000 index 0000000000..36d947a9b9 --- /dev/null +++ b/Lang/Factor/Deepcopy @@ -0,0 +1 @@ +../../Task/Deepcopy/Factor \ No newline at end of file diff --git a/Lang/Factor/Doubly-linked-list-Element-definition b/Lang/Factor/Doubly-linked-list-Element-definition new file mode 120000 index 0000000000..1451f09d4c --- /dev/null +++ b/Lang/Factor/Doubly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Element-definition/Factor \ No newline at end of file diff --git a/Lang/Factor/Extensible-prime-generator b/Lang/Factor/Extensible-prime-generator new file mode 120000 index 0000000000..34c98b8745 --- /dev/null +++ b/Lang/Factor/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/Factor \ No newline at end of file diff --git a/Lang/Factor/First-class-environments b/Lang/Factor/First-class-environments new file mode 120000 index 0000000000..ee7f2c546c --- /dev/null +++ b/Lang/Factor/First-class-environments @@ -0,0 +1 @@ +../../Task/First-class-environments/Factor \ No newline at end of file diff --git a/Lang/Factor/Generate-Chess960-starting-position b/Lang/Factor/Generate-Chess960-starting-position new file mode 120000 index 0000000000..d846f342e8 --- /dev/null +++ b/Lang/Factor/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/Factor \ No newline at end of file diff --git a/Lang/Factor/Globally-replace-text-in-several-files b/Lang/Factor/Globally-replace-text-in-several-files new file mode 120000 index 0000000000..19ff2e0e93 --- /dev/null +++ b/Lang/Factor/Globally-replace-text-in-several-files @@ -0,0 +1 @@ +../../Task/Globally-replace-text-in-several-files/Factor \ No newline at end of file diff --git a/Lang/Factor/Hofstadter-Conway-$10,000-sequence b/Lang/Factor/Hofstadter-Conway-$10,000-sequence new file mode 120000 index 0000000000..13898a7054 --- /dev/null +++ b/Lang/Factor/Hofstadter-Conway-$10,000-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Conway-$10,000-sequence/Factor \ No newline at end of file diff --git a/Lang/Factor/Holidays-related-to-Easter b/Lang/Factor/Holidays-related-to-Easter new file mode 120000 index 0000000000..66c38e3a48 --- /dev/null +++ b/Lang/Factor/Holidays-related-to-Easter @@ -0,0 +1 @@ +../../Task/Holidays-related-to-Easter/Factor \ No newline at end of file diff --git a/Lang/Factor/Huffman-coding b/Lang/Factor/Huffman-coding new file mode 120000 index 0000000000..637bf24c91 --- /dev/null +++ b/Lang/Factor/Huffman-coding @@ -0,0 +1 @@ +../../Task/Huffman-coding/Factor \ No newline at end of file diff --git a/Lang/Factor/Multiplicative-order b/Lang/Factor/Multiplicative-order new file mode 120000 index 0000000000..3c7f1549a2 --- /dev/null +++ b/Lang/Factor/Multiplicative-order @@ -0,0 +1 @@ +../../Task/Multiplicative-order/Factor \ No newline at end of file diff --git a/Lang/Factor/Numeric-error-propagation b/Lang/Factor/Numeric-error-propagation new file mode 120000 index 0000000000..d0750a3c12 --- /dev/null +++ b/Lang/Factor/Numeric-error-propagation @@ -0,0 +1 @@ +../../Task/Numeric-error-propagation/Factor \ No newline at end of file diff --git a/Lang/Factor/Plot-coordinate-pairs b/Lang/Factor/Plot-coordinate-pairs new file mode 120000 index 0000000000..e83e0b79f9 --- /dev/null +++ b/Lang/Factor/Plot-coordinate-pairs @@ -0,0 +1 @@ +../../Task/Plot-coordinate-pairs/Factor \ No newline at end of file diff --git a/Lang/Factor/Queue-Definition b/Lang/Factor/Queue-Definition new file mode 120000 index 0000000000..2df1827965 --- /dev/null +++ b/Lang/Factor/Queue-Definition @@ -0,0 +1 @@ +../../Task/Queue-Definition/Factor \ No newline at end of file diff --git a/Lang/Factor/Ranking-methods b/Lang/Factor/Ranking-methods new file mode 120000 index 0000000000..15a4f7b2e4 --- /dev/null +++ b/Lang/Factor/Ranking-methods @@ -0,0 +1 @@ +../../Task/Ranking-methods/Factor \ No newline at end of file diff --git a/Lang/Factor/Roots-of-unity b/Lang/Factor/Roots-of-unity new file mode 120000 index 0000000000..e047c33c9b --- /dev/null +++ b/Lang/Factor/Roots-of-unity @@ -0,0 +1 @@ +../../Task/Roots-of-unity/Factor \ No newline at end of file diff --git a/Lang/Factor/Self-referential-sequence b/Lang/Factor/Self-referential-sequence new file mode 120000 index 0000000000..36b668e7ee --- /dev/null +++ b/Lang/Factor/Self-referential-sequence @@ -0,0 +1 @@ +../../Task/Self-referential-sequence/Factor \ No newline at end of file diff --git a/Lang/Factor/Set-consolidation b/Lang/Factor/Set-consolidation new file mode 120000 index 0000000000..26fa82ab6e --- /dev/null +++ b/Lang/Factor/Set-consolidation @@ -0,0 +1 @@ +../../Task/Set-consolidation/Factor \ No newline at end of file diff --git a/Lang/Factor/Set-puzzle b/Lang/Factor/Set-puzzle new file mode 120000 index 0000000000..ce46b9f12c --- /dev/null +++ b/Lang/Factor/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/Factor \ No newline at end of file diff --git a/Lang/Factor/Sierpinski-carpet b/Lang/Factor/Sierpinski-carpet new file mode 120000 index 0000000000..7d9f9aa62d --- /dev/null +++ b/Lang/Factor/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Factor \ No newline at end of file diff --git a/Lang/Factor/Sorting-algorithms-Cocktail-sort b/Lang/Factor/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..d29b1d1c11 --- /dev/null +++ b/Lang/Factor/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Factor \ No newline at end of file diff --git a/Lang/Factor/Sorting-algorithms-Selection-sort b/Lang/Factor/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..ec99115825 --- /dev/null +++ b/Lang/Factor/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Factor \ No newline at end of file diff --git a/Lang/Factor/Topswops b/Lang/Factor/Topswops new file mode 120000 index 0000000000..cd8e8c84f8 --- /dev/null +++ b/Lang/Factor/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/Factor \ No newline at end of file diff --git a/Lang/Factor/Variable-size-Get b/Lang/Factor/Variable-size-Get new file mode 120000 index 0000000000..014710b3f0 --- /dev/null +++ b/Lang/Factor/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/Factor \ No newline at end of file diff --git a/Lang/Forth/Maze-generation b/Lang/Forth/Maze-generation new file mode 120000 index 0000000000..bbd84047b4 --- /dev/null +++ b/Lang/Forth/Maze-generation @@ -0,0 +1 @@ +../../Task/Maze-generation/Forth \ No newline at end of file diff --git a/Lang/Fortran/QR-decomposition b/Lang/Fortran/QR-decomposition new file mode 120000 index 0000000000..0bb6efabdf --- /dev/null +++ b/Lang/Fortran/QR-decomposition @@ -0,0 +1 @@ +../../Task/QR-decomposition/Fortran \ No newline at end of file diff --git a/Lang/Frink/Abundant,-deficient-and-perfect-number-classifications b/Lang/Frink/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..e7b0bfe1bc --- /dev/null +++ b/Lang/Frink/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/Frink \ No newline at end of file diff --git a/Lang/Frink/Check-that-file-exists b/Lang/Frink/Check-that-file-exists new file mode 120000 index 0000000000..ca6223e692 --- /dev/null +++ b/Lang/Frink/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/Frink \ No newline at end of file diff --git a/Lang/Frink/Conways-Game-of-Life b/Lang/Frink/Conways-Game-of-Life new file mode 120000 index 0000000000..53726328db --- /dev/null +++ b/Lang/Frink/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/Frink \ No newline at end of file diff --git a/Lang/Frink/Copy-a-string b/Lang/Frink/Copy-a-string new file mode 120000 index 0000000000..494a3c5683 --- /dev/null +++ b/Lang/Frink/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/Frink \ No newline at end of file diff --git a/Lang/Frink/Fractal-tree b/Lang/Frink/Fractal-tree new file mode 120000 index 0000000000..755ad92c9d --- /dev/null +++ b/Lang/Frink/Fractal-tree @@ -0,0 +1 @@ +../../Task/Fractal-tree/Frink \ No newline at end of file diff --git a/Lang/Frink/Generate-lower-case-ASCII-alphabet b/Lang/Frink/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..0d641b4626 --- /dev/null +++ b/Lang/Frink/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Frink \ No newline at end of file diff --git a/Lang/Frink/Hostname b/Lang/Frink/Hostname new file mode 120000 index 0000000000..9220a3f145 --- /dev/null +++ b/Lang/Frink/Hostname @@ -0,0 +1 @@ +../../Task/Hostname/Frink \ No newline at end of file diff --git a/Lang/Frink/Josephus-problem b/Lang/Frink/Josephus-problem new file mode 120000 index 0000000000..a8789d3921 --- /dev/null +++ b/Lang/Frink/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Frink \ No newline at end of file diff --git a/Lang/Frink/Look-and-say-sequence b/Lang/Frink/Look-and-say-sequence new file mode 120000 index 0000000000..b459fd4f86 --- /dev/null +++ b/Lang/Frink/Look-and-say-sequence @@ -0,0 +1 @@ +../../Task/Look-and-say-sequence/Frink \ No newline at end of file diff --git a/Lang/Frink/Loop-over-multiple-arrays-simultaneously b/Lang/Frink/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..817a3e30b3 --- /dev/null +++ b/Lang/Frink/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/Frink \ No newline at end of file diff --git a/Lang/Frink/Lucas-Lehmer-test b/Lang/Frink/Lucas-Lehmer-test new file mode 120000 index 0000000000..6e582040bf --- /dev/null +++ b/Lang/Frink/Lucas-Lehmer-test @@ -0,0 +1 @@ +../../Task/Lucas-Lehmer-test/Frink \ No newline at end of file diff --git a/Lang/Frink/Mandelbrot-set b/Lang/Frink/Mandelbrot-set new file mode 120000 index 0000000000..f9576101c0 --- /dev/null +++ b/Lang/Frink/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/Frink \ No newline at end of file diff --git a/Lang/Frink/N-queens-problem b/Lang/Frink/N-queens-problem new file mode 120000 index 0000000000..0d08552fdc --- /dev/null +++ b/Lang/Frink/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Frink \ No newline at end of file diff --git a/Lang/Frink/Pascals-triangle b/Lang/Frink/Pascals-triangle new file mode 120000 index 0000000000..0d330c0cb8 --- /dev/null +++ b/Lang/Frink/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/Frink \ No newline at end of file diff --git a/Lang/Frink/Random-numbers b/Lang/Frink/Random-numbers new file mode 120000 index 0000000000..71aed7f61b --- /dev/null +++ b/Lang/Frink/Random-numbers @@ -0,0 +1 @@ +../../Task/Random-numbers/Frink \ No newline at end of file diff --git a/Lang/Frink/Roots-of-unity b/Lang/Frink/Roots-of-unity new file mode 120000 index 0000000000..259d965c3a --- /dev/null +++ b/Lang/Frink/Roots-of-unity @@ -0,0 +1 @@ +../../Task/Roots-of-unity/Frink \ No newline at end of file diff --git a/Lang/Frink/SHA-256 b/Lang/Frink/SHA-256 new file mode 120000 index 0000000000..cd8ca4e78f --- /dev/null +++ b/Lang/Frink/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Frink \ No newline at end of file diff --git a/Lang/Frink/Sieve-of-Eratosthenes b/Lang/Frink/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..ee76b15ee0 --- /dev/null +++ b/Lang/Frink/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Frink \ No newline at end of file diff --git a/Lang/Frink/String-length b/Lang/Frink/String-length new file mode 120000 index 0000000000..f5bf20d3bd --- /dev/null +++ b/Lang/Frink/String-length @@ -0,0 +1 @@ +../../Task/String-length/Frink \ No newline at end of file diff --git a/Lang/Frink/Sum-multiples-of-3-and-5 b/Lang/Frink/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..178d901465 --- /dev/null +++ b/Lang/Frink/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Frink \ No newline at end of file diff --git a/Lang/Frink/Sum-of-a-series b/Lang/Frink/Sum-of-a-series new file mode 120000 index 0000000000..e4a22a9203 --- /dev/null +++ b/Lang/Frink/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Frink \ No newline at end of file diff --git a/Lang/Frink/Towers-of-Hanoi b/Lang/Frink/Towers-of-Hanoi new file mode 120000 index 0000000000..1f8fa02419 --- /dev/null +++ b/Lang/Frink/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Frink \ No newline at end of file diff --git a/Lang/Gambas/Empty-program b/Lang/Gambas/Empty-program new file mode 120000 index 0000000000..9889b074a4 --- /dev/null +++ b/Lang/Gambas/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Quine b/Lang/Gambas/Quine new file mode 120000 index 0000000000..feae4b2f1f --- /dev/null +++ b/Lang/Gambas/Quine @@ -0,0 +1 @@ +../../Task/Quine/Gambas \ No newline at end of file diff --git a/Lang/Go/Boolean-values b/Lang/Go/Boolean-values new file mode 120000 index 0000000000..e240e1e0cd --- /dev/null +++ b/Lang/Go/Boolean-values @@ -0,0 +1 @@ +../../Task/Boolean-values/Go \ No newline at end of file diff --git a/Lang/Go/Call-a-function-in-a-shared-library b/Lang/Go/Call-a-function-in-a-shared-library new file mode 120000 index 0000000000..9e5fed13b1 --- /dev/null +++ b/Lang/Go/Call-a-function-in-a-shared-library @@ -0,0 +1 @@ +../../Task/Call-a-function-in-a-shared-library/Go \ No newline at end of file diff --git a/Lang/Go/Catmull-Clark-subdivision-surface b/Lang/Go/Catmull-Clark-subdivision-surface new file mode 120000 index 0000000000..5184e15f6e --- /dev/null +++ b/Lang/Go/Catmull-Clark-subdivision-surface @@ -0,0 +1 @@ +../../Task/Catmull-Clark-subdivision-surface/Go \ No newline at end of file diff --git a/Lang/Go/Executable-library b/Lang/Go/Executable-library new file mode 120000 index 0000000000..ce73fa9d7a --- /dev/null +++ b/Lang/Go/Executable-library @@ -0,0 +1 @@ +../../Task/Executable-library/Go \ No newline at end of file diff --git a/Lang/Go/Include-a-file b/Lang/Go/Include-a-file new file mode 120000 index 0000000000..ad4a0d9560 --- /dev/null +++ b/Lang/Go/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/Go \ No newline at end of file diff --git a/Lang/Go/Yahoo--search-interface b/Lang/Go/Yahoo--search-interface new file mode 120000 index 0000000000..5b35ab8222 --- /dev/null +++ b/Lang/Go/Yahoo--search-interface @@ -0,0 +1 @@ +../../Task/Yahoo--search-interface/Go \ No newline at end of file diff --git a/Lang/Groovy/Arithmetic-geometric-mean-Calculate-Pi b/Lang/Groovy/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..85af23e568 --- /dev/null +++ b/Lang/Groovy/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Kaprekar-numbers b/Lang/Groovy/Kaprekar-numbers new file mode 120000 index 0000000000..90c36aa02f --- /dev/null +++ b/Lang/Groovy/Kaprekar-numbers @@ -0,0 +1 @@ +../../Task/Kaprekar-numbers/Groovy \ No newline at end of file diff --git a/Lang/Harbour/Bitwise-operations b/Lang/Harbour/Bitwise-operations new file mode 120000 index 0000000000..1dd34daf32 --- /dev/null +++ b/Lang/Harbour/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/Harbour \ No newline at end of file diff --git a/Lang/Haxe/CRC-32 b/Lang/Haxe/CRC-32 new file mode 120000 index 0000000000..81ac134326 --- /dev/null +++ b/Lang/Haxe/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Factorial b/Lang/Haxe/Factorial new file mode 120000 index 0000000000..16f06915ba --- /dev/null +++ b/Lang/Haxe/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Loops-Break b/Lang/Haxe/Loops-Break new file mode 120000 index 0000000000..8e987da95e --- /dev/null +++ b/Lang/Haxe/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Loops-Continue b/Lang/Haxe/Loops-Continue new file mode 120000 index 0000000000..0f17531675 --- /dev/null +++ b/Lang/Haxe/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Loops-Do-while b/Lang/Haxe/Loops-Do-while new file mode 120000 index 0000000000..975836763c --- /dev/null +++ b/Lang/Haxe/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Loops-Downward-for b/Lang/Haxe/Loops-Downward-for new file mode 120000 index 0000000000..cf9c14593c --- /dev/null +++ b/Lang/Haxe/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Loops-For-with-a-specified-step b/Lang/Haxe/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..302472a0b1 --- /dev/null +++ b/Lang/Haxe/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Loops-Infinite b/Lang/Haxe/Loops-Infinite new file mode 120000 index 0000000000..7a8b4c5aa7 --- /dev/null +++ b/Lang/Haxe/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Loops-N-plus-one-half b/Lang/Haxe/Loops-N-plus-one-half new file mode 120000 index 0000000000..98cb3b1817 --- /dev/null +++ b/Lang/Haxe/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Loops-While b/Lang/Haxe/Loops-While new file mode 120000 index 0000000000..6136a53529 --- /dev/null +++ b/Lang/Haxe/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Haxe \ No newline at end of file diff --git a/Lang/Haxe/MD5 b/Lang/Haxe/MD5 new file mode 120000 index 0000000000..64acd7656a --- /dev/null +++ b/Lang/Haxe/MD5 @@ -0,0 +1 @@ +../../Task/MD5/Haxe \ No newline at end of file diff --git a/Lang/Haxe/SHA-1 b/Lang/Haxe/SHA-1 new file mode 120000 index 0000000000..31dd24a8f9 --- /dev/null +++ b/Lang/Haxe/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Haxe \ No newline at end of file diff --git a/Lang/Haxe/SHA-256 b/Lang/Haxe/SHA-256 new file mode 120000 index 0000000000..3b16087a27 --- /dev/null +++ b/Lang/Haxe/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Sorting-algorithms-Bubble-sort b/Lang/Haxe/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..652873f00b --- /dev/null +++ b/Lang/Haxe/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Sorting-algorithms-Cocktail-sort b/Lang/Haxe/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..8f643190d4 --- /dev/null +++ b/Lang/Haxe/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Sorting-algorithms-Comb-sort b/Lang/Haxe/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..6f4481511f --- /dev/null +++ b/Lang/Haxe/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Sorting-algorithms-Counting-sort b/Lang/Haxe/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..61ec74efdf --- /dev/null +++ b/Lang/Haxe/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Sorting-algorithms-Gnome-sort b/Lang/Haxe/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..bfa468d5b9 --- /dev/null +++ b/Lang/Haxe/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Sorting-algorithms-Heapsort b/Lang/Haxe/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..470840b944 --- /dev/null +++ b/Lang/Haxe/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Sorting-algorithms-Insertion-sort b/Lang/Haxe/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..f63dd7204a --- /dev/null +++ b/Lang/Haxe/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Sorting-algorithms-Pancake-sort b/Lang/Haxe/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..cacb37656f --- /dev/null +++ b/Lang/Haxe/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Sorting-algorithms-Shell-sort b/Lang/Haxe/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..e6b3397810 --- /dev/null +++ b/Lang/Haxe/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Haxe \ No newline at end of file diff --git a/Lang/Haxe/String-interpolation--included- b/Lang/Haxe/String-interpolation--included- new file mode 120000 index 0000000000..950bb9d339 --- /dev/null +++ b/Lang/Haxe/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Sum-of-a-series b/Lang/Haxe/Sum-of-a-series new file mode 120000 index 0000000000..bc555fd411 --- /dev/null +++ b/Lang/Haxe/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Haxe \ No newline at end of file diff --git a/Lang/Idris/Quaternion-type b/Lang/Idris/Quaternion-type new file mode 120000 index 0000000000..6489466168 --- /dev/null +++ b/Lang/Idris/Quaternion-type @@ -0,0 +1 @@ +../../Task/Quaternion-type/Idris \ No newline at end of file diff --git a/Lang/J/00DESCRIPTION b/Lang/J/00DESCRIPTION index 76c6c4533a..70d37ec67b 100644 --- a/Lang/J/00DESCRIPTION +++ b/Lang/J/00DESCRIPTION @@ -37,7 +37,7 @@ J is meant to be read with the aid of a computer. J sentences are single lines a When learning how a J sentence works, you can also try simpler sentences with the same data or perhaps related data. When trying to understand contexts that use large data structures, it can often be wise to investigate small, representative samples until you understand how the code works. -Unless you attend an institution which has made a J interpreter available to you through your web browser (or preinstalled on your machine), if you want to see how J works you should probably [http://www.jsoftware.com/stable.htm install] a copy of J -- or you can try one of the "try me" links, below. +Unless you attend an institution which has made a J interpreter available to you through your web browser (or preinstalled on your machine), if you want to see how J works you should probably [https://code.jsoftware.com/wiki/System/Installation install] a copy of J -- or you can try one of the "try me" links, below. If you want to understand how to experiment with alternative expressions you should probably also be studying some of its [[j:Guides/Getting%20Started#Documentation|documentation]]. For example, the phrase (+/ % #) finds the average of a list of numbers. @@ -104,7 +104,7 @@ If you want to be a bit more interactive, and get some guidance from J gurus, yo If you don't have an IRC client you can try [http://webchat.freenode.net/?randomnick=1&channels=jsoftware freenode's web interface] (or just [http://webchat.freenode.net/?channels=jsoftware&randomnick=1 give it a quick spin]). More [[j:Community/IRC|details about the J IRC community]] is available. -If any of that piques your interest, and you want to explore a little more, you can [http://www.jsoftware.com/stable.htm download J] and [http://www.jsoftware.com/forums.htm join the J forums]. +If any of that piques your interest, and you want to explore a little more, you can [http://www.jsoftware.com/ download J] and [http://www.jsoftware.com/forums.htm join the J forums]. If you have problems executing any of the J code here on Rosetta, please make a note of it either on the task page itself, on the talk page, or on the appropriate [http://forums.jsoftware.com J forum], whichever is best. It might be that there's a version dependency that needs to be documented, or you might have found an actual bug. diff --git a/Lang/Java/00DESCRIPTION b/Lang/Java/00DESCRIPTION index da0fb3b0fe..72a980a538 100644 --- a/Lang/Java/00DESCRIPTION +++ b/Lang/Java/00DESCRIPTION @@ -38,7 +38,6 @@ According to some [http://www.tiobe.com/tpci.htm sources], Java is currently one Useful Java links: * [http://www.java.com java.com] -* [http://www.java.net java.net] * [http://openjdk.java.net OpenJDK] ==Todo== diff --git a/Lang/Java/Bulls-and-cows-Player b/Lang/Java/Bulls-and-cows-Player new file mode 120000 index 0000000000..83ee5361d5 --- /dev/null +++ b/Lang/Java/Bulls-and-cows-Player @@ -0,0 +1 @@ +../../Task/Bulls-and-cows-Player/Java \ No newline at end of file diff --git a/Lang/Java/Check-Machin-like-formulas b/Lang/Java/Check-Machin-like-formulas new file mode 120000 index 0000000000..068370b6ca --- /dev/null +++ b/Lang/Java/Check-Machin-like-formulas @@ -0,0 +1 @@ +../../Task/Check-Machin-like-formulas/Java \ No newline at end of file diff --git a/Lang/Java/Combinations-and-permutations b/Lang/Java/Combinations-and-permutations new file mode 120000 index 0000000000..df7251ff25 --- /dev/null +++ b/Lang/Java/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/Java \ No newline at end of file diff --git a/Lang/Java/Doubly-linked-list-Definition b/Lang/Java/Doubly-linked-list-Definition new file mode 120000 index 0000000000..a11bc1f3b4 --- /dev/null +++ b/Lang/Java/Doubly-linked-list-Definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Definition/Java \ No newline at end of file diff --git a/Lang/Java/Doubly-linked-list-Element-insertion b/Lang/Java/Doubly-linked-list-Element-insertion new file mode 120000 index 0000000000..d421a69272 --- /dev/null +++ b/Lang/Java/Doubly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Element-insertion/Java \ No newline at end of file diff --git a/Lang/Java/Pascals-triangle-Puzzle b/Lang/Java/Pascals-triangle-Puzzle new file mode 120000 index 0000000000..e706b60def --- /dev/null +++ b/Lang/Java/Pascals-triangle-Puzzle @@ -0,0 +1 @@ +../../Task/Pascals-triangle-Puzzle/Java \ No newline at end of file diff --git a/Lang/JavaScript/Benfords-law b/Lang/JavaScript/Benfords-law new file mode 120000 index 0000000000..a29de7daa0 --- /dev/null +++ b/Lang/JavaScript/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Cholesky-decomposition b/Lang/JavaScript/Cholesky-decomposition new file mode 120000 index 0000000000..d5539c77ce --- /dev/null +++ b/Lang/JavaScript/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Numerical-integration-Gauss-Legendre-Quadrature b/Lang/JavaScript/Numerical-integration-Gauss-Legendre-Quadrature new file mode 120000 index 0000000000..c5999e01b4 --- /dev/null +++ b/Lang/JavaScript/Numerical-integration-Gauss-Legendre-Quadrature @@ -0,0 +1 @@ +../../Task/Numerical-integration-Gauss-Legendre-Quadrature/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/SHA-256 b/Lang/JavaScript/SHA-256 new file mode 120000 index 0000000000..ad4005ecc7 --- /dev/null +++ b/Lang/JavaScript/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Time-a-function b/Lang/JavaScript/Time-a-function new file mode 120000 index 0000000000..d9af048e1b --- /dev/null +++ b/Lang/JavaScript/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Variable-length-quantity b/Lang/JavaScript/Variable-length-quantity new file mode 120000 index 0000000000..385aa75382 --- /dev/null +++ b/Lang/JavaScript/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/JavaScript \ No newline at end of file diff --git a/Lang/Julia/Catmull-Clark-subdivision-surface b/Lang/Julia/Catmull-Clark-subdivision-surface new file mode 120000 index 0000000000..f4d643a025 --- /dev/null +++ b/Lang/Julia/Catmull-Clark-subdivision-surface @@ -0,0 +1 @@ +../../Task/Catmull-Clark-subdivision-surface/Julia \ No newline at end of file diff --git a/Lang/Julia/SOAP b/Lang/Julia/SOAP new file mode 120000 index 0000000000..a1b9cc2a5f --- /dev/null +++ b/Lang/Julia/SOAP @@ -0,0 +1 @@ +../../Task/SOAP/Julia \ No newline at end of file diff --git a/Lang/LOLCODE/Arrays b/Lang/LOLCODE/Arrays new file mode 120000 index 0000000000..89154a462e --- /dev/null +++ b/Lang/LOLCODE/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Comments b/Lang/LOLCODE/Comments new file mode 120000 index 0000000000..229c4becf5 --- /dev/null +++ b/Lang/LOLCODE/Comments @@ -0,0 +1 @@ +../../Task/Comments/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/Even-or-odd b/Lang/LOLCODE/Even-or-odd new file mode 120000 index 0000000000..6b6a9a055c --- /dev/null +++ b/Lang/LOLCODE/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/LOLCODE \ No newline at end of file diff --git a/Lang/LOLCODE/User-input-Text b/Lang/LOLCODE/User-input-Text new file mode 120000 index 0000000000..f07cf7f73e --- /dev/null +++ b/Lang/LOLCODE/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/LOLCODE \ No newline at end of file diff --git a/Lang/Lambdatalk/Matrix-multiplication b/Lang/Lambdatalk/Matrix-multiplication new file mode 120000 index 0000000000..2da680738a --- /dev/null +++ b/Lang/Lambdatalk/Matrix-multiplication @@ -0,0 +1 @@ +../../Task/Matrix-multiplication/Lambdatalk \ No newline at end of file diff --git a/Lang/Lambdatalk/Mutual-recursion b/Lang/Lambdatalk/Mutual-recursion new file mode 120000 index 0000000000..4c9497cf18 --- /dev/null +++ b/Lang/Lambdatalk/Mutual-recursion @@ -0,0 +1 @@ +../../Task/Mutual-recursion/Lambdatalk \ No newline at end of file diff --git a/Lang/Lambdatalk/Prime-decomposition b/Lang/Lambdatalk/Prime-decomposition new file mode 120000 index 0000000000..7403269ad5 --- /dev/null +++ b/Lang/Lambdatalk/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/Lambdatalk \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Calendar b/Lang/Liberty-BASIC/Calendar new file mode 120000 index 0000000000..59338ff7ff --- /dev/null +++ b/Lang/Liberty-BASIC/Calendar @@ -0,0 +1 @@ +../../Task/Calendar/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Grayscale-image b/Lang/Liberty-BASIC/Grayscale-image new file mode 120000 index 0000000000..258e09c47a --- /dev/null +++ b/Lang/Liberty-BASIC/Grayscale-image @@ -0,0 +1 @@ +../../Task/Grayscale-image/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Number-names b/Lang/Liberty-BASIC/Number-names new file mode 120000 index 0000000000..6c820007e4 --- /dev/null +++ b/Lang/Liberty-BASIC/Number-names @@ -0,0 +1 @@ +../../Task/Number-names/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Liberty-BASIC/Zero-to-the-zero-power b/Lang/Liberty-BASIC/Zero-to-the-zero-power new file mode 120000 index 0000000000..430b5d2f0f --- /dev/null +++ b/Lang/Liberty-BASIC/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Lobster/00DESCRIPTION b/Lang/Lobster/00DESCRIPTION index 4e7d54dc2d..5fae424261 100644 --- a/Lang/Lobster/00DESCRIPTION +++ b/Lang/Lobster/00DESCRIPTION @@ -1,5 +1,8 @@ {{language|Lobster -|site=http://strlen.com/lobster}} +|site=http://strlen.com/lobster +|gc=yes +|checking=static +|strength=strong}} '''Lobster''' is a general purpose programming language originally created for programming games. It has a [[Python]]-like syntax, with a static type system that feels like dynamic typing thanks to flow-sensitive type inference and specialization. It has lightweight anonymous functions, encouraging every function to look like a built-in control structure. Additionally it has vector operations, multi-methods, coroutines and immutable types. It is currently implemented as a bytecode VM that runs on all desktop and mobile platforms (through SDL), and comes with built-in functionality for easy access to OpenGL, FreeType etc. \ No newline at end of file diff --git a/Lang/Lobster/Chinese-remainder-theorem b/Lang/Lobster/Chinese-remainder-theorem new file mode 120000 index 0000000000..2d582ff07e --- /dev/null +++ b/Lang/Lobster/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/Lobster \ No newline at end of file diff --git a/Lang/Lobster/Cholesky-decomposition b/Lang/Lobster/Cholesky-decomposition new file mode 120000 index 0000000000..ff5d3e3927 --- /dev/null +++ b/Lang/Lobster/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/Lobster \ No newline at end of file diff --git a/Lang/Lobster/Combinations b/Lang/Lobster/Combinations new file mode 120000 index 0000000000..dd6d8c7d84 --- /dev/null +++ b/Lang/Lobster/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/Lobster \ No newline at end of file diff --git a/Lang/Lobster/Combinations-with-repetitions b/Lang/Lobster/Combinations-with-repetitions new file mode 120000 index 0000000000..95808701ff --- /dev/null +++ b/Lang/Lobster/Combinations-with-repetitions @@ -0,0 +1 @@ +../../Task/Combinations-with-repetitions/Lobster \ No newline at end of file diff --git a/Lang/Lobster/Gray-code b/Lang/Lobster/Gray-code new file mode 120000 index 0000000000..042c05720d --- /dev/null +++ b/Lang/Lobster/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/Lobster \ No newline at end of file diff --git a/Lang/Lobster/IBAN b/Lang/Lobster/IBAN new file mode 120000 index 0000000000..8052e4e2d5 --- /dev/null +++ b/Lang/Lobster/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Lobster \ No newline at end of file diff --git a/Lang/Lobster/LU-decomposition b/Lang/Lobster/LU-decomposition new file mode 120000 index 0000000000..9b691f497a --- /dev/null +++ b/Lang/Lobster/LU-decomposition @@ -0,0 +1 @@ +../../Task/LU-decomposition/Lobster \ No newline at end of file diff --git a/Lang/Lobster/Levenshtein-distance b/Lang/Lobster/Levenshtein-distance new file mode 120000 index 0000000000..0c4bb84ce2 --- /dev/null +++ b/Lang/Lobster/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Lobster \ No newline at end of file diff --git a/Lang/Lobster/Long-multiplication b/Lang/Lobster/Long-multiplication new file mode 120000 index 0000000000..07044afe53 --- /dev/null +++ b/Lang/Lobster/Long-multiplication @@ -0,0 +1 @@ +../../Task/Long-multiplication/Lobster \ No newline at end of file diff --git a/Lang/Lobster/Permutations b/Lang/Lobster/Permutations new file mode 120000 index 0000000000..90e01f08a5 --- /dev/null +++ b/Lang/Lobster/Permutations @@ -0,0 +1 @@ +../../Task/Permutations/Lobster \ No newline at end of file diff --git a/Lang/Lobster/Random-numbers b/Lang/Lobster/Random-numbers new file mode 120000 index 0000000000..204fe90117 --- /dev/null +++ b/Lang/Lobster/Random-numbers @@ -0,0 +1 @@ +../../Task/Random-numbers/Lobster \ No newline at end of file diff --git a/Lang/Lobster/Sorting-algorithms-Heapsort b/Lang/Lobster/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..62de40c364 --- /dev/null +++ b/Lang/Lobster/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Lobster \ No newline at end of file diff --git a/Lang/Lua/00DESCRIPTION b/Lang/Lua/00DESCRIPTION index aee873525c..a5d49c631e 100644 --- a/Lang/Lua/00DESCRIPTION +++ b/Lang/Lua/00DESCRIPTION @@ -48,7 +48,6 @@ Lua has 355 unimplemented programming tasks: Atomic updates Average loop length Balanced ternary - Bernoulli numbers Best shuffle Bitcoin/address validation Bitcoin/public point to address @@ -158,7 +157,6 @@ Lua has 355 unimplemented programming tasks: History variables Hofstadter Figure-Figure sequences Hofstadter Q sequence - Hofstadter-Conway $10,000 sequence Honeycombs Horizontal sundial calculations Host introspection @@ -344,7 +342,6 @@ Lua has 355 unimplemented programming tasks: The ISAAC Cipher The Name Game Thiele's interpolation formula - Tic-tac-toe Topic variable Topological sort Total circles area diff --git a/Lang/Lua/Bernoulli-numbers b/Lang/Lua/Bernoulli-numbers new file mode 120000 index 0000000000..aff3133751 --- /dev/null +++ b/Lang/Lua/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/Lua \ No newline at end of file diff --git a/Lang/Lua/Continued-fraction b/Lang/Lua/Continued-fraction new file mode 120000 index 0000000000..7ee4008785 --- /dev/null +++ b/Lang/Lua/Continued-fraction @@ -0,0 +1 @@ +../../Task/Continued-fraction/Lua \ No newline at end of file diff --git a/Lang/Lua/MD5-Implementation b/Lang/Lua/MD5-Implementation new file mode 120000 index 0000000000..949410dd56 --- /dev/null +++ b/Lang/Lua/MD5-Implementation @@ -0,0 +1 @@ +../../Task/MD5-Implementation/Lua \ No newline at end of file diff --git a/Lang/Lua/Sierpinski-triangle b/Lang/Lua/Sierpinski-triangle new file mode 120000 index 0000000000..2937410a14 --- /dev/null +++ b/Lang/Lua/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/Lua \ No newline at end of file diff --git a/Lang/Lua/Tic-tac-toe b/Lang/Lua/Tic-tac-toe new file mode 120000 index 0000000000..74c52cd051 --- /dev/null +++ b/Lang/Lua/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Lua \ No newline at end of file diff --git a/Lang/MAPPER/00DESCRIPTION b/Lang/MAPPER/00DESCRIPTION index 917d77c8ef..ac0ac7ec31 100644 --- a/Lang/MAPPER/00DESCRIPTION +++ b/Lang/MAPPER/00DESCRIPTION @@ -9,7 +9,7 @@ |exec=interpreted}} -MAPPER (also more recently known as BIS) was originally a product of the Sperry Corporation and was a mainframe product implemented on the Sperry 1100 systems. +MAPPER (also more recently known as BIS) was originally a product of the Sperry Corporation and was a mainframe product implemented on the Sperry 1100 systems. It was designed by Louis Schlueter in 1968. It was the first spread sheet with 150 user functions to process data. The run script language was created in the early 70's as the first Macros. In the 80's it was called a 4GL and was also the first major programming language that was easy to learn. Many of the manual function users became Run Designers and developed their own applications. This eliminates the need for the Data Processing (Programmers) Department. After the merger of Sperry and Burroughs to create the Unisys Corporation, MAPPER was implemented on additional platforms, and is today available on diff --git a/Lang/MATLAB/Amicable-pairs b/Lang/MATLAB/Amicable-pairs new file mode 120000 index 0000000000..cb7e084353 --- /dev/null +++ b/Lang/MATLAB/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Universal-Turing-machine b/Lang/MATLAB/Universal-Turing-machine new file mode 120000 index 0000000000..3b0dee0097 --- /dev/null +++ b/Lang/MATLAB/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/XML-Input b/Lang/MATLAB/XML-Input new file mode 120000 index 0000000000..40d3c1901b --- /dev/null +++ b/Lang/MATLAB/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/XML-Output b/Lang/MATLAB/XML-Output new file mode 120000 index 0000000000..243b775aa6 --- /dev/null +++ b/Lang/MATLAB/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/MATLAB \ No newline at end of file diff --git a/Lang/MSX-Basic/00DESCRIPTION b/Lang/MSX-Basic/00DESCRIPTION index b32f20e269..0cdbced1f6 100644 --- a/Lang/MSX-Basic/00DESCRIPTION +++ b/Lang/MSX-Basic/00DESCRIPTION @@ -18,8 +18,8 @@ MSX BASIC is a dialect of the BASIC programming language. It is an extended vers =={{header|MSX Basic}}== 10 Rem Count 1 to 10 and print! 20 for a=1 to 10 -20 Print a -30 Next a +30 Print a +40 Next a
'''MSX Basic''' initially introduced to Rosetta Code on July 10, 2016 by [http://rosettacode.org/wiki/User:Kaizen Paulo Almeida]
MSX Basic and the MSX logo are registered trademarks of MSX Japan
\ No newline at end of file diff --git a/Lang/Maple/Generate-lower-case-ASCII-alphabet b/Lang/Maple/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..af7621efac --- /dev/null +++ b/Lang/Maple/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Maple \ No newline at end of file diff --git a/Lang/Maple/Left-factorials b/Lang/Maple/Left-factorials new file mode 120000 index 0000000000..d709685004 --- /dev/null +++ b/Lang/Maple/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/Maple \ No newline at end of file diff --git a/Lang/Maple/Pascals-triangle-Puzzle b/Lang/Maple/Pascals-triangle-Puzzle new file mode 120000 index 0000000000..f51f68445e --- /dev/null +++ b/Lang/Maple/Pascals-triangle-Puzzle @@ -0,0 +1 @@ +../../Task/Pascals-triangle-Puzzle/Maple \ No newline at end of file diff --git a/Lang/Maple/Quaternion-type b/Lang/Maple/Quaternion-type new file mode 120000 index 0000000000..dc174952ef --- /dev/null +++ b/Lang/Maple/Quaternion-type @@ -0,0 +1 @@ +../../Task/Quaternion-type/Maple \ No newline at end of file diff --git a/Lang/Maple/Sequence-of-non-squares b/Lang/Maple/Sequence-of-non-squares new file mode 120000 index 0000000000..46d5c160a0 --- /dev/null +++ b/Lang/Maple/Sequence-of-non-squares @@ -0,0 +1 @@ +../../Task/Sequence-of-non-squares/Maple \ No newline at end of file diff --git a/Lang/Maple/Spiral-matrix b/Lang/Maple/Spiral-matrix new file mode 120000 index 0000000000..3c0f2a05a2 --- /dev/null +++ b/Lang/Maple/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Maple \ No newline at end of file diff --git a/Lang/Maple/Visualize-a-tree b/Lang/Maple/Visualize-a-tree new file mode 120000 index 0000000000..918107c7e3 --- /dev/null +++ b/Lang/Maple/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/Maple \ No newline at end of file diff --git a/Lang/Nial/Fibonacci-sequence b/Lang/Nial/Fibonacci-sequence new file mode 120000 index 0000000000..7d4d6aaabb --- /dev/null +++ b/Lang/Nial/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Nial \ No newline at end of file diff --git a/Lang/Nim/Calendar b/Lang/Nim/Calendar new file mode 120000 index 0000000000..3acfff7626 --- /dev/null +++ b/Lang/Nim/Calendar @@ -0,0 +1 @@ +../../Task/Calendar/Nim \ No newline at end of file diff --git a/Lang/Nim/Carmichael-3-strong-pseudoprimes b/Lang/Nim/Carmichael-3-strong-pseudoprimes new file mode 120000 index 0000000000..2098709649 --- /dev/null +++ b/Lang/Nim/Carmichael-3-strong-pseudoprimes @@ -0,0 +1 @@ +../../Task/Carmichael-3-strong-pseudoprimes/Nim \ No newline at end of file diff --git a/Lang/Nim/Continued-fraction b/Lang/Nim/Continued-fraction new file mode 120000 index 0000000000..7980800492 --- /dev/null +++ b/Lang/Nim/Continued-fraction @@ -0,0 +1 @@ +../../Task/Continued-fraction/Nim \ No newline at end of file diff --git a/Lang/Nim/Convert-decimal-number-to-rational b/Lang/Nim/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..b54892aa61 --- /dev/null +++ b/Lang/Nim/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/Nim \ No newline at end of file diff --git a/Lang/Nim/Deconvolution-1D b/Lang/Nim/Deconvolution-1D new file mode 120000 index 0000000000..b7d0b68cf6 --- /dev/null +++ b/Lang/Nim/Deconvolution-1D @@ -0,0 +1 @@ +../../Task/Deconvolution-1D/Nim \ No newline at end of file diff --git a/Lang/Nim/K-means++-clustering b/Lang/Nim/K-means++-clustering new file mode 120000 index 0000000000..3d528a2aed --- /dev/null +++ b/Lang/Nim/K-means++-clustering @@ -0,0 +1 @@ +../../Task/K-means++-clustering/Nim \ No newline at end of file diff --git a/Lang/Nim/Numeric-error-propagation b/Lang/Nim/Numeric-error-propagation new file mode 120000 index 0000000000..3fbd072f75 --- /dev/null +++ b/Lang/Nim/Numeric-error-propagation @@ -0,0 +1 @@ +../../Task/Numeric-error-propagation/Nim \ No newline at end of file diff --git a/Lang/Nim/Numerical-integration-Gauss-Legendre-Quadrature b/Lang/Nim/Numerical-integration-Gauss-Legendre-Quadrature new file mode 120000 index 0000000000..07f6b7889b --- /dev/null +++ b/Lang/Nim/Numerical-integration-Gauss-Legendre-Quadrature @@ -0,0 +1 @@ +../../Task/Numerical-integration-Gauss-Legendre-Quadrature/Nim \ No newline at end of file diff --git a/Lang/Nim/Permutation-test b/Lang/Nim/Permutation-test new file mode 120000 index 0000000000..31098e2f65 --- /dev/null +++ b/Lang/Nim/Permutation-test @@ -0,0 +1 @@ +../../Task/Permutation-test/Nim \ No newline at end of file diff --git a/Lang/Nim/Roots-of-a-function b/Lang/Nim/Roots-of-a-function new file mode 120000 index 0000000000..2f9dfc9af5 --- /dev/null +++ b/Lang/Nim/Roots-of-a-function @@ -0,0 +1 @@ +../../Task/Roots-of-a-function/Nim \ No newline at end of file diff --git a/Lang/Nim/Set-consolidation b/Lang/Nim/Set-consolidation new file mode 120000 index 0000000000..53e361f0b4 --- /dev/null +++ b/Lang/Nim/Set-consolidation @@ -0,0 +1 @@ +../../Task/Set-consolidation/Nim \ No newline at end of file diff --git a/Lang/Nim/Simulate-input-Keyboard b/Lang/Nim/Simulate-input-Keyboard new file mode 120000 index 0000000000..fc12cb9622 --- /dev/null +++ b/Lang/Nim/Simulate-input-Keyboard @@ -0,0 +1 @@ +../../Task/Simulate-input-Keyboard/Nim \ No newline at end of file diff --git a/Lang/Nim/Thieles-interpolation-formula b/Lang/Nim/Thieles-interpolation-formula new file mode 120000 index 0000000000..c63a4492ad --- /dev/null +++ b/Lang/Nim/Thieles-interpolation-formula @@ -0,0 +1 @@ +../../Task/Thieles-interpolation-formula/Nim \ No newline at end of file diff --git a/Lang/Nim/Topswops b/Lang/Nim/Topswops new file mode 120000 index 0000000000..8969fd2069 --- /dev/null +++ b/Lang/Nim/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/Nim \ No newline at end of file diff --git a/Lang/OCaml/String-prepend b/Lang/OCaml/String-prepend new file mode 120000 index 0000000000..ddb5caac02 --- /dev/null +++ b/Lang/OCaml/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Voronoi-diagram b/Lang/OCaml/Voronoi-diagram new file mode 120000 index 0000000000..8fc12dd404 --- /dev/null +++ b/Lang/OCaml/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/OCaml \ No newline at end of file diff --git a/Lang/Objeck/24-game b/Lang/Objeck/24-game new file mode 120000 index 0000000000..ab33966740 --- /dev/null +++ b/Lang/Objeck/24-game @@ -0,0 +1 @@ +../../Task/24-game/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Sum-digits-of-an-integer b/Lang/Objeck/Sum-digits-of-an-integer new file mode 120000 index 0000000000..d5da5a3e38 --- /dev/null +++ b/Lang/Objeck/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Unix-ls b/Lang/Objeck/Unix-ls new file mode 120000 index 0000000000..0e5296957e --- /dev/null +++ b/Lang/Objeck/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/Objeck \ No newline at end of file diff --git a/Lang/Ol/Arbitrary-precision-integers--included- b/Lang/Ol/Arbitrary-precision-integers--included- new file mode 120000 index 0000000000..daa95c5a35 --- /dev/null +++ b/Lang/Ol/Arbitrary-precision-integers--included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers--included-/Ol \ No newline at end of file diff --git a/Lang/Ol/Binary-search b/Lang/Ol/Binary-search new file mode 120000 index 0000000000..40e73ad122 --- /dev/null +++ b/Lang/Ol/Binary-search @@ -0,0 +1 @@ +../../Task/Binary-search/Ol \ No newline at end of file diff --git a/Lang/Ol/Currying b/Lang/Ol/Currying new file mode 120000 index 0000000000..c43bf582ab --- /dev/null +++ b/Lang/Ol/Currying @@ -0,0 +1 @@ +../../Task/Currying/Ol \ No newline at end of file diff --git a/Lang/Ol/Empty-program b/Lang/Ol/Empty-program new file mode 120000 index 0000000000..910cf9f70f --- /dev/null +++ b/Lang/Ol/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/Ol \ No newline at end of file diff --git a/Lang/Ol/Enumerations b/Lang/Ol/Enumerations new file mode 120000 index 0000000000..40bde4346f --- /dev/null +++ b/Lang/Ol/Enumerations @@ -0,0 +1 @@ +../../Task/Enumerations/Ol \ No newline at end of file diff --git a/Lang/Ol/Even-or-odd b/Lang/Ol/Even-or-odd new file mode 120000 index 0000000000..9c3096d775 --- /dev/null +++ b/Lang/Ol/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Ol \ No newline at end of file diff --git a/Lang/Ol/Extreme-floating-point-values b/Lang/Ol/Extreme-floating-point-values new file mode 120000 index 0000000000..83521b2a28 --- /dev/null +++ b/Lang/Ol/Extreme-floating-point-values @@ -0,0 +1 @@ +../../Task/Extreme-floating-point-values/Ol \ No newline at end of file diff --git a/Lang/Ol/Hello-world-Text b/Lang/Ol/Hello-world-Text new file mode 120000 index 0000000000..3c20db9317 --- /dev/null +++ b/Lang/Ol/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Ol \ No newline at end of file diff --git a/Lang/Ol/Huffman-coding b/Lang/Ol/Huffman-coding new file mode 120000 index 0000000000..f12ed889ec --- /dev/null +++ b/Lang/Ol/Huffman-coding @@ -0,0 +1 @@ +../../Task/Huffman-coding/Ol \ No newline at end of file diff --git a/Lang/Ol/Identity-matrix b/Lang/Ol/Identity-matrix new file mode 120000 index 0000000000..758d17702c --- /dev/null +++ b/Lang/Ol/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/Ol \ No newline at end of file diff --git a/Lang/Ol/Include-a-file b/Lang/Ol/Include-a-file new file mode 120000 index 0000000000..df25e4a794 --- /dev/null +++ b/Lang/Ol/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/Ol \ No newline at end of file diff --git a/Lang/Ol/Interactive-programming b/Lang/Ol/Interactive-programming new file mode 120000 index 0000000000..5049b6e558 --- /dev/null +++ b/Lang/Ol/Interactive-programming @@ -0,0 +1 @@ +../../Task/Interactive-programming/Ol \ No newline at end of file diff --git a/Lang/Ol/JSON b/Lang/Ol/JSON new file mode 120000 index 0000000000..4cd702c1b2 --- /dev/null +++ b/Lang/Ol/JSON @@ -0,0 +1 @@ +../../Task/JSON/Ol \ No newline at end of file diff --git a/Lang/Ol/Langtons-ant b/Lang/Ol/Langtons-ant new file mode 120000 index 0000000000..6f33dfde2a --- /dev/null +++ b/Lang/Ol/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/Ol \ No newline at end of file diff --git a/Lang/Ol/Loops-Foreach b/Lang/Ol/Loops-Foreach new file mode 120000 index 0000000000..9263d2f1da --- /dev/null +++ b/Lang/Ol/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Ol \ No newline at end of file diff --git a/Lang/Ol/MD5 b/Lang/Ol/MD5 new file mode 120000 index 0000000000..2239d9f6ea --- /dev/null +++ b/Lang/Ol/MD5 @@ -0,0 +1 @@ +../../Task/MD5/Ol \ No newline at end of file diff --git a/Lang/Ol/Metaprogramming b/Lang/Ol/Metaprogramming new file mode 120000 index 0000000000..018a0b9cd5 --- /dev/null +++ b/Lang/Ol/Metaprogramming @@ -0,0 +1 @@ +../../Task/Metaprogramming/Ol \ No newline at end of file diff --git a/Lang/Ol/Primality-by-trial-division b/Lang/Ol/Primality-by-trial-division new file mode 120000 index 0000000000..cfecda824e --- /dev/null +++ b/Lang/Ol/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/Ol \ No newline at end of file diff --git a/Lang/Ol/Stack b/Lang/Ol/Stack new file mode 120000 index 0000000000..aaffdca59f --- /dev/null +++ b/Lang/Ol/Stack @@ -0,0 +1 @@ +../../Task/Stack/Ol \ No newline at end of file diff --git a/Lang/Ol/Unicode-variable-names b/Lang/Ol/Unicode-variable-names new file mode 120000 index 0000000000..9fa44c0e8c --- /dev/null +++ b/Lang/Ol/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Ol \ No newline at end of file diff --git a/Lang/PHP/Append-a-record-to-the-end-of-a-text-file b/Lang/PHP/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..00dabaee72 --- /dev/null +++ b/Lang/PHP/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/PHP \ No newline at end of file diff --git a/Lang/PHP/Currying b/Lang/PHP/Currying new file mode 120000 index 0000000000..411f584683 --- /dev/null +++ b/Lang/PHP/Currying @@ -0,0 +1 @@ +../../Task/Currying/PHP \ No newline at end of file diff --git a/Lang/PHP/Entropy b/Lang/PHP/Entropy new file mode 120000 index 0000000000..33410ea620 --- /dev/null +++ b/Lang/PHP/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/PHP \ No newline at end of file diff --git a/Lang/PHP/Execute-a-Markov-algorithm b/Lang/PHP/Execute-a-Markov-algorithm new file mode 120000 index 0000000000..93dbe50531 --- /dev/null +++ b/Lang/PHP/Execute-a-Markov-algorithm @@ -0,0 +1 @@ +../../Task/Execute-a-Markov-algorithm/PHP \ No newline at end of file diff --git a/Lang/PHP/Fast-Fourier-transform b/Lang/PHP/Fast-Fourier-transform new file mode 120000 index 0000000000..50e6b9c730 --- /dev/null +++ b/Lang/PHP/Fast-Fourier-transform @@ -0,0 +1 @@ +../../Task/Fast-Fourier-transform/PHP \ No newline at end of file diff --git a/Lang/PHP/Hello-world-Newline-omission b/Lang/PHP/Hello-world-Newline-omission new file mode 120000 index 0000000000..c75d526294 --- /dev/null +++ b/Lang/PHP/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/PHP \ No newline at end of file diff --git a/Lang/PHP/Longest-string-challenge b/Lang/PHP/Longest-string-challenge new file mode 120000 index 0000000000..6901e4ddbd --- /dev/null +++ b/Lang/PHP/Longest-string-challenge @@ -0,0 +1 @@ +../../Task/Longest-string-challenge/PHP \ No newline at end of file diff --git a/Lang/PHP/Move-to-front-algorithm b/Lang/PHP/Move-to-front-algorithm new file mode 120000 index 0000000000..5113adb8fa --- /dev/null +++ b/Lang/PHP/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/PHP \ No newline at end of file diff --git a/Lang/PHP/Pythagorean-triples b/Lang/PHP/Pythagorean-triples new file mode 120000 index 0000000000..fda9ea2417 --- /dev/null +++ b/Lang/PHP/Pythagorean-triples @@ -0,0 +1 @@ +../../Task/Pythagorean-triples/PHP \ No newline at end of file diff --git a/Lang/PHP/Ray-casting-algorithm b/Lang/PHP/Ray-casting-algorithm new file mode 120000 index 0000000000..b75c0bf73e --- /dev/null +++ b/Lang/PHP/Ray-casting-algorithm @@ -0,0 +1 @@ +../../Task/Ray-casting-algorithm/PHP \ No newline at end of file diff --git a/Lang/PHP/Read-a-configuration-file b/Lang/PHP/Read-a-configuration-file new file mode 120000 index 0000000000..e6d779151d --- /dev/null +++ b/Lang/PHP/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/PHP \ No newline at end of file diff --git a/Lang/PHP/Read-a-specific-line-from-a-file b/Lang/PHP/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..490919373f --- /dev/null +++ b/Lang/PHP/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/PHP \ No newline at end of file diff --git a/Lang/PHP/Sierpinski-carpet b/Lang/PHP/Sierpinski-carpet new file mode 120000 index 0000000000..63ea47084a --- /dev/null +++ b/Lang/PHP/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/PHP \ No newline at end of file diff --git a/Lang/PHP/Sierpinski-triangle b/Lang/PHP/Sierpinski-triangle new file mode 120000 index 0000000000..09687d900f --- /dev/null +++ b/Lang/PHP/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/PHP \ No newline at end of file diff --git a/Lang/PHP/Speech-synthesis b/Lang/PHP/Speech-synthesis new file mode 120000 index 0000000000..03b076c9b6 --- /dev/null +++ b/Lang/PHP/Speech-synthesis @@ -0,0 +1 @@ +../../Task/Speech-synthesis/PHP \ No newline at end of file diff --git a/Lang/PHP/Sum-multiples-of-3-and-5 b/Lang/PHP/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..1e3d6828d3 --- /dev/null +++ b/Lang/PHP/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/PHP \ No newline at end of file diff --git a/Lang/PHP/Terminal-control-Cursor-positioning b/Lang/PHP/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..1dd80e98f6 --- /dev/null +++ b/Lang/PHP/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/PHP \ No newline at end of file diff --git a/Lang/PHP/Update-a-configuration-file b/Lang/PHP/Update-a-configuration-file new file mode 120000 index 0000000000..cf2bc2656e --- /dev/null +++ b/Lang/PHP/Update-a-configuration-file @@ -0,0 +1 @@ +../../Task/Update-a-configuration-file/PHP \ No newline at end of file diff --git a/Lang/PL-pgSQL/Fibonacci-sequence b/Lang/PL-pgSQL/Fibonacci-sequence new file mode 120000 index 0000000000..52642e0965 --- /dev/null +++ b/Lang/PL-pgSQL/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/PL-pgSQL \ No newline at end of file diff --git a/Lang/Perl-6/00DESCRIPTION b/Lang/Perl-6/00DESCRIPTION index e54994bc7e..c8c95454b3 100644 --- a/Lang/Perl-6/00DESCRIPTION +++ b/Lang/Perl-6/00DESCRIPTION @@ -19,7 +19,7 @@ [https://tio.run/#perl6 Try Perl 6 on tio.run].
[https://glot.io/new/perl6 Try Perl 6 on glot.io]. {{infobox_end}} -Perl 6 is the up-and-coming little sister to Perl 5. +Perl 6 is a member of the Perl family of programming languages. Though it resembles previous versions of [[Perl]] to no small degree, Perl 6 is substantially a new language; by design, it isn't backwards-compatible with Perl 5. The first official release was at Christmas of 2015. @@ -35,4 +35,7 @@ Compiler releases have date-based versions, and these are typically used in Rose The only compiler implementing the full test suite, Rakudo, currently runs on either of two backends, MoarVM or JVM. Subsequent language revisions are planned for release on a roughly yearly cycle. +==A Note on the Renaming== +As of October 2019, "Perl 6" was renamed as "Raku". Since the old name has been in use for many years, it will take some time for the new designation to propagate widely. Expect to see both names in use for some time, but understand that they refer to exactly the same underlying idea. In particular, here on Rosetta Code essentially all tasks are currently listed under Perl 6, and there are no immediate plans to change this. +
\ No newline at end of file diff --git a/Lang/Perl-6/Bitmap-Flood-fill b/Lang/Perl-6/Bitmap-Flood-fill new file mode 120000 index 0000000000..0f6da78766 --- /dev/null +++ b/Lang/Perl-6/Bitmap-Flood-fill @@ -0,0 +1 @@ +../../Task/Bitmap-Flood-fill/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Color-of-a-screen-pixel b/Lang/Perl-6/Color-of-a-screen-pixel new file mode 120000 index 0000000000..02a9d2b4b7 --- /dev/null +++ b/Lang/Perl-6/Color-of-a-screen-pixel @@ -0,0 +1 @@ +../../Task/Color-of-a-screen-pixel/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Colour-pinstripe-Printer b/Lang/Perl-6/Colour-pinstripe-Printer new file mode 120000 index 0000000000..b2ada4f784 --- /dev/null +++ b/Lang/Perl-6/Colour-pinstripe-Printer @@ -0,0 +1 @@ +../../Task/Colour-pinstripe-Printer/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Joystick-position b/Lang/Perl-6/Joystick-position new file mode 120000 index 0000000000..9533f1a86b --- /dev/null +++ b/Lang/Perl-6/Joystick-position @@ -0,0 +1 @@ +../../Task/Joystick-position/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/OpenGL b/Lang/Perl-6/OpenGL new file mode 120000 index 0000000000..f60ee82780 --- /dev/null +++ b/Lang/Perl-6/OpenGL @@ -0,0 +1 @@ +../../Task/OpenGL/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Pinstripe-Printer b/Lang/Perl-6/Pinstripe-Printer new file mode 120000 index 0000000000..d389b7e342 --- /dev/null +++ b/Lang/Perl-6/Pinstripe-Printer @@ -0,0 +1 @@ +../../Task/Pinstripe-Printer/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Record-sound b/Lang/Perl-6/Record-sound new file mode 120000 index 0000000000..7380dce9be --- /dev/null +++ b/Lang/Perl-6/Record-sound @@ -0,0 +1 @@ +../../Task/Record-sound/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Sutherland-Hodgman-polygon-clipping b/Lang/Perl-6/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..eb763d2b33 --- /dev/null +++ b/Lang/Perl-6/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Use-another-language-to-call-a-function b/Lang/Perl-6/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..ac9ed06773 --- /dev/null +++ b/Lang/Perl-6/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Vigen-re-cipher-Cryptanalysis b/Lang/Perl-6/Vigen-re-cipher-Cryptanalysis new file mode 120000 index 0000000000..5a1dd76a79 --- /dev/null +++ b/Lang/Perl-6/Vigen-re-cipher-Cryptanalysis @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher-Cryptanalysis/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Write-to-Windows-event-log b/Lang/Perl-6/Write-to-Windows-event-log new file mode 120000 index 0000000000..af3c231768 --- /dev/null +++ b/Lang/Perl-6/Write-to-Windows-event-log @@ -0,0 +1 @@ +../../Task/Write-to-Windows-event-log/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Yahoo--search-interface b/Lang/Perl-6/Yahoo--search-interface new file mode 120000 index 0000000000..c75a8d1ca2 --- /dev/null +++ b/Lang/Perl-6/Yahoo--search-interface @@ -0,0 +1 @@ +../../Task/Yahoo--search-interface/Perl-6 \ No newline at end of file diff --git a/Lang/Perl/Binary-strings b/Lang/Perl/Binary-strings new file mode 120000 index 0000000000..289ed23511 --- /dev/null +++ b/Lang/Perl/Binary-strings @@ -0,0 +1 @@ +../../Task/Binary-strings/Perl \ No newline at end of file diff --git a/Lang/Perl/Call-a-function-in-a-shared-library b/Lang/Perl/Call-a-function-in-a-shared-library new file mode 120000 index 0000000000..7924221eae --- /dev/null +++ b/Lang/Perl/Call-a-function-in-a-shared-library @@ -0,0 +1 @@ +../../Task/Call-a-function-in-a-shared-library/Perl \ No newline at end of file diff --git a/Lang/Perl/Color-of-a-screen-pixel b/Lang/Perl/Color-of-a-screen-pixel new file mode 120000 index 0000000000..a605065662 --- /dev/null +++ b/Lang/Perl/Color-of-a-screen-pixel @@ -0,0 +1 @@ +../../Task/Color-of-a-screen-pixel/Perl \ No newline at end of file diff --git a/Lang/Perl/Color-quantization b/Lang/Perl/Color-quantization new file mode 120000 index 0000000000..346de5a532 --- /dev/null +++ b/Lang/Perl/Color-quantization @@ -0,0 +1 @@ +../../Task/Color-quantization/Perl \ No newline at end of file diff --git a/Lang/Perl/Image-convolution b/Lang/Perl/Image-convolution new file mode 120000 index 0000000000..9a954e7cd5 --- /dev/null +++ b/Lang/Perl/Image-convolution @@ -0,0 +1 @@ +../../Task/Image-convolution/Perl \ No newline at end of file diff --git a/Lang/Perl/Median-filter b/Lang/Perl/Median-filter new file mode 120000 index 0000000000..ffb22a7745 --- /dev/null +++ b/Lang/Perl/Median-filter @@ -0,0 +1 @@ +../../Task/Median-filter/Perl \ No newline at end of file diff --git a/Lang/Perl/QR-decomposition b/Lang/Perl/QR-decomposition new file mode 120000 index 0000000000..8926defb0d --- /dev/null +++ b/Lang/Perl/QR-decomposition @@ -0,0 +1 @@ +../../Task/QR-decomposition/Perl \ No newline at end of file diff --git a/Lang/Perl/Solve-the-no-connection-puzzle b/Lang/Perl/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..637fa924a4 --- /dev/null +++ b/Lang/Perl/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/Perl \ No newline at end of file diff --git a/Lang/Perl/Sutherland-Hodgman-polygon-clipping b/Lang/Perl/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..7e52906947 --- /dev/null +++ b/Lang/Perl/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/Perl \ No newline at end of file diff --git a/Lang/Perl/Thieles-interpolation-formula b/Lang/Perl/Thieles-interpolation-formula new file mode 120000 index 0000000000..17e3e5c48a --- /dev/null +++ b/Lang/Perl/Thieles-interpolation-formula @@ -0,0 +1 @@ +../../Task/Thieles-interpolation-formula/Perl \ No newline at end of file diff --git a/Lang/Perl/Vigen-re-cipher-Cryptanalysis b/Lang/Perl/Vigen-re-cipher-Cryptanalysis new file mode 120000 index 0000000000..54fa2c6b20 --- /dev/null +++ b/Lang/Perl/Vigen-re-cipher-Cryptanalysis @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher-Cryptanalysis/Perl \ No newline at end of file diff --git a/Lang/Phix/00DESCRIPTION b/Lang/Phix/00DESCRIPTION index ed2e3e4736..6828da21c0 100644 --- a/Lang/Phix/00DESCRIPTION +++ b/Lang/Phix/00DESCRIPTION @@ -13,7 +13,7 @@ }} Phix is a self-hosted hybrid interpreter/compiler, developed by Pete Lomax. It is very easy to use, and similar to Euphoria. -A simple 20MB download contains a pre-compiled executable, all the sources, and'' '''everything''' ''needed to recompile them, in about 15 seconds. The download also contains a full-featured programmer's editor and 130+ demo programs. +[http://phix.x10.mx/download.php A simple 20MB download] contains a pre-compiled executable, all the sources, and'' '''everything''' ''needed to recompile them, in about 15 seconds. The download also contains a full-featured programmer's editor and 130+ demo programs. Perhaps the most striking feature of Phix is that it has just five builtin data types:
diff --git a/Lang/Phix/Anonymous-recursion b/Lang/Phix/Anonymous-recursion
new file mode 120000
index 0000000000..70f6b1590f
--- /dev/null
+++ b/Lang/Phix/Anonymous-recursion
@@ -0,0 +1 @@
+../../Task/Anonymous-recursion/Phix
\ No newline at end of file
diff --git a/Lang/Phix/Classes b/Lang/Phix/Classes
new file mode 120000
index 0000000000..e94aa65ed5
--- /dev/null
+++ b/Lang/Phix/Classes
@@ -0,0 +1 @@
+../../Task/Classes/Phix
\ No newline at end of file
diff --git a/Lang/Phix/Documentation b/Lang/Phix/Documentation
new file mode 120000
index 0000000000..772a3d05d0
--- /dev/null
+++ b/Lang/Phix/Documentation
@@ -0,0 +1 @@
+../../Task/Documentation/Phix
\ No newline at end of file
diff --git a/Lang/Phix/Hello-world-Web-server b/Lang/Phix/Hello-world-Web-server
new file mode 120000
index 0000000000..fa49a64e00
--- /dev/null
+++ b/Lang/Phix/Hello-world-Web-server
@@ -0,0 +1 @@
+../../Task/Hello-world-Web-server/Phix
\ No newline at end of file
diff --git a/Lang/Phix/Record-sound b/Lang/Phix/Record-sound
new file mode 120000
index 0000000000..313906ce5e
--- /dev/null
+++ b/Lang/Phix/Record-sound
@@ -0,0 +1 @@
+../../Task/Record-sound/Phix
\ No newline at end of file
diff --git a/Lang/Phix/SOAP b/Lang/Phix/SOAP
new file mode 120000
index 0000000000..40826584f7
--- /dev/null
+++ b/Lang/Phix/SOAP
@@ -0,0 +1 @@
+../../Task/SOAP/Phix
\ No newline at end of file
diff --git a/Lang/Phix/Send-email b/Lang/Phix/Send-email
new file mode 120000
index 0000000000..7c1642e160
--- /dev/null
+++ b/Lang/Phix/Send-email
@@ -0,0 +1 @@
+../../Task/Send-email/Phix
\ No newline at end of file
diff --git a/Lang/Phix/Speech-synthesis b/Lang/Phix/Speech-synthesis
new file mode 120000
index 0000000000..55478c7938
--- /dev/null
+++ b/Lang/Phix/Speech-synthesis
@@ -0,0 +1 @@
+../../Task/Speech-synthesis/Phix
\ No newline at end of file
diff --git a/Lang/Phix/XML-Input b/Lang/Phix/XML-Input
new file mode 120000
index 0000000000..a3f0dc8484
--- /dev/null
+++ b/Lang/Phix/XML-Input
@@ -0,0 +1 @@
+../../Task/XML-Input/Phix
\ No newline at end of file
diff --git a/Lang/PicoLisp/Magic-squares-of-odd-order b/Lang/PicoLisp/Magic-squares-of-odd-order
new file mode 120000
index 0000000000..376afbdf78
--- /dev/null
+++ b/Lang/PicoLisp/Magic-squares-of-odd-order
@@ -0,0 +1 @@
+../../Task/Magic-squares-of-odd-order/PicoLisp
\ No newline at end of file
diff --git a/Lang/Pike/Associative-array-Creation b/Lang/Pike/Associative-array-Creation
new file mode 120000
index 0000000000..d329461618
--- /dev/null
+++ b/Lang/Pike/Associative-array-Creation
@@ -0,0 +1 @@
+../../Task/Associative-array-Creation/Pike
\ No newline at end of file
diff --git a/Lang/Pike/Bitwise-operations b/Lang/Pike/Bitwise-operations
new file mode 120000
index 0000000000..f9993e4311
--- /dev/null
+++ b/Lang/Pike/Bitwise-operations
@@ -0,0 +1 @@
+../../Task/Bitwise-operations/Pike
\ No newline at end of file
diff --git a/Lang/Pike/CRC-32 b/Lang/Pike/CRC-32
new file mode 120000
index 0000000000..78bb4904c3
--- /dev/null
+++ b/Lang/Pike/CRC-32
@@ -0,0 +1 @@
+../../Task/CRC-32/Pike
\ No newline at end of file
diff --git a/Lang/Pike/Compound-data-type b/Lang/Pike/Compound-data-type
new file mode 120000
index 0000000000..2ced003025
--- /dev/null
+++ b/Lang/Pike/Compound-data-type
@@ -0,0 +1 @@
+../../Task/Compound-data-type/Pike
\ No newline at end of file
diff --git a/Lang/Pike/Count-in-octal b/Lang/Pike/Count-in-octal
new file mode 120000
index 0000000000..d94a66255c
--- /dev/null
+++ b/Lang/Pike/Count-in-octal
@@ -0,0 +1 @@
+../../Task/Count-in-octal/Pike
\ No newline at end of file
diff --git a/Lang/Pike/Count-occurrences-of-a-substring b/Lang/Pike/Count-occurrences-of-a-substring
new file mode 120000
index 0000000000..f93ea0a6e2
--- /dev/null
+++ b/Lang/Pike/Count-occurrences-of-a-substring
@@ -0,0 +1 @@
+../../Task/Count-occurrences-of-a-substring/Pike
\ No newline at end of file
diff --git a/Lang/Pike/Environment-variables b/Lang/Pike/Environment-variables
new file mode 120000
index 0000000000..aef6b5ce11
--- /dev/null
+++ b/Lang/Pike/Environment-variables
@@ -0,0 +1 @@
+../../Task/Environment-variables/Pike
\ No newline at end of file
diff --git a/Lang/Pike/File-input-output b/Lang/Pike/File-input-output
new file mode 120000
index 0000000000..a73ed82771
--- /dev/null
+++ b/Lang/Pike/File-input-output
@@ -0,0 +1 @@
+../../Task/File-input-output/Pike
\ No newline at end of file
diff --git a/Lang/Pike/Hash-from-two-arrays b/Lang/Pike/Hash-from-two-arrays
new file mode 120000
index 0000000000..5da3715263
--- /dev/null
+++ b/Lang/Pike/Hash-from-two-arrays
@@ -0,0 +1 @@
+../../Task/Hash-from-two-arrays/Pike
\ No newline at end of file
diff --git a/Lang/Pike/Hello-world-Newline-omission b/Lang/Pike/Hello-world-Newline-omission
new file mode 120000
index 0000000000..2f56739483
--- /dev/null
+++ b/Lang/Pike/Hello-world-Newline-omission
@@ -0,0 +1 @@
+../../Task/Hello-world-Newline-omission/Pike
\ No newline at end of file
diff --git a/Lang/Pike/Hello-world-Standard-error b/Lang/Pike/Hello-world-Standard-error
new file mode 120000
index 0000000000..2f6401e8ac
--- /dev/null
+++ b/Lang/Pike/Hello-world-Standard-error
@@ -0,0 +1 @@
+../../Task/Hello-world-Standard-error/Pike
\ No newline at end of file
diff --git a/Lang/Pike/Hello-world-Web-server b/Lang/Pike/Hello-world-Web-server
new file mode 120000
index 0000000000..5e5d9874d1
--- /dev/null
+++ b/Lang/Pike/Hello-world-Web-server
@@ -0,0 +1 @@
+../../Task/Hello-world-Web-server/Pike
\ No newline at end of file
diff --git a/Lang/Pike/Include-a-file b/Lang/Pike/Include-a-file
new file mode 120000
index 0000000000..0da0985758
--- /dev/null
+++ b/Lang/Pike/Include-a-file
@@ -0,0 +1 @@
+../../Task/Include-a-file/Pike
\ No newline at end of file
diff --git a/Lang/Pike/Integer-sequence b/Lang/Pike/Integer-sequence
new file mode 120000
index 0000000000..1b236bf4e0
--- /dev/null
+++ b/Lang/Pike/Integer-sequence
@@ -0,0 +1 @@
+../../Task/Integer-sequence/Pike
\ No newline at end of file
diff --git a/Lang/Pike/Letter-frequency b/Lang/Pike/Letter-frequency
new file mode 120000
index 0000000000..bbd7107d57
--- /dev/null
+++ b/Lang/Pike/Letter-frequency
@@ -0,0 +1 @@
+../../Task/Letter-frequency/Pike
\ No newline at end of file
diff --git a/Lang/Pike/Loop-over-multiple-arrays-simultaneously b/Lang/Pike/Loop-over-multiple-arrays-simultaneously
new file mode 120000
index 0000000000..8c93d12a90
--- /dev/null
+++ b/Lang/Pike/Loop-over-multiple-arrays-simultaneously
@@ -0,0 +1 @@
+../../Task/Loop-over-multiple-arrays-simultaneously/Pike
\ No newline at end of file
diff --git a/Lang/Pike/Loops-Nested b/Lang/Pike/Loops-Nested
new file mode 120000
index 0000000000..714dbd71de
--- /dev/null
+++ b/Lang/Pike/Loops-Nested
@@ -0,0 +1 @@
+../../Task/Loops-Nested/Pike
\ No newline at end of file
diff --git a/Lang/Pike/Reverse-a-string b/Lang/Pike/Reverse-a-string
new file mode 120000
index 0000000000..65e4dc00a8
--- /dev/null
+++ b/Lang/Pike/Reverse-a-string
@@ -0,0 +1 @@
+../../Task/Reverse-a-string/Pike
\ No newline at end of file
diff --git a/Lang/Pike/Reverse-words-in-a-string b/Lang/Pike/Reverse-words-in-a-string
new file mode 120000
index 0000000000..ec2da1c7e2
--- /dev/null
+++ b/Lang/Pike/Reverse-words-in-a-string
@@ -0,0 +1 @@
+../../Task/Reverse-words-in-a-string/Pike
\ No newline at end of file
diff --git a/Lang/Pike/SHA-1 b/Lang/Pike/SHA-1
new file mode 120000
index 0000000000..dc0af5d07e
--- /dev/null
+++ b/Lang/Pike/SHA-1
@@ -0,0 +1 @@
+../../Task/SHA-1/Pike
\ No newline at end of file
diff --git a/Lang/Pike/SHA-256 b/Lang/Pike/SHA-256
new file mode 120000
index 0000000000..6821dcadd6
--- /dev/null
+++ b/Lang/Pike/SHA-256
@@ -0,0 +1 @@
+../../Task/SHA-256/Pike
\ No newline at end of file
diff --git a/Lang/Pike/Show-the-epoch b/Lang/Pike/Show-the-epoch
new file mode 120000
index 0000000000..50e5d71faa
--- /dev/null
+++ b/Lang/Pike/Show-the-epoch
@@ -0,0 +1 @@
+../../Task/Show-the-epoch/Pike
\ No newline at end of file
diff --git a/Lang/Pike/Sorting-algorithms-Sleep-sort b/Lang/Pike/Sorting-algorithms-Sleep-sort
new file mode 120000
index 0000000000..a16aa3bf19
--- /dev/null
+++ b/Lang/Pike/Sorting-algorithms-Sleep-sort
@@ -0,0 +1 @@
+../../Task/Sorting-algorithms-Sleep-sort/Pike
\ No newline at end of file
diff --git a/Lang/Pike/Stack b/Lang/Pike/Stack
new file mode 120000
index 0000000000..8556e9226e
--- /dev/null
+++ b/Lang/Pike/Stack
@@ -0,0 +1 @@
+../../Task/Stack/Pike
\ No newline at end of file
diff --git a/Lang/Pike/String-append b/Lang/Pike/String-append
new file mode 120000
index 0000000000..40af5cb496
--- /dev/null
+++ b/Lang/Pike/String-append
@@ -0,0 +1 @@
+../../Task/String-append/Pike
\ No newline at end of file
diff --git a/Lang/Pike/String-case b/Lang/Pike/String-case
new file mode 120000
index 0000000000..81986e53a1
--- /dev/null
+++ b/Lang/Pike/String-case
@@ -0,0 +1 @@
+../../Task/String-case/Pike
\ No newline at end of file
diff --git a/Lang/Pike/String-concatenation b/Lang/Pike/String-concatenation
new file mode 120000
index 0000000000..438bf0b082
--- /dev/null
+++ b/Lang/Pike/String-concatenation
@@ -0,0 +1 @@
+../../Task/String-concatenation/Pike
\ No newline at end of file
diff --git a/Lang/Pike/System-time b/Lang/Pike/System-time
new file mode 120000
index 0000000000..c1f46cab2a
--- /dev/null
+++ b/Lang/Pike/System-time
@@ -0,0 +1 @@
+../../Task/System-time/Pike
\ No newline at end of file
diff --git a/Lang/Pike/Time-a-function b/Lang/Pike/Time-a-function
new file mode 120000
index 0000000000..338d38d423
--- /dev/null
+++ b/Lang/Pike/Time-a-function
@@ -0,0 +1 @@
+../../Task/Time-a-function/Pike
\ No newline at end of file
diff --git a/Lang/Pike/Truncatable-primes b/Lang/Pike/Truncatable-primes
new file mode 120000
index 0000000000..1e673dd280
--- /dev/null
+++ b/Lang/Pike/Truncatable-primes
@@ -0,0 +1 @@
+../../Task/Truncatable-primes/Pike
\ No newline at end of file
diff --git a/Lang/Pike/URL-decoding b/Lang/Pike/URL-decoding
new file mode 120000
index 0000000000..b5c2ba6f09
--- /dev/null
+++ b/Lang/Pike/URL-decoding
@@ -0,0 +1 @@
+../../Task/URL-decoding/Pike
\ No newline at end of file
diff --git a/Lang/Pike/URL-encoding b/Lang/Pike/URL-encoding
new file mode 120000
index 0000000000..dea36a2a04
--- /dev/null
+++ b/Lang/Pike/URL-encoding
@@ -0,0 +1 @@
+../../Task/URL-encoding/Pike
\ No newline at end of file
diff --git a/Lang/Pike/Unicode-strings b/Lang/Pike/Unicode-strings
new file mode 120000
index 0000000000..7dad4d5d94
--- /dev/null
+++ b/Lang/Pike/Unicode-strings
@@ -0,0 +1 @@
+../../Task/Unicode-strings/Pike
\ No newline at end of file
diff --git a/Lang/Pike/Unicode-variable-names b/Lang/Pike/Unicode-variable-names
new file mode 120000
index 0000000000..a0aa7a1afc
--- /dev/null
+++ b/Lang/Pike/Unicode-variable-names
@@ -0,0 +1 @@
+../../Task/Unicode-variable-names/Pike
\ No newline at end of file
diff --git a/Lang/Pike/Unix-ls b/Lang/Pike/Unix-ls
new file mode 120000
index 0000000000..34b7cecb24
--- /dev/null
+++ b/Lang/Pike/Unix-ls
@@ -0,0 +1 @@
+../../Task/Unix-ls/Pike
\ No newline at end of file
diff --git a/Lang/Pike/Zero-to-the-zero-power b/Lang/Pike/Zero-to-the-zero-power
new file mode 120000
index 0000000000..4618509330
--- /dev/null
+++ b/Lang/Pike/Zero-to-the-zero-power
@@ -0,0 +1 @@
+../../Task/Zero-to-the-zero-power/Pike
\ No newline at end of file
diff --git a/Lang/Pony/99-Bottles-of-Beer b/Lang/Pony/99-Bottles-of-Beer
new file mode 120000
index 0000000000..1f90ea8194
--- /dev/null
+++ b/Lang/Pony/99-Bottles-of-Beer
@@ -0,0 +1 @@
+../../Task/99-Bottles-of-Beer/Pony
\ No newline at end of file
diff --git a/Lang/PowerShell/Active-Directory-Search-for-a-user b/Lang/PowerShell/Active-Directory-Search-for-a-user
new file mode 120000
index 0000000000..d428500ce9
--- /dev/null
+++ b/Lang/PowerShell/Active-Directory-Search-for-a-user
@@ -0,0 +1 @@
+../../Task/Active-Directory-Search-for-a-user/PowerShell
\ No newline at end of file
diff --git a/Lang/PowerShell/Averages-Simple-moving-average b/Lang/PowerShell/Averages-Simple-moving-average
new file mode 120000
index 0000000000..e3f0e41cd5
--- /dev/null
+++ b/Lang/PowerShell/Averages-Simple-moving-average
@@ -0,0 +1 @@
+../../Task/Averages-Simple-moving-average/PowerShell
\ No newline at end of file
diff --git a/Lang/PowerShell/Polynomial-regression b/Lang/PowerShell/Polynomial-regression
new file mode 120000
index 0000000000..5d5dd6fb13
--- /dev/null
+++ b/Lang/PowerShell/Polynomial-regression
@@ -0,0 +1 @@
+../../Task/Polynomial-regression/PowerShell
\ No newline at end of file
diff --git a/Lang/PowerShell/QR-decomposition b/Lang/PowerShell/QR-decomposition
new file mode 120000
index 0000000000..1cea69c34d
--- /dev/null
+++ b/Lang/PowerShell/QR-decomposition
@@ -0,0 +1 @@
+../../Task/QR-decomposition/PowerShell
\ No newline at end of file
diff --git a/Lang/PowerShell/RSA-code b/Lang/PowerShell/RSA-code
new file mode 120000
index 0000000000..6eda0d005b
--- /dev/null
+++ b/Lang/PowerShell/RSA-code
@@ -0,0 +1 @@
+../../Task/RSA-code/PowerShell
\ No newline at end of file
diff --git a/Lang/Processing/Bitmap b/Lang/Processing/Bitmap
new file mode 120000
index 0000000000..df644a6e5b
--- /dev/null
+++ b/Lang/Processing/Bitmap
@@ -0,0 +1 @@
+../../Task/Bitmap/Processing
\ No newline at end of file
diff --git a/Lang/Processing/Draw-a-clock b/Lang/Processing/Draw-a-clock
new file mode 120000
index 0000000000..aeb456935b
--- /dev/null
+++ b/Lang/Processing/Draw-a-clock
@@ -0,0 +1 @@
+../../Task/Draw-a-clock/Processing
\ No newline at end of file
diff --git a/Lang/Processing/Draw-a-cuboid b/Lang/Processing/Draw-a-cuboid
new file mode 120000
index 0000000000..44aea600ea
--- /dev/null
+++ b/Lang/Processing/Draw-a-cuboid
@@ -0,0 +1 @@
+../../Task/Draw-a-cuboid/Processing
\ No newline at end of file
diff --git a/Lang/Processing/Shell-one-liner b/Lang/Processing/Shell-one-liner
new file mode 120000
index 0000000000..20dc579443
--- /dev/null
+++ b/Lang/Processing/Shell-one-liner
@@ -0,0 +1 @@
+../../Task/Shell-one-liner/Processing
\ No newline at end of file
diff --git a/Lang/Processing/Start-from-a-main-routine b/Lang/Processing/Start-from-a-main-routine
new file mode 120000
index 0000000000..f454282f89
--- /dev/null
+++ b/Lang/Processing/Start-from-a-main-routine
@@ -0,0 +1 @@
+../../Task/Start-from-a-main-routine/Processing
\ No newline at end of file
diff --git a/Lang/Prolog/Carmichael-3-strong-pseudoprimes b/Lang/Prolog/Carmichael-3-strong-pseudoprimes
new file mode 120000
index 0000000000..cd5e1c3eb8
--- /dev/null
+++ b/Lang/Prolog/Carmichael-3-strong-pseudoprimes
@@ -0,0 +1 @@
+../../Task/Carmichael-3-strong-pseudoprimes/Prolog
\ No newline at end of file
diff --git a/Lang/Prolog/Chinese-remainder-theorem b/Lang/Prolog/Chinese-remainder-theorem
new file mode 120000
index 0000000000..f7957e87df
--- /dev/null
+++ b/Lang/Prolog/Chinese-remainder-theorem
@@ -0,0 +1 @@
+../../Task/Chinese-remainder-theorem/Prolog
\ No newline at end of file
diff --git a/Lang/Prolog/Compile-time-calculation b/Lang/Prolog/Compile-time-calculation
new file mode 120000
index 0000000000..bce77d340d
--- /dev/null
+++ b/Lang/Prolog/Compile-time-calculation
@@ -0,0 +1 @@
+../../Task/Compile-time-calculation/Prolog
\ No newline at end of file
diff --git a/Lang/Prolog/Count-in-octal b/Lang/Prolog/Count-in-octal
new file mode 120000
index 0000000000..10141ae2be
--- /dev/null
+++ b/Lang/Prolog/Count-in-octal
@@ -0,0 +1 @@
+../../Task/Count-in-octal/Prolog
\ No newline at end of file
diff --git a/Lang/Prolog/Count-the-coins b/Lang/Prolog/Count-the-coins
new file mode 120000
index 0000000000..a4f4d67a95
--- /dev/null
+++ b/Lang/Prolog/Count-the-coins
@@ -0,0 +1 @@
+../../Task/Count-the-coins/Prolog
\ No newline at end of file
diff --git a/Lang/Prolog/Detect-division-by-zero b/Lang/Prolog/Detect-division-by-zero
new file mode 120000
index 0000000000..c0ad8cb5c8
--- /dev/null
+++ b/Lang/Prolog/Detect-division-by-zero
@@ -0,0 +1 @@
+../../Task/Detect-division-by-zero/Prolog
\ No newline at end of file
diff --git a/Lang/Prolog/Empty-directory b/Lang/Prolog/Empty-directory
new file mode 120000
index 0000000000..67b2db8ea2
--- /dev/null
+++ b/Lang/Prolog/Empty-directory
@@ -0,0 +1 @@
+../../Task/Empty-directory/Prolog
\ No newline at end of file
diff --git a/Lang/Prolog/Enumerations b/Lang/Prolog/Enumerations
new file mode 120000
index 0000000000..4f98d8c016
--- /dev/null
+++ b/Lang/Prolog/Enumerations
@@ -0,0 +1 @@
+../../Task/Enumerations/Prolog
\ No newline at end of file
diff --git a/Lang/Prolog/Factors-of-a-Mersenne-number b/Lang/Prolog/Factors-of-a-Mersenne-number
new file mode 120000
index 0000000000..fd2b73204a
--- /dev/null
+++ b/Lang/Prolog/Factors-of-a-Mersenne-number
@@ -0,0 +1 @@
+../../Task/Factors-of-a-Mersenne-number/Prolog
\ No newline at end of file
diff --git a/Lang/Prolog/Fractran b/Lang/Prolog/Fractran
new file mode 120000
index 0000000000..b6205a38a3
--- /dev/null
+++ b/Lang/Prolog/Fractran
@@ -0,0 +1 @@
+../../Task/Fractran/Prolog
\ No newline at end of file
diff --git a/Lang/Prolog/Hash-join b/Lang/Prolog/Hash-join
new file mode 120000
index 0000000000..cf1c84158d
--- /dev/null
+++ b/Lang/Prolog/Hash-join
@@ -0,0 +1 @@
+../../Task/Hash-join/Prolog
\ No newline at end of file
diff --git a/Lang/Prolog/Lucas-Lehmer-test b/Lang/Prolog/Lucas-Lehmer-test
new file mode 120000
index 0000000000..6f522203b6
--- /dev/null
+++ b/Lang/Prolog/Lucas-Lehmer-test
@@ -0,0 +1 @@
+../../Task/Lucas-Lehmer-test/Prolog
\ No newline at end of file
diff --git a/Lang/Prolog/Modular-inverse b/Lang/Prolog/Modular-inverse
new file mode 120000
index 0000000000..57e15b23d3
--- /dev/null
+++ b/Lang/Prolog/Modular-inverse
@@ -0,0 +1 @@
+../../Task/Modular-inverse/Prolog
\ No newline at end of file
diff --git a/Lang/Prolog/Multiplication-tables b/Lang/Prolog/Multiplication-tables
new file mode 120000
index 0000000000..6c01f2b0d6
--- /dev/null
+++ b/Lang/Prolog/Multiplication-tables
@@ -0,0 +1 @@
+../../Task/Multiplication-tables/Prolog
\ No newline at end of file
diff --git a/Lang/Prolog/Nth-root b/Lang/Prolog/Nth-root
new file mode 120000
index 0000000000..2440599e47
--- /dev/null
+++ b/Lang/Prolog/Nth-root
@@ -0,0 +1 @@
+../../Task/Nth-root/Prolog
\ No newline at end of file
diff --git a/Lang/Prolog/Number-names b/Lang/Prolog/Number-names
new file mode 120000
index 0000000000..df5a8a5dd2
--- /dev/null
+++ b/Lang/Prolog/Number-names
@@ -0,0 +1 @@
+../../Task/Number-names/Prolog
\ No newline at end of file
diff --git a/Lang/Prolog/Number-reversal-game b/Lang/Prolog/Number-reversal-game
new file mode 120000
index 0000000000..3a41d537c2
--- /dev/null
+++ b/Lang/Prolog/Number-reversal-game
@@ -0,0 +1 @@
+../../Task/Number-reversal-game/Prolog
\ No newline at end of file
diff --git a/Lang/Prolog/Polymorphism b/Lang/Prolog/Polymorphism
new file mode 120000
index 0000000000..84b671c757
--- /dev/null
+++ b/Lang/Prolog/Polymorphism
@@ -0,0 +1 @@
+../../Task/Polymorphism/Prolog
\ No newline at end of file
diff --git a/Lang/Prolog/Pythagorean-triples b/Lang/Prolog/Pythagorean-triples
new file mode 120000
index 0000000000..0087bad6e9
--- /dev/null
+++ b/Lang/Prolog/Pythagorean-triples
@@ -0,0 +1 @@
+../../Task/Pythagorean-triples/Prolog
\ No newline at end of file
diff --git a/Lang/Prolog/Roots-of-unity b/Lang/Prolog/Roots-of-unity
new file mode 120000
index 0000000000..2db76fe2d7
--- /dev/null
+++ b/Lang/Prolog/Roots-of-unity
@@ -0,0 +1 @@
+../../Task/Roots-of-unity/Prolog
\ No newline at end of file
diff --git a/Lang/Prolog/Set-puzzle b/Lang/Prolog/Set-puzzle
new file mode 120000
index 0000000000..baffaa089c
--- /dev/null
+++ b/Lang/Prolog/Set-puzzle
@@ -0,0 +1 @@
+../../Task/Set-puzzle/Prolog
\ No newline at end of file
diff --git a/Lang/Prolog/Solve-a-Hopido-puzzle b/Lang/Prolog/Solve-a-Hopido-puzzle
new file mode 120000
index 0000000000..91782909ee
--- /dev/null
+++ b/Lang/Prolog/Solve-a-Hopido-puzzle
@@ -0,0 +1 @@
+../../Task/Solve-a-Hopido-puzzle/Prolog
\ No newline at end of file
diff --git a/Lang/Prolog/Solve-a-Numbrix-puzzle b/Lang/Prolog/Solve-a-Numbrix-puzzle
new file mode 120000
index 0000000000..bf61f2cf6c
--- /dev/null
+++ b/Lang/Prolog/Solve-a-Numbrix-puzzle
@@ -0,0 +1 @@
+../../Task/Solve-a-Numbrix-puzzle/Prolog
\ No newline at end of file
diff --git a/Lang/Prolog/Sorting-algorithms-Bogosort b/Lang/Prolog/Sorting-algorithms-Bogosort
new file mode 120000
index 0000000000..a4ca22489f
--- /dev/null
+++ b/Lang/Prolog/Sorting-algorithms-Bogosort
@@ -0,0 +1 @@
+../../Task/Sorting-algorithms-Bogosort/Prolog
\ No newline at end of file
diff --git a/Lang/Prolog/Stair-climbing-puzzle b/Lang/Prolog/Stair-climbing-puzzle
new file mode 120000
index 0000000000..88469dee2a
--- /dev/null
+++ b/Lang/Prolog/Stair-climbing-puzzle
@@ -0,0 +1 @@
+../../Task/Stair-climbing-puzzle/Prolog
\ No newline at end of file
diff --git a/Lang/Prolog/Test-a-function b/Lang/Prolog/Test-a-function
new file mode 120000
index 0000000000..6b83074e4c
--- /dev/null
+++ b/Lang/Prolog/Test-a-function
@@ -0,0 +1 @@
+../../Task/Test-a-function/Prolog
\ No newline at end of file
diff --git a/Lang/Pyret/Zero-to-the-zero-power b/Lang/Pyret/Zero-to-the-zero-power
new file mode 120000
index 0000000000..e4e18f815f
--- /dev/null
+++ b/Lang/Pyret/Zero-to-the-zero-power
@@ -0,0 +1 @@
+../../Task/Zero-to-the-zero-power/Pyret
\ No newline at end of file
diff --git a/Lang/R/Address-of-a-variable b/Lang/R/Address-of-a-variable
new file mode 120000
index 0000000000..ed4a5ee38c
--- /dev/null
+++ b/Lang/R/Address-of-a-variable
@@ -0,0 +1 @@
+../../Task/Address-of-a-variable/R
\ No newline at end of file
diff --git a/Lang/R/CSV-to-HTML-translation b/Lang/R/CSV-to-HTML-translation
new file mode 120000
index 0000000000..f7946c2a58
--- /dev/null
+++ b/Lang/R/CSV-to-HTML-translation
@@ -0,0 +1 @@
+../../Task/CSV-to-HTML-translation/R
\ No newline at end of file
diff --git a/Lang/R/Gaussian-elimination b/Lang/R/Gaussian-elimination
new file mode 120000
index 0000000000..4d74feea7d
--- /dev/null
+++ b/Lang/R/Gaussian-elimination
@@ -0,0 +1 @@
+../../Task/Gaussian-elimination/R
\ No newline at end of file
diff --git a/Lang/R/Hello-world-Web-server b/Lang/R/Hello-world-Web-server
new file mode 120000
index 0000000000..35c46b642f
--- /dev/null
+++ b/Lang/R/Hello-world-Web-server
@@ -0,0 +1 @@
+../../Task/Hello-world-Web-server/R
\ No newline at end of file
diff --git a/Lang/R/Hofstadter-Q-sequence b/Lang/R/Hofstadter-Q-sequence
new file mode 120000
index 0000000000..64e956e787
--- /dev/null
+++ b/Lang/R/Hofstadter-Q-sequence
@@ -0,0 +1 @@
+../../Task/Hofstadter-Q-sequence/R
\ No newline at end of file
diff --git a/Lang/R/LU-decomposition b/Lang/R/LU-decomposition
new file mode 120000
index 0000000000..fa69fa3e28
--- /dev/null
+++ b/Lang/R/LU-decomposition
@@ -0,0 +1 @@
+../../Task/LU-decomposition/R
\ No newline at end of file
diff --git a/Lang/R/Left-factorials b/Lang/R/Left-factorials
new file mode 120000
index 0000000000..1dcb5ab2cb
--- /dev/null
+++ b/Lang/R/Left-factorials
@@ -0,0 +1 @@
+../../Task/Left-factorials/R
\ No newline at end of file
diff --git a/Lang/R/Narcissistic-decimal-number b/Lang/R/Narcissistic-decimal-number
new file mode 120000
index 0000000000..32d5d44a5c
--- /dev/null
+++ b/Lang/R/Narcissistic-decimal-number
@@ -0,0 +1 @@
+../../Task/Narcissistic-decimal-number/R
\ No newline at end of file
diff --git a/Lang/R/Number-names b/Lang/R/Number-names
new file mode 120000
index 0000000000..190f4c43e6
--- /dev/null
+++ b/Lang/R/Number-names
@@ -0,0 +1 @@
+../../Task/Number-names/R
\ No newline at end of file
diff --git a/Lang/R/Sockets b/Lang/R/Sockets
new file mode 120000
index 0000000000..0816745329
--- /dev/null
+++ b/Lang/R/Sockets
@@ -0,0 +1 @@
+../../Task/Sockets/R
\ No newline at end of file
diff --git a/Lang/R/Strip-whitespace-from-a-string-Top-and-tail b/Lang/R/Strip-whitespace-from-a-string-Top-and-tail
new file mode 120000
index 0000000000..447c7157c0
--- /dev/null
+++ b/Lang/R/Strip-whitespace-from-a-string-Top-and-tail
@@ -0,0 +1 @@
+../../Task/Strip-whitespace-from-a-string-Top-and-tail/R
\ No newline at end of file
diff --git a/Lang/R/Unix-ls b/Lang/R/Unix-ls
new file mode 120000
index 0000000000..a771c3e3b7
--- /dev/null
+++ b/Lang/R/Unix-ls
@@ -0,0 +1 @@
+../../Task/Unix-ls/R
\ No newline at end of file
diff --git a/Lang/REXX/00DESCRIPTION b/Lang/REXX/00DESCRIPTION
index 1c7ce1696d..49effbae75 100644
--- a/Lang/REXX/00DESCRIPTION
+++ b/Lang/REXX/00DESCRIPTION
@@ -16,8 +16,10 @@
 
 
 '''REXX'''   is also spelled:
-::*    Rexx 
-::*    REXX  
+::*    Rexx 
+::*    REXX  
+
+:::::::   but the primary official spelling is '''REXX''' and is the spelling used here on Rosetta Code.
 
  
 
@@ -47,7 +49,7 @@
 
 * '''[[PC/REXX]]''' is the first classic REXX implemented outside of IBM mainframes, intended for IBM DOS and MS DOS.   Written by Mansfield Software Group, Inc., REXX was bundled with KEDIT, a license is required to use this product.
 
-* '''[[Personal REXX]]''' is a classic REXX that is intended for IBM DOS and MS DOS, written by a Quercus Systems, a license is required to use this product.   
+* '''[[Personal REXX]]''' is a classic REXX that is intended for IBM DOS and MS DOS, written by a Quercus Systems, a license is required to use this product.   It is also known as REXX/Personal.  
 
 * '''Portable REXX'''   (see the   '''R4 REXX'''   entry, below).
  
@@ -57,6 +59,8 @@
 
 * '''[[REXX/imc]]''' a classic REXX developed by Ian M. Collier (imc) for Linux/Unix. 
 
+* '''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!'''.
 
 * '''[[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.
diff --git a/Lang/REXX/First-class-functions-Use-numbers-analogously b/Lang/REXX/First-class-functions-Use-numbers-analogously
new file mode 120000
index 0000000000..bfa7eaaed4
--- /dev/null
+++ b/Lang/REXX/First-class-functions-Use-numbers-analogously
@@ -0,0 +1 @@
+../../Task/First-class-functions-Use-numbers-analogously/REXX
\ No newline at end of file
diff --git a/Lang/Red/Bitwise-IO b/Lang/Red/Bitwise-IO
new file mode 120000
index 0000000000..95931e466d
--- /dev/null
+++ b/Lang/Red/Bitwise-IO
@@ -0,0 +1 @@
+../../Task/Bitwise-IO/Red
\ No newline at end of file
diff --git a/Lang/Red/Bitwise-operations b/Lang/Red/Bitwise-operations
new file mode 120000
index 0000000000..a75a04e59c
--- /dev/null
+++ b/Lang/Red/Bitwise-operations
@@ -0,0 +1 @@
+../../Task/Bitwise-operations/Red
\ No newline at end of file
diff --git a/Lang/Red/Pascals-triangle b/Lang/Red/Pascals-triangle
new file mode 120000
index 0000000000..af9035b891
--- /dev/null
+++ b/Lang/Red/Pascals-triangle
@@ -0,0 +1 @@
+../../Task/Pascals-triangle/Red
\ No newline at end of file
diff --git a/Lang/Red/Quaternion-type b/Lang/Red/Quaternion-type
new file mode 120000
index 0000000000..7b5fc87ddd
--- /dev/null
+++ b/Lang/Red/Quaternion-type
@@ -0,0 +1 @@
+../../Task/Quaternion-type/Red
\ No newline at end of file
diff --git a/Lang/Red/Voronoi-diagram b/Lang/Red/Voronoi-diagram
new file mode 120000
index 0000000000..4aa864e1f0
--- /dev/null
+++ b/Lang/Red/Voronoi-diagram
@@ -0,0 +1 @@
+../../Task/Voronoi-diagram/Red
\ No newline at end of file
diff --git a/Lang/Robotic/Copy-a-string b/Lang/Robotic/Copy-a-string
new file mode 120000
index 0000000000..1710046da6
--- /dev/null
+++ b/Lang/Robotic/Copy-a-string
@@ -0,0 +1 @@
+../../Task/Copy-a-string/Robotic
\ No newline at end of file
diff --git a/Lang/Robotic/Empty-string b/Lang/Robotic/Empty-string
new file mode 120000
index 0000000000..e2a3d1c164
--- /dev/null
+++ b/Lang/Robotic/Empty-string
@@ -0,0 +1 @@
+../../Task/Empty-string/Robotic
\ No newline at end of file
diff --git a/Lang/Robotic/Factorial b/Lang/Robotic/Factorial
new file mode 120000
index 0000000000..060f33e0a2
--- /dev/null
+++ b/Lang/Robotic/Factorial
@@ -0,0 +1 @@
+../../Task/Factorial/Robotic
\ No newline at end of file
diff --git a/Lang/Robotic/Jump-anywhere b/Lang/Robotic/Jump-anywhere
new file mode 120000
index 0000000000..40318e9de5
--- /dev/null
+++ b/Lang/Robotic/Jump-anywhere
@@ -0,0 +1 @@
+../../Task/Jump-anywhere/Robotic
\ No newline at end of file
diff --git a/Lang/Robotic/Keyboard-input-Keypress-check b/Lang/Robotic/Keyboard-input-Keypress-check
new file mode 120000
index 0000000000..feee12b44b
--- /dev/null
+++ b/Lang/Robotic/Keyboard-input-Keypress-check
@@ -0,0 +1 @@
+../../Task/Keyboard-input-Keypress-check/Robotic
\ No newline at end of file
diff --git a/Lang/Robotic/Loops-Infinite b/Lang/Robotic/Loops-Infinite
new file mode 120000
index 0000000000..dd83f6a809
--- /dev/null
+++ b/Lang/Robotic/Loops-Infinite
@@ -0,0 +1 @@
+../../Task/Loops-Infinite/Robotic
\ No newline at end of file
diff --git a/Lang/Robotic/String-append b/Lang/Robotic/String-append
new file mode 120000
index 0000000000..7590166d9c
--- /dev/null
+++ b/Lang/Robotic/String-append
@@ -0,0 +1 @@
+../../Task/String-append/Robotic
\ No newline at end of file
diff --git a/Lang/Robotic/String-comparison b/Lang/Robotic/String-comparison
new file mode 120000
index 0000000000..d5a3c25e51
--- /dev/null
+++ b/Lang/Robotic/String-comparison
@@ -0,0 +1 @@
+../../Task/String-comparison/Robotic
\ No newline at end of file
diff --git a/Lang/Ruby/Terminal-control-Inverse-video b/Lang/Ruby/Terminal-control-Inverse-video
new file mode 120000
index 0000000000..5f91bdf2a2
--- /dev/null
+++ b/Lang/Ruby/Terminal-control-Inverse-video
@@ -0,0 +1 @@
+../../Task/Terminal-control-Inverse-video/Ruby
\ No newline at end of file
diff --git a/Lang/Rust/Casting-out-nines b/Lang/Rust/Casting-out-nines
new file mode 120000
index 0000000000..3c121221f8
--- /dev/null
+++ b/Lang/Rust/Casting-out-nines
@@ -0,0 +1 @@
+../../Task/Casting-out-nines/Rust
\ No newline at end of file
diff --git a/Lang/Rust/Exceptions b/Lang/Rust/Exceptions
new file mode 120000
index 0000000000..6d21f62967
--- /dev/null
+++ b/Lang/Rust/Exceptions
@@ -0,0 +1 @@
+../../Task/Exceptions/Rust
\ No newline at end of file
diff --git a/Lang/Rust/File-modification-time b/Lang/Rust/File-modification-time
new file mode 120000
index 0000000000..9e4ff2b21e
--- /dev/null
+++ b/Lang/Rust/File-modification-time
@@ -0,0 +1 @@
+../../Task/File-modification-time/Rust
\ No newline at end of file
diff --git a/Lang/Rust/Five-weekends b/Lang/Rust/Five-weekends
new file mode 120000
index 0000000000..9281679559
--- /dev/null
+++ b/Lang/Rust/Five-weekends
@@ -0,0 +1 @@
+../../Task/Five-weekends/Rust
\ No newline at end of file
diff --git a/Lang/Rust/LZW-compression b/Lang/Rust/LZW-compression
new file mode 120000
index 0000000000..f1b83d2b34
--- /dev/null
+++ b/Lang/Rust/LZW-compression
@@ -0,0 +1 @@
+../../Task/LZW-compression/Rust
\ No newline at end of file
diff --git a/Lang/Rust/Last-letter-first-letter b/Lang/Rust/Last-letter-first-letter
new file mode 120000
index 0000000000..ebbf485698
--- /dev/null
+++ b/Lang/Rust/Last-letter-first-letter
@@ -0,0 +1 @@
+../../Task/Last-letter-first-letter/Rust
\ No newline at end of file
diff --git a/Lang/Rust/Matrix-exponentiation-operator b/Lang/Rust/Matrix-exponentiation-operator
new file mode 120000
index 0000000000..56c8f1c5ff
--- /dev/null
+++ b/Lang/Rust/Matrix-exponentiation-operator
@@ -0,0 +1 @@
+../../Task/Matrix-exponentiation-operator/Rust
\ No newline at end of file
diff --git a/Lang/Rust/Optional-parameters b/Lang/Rust/Optional-parameters
new file mode 120000
index 0000000000..9102ee27b5
--- /dev/null
+++ b/Lang/Rust/Optional-parameters
@@ -0,0 +1 @@
+../../Task/Optional-parameters/Rust
\ No newline at end of file
diff --git a/Lang/Rust/Phrase-reversals b/Lang/Rust/Phrase-reversals
new file mode 120000
index 0000000000..6accdaa86a
--- /dev/null
+++ b/Lang/Rust/Phrase-reversals
@@ -0,0 +1 @@
+../../Task/Phrase-reversals/Rust
\ No newline at end of file
diff --git a/Lang/Rust/Rep-string b/Lang/Rust/Rep-string
new file mode 120000
index 0000000000..1d5baa5c47
--- /dev/null
+++ b/Lang/Rust/Rep-string
@@ -0,0 +1 @@
+../../Task/Rep-string/Rust
\ No newline at end of file
diff --git a/Lang/Rust/Terminal-control-Ringing-the-terminal-bell b/Lang/Rust/Terminal-control-Ringing-the-terminal-bell
new file mode 120000
index 0000000000..13c233f3b4
--- /dev/null
+++ b/Lang/Rust/Terminal-control-Ringing-the-terminal-bell
@@ -0,0 +1 @@
+../../Task/Terminal-control-Ringing-the-terminal-bell/Rust
\ No newline at end of file
diff --git a/Lang/Rust/Vampire-number b/Lang/Rust/Vampire-number
new file mode 120000
index 0000000000..2eae242d5e
--- /dev/null
+++ b/Lang/Rust/Vampire-number
@@ -0,0 +1 @@
+../../Task/Vampire-number/Rust
\ No newline at end of file
diff --git a/Lang/Rust/XML-Input b/Lang/Rust/XML-Input
new file mode 120000
index 0000000000..a2c7d20acc
--- /dev/null
+++ b/Lang/Rust/XML-Input
@@ -0,0 +1 @@
+../../Task/XML-Input/Rust
\ No newline at end of file
diff --git a/Lang/Scala/Deal-cards-for-FreeCell b/Lang/Scala/Deal-cards-for-FreeCell
new file mode 120000
index 0000000000..f79dddc576
--- /dev/null
+++ b/Lang/Scala/Deal-cards-for-FreeCell
@@ -0,0 +1 @@
+../../Task/Deal-cards-for-FreeCell/Scala
\ No newline at end of file
diff --git a/Lang/Scala/Verify-distribution-uniformity-Naive b/Lang/Scala/Verify-distribution-uniformity-Naive
new file mode 120000
index 0000000000..75245e4f2d
--- /dev/null
+++ b/Lang/Scala/Verify-distribution-uniformity-Naive
@@ -0,0 +1 @@
+../../Task/Verify-distribution-uniformity-Naive/Scala
\ No newline at end of file
diff --git a/Lang/Shen/Flatten-a-list b/Lang/Shen/Flatten-a-list
new file mode 120000
index 0000000000..67f051f8c9
--- /dev/null
+++ b/Lang/Shen/Flatten-a-list
@@ -0,0 +1 @@
+../../Task/Flatten-a-list/Shen
\ No newline at end of file
diff --git a/Lang/Shen/Permutations b/Lang/Shen/Permutations
new file mode 120000
index 0000000000..0eccf4f433
--- /dev/null
+++ b/Lang/Shen/Permutations
@@ -0,0 +1 @@
+../../Task/Permutations/Shen
\ No newline at end of file
diff --git a/Lang/Shen/Roman-numerals-Encode b/Lang/Shen/Roman-numerals-Encode
new file mode 120000
index 0000000000..4eba812a1f
--- /dev/null
+++ b/Lang/Shen/Roman-numerals-Encode
@@ -0,0 +1 @@
+../../Task/Roman-numerals-Encode/Shen
\ No newline at end of file
diff --git a/Lang/Sidef/Average-loop-length b/Lang/Sidef/Average-loop-length
new file mode 120000
index 0000000000..08cca2b903
--- /dev/null
+++ b/Lang/Sidef/Average-loop-length
@@ -0,0 +1 @@
+../../Task/Average-loop-length/Sidef
\ No newline at end of file
diff --git a/Lang/Smalltalk/00DESCRIPTION b/Lang/Smalltalk/00DESCRIPTION
index 23120e1444..5e2e3d1862 100644
--- a/Lang/Smalltalk/00DESCRIPTION
+++ b/Lang/Smalltalk/00DESCRIPTION
@@ -292,7 +292,8 @@ JavaScript's functions are a syntactic different but semantically equal to Small
 ==Implementations==
 
 * Amber Smalltalk
-* Dolphin Smalltalk; (still actively developed?)
+* Dolphin Smalltalk; open source
+* GemStone/S; object-oriented Smalltalk database, free for private and commercial use
 * GNU Smalltalk; open source
 * Pharo; open source, mostly compatible to Squeak
 * S#
diff --git a/Lang/Smalltalk/Guess-the-number-With-feedback b/Lang/Smalltalk/Guess-the-number-With-feedback
new file mode 120000
index 0000000000..fea2fb4f94
--- /dev/null
+++ b/Lang/Smalltalk/Guess-the-number-With-feedback
@@ -0,0 +1 @@
+../../Task/Guess-the-number-With-feedback/Smalltalk
\ No newline at end of file
diff --git a/Lang/Standard-ML/Day-of-the-week b/Lang/Standard-ML/Day-of-the-week
new file mode 120000
index 0000000000..c57f3e869f
--- /dev/null
+++ b/Lang/Standard-ML/Day-of-the-week
@@ -0,0 +1 @@
+../../Task/Day-of-the-week/Standard-ML
\ No newline at end of file
diff --git a/Lang/Standard-ML/Factors-of-an-integer b/Lang/Standard-ML/Factors-of-an-integer
new file mode 120000
index 0000000000..4292ca61e4
--- /dev/null
+++ b/Lang/Standard-ML/Factors-of-an-integer
@@ -0,0 +1 @@
+../../Task/Factors-of-an-integer/Standard-ML
\ No newline at end of file
diff --git a/Lang/Stata/Bitmap-Write-a-PPM-file b/Lang/Stata/Bitmap-Write-a-PPM-file
new file mode 120000
index 0000000000..81ffd7f249
--- /dev/null
+++ b/Lang/Stata/Bitmap-Write-a-PPM-file
@@ -0,0 +1 @@
+../../Task/Bitmap-Write-a-PPM-file/Stata
\ No newline at end of file
diff --git a/Lang/Stata/Conjugate-transpose b/Lang/Stata/Conjugate-transpose
new file mode 120000
index 0000000000..3b2342a181
--- /dev/null
+++ b/Lang/Stata/Conjugate-transpose
@@ -0,0 +1 @@
+../../Task/Conjugate-transpose/Stata
\ No newline at end of file
diff --git a/Lang/Stata/Write-float-arrays-to-a-text-file b/Lang/Stata/Write-float-arrays-to-a-text-file
new file mode 120000
index 0000000000..189e2e6e92
--- /dev/null
+++ b/Lang/Stata/Write-float-arrays-to-a-text-file
@@ -0,0 +1 @@
+../../Task/Write-float-arrays-to-a-text-file/Stata
\ No newline at end of file
diff --git a/Lang/Swift/Almost-prime b/Lang/Swift/Almost-prime
new file mode 120000
index 0000000000..ae5f575395
--- /dev/null
+++ b/Lang/Swift/Almost-prime
@@ -0,0 +1 @@
+../../Task/Almost-prime/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Arithmetic-Rational b/Lang/Swift/Arithmetic-Rational
new file mode 120000
index 0000000000..30e7c0d468
--- /dev/null
+++ b/Lang/Swift/Arithmetic-Rational
@@ -0,0 +1 @@
+../../Task/Arithmetic-Rational/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Averages-Mean-angle b/Lang/Swift/Averages-Mean-angle
new file mode 120000
index 0000000000..3228d96bfe
--- /dev/null
+++ b/Lang/Swift/Averages-Mean-angle
@@ -0,0 +1 @@
+../../Task/Averages-Mean-angle/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Averages-Mean-time-of-day b/Lang/Swift/Averages-Mean-time-of-day
new file mode 120000
index 0000000000..9f773dda17
--- /dev/null
+++ b/Lang/Swift/Averages-Mean-time-of-day
@@ -0,0 +1 @@
+../../Task/Averages-Mean-time-of-day/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Averages-Root-mean-square b/Lang/Swift/Averages-Root-mean-square
new file mode 120000
index 0000000000..1512629167
--- /dev/null
+++ b/Lang/Swift/Averages-Root-mean-square
@@ -0,0 +1 @@
+../../Task/Averages-Root-mean-square/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Averages-Simple-moving-average b/Lang/Swift/Averages-Simple-moving-average
new file mode 120000
index 0000000000..507dcb5af9
--- /dev/null
+++ b/Lang/Swift/Averages-Simple-moving-average
@@ -0,0 +1 @@
+../../Task/Averages-Simple-moving-average/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Bernoulli-numbers b/Lang/Swift/Bernoulli-numbers
new file mode 120000
index 0000000000..388b9cf338
--- /dev/null
+++ b/Lang/Swift/Bernoulli-numbers
@@ -0,0 +1 @@
+../../Task/Bernoulli-numbers/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Carmichael-3-strong-pseudoprimes b/Lang/Swift/Carmichael-3-strong-pseudoprimes
new file mode 120000
index 0000000000..d5ce337186
--- /dev/null
+++ b/Lang/Swift/Carmichael-3-strong-pseudoprimes
@@ -0,0 +1 @@
+../../Task/Carmichael-3-strong-pseudoprimes/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Continued-fraction b/Lang/Swift/Continued-fraction
new file mode 120000
index 0000000000..451172bbf8
--- /dev/null
+++ b/Lang/Swift/Continued-fraction
@@ -0,0 +1 @@
+../../Task/Continued-fraction/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Conways-Game-of-Life b/Lang/Swift/Conways-Game-of-Life
new file mode 120000
index 0000000000..c006095bf0
--- /dev/null
+++ b/Lang/Swift/Conways-Game-of-Life
@@ -0,0 +1 @@
+../../Task/Conways-Game-of-Life/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Count-in-factors b/Lang/Swift/Count-in-factors
new file mode 120000
index 0000000000..5328dff772
--- /dev/null
+++ b/Lang/Swift/Count-in-factors
@@ -0,0 +1 @@
+../../Task/Count-in-factors/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Evaluate-binomial-coefficients b/Lang/Swift/Evaluate-binomial-coefficients
new file mode 120000
index 0000000000..e4e0ce5eb6
--- /dev/null
+++ b/Lang/Swift/Evaluate-binomial-coefficients
@@ -0,0 +1 @@
+../../Task/Evaluate-binomial-coefficients/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Fibonacci-word b/Lang/Swift/Fibonacci-word
new file mode 120000
index 0000000000..bfbfd4b15d
--- /dev/null
+++ b/Lang/Swift/Fibonacci-word
@@ -0,0 +1 @@
+../../Task/Fibonacci-word/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Four-bit-adder b/Lang/Swift/Four-bit-adder
new file mode 120000
index 0000000000..776acaf8ec
--- /dev/null
+++ b/Lang/Swift/Four-bit-adder
@@ -0,0 +1 @@
+../../Task/Four-bit-adder/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Gray-code b/Lang/Swift/Gray-code
new file mode 120000
index 0000000000..b1f9821f72
--- /dev/null
+++ b/Lang/Swift/Gray-code
@@ -0,0 +1 @@
+../../Task/Gray-code/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Knapsack-problem-Bounded b/Lang/Swift/Knapsack-problem-Bounded
new file mode 120000
index 0000000000..15a93ee588
--- /dev/null
+++ b/Lang/Swift/Knapsack-problem-Bounded
@@ -0,0 +1 @@
+../../Task/Knapsack-problem-Bounded/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Knights-tour b/Lang/Swift/Knights-tour
new file mode 120000
index 0000000000..42d56e737f
--- /dev/null
+++ b/Lang/Swift/Knights-tour
@@ -0,0 +1 @@
+../../Task/Knights-tour/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Left-factorials b/Lang/Swift/Left-factorials
new file mode 120000
index 0000000000..6eeec55e3c
--- /dev/null
+++ b/Lang/Swift/Left-factorials
@@ -0,0 +1 @@
+../../Task/Left-factorials/Swift
\ No newline at end of file
diff --git a/Lang/Swift/List-comprehensions b/Lang/Swift/List-comprehensions
new file mode 120000
index 0000000000..9e3762c0c1
--- /dev/null
+++ b/Lang/Swift/List-comprehensions
@@ -0,0 +1 @@
+../../Task/List-comprehensions/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Matrix-multiplication b/Lang/Swift/Matrix-multiplication
new file mode 120000
index 0000000000..93b26272dc
--- /dev/null
+++ b/Lang/Swift/Matrix-multiplication
@@ -0,0 +1 @@
+../../Task/Matrix-multiplication/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Matrix-transposition b/Lang/Swift/Matrix-transposition
new file mode 120000
index 0000000000..0d2b9267b9
--- /dev/null
+++ b/Lang/Swift/Matrix-transposition
@@ -0,0 +1 @@
+../../Task/Matrix-transposition/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Menu b/Lang/Swift/Menu
new file mode 120000
index 0000000000..1968a1e565
--- /dev/null
+++ b/Lang/Swift/Menu
@@ -0,0 +1 @@
+../../Task/Menu/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Modular-exponentiation b/Lang/Swift/Modular-exponentiation
new file mode 120000
index 0000000000..973f4e84ae
--- /dev/null
+++ b/Lang/Swift/Modular-exponentiation
@@ -0,0 +1 @@
+../../Task/Modular-exponentiation/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Modular-inverse b/Lang/Swift/Modular-inverse
new file mode 120000
index 0000000000..d81dc2f358
--- /dev/null
+++ b/Lang/Swift/Modular-inverse
@@ -0,0 +1 @@
+../../Task/Modular-inverse/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Narcissistic-decimal-number b/Lang/Swift/Narcissistic-decimal-number
new file mode 120000
index 0000000000..8eac9dafb1
--- /dev/null
+++ b/Lang/Swift/Narcissistic-decimal-number
@@ -0,0 +1 @@
+../../Task/Narcissistic-decimal-number/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Nth-root b/Lang/Swift/Nth-root
new file mode 120000
index 0000000000..8e0382fc18
--- /dev/null
+++ b/Lang/Swift/Nth-root
@@ -0,0 +1 @@
+../../Task/Nth-root/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Parallel-calculations b/Lang/Swift/Parallel-calculations
new file mode 120000
index 0000000000..f4edccf596
--- /dev/null
+++ b/Lang/Swift/Parallel-calculations
@@ -0,0 +1 @@
+../../Task/Parallel-calculations/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Pernicious-numbers b/Lang/Swift/Pernicious-numbers
new file mode 120000
index 0000000000..7d53d764e1
--- /dev/null
+++ b/Lang/Swift/Pernicious-numbers
@@ -0,0 +1 @@
+../../Task/Pernicious-numbers/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Polynomial-long-division b/Lang/Swift/Polynomial-long-division
new file mode 120000
index 0000000000..203c4969bf
--- /dev/null
+++ b/Lang/Swift/Polynomial-long-division
@@ -0,0 +1 @@
+../../Task/Polynomial-long-division/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Price-fraction b/Lang/Swift/Price-fraction
new file mode 120000
index 0000000000..918f59d8cc
--- /dev/null
+++ b/Lang/Swift/Price-fraction
@@ -0,0 +1 @@
+../../Task/Price-fraction/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Self-describing-numbers b/Lang/Swift/Self-describing-numbers
new file mode 120000
index 0000000000..46c4af7ef5
--- /dev/null
+++ b/Lang/Swift/Self-describing-numbers
@@ -0,0 +1 @@
+../../Task/Self-describing-numbers/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Semordnilap b/Lang/Swift/Semordnilap
new file mode 120000
index 0000000000..4cb0acedd4
--- /dev/null
+++ b/Lang/Swift/Semordnilap
@@ -0,0 +1 @@
+../../Task/Semordnilap/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Sort-an-array-of-composite-structures b/Lang/Swift/Sort-an-array-of-composite-structures
new file mode 120000
index 0000000000..53bd3d7929
--- /dev/null
+++ b/Lang/Swift/Sort-an-array-of-composite-structures
@@ -0,0 +1 @@
+../../Task/Sort-an-array-of-composite-structures/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Time-a-function b/Lang/Swift/Time-a-function
new file mode 120000
index 0000000000..0ed9c95b21
--- /dev/null
+++ b/Lang/Swift/Time-a-function
@@ -0,0 +1 @@
+../../Task/Time-a-function/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Vector-products b/Lang/Swift/Vector-products
new file mode 120000
index 0000000000..4f94a0247a
--- /dev/null
+++ b/Lang/Swift/Vector-products
@@ -0,0 +1 @@
+../../Task/Vector-products/Swift
\ No newline at end of file
diff --git a/Lang/Swift/Vigen-re-cipher b/Lang/Swift/Vigen-re-cipher
new file mode 120000
index 0000000000..dfb3058324
--- /dev/null
+++ b/Lang/Swift/Vigen-re-cipher
@@ -0,0 +1 @@
+../../Task/Vigen-re-cipher/Swift
\ No newline at end of file
diff --git a/Lang/UNIX-Shell/Execute-Brain---- b/Lang/UNIX-Shell/Execute-Brain----
new file mode 120000
index 0000000000..3bf61c145d
--- /dev/null
+++ b/Lang/UNIX-Shell/Execute-Brain----
@@ -0,0 +1 @@
+../../Task/Execute-Brain----/UNIX-Shell
\ No newline at end of file
diff --git a/Lang/UNIX-Shell/Universal-Turing-machine b/Lang/UNIX-Shell/Universal-Turing-machine
new file mode 120000
index 0000000000..973f316e0e
--- /dev/null
+++ b/Lang/UNIX-Shell/Universal-Turing-machine
@@ -0,0 +1 @@
+../../Task/Universal-Turing-machine/UNIX-Shell
\ No newline at end of file
diff --git a/Lang/V/100-doors b/Lang/V/100-doors
new file mode 120000
index 0000000000..2ec21ab9e7
--- /dev/null
+++ b/Lang/V/100-doors
@@ -0,0 +1 @@
+../../Task/100-doors/V
\ No newline at end of file
diff --git a/Lang/VHDL/FizzBuzz b/Lang/VHDL/FizzBuzz
new file mode 120000
index 0000000000..4862d2ee88
--- /dev/null
+++ b/Lang/VHDL/FizzBuzz
@@ -0,0 +1 @@
+../../Task/FizzBuzz/VHDL
\ No newline at end of file
diff --git a/Lang/Vala/Abstract-type b/Lang/Vala/Abstract-type
new file mode 120000
index 0000000000..19fdfc80bd
--- /dev/null
+++ b/Lang/Vala/Abstract-type
@@ -0,0 +1 @@
+../../Task/Abstract-type/Vala
\ No newline at end of file
diff --git a/Lang/Vala/Abundant,-deficient-and-perfect-number-classifications b/Lang/Vala/Abundant,-deficient-and-perfect-number-classifications
new file mode 120000
index 0000000000..c210f23053
--- /dev/null
+++ b/Lang/Vala/Abundant,-deficient-and-perfect-number-classifications
@@ -0,0 +1 @@
+../../Task/Abundant,-deficient-and-perfect-number-classifications/Vala
\ No newline at end of file
diff --git a/Lang/Vala/Ackermann-function b/Lang/Vala/Ackermann-function
new file mode 120000
index 0000000000..a1d773b26a
--- /dev/null
+++ b/Lang/Vala/Ackermann-function
@@ -0,0 +1 @@
+../../Task/Ackermann-function/Vala
\ No newline at end of file
diff --git a/Lang/Vala/Averages-Mean-angle b/Lang/Vala/Averages-Mean-angle
new file mode 120000
index 0000000000..08e2a6646d
--- /dev/null
+++ b/Lang/Vala/Averages-Mean-angle
@@ -0,0 +1 @@
+../../Task/Averages-Mean-angle/Vala
\ No newline at end of file
diff --git a/Lang/Vala/CRC-32 b/Lang/Vala/CRC-32
new file mode 120000
index 0000000000..0bc5c0509e
--- /dev/null
+++ b/Lang/Vala/CRC-32
@@ -0,0 +1 @@
+../../Task/CRC-32/Vala
\ No newline at end of file
diff --git a/Lang/Vala/Carmichael-3-strong-pseudoprimes b/Lang/Vala/Carmichael-3-strong-pseudoprimes
new file mode 120000
index 0000000000..066ea55fca
--- /dev/null
+++ b/Lang/Vala/Carmichael-3-strong-pseudoprimes
@@ -0,0 +1 @@
+../../Task/Carmichael-3-strong-pseudoprimes/Vala
\ No newline at end of file
diff --git a/Lang/Vala/Catalan-numbers b/Lang/Vala/Catalan-numbers
new file mode 120000
index 0000000000..ec5fc3591e
--- /dev/null
+++ b/Lang/Vala/Catalan-numbers
@@ -0,0 +1 @@
+../../Task/Catalan-numbers/Vala
\ No newline at end of file
diff --git a/Lang/Vala/Catalan-numbers-Pascals-triangle b/Lang/Vala/Catalan-numbers-Pascals-triangle
new file mode 120000
index 0000000000..fbbfae5286
--- /dev/null
+++ b/Lang/Vala/Catalan-numbers-Pascals-triangle
@@ -0,0 +1 @@
+../../Task/Catalan-numbers-Pascals-triangle/Vala
\ No newline at end of file
diff --git a/Lang/Vala/Compound-data-type b/Lang/Vala/Compound-data-type
new file mode 120000
index 0000000000..5bfb554f9c
--- /dev/null
+++ b/Lang/Vala/Compound-data-type
@@ -0,0 +1 @@
+../../Task/Compound-data-type/Vala
\ No newline at end of file
diff --git a/Lang/Vala/Convert-decimal-number-to-rational b/Lang/Vala/Convert-decimal-number-to-rational
new file mode 120000
index 0000000000..f7827d6aee
--- /dev/null
+++ b/Lang/Vala/Convert-decimal-number-to-rational
@@ -0,0 +1 @@
+../../Task/Convert-decimal-number-to-rational/Vala
\ No newline at end of file
diff --git a/Lang/Vala/Loop-over-multiple-arrays-simultaneously b/Lang/Vala/Loop-over-multiple-arrays-simultaneously
new file mode 120000
index 0000000000..ca41ee03f9
--- /dev/null
+++ b/Lang/Vala/Loop-over-multiple-arrays-simultaneously
@@ -0,0 +1 @@
+../../Task/Loop-over-multiple-arrays-simultaneously/Vala
\ No newline at end of file
diff --git a/Lang/Vala/Loops-Continue b/Lang/Vala/Loops-Continue
new file mode 120000
index 0000000000..8db5e39345
--- /dev/null
+++ b/Lang/Vala/Loops-Continue
@@ -0,0 +1 @@
+../../Task/Loops-Continue/Vala
\ No newline at end of file
diff --git a/Lang/Vala/Loops-Do-while b/Lang/Vala/Loops-Do-while
new file mode 120000
index 0000000000..6fe0a28f0a
--- /dev/null
+++ b/Lang/Vala/Loops-Do-while
@@ -0,0 +1 @@
+../../Task/Loops-Do-while/Vala
\ No newline at end of file
diff --git a/Lang/Vala/Loops-Downward-for b/Lang/Vala/Loops-Downward-for
new file mode 120000
index 0000000000..4be9d84559
--- /dev/null
+++ b/Lang/Vala/Loops-Downward-for
@@ -0,0 +1 @@
+../../Task/Loops-Downward-for/Vala
\ No newline at end of file
diff --git a/Lang/Vala/Loops-For-with-a-specified-step b/Lang/Vala/Loops-For-with-a-specified-step
new file mode 120000
index 0000000000..36a77a325c
--- /dev/null
+++ b/Lang/Vala/Loops-For-with-a-specified-step
@@ -0,0 +1 @@
+../../Task/Loops-For-with-a-specified-step/Vala
\ No newline at end of file
diff --git a/Lang/Vala/Loops-Foreach b/Lang/Vala/Loops-Foreach
new file mode 120000
index 0000000000..778bbf6a70
--- /dev/null
+++ b/Lang/Vala/Loops-Foreach
@@ -0,0 +1 @@
+../../Task/Loops-Foreach/Vala
\ No newline at end of file
diff --git a/Lang/Vala/Loops-N-plus-one-half b/Lang/Vala/Loops-N-plus-one-half
new file mode 120000
index 0000000000..63c054d7ed
--- /dev/null
+++ b/Lang/Vala/Loops-N-plus-one-half
@@ -0,0 +1 @@
+../../Task/Loops-N-plus-one-half/Vala
\ No newline at end of file
diff --git a/Lang/Vala/Loops-Nested b/Lang/Vala/Loops-Nested
new file mode 120000
index 0000000000..33a2f1d6e8
--- /dev/null
+++ b/Lang/Vala/Loops-Nested
@@ -0,0 +1 @@
+../../Task/Loops-Nested/Vala
\ No newline at end of file
diff --git a/Lang/Vala/Loops-While b/Lang/Vala/Loops-While
new file mode 120000
index 0000000000..b2eafb4e5a
--- /dev/null
+++ b/Lang/Vala/Loops-While
@@ -0,0 +1 @@
+../../Task/Loops-While/Vala
\ No newline at end of file
diff --git a/Lang/Vala/Map-range b/Lang/Vala/Map-range
new file mode 120000
index 0000000000..9c12392b8a
--- /dev/null
+++ b/Lang/Vala/Map-range
@@ -0,0 +1 @@
+../../Task/Map-range/Vala
\ No newline at end of file
diff --git a/Lang/Vala/Roman-numerals-Encode b/Lang/Vala/Roman-numerals-Encode
new file mode 120000
index 0000000000..cf757315e1
--- /dev/null
+++ b/Lang/Vala/Roman-numerals-Encode
@@ -0,0 +1 @@
+../../Task/Roman-numerals-Encode/Vala
\ No newline at end of file
diff --git a/Lang/Vala/Rot-13 b/Lang/Vala/Rot-13
new file mode 120000
index 0000000000..2207be271c
--- /dev/null
+++ b/Lang/Vala/Rot-13
@@ -0,0 +1 @@
+../../Task/Rot-13/Vala
\ No newline at end of file
diff --git a/Lang/Vala/Sorting-algorithms-Bubble-sort b/Lang/Vala/Sorting-algorithms-Bubble-sort
new file mode 120000
index 0000000000..8dd5779d50
--- /dev/null
+++ b/Lang/Vala/Sorting-algorithms-Bubble-sort
@@ -0,0 +1 @@
+../../Task/Sorting-algorithms-Bubble-sort/Vala
\ No newline at end of file
diff --git a/Lang/Vala/Sorting-algorithms-Cocktail-sort b/Lang/Vala/Sorting-algorithms-Cocktail-sort
new file mode 120000
index 0000000000..e2730df2af
--- /dev/null
+++ b/Lang/Vala/Sorting-algorithms-Cocktail-sort
@@ -0,0 +1 @@
+../../Task/Sorting-algorithms-Cocktail-sort/Vala
\ No newline at end of file
diff --git a/Lang/Vala/Sorting-algorithms-Heapsort b/Lang/Vala/Sorting-algorithms-Heapsort
new file mode 120000
index 0000000000..2a1dd0fbfb
--- /dev/null
+++ b/Lang/Vala/Sorting-algorithms-Heapsort
@@ -0,0 +1 @@
+../../Task/Sorting-algorithms-Heapsort/Vala
\ No newline at end of file
diff --git a/Lang/Vala/Sorting-algorithms-Insertion-sort b/Lang/Vala/Sorting-algorithms-Insertion-sort
new file mode 120000
index 0000000000..e1b2c06037
--- /dev/null
+++ b/Lang/Vala/Sorting-algorithms-Insertion-sort
@@ -0,0 +1 @@
+../../Task/Sorting-algorithms-Insertion-sort/Vala
\ No newline at end of file
diff --git a/Lang/Vala/String-append b/Lang/Vala/String-append
new file mode 120000
index 0000000000..87bd328f15
--- /dev/null
+++ b/Lang/Vala/String-append
@@ -0,0 +1 @@
+../../Task/String-append/Vala
\ No newline at end of file
diff --git a/Lang/Vala/String-comparison b/Lang/Vala/String-comparison
new file mode 120000
index 0000000000..ac8d1ba999
--- /dev/null
+++ b/Lang/Vala/String-comparison
@@ -0,0 +1 @@
+../../Task/String-comparison/Vala
\ No newline at end of file
diff --git a/Lang/Vala/String-concatenation b/Lang/Vala/String-concatenation
new file mode 120000
index 0000000000..52e40c6fd2
--- /dev/null
+++ b/Lang/Vala/String-concatenation
@@ -0,0 +1 @@
+../../Task/String-concatenation/Vala
\ No newline at end of file
diff --git a/Lang/Vala/String-interpolation--included- b/Lang/Vala/String-interpolation--included-
new file mode 120000
index 0000000000..6d8a3317c0
--- /dev/null
+++ b/Lang/Vala/String-interpolation--included-
@@ -0,0 +1 @@
+../../Task/String-interpolation--included-/Vala
\ No newline at end of file
diff --git a/Lang/Vala/String-matching b/Lang/Vala/String-matching
new file mode 120000
index 0000000000..34a8c65305
--- /dev/null
+++ b/Lang/Vala/String-matching
@@ -0,0 +1 @@
+../../Task/String-matching/Vala
\ No newline at end of file
diff --git a/Lang/Visual-Basic-.NET/Append-a-record-to-the-end-of-a-text-file b/Lang/Visual-Basic-.NET/Append-a-record-to-the-end-of-a-text-file
new file mode 120000
index 0000000000..2ba8cc146c
--- /dev/null
+++ b/Lang/Visual-Basic-.NET/Append-a-record-to-the-end-of-a-text-file
@@ -0,0 +1 @@
+../../Task/Append-a-record-to-the-end-of-a-text-file/Visual-Basic-.NET
\ No newline at end of file
diff --git a/Lang/Visual-Basic-.NET/Balanced-ternary b/Lang/Visual-Basic-.NET/Balanced-ternary
new file mode 120000
index 0000000000..0408431760
--- /dev/null
+++ b/Lang/Visual-Basic-.NET/Balanced-ternary
@@ -0,0 +1 @@
+../../Task/Balanced-ternary/Visual-Basic-.NET
\ No newline at end of file
diff --git a/Lang/Visual-Basic-.NET/Detect-division-by-zero b/Lang/Visual-Basic-.NET/Detect-division-by-zero
new file mode 120000
index 0000000000..c202b7be02
--- /dev/null
+++ b/Lang/Visual-Basic-.NET/Detect-division-by-zero
@@ -0,0 +1 @@
+../../Task/Detect-division-by-zero/Visual-Basic-.NET
\ No newline at end of file
diff --git a/Lang/Visual-Basic-.NET/Execute-a-system-command b/Lang/Visual-Basic-.NET/Execute-a-system-command
new file mode 120000
index 0000000000..8e56380b13
--- /dev/null
+++ b/Lang/Visual-Basic-.NET/Execute-a-system-command
@@ -0,0 +1 @@
+../../Task/Execute-a-system-command/Visual-Basic-.NET
\ No newline at end of file
diff --git a/Lang/Visual-Basic-.NET/Filter b/Lang/Visual-Basic-.NET/Filter
new file mode 120000
index 0000000000..2f83d3d82a
--- /dev/null
+++ b/Lang/Visual-Basic-.NET/Filter
@@ -0,0 +1 @@
+../../Task/Filter/Visual-Basic-.NET
\ No newline at end of file
diff --git a/Lang/Visual-Basic-.NET/Generate-lower-case-ASCII-alphabet b/Lang/Visual-Basic-.NET/Generate-lower-case-ASCII-alphabet
new file mode 120000
index 0000000000..fd91bd0f88
--- /dev/null
+++ b/Lang/Visual-Basic-.NET/Generate-lower-case-ASCII-alphabet
@@ -0,0 +1 @@
+../../Task/Generate-lower-case-ASCII-alphabet/Visual-Basic-.NET
\ No newline at end of file
diff --git a/Lang/Visual-Basic-.NET/Generic-swap b/Lang/Visual-Basic-.NET/Generic-swap
new file mode 120000
index 0000000000..e2051c0f08
--- /dev/null
+++ b/Lang/Visual-Basic-.NET/Generic-swap
@@ -0,0 +1 @@
+../../Task/Generic-swap/Visual-Basic-.NET
\ No newline at end of file
diff --git a/Lang/Visual-Basic-.NET/MD5 b/Lang/Visual-Basic-.NET/MD5
new file mode 120000
index 0000000000..172da3ee55
--- /dev/null
+++ b/Lang/Visual-Basic-.NET/MD5
@@ -0,0 +1 @@
+../../Task/MD5/Visual-Basic-.NET
\ No newline at end of file
diff --git a/Lang/Visual-Basic-.NET/Parametric-polymorphism b/Lang/Visual-Basic-.NET/Parametric-polymorphism
new file mode 120000
index 0000000000..8820b35e5b
--- /dev/null
+++ b/Lang/Visual-Basic-.NET/Parametric-polymorphism
@@ -0,0 +1 @@
+../../Task/Parametric-polymorphism/Visual-Basic-.NET
\ No newline at end of file
diff --git a/Lang/Visual-Basic-.NET/Zeckendorf-arithmetic b/Lang/Visual-Basic-.NET/Zeckendorf-arithmetic
new file mode 120000
index 0000000000..2cf29c8465
--- /dev/null
+++ b/Lang/Visual-Basic-.NET/Zeckendorf-arithmetic
@@ -0,0 +1 @@
+../../Task/Zeckendorf-arithmetic/Visual-Basic-.NET
\ No newline at end of file
diff --git a/Lang/WebAssembly/Factorial b/Lang/WebAssembly/Factorial
new file mode 120000
index 0000000000..ef1e0b9937
--- /dev/null
+++ b/Lang/WebAssembly/Factorial
@@ -0,0 +1 @@
+../../Task/Factorial/WebAssembly
\ No newline at end of file
diff --git a/Lang/X86-Assembly/Ackermann-function b/Lang/X86-Assembly/Ackermann-function
new file mode 120000
index 0000000000..238514955a
--- /dev/null
+++ b/Lang/X86-Assembly/Ackermann-function
@@ -0,0 +1 @@
+../../Task/Ackermann-function/X86-Assembly
\ No newline at end of file
diff --git a/Lang/X86-Assembly/Copy-a-string b/Lang/X86-Assembly/Copy-a-string
new file mode 120000
index 0000000000..3bc21a5c58
--- /dev/null
+++ b/Lang/X86-Assembly/Copy-a-string
@@ -0,0 +1 @@
+../../Task/Copy-a-string/X86-Assembly
\ No newline at end of file
diff --git a/Lang/X86-Assembly/Factors-of-an-integer b/Lang/X86-Assembly/Factors-of-an-integer
new file mode 120000
index 0000000000..81884dfb31
--- /dev/null
+++ b/Lang/X86-Assembly/Factors-of-an-integer
@@ -0,0 +1 @@
+../../Task/Factors-of-an-integer/X86-Assembly
\ No newline at end of file
diff --git a/Lang/X86-Assembly/Iterated-digits-squaring b/Lang/X86-Assembly/Iterated-digits-squaring
new file mode 120000
index 0000000000..c88b09e73d
--- /dev/null
+++ b/Lang/X86-Assembly/Iterated-digits-squaring
@@ -0,0 +1 @@
+../../Task/Iterated-digits-squaring/X86-Assembly
\ No newline at end of file
diff --git a/Lang/X86-Assembly/Loop-over-multiple-arrays-simultaneously b/Lang/X86-Assembly/Loop-over-multiple-arrays-simultaneously
new file mode 120000
index 0000000000..6f37854e87
--- /dev/null
+++ b/Lang/X86-Assembly/Loop-over-multiple-arrays-simultaneously
@@ -0,0 +1 @@
+../../Task/Loop-over-multiple-arrays-simultaneously/X86-Assembly
\ No newline at end of file
diff --git a/Lang/X86-Assembly/Loops-Continue b/Lang/X86-Assembly/Loops-Continue
new file mode 120000
index 0000000000..803f22d5e0
--- /dev/null
+++ b/Lang/X86-Assembly/Loops-Continue
@@ -0,0 +1 @@
+../../Task/Loops-Continue/X86-Assembly
\ No newline at end of file
diff --git a/Lang/X86-Assembly/Loops-Do-while b/Lang/X86-Assembly/Loops-Do-while
new file mode 120000
index 0000000000..8bada22f74
--- /dev/null
+++ b/Lang/X86-Assembly/Loops-Do-while
@@ -0,0 +1 @@
+../../Task/Loops-Do-while/X86-Assembly
\ No newline at end of file
diff --git a/Lang/X86-Assembly/Pascals-triangle b/Lang/X86-Assembly/Pascals-triangle
new file mode 120000
index 0000000000..721f3956ce
--- /dev/null
+++ b/Lang/X86-Assembly/Pascals-triangle
@@ -0,0 +1 @@
+../../Task/Pascals-triangle/X86-Assembly
\ No newline at end of file
diff --git a/Lang/XPL0/00DESCRIPTION b/Lang/XPL0/00DESCRIPTION
index 39875b4f33..3865cfe8fe 100644
--- a/Lang/XPL0/00DESCRIPTION
+++ b/Lang/XPL0/00DESCRIPTION
@@ -8,9 +8,9 @@ XPL0 compiler was written in ALGOL, which was then used to create a compiler
 written in XPL0's syntax.
 
 XPL0 has been implemented on more than a dozen processors, but it's
-currently maintained for IBM-type PCs. Programs run under DOS and under versions of Windows that can still run DOS apps. Free, open-source versions of the
+currently maintained on the Raspberry Pi and IBM-type PCs. Programs run under Linux, Windows, and DOS. Free, open-source versions of the
 compilers (interpreted, assembly-code compiled, and optimizing) are
-available from the official website: xpl0.org [http://www.xpl0.org/]. The 32-bit version of the compiler, XPLPX, was used for all these Rosetta Code tasks.
+available from the official website: xpl0.org [http://www.xpl0.org/]. The 32-bit version of the DOS compiler, XPLPX, was used for most of these Rosetta Code tasks, but more recent tasks were implemented using the compilers for the Raspberry Pi.
 
 Here's how the traditional Hello World program is coded:
 
@@ -26,6 +26,12 @@ a printer, a file, or out a serial port by using a different number.
 
 All names must be declared before they can be used. The command word
 ''code'' associates the name Text to the built-in routine number 12, which
-outputs strings. There are about 80 of these built-in routines that
+outputs strings. There are over a hundred of these built-in routines that
 provide capabilities such as input and output, graphics, and trig
-functions.
\ No newline at end of file
+functions.
+
+The Raspberry Pi versions of the compilers (as well as the Windows' version, EXPL-32) automatically declare ''code'' declarations. Thus the above program can simply be written as:
+
+
+      Text(0, "Hello World!")
+
\ No newline at end of file diff --git a/Lang/XPL0/ABC-Problem b/Lang/XPL0/ABC-Problem new file mode 120000 index 0000000000..3052c2fe6c --- /dev/null +++ b/Lang/XPL0/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Fibonacci-sequence b/Lang/XPL0/Fibonacci-sequence new file mode 120000 index 0000000000..23a549c4ed --- /dev/null +++ b/Lang/XPL0/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Formatted-numeric-output b/Lang/XPL0/Formatted-numeric-output new file mode 120000 index 0000000000..813aac4811 --- /dev/null +++ b/Lang/XPL0/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Hello-world-Graphical b/Lang/XPL0/Hello-world-Graphical new file mode 120000 index 0000000000..6cf4167147 --- /dev/null +++ b/Lang/XPL0/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Input-loop b/Lang/XPL0/Input-loop new file mode 120000 index 0000000000..d997068fdd --- /dev/null +++ b/Lang/XPL0/Input-loop @@ -0,0 +1 @@ +../../Task/Input-loop/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Read-a-file-line-by-line b/Lang/XPL0/Read-a-file-line-by-line new file mode 120000 index 0000000000..25ebe1b351 --- /dev/null +++ b/Lang/XPL0/Read-a-file-line-by-line @@ -0,0 +1 @@ +../../Task/Read-a-file-line-by-line/XPL0 \ No newline at end of file diff --git a/Lang/XPL0/Zero-to-the-zero-power b/Lang/XPL0/Zero-to-the-zero-power new file mode 120000 index 0000000000..d46832a578 --- /dev/null +++ b/Lang/XPL0/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/XPL0 \ No newline at end of file diff --git a/Lang/XQuery/A+B b/Lang/XQuery/A+B new file mode 120000 index 0000000000..74c8c16ae7 --- /dev/null +++ b/Lang/XQuery/A+B @@ -0,0 +1 @@ +../../Task/A+B/XQuery \ No newline at end of file diff --git a/Lang/XQuery/JSON b/Lang/XQuery/JSON new file mode 120000 index 0000000000..a2d4e69101 --- /dev/null +++ b/Lang/XQuery/JSON @@ -0,0 +1 @@ +../../Task/JSON/XQuery \ No newline at end of file diff --git a/Lang/XQuery/Longest-string-challenge b/Lang/XQuery/Longest-string-challenge new file mode 120000 index 0000000000..da51732651 --- /dev/null +++ b/Lang/XQuery/Longest-string-challenge @@ -0,0 +1 @@ +../../Task/Longest-string-challenge/XQuery \ No newline at end of file diff --git a/Lang/XQuery/XML-Output b/Lang/XQuery/XML-Output new file mode 120000 index 0000000000..29c4e98eb0 --- /dev/null +++ b/Lang/XQuery/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/XQuery \ No newline at end of file diff --git a/Task/100-doors/C-sharp/100-doors-2.cs b/Task/100-doors/C-sharp/100-doors-2.cs index 1b18af4e1d..e157701666 100644 --- a/Task/100-doors/C-sharp/100-doors-2.cs +++ b/Task/100-doors/C-sharp/100-doors-2.cs @@ -3,29 +3,18 @@ namespace ConsoleApplication1 using System; class Program { - static void Main() + static void Main(string[] args) { - //The o variable stores the number of the next OPEN door. - int o = 1; - int f = 1; - int l = 5; - Random r = new Random(); - o = r.Next(f, l); + //Perform the operation. + bool[] doors = new bool[100]; + int n = 0; + int d; + while ((d = (++n * n)) <= 100) + doors[d - 1] = true; - //The d variable determines the door to be output next. - for (int d = 1; d <= 100; d++) - { - Console.Write("Door #{0}: ", d); - if (d == o) - { - Console.WriteLine("Open"); - f = f + 5; - l = l + 5; - o = r.Next(f, l); - } - else - Console.WriteLine("Closed"); - } + //Perform the presentation. + for (d = 0; d < doors.Length; d++) + Console.WriteLine("Door #{0}: {1}", d + 1, doors[d] ? "Open" : "Closed"); Console.ReadKey(true); } } diff --git a/Task/100-doors/C-sharp/100-doors-3.cs b/Task/100-doors/C-sharp/100-doors-3.cs index e157701666..abd365f161 100644 --- a/Task/100-doors/C-sharp/100-doors-3.cs +++ b/Task/100-doors/C-sharp/100-doors-3.cs @@ -3,17 +3,15 @@ namespace ConsoleApplication1 using System; class Program { - static void Main(string[] args) + static void Main() { - //Perform the operation. bool[] doors = new bool[100]; - int n = 0; - int d; - while ((d = (++n * n)) <= 100) - doors[d - 1] = true; - //Perform the presentation. - for (d = 0; d < doors.Length; d++) + //The number of passes can be 1-based, but the number of doors must be 0-based. + for (int p = 1; p <= 100; p++) + for (int d = p - 1; d < 100; d += p) + doors[d] = !doors[d]; + for (int d = 0; d < 100; d++) Console.WriteLine("Door #{0}: {1}", d + 1, doors[d] ? "Open" : "Closed"); Console.ReadKey(true); } diff --git a/Task/100-doors/C-sharp/100-doors-4.cs b/Task/100-doors/C-sharp/100-doors-4.cs index abd365f161..9524cdb716 100644 --- a/Task/100-doors/C-sharp/100-doors-4.cs +++ b/Task/100-doors/C-sharp/100-doors-4.cs @@ -5,14 +5,11 @@ namespace ConsoleApplication1 { static void Main() { - bool[] doors = new bool[100]; + double n; - //The number of passes can be 1-based, but the number of doors must be 0-based. - for (int p = 1; p <= 100; p++) - for (int d = p - 1; d < 100; d += p) - doors[d] = !doors[d]; - for (int d = 0; d < 100; d++) - Console.WriteLine("Door #{0}: {1}", d + 1, doors[d] ? "Open" : "Closed"); + //If the current door number is the perfect square of an integer, say it is open, else say it is closed. + for (int d = 1; d <= 100; d++) + Console.WriteLine("Door #{0}: {1}", d, (n = Math.Sqrt(d)) == (int)n ? "Open" : "Closed"); Console.ReadKey(true); } } diff --git a/Task/100-doors/EDSAC-order-code/100-doors.edsac b/Task/100-doors/EDSAC-order-code/100-doors.edsac new file mode 100644 index 0000000000..b57dfaf198 --- /dev/null +++ b/Task/100-doors/EDSAC-order-code/100-doors.edsac @@ -0,0 +1,115 @@ +[Hundred doors problem from Rosetta Code website] +[EDSAC program, Initial Orders 2] + +[Library subroutine M3. Prints header and is then overwritten. +Here, the last character sets the teleprinter to figures.] + PFGKIFAFRDLFUFOFE@A6FG@E8FEZPF + @&*THE!OPEN!DOORS!ARE@&# + ..PZ [blank tape, needed to mark end of header text] + +[Library subroutine P6. Prints strictly positive integer. +32 locations; working locations 1, 4, 5] + T56K [define load address for subroutine] + GKA3FT25@H29@VFT4DA3@TFH30@S6@T1F + V4DU4DAFG26@TFTFO5FA4DF4FS4F + L4FT4DA1FS3@G9@EFSFO31@E20@J995FJF!F + + T88K [define load address for main program] + GK [set @ (theta) for relative addresses] + +[The 100 doors are at locations 200..299. +Doors are numbered 0..99 internally, and 1..100 for output. +The base address and the number of doors can be varied. +The value of a door is 0 if open, negative if closed.] + + [Constants. Program also uses order 'P 1 F' + which is permanently at absolute address 2.] + [0] P200F [address of door #0] + [1] P100F [number of doors, as an address] + [2] UF [makes S order from T, since 'S' = 'T' + 'U'] + [3] MF [makes A order from T, since 'A' = 'T' + 'M'] + [4] V2047D [all 1's for "closed" (any negative value will do)] + [5] &F [line feed] + [6] @F [carriage return] + [7] K4096F [teleprinter null[ + + [Variables] + [8] PF [pass number; step when toggling doors] + [9] PF [door number, as address, 0-based] + [10] PF [order referring to door 0] + + [Enter with acc = 0] + [Part 1 : close all the doors] + [11] T8@ [pass := 0 (used in part 2)] + T9@ [door number := 0] + A16@ [load 'T F' order] + A@ [add base address] + T10@ [store T order for door #0] + [16] TF [clear acc; also serves as constant] + A9@ [load door number] + A10@ [make T order] + T21@ [plant in code] + A4@ [load value for "closed"] + [21] TF [store in current door] + A9@ [load door number] + A2F [add 1] + U9@ [update door number] + S1@ [done all doors yet?] + G16@ [if not, loop back] + + [Part 2 : 100 passes, toggling the doors] + [27] TF [clear acc] + A8@ [load pass number] + A2F [add 1] + T8@ [save updated pass number] + S2F [make -1] + U9@ [door number := -1] + A8@ [add pass number to get first door toggled on this pass] + S1@ [gone beyond end?] + E50@ [if so, move on to part 3] + [36] A1@ [restore acc after test] + U9@ [store current door number] + A10@ [make T order to load status] + U44@ [plant T order for first door in pass] + A2@ [convert to S order] + T43@ [plant S order] + A4@ [load value for "closed"] + [43] SF [subtract status; toggles status] + [44] TF [update status] + A9@ [load door number just toggled] + A8@ [add pass number to get next door in pass] + S1@ [gone beyond end?] + G36@ [no, loop to do next door] + E27@ [yes, loop to do next pass] + + [Part 3 : Print list of open doors. + Header has set teleprinter to figures.] + [50] TF [clear acc] + T9@ [door nr := 0] + A10@ [T order for door 0] + A3@ [convert to A order] + T10@ + [55] TF + A9@ [load door number] + A10@ [make A order to load value] + T59@ [plant in next order] + [59] AF [acc := 0 if open, < 0 if closed] + G69@ [skip if closed] + A9@ [door number as address] + A2F [add 1 for 1-based output] + RD [shift 1 right, address --> integer] + TF [store integer at 0 for printing] + [65] A65@ [for return from subroutine] + G56F [call subroutine to print door number] + O6@ [followed by CRLF] + O5@ + [69] TF [clear acc] + A9@ [load door number] + A2F [add 1] + U9@ [update door number] + S1@ [done all doors yet?] + G55@ [if not, loop back] + [75] O7@ [output null to flush teleprinter buffer] + ZF [stop] + E11Z [define relative start address] + PF diff --git a/Task/100-doors/Java/100-doors-2.java b/Task/100-doors/Java/100-doors-2.java index 8faa42f92b..d56c734393 100644 --- a/Task/100-doors/Java/100-doors-2.java +++ b/Task/100-doors/Java/100-doors-2.java @@ -1,6 +1,14 @@ -class HundredDoors { +import java.util.BitSet; + +public class HundredDoors { public static void main(String[] args) { - for (int i = 1; i <= 10; i++) - System.out.printf("Door %d is open.%n", i * i); + final int n = 100; + var a = new BitSet(n); + for (int i = 1; i <= n; i++) { + for (int j = i - 1; j < n; j += i) { + a.flip(j); + } + } + a.stream().map(i -> i + 1).forEachOrdered(System.out::println); } } diff --git a/Task/100-doors/Java/100-doors-3.java b/Task/100-doors/Java/100-doors-3.java index 8d9ada9050..8faa42f92b 100644 --- a/Task/100-doors/Java/100-doors-3.java +++ b/Task/100-doors/Java/100-doors-3.java @@ -1,12 +1,6 @@ -import java.util.stream.Collectors; -import java.util.stream.IntStream; - class HundredDoors { - public static void main(String args[]) { - String openDoors = IntStream.rangeClosed(1, 100) - .filter(i -> Math.pow((int) Math.sqrt(i), 2) == i) - .mapToObj(Integer::toString) - .collect(Collectors.joining(", ")); - System.out.printf("Open doors: %s%n", openDoors); + public static void main(String[] args) { + for (int i = 1; i <= 10; i++) + System.out.printf("Door %d is open.%n", i * i); } } diff --git a/Task/100-doors/Java/100-doors-4.java b/Task/100-doors/Java/100-doors-4.java new file mode 100644 index 0000000000..8d9ada9050 --- /dev/null +++ b/Task/100-doors/Java/100-doors-4.java @@ -0,0 +1,12 @@ +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +class HundredDoors { + public static void main(String args[]) { + String openDoors = IntStream.rangeClosed(1, 100) + .filter(i -> Math.pow((int) Math.sqrt(i), 2) == i) + .mapToObj(Integer::toString) + .collect(Collectors.joining(", ")); + System.out.printf("Open doors: %s%n", openDoors); + } +} diff --git a/Task/100-doors/Nim/100-doors-1.nim b/Task/100-doors/Nim/100-doors-1.nim index 8b914ad3d1..43a373ee70 100644 --- a/Task/100-doors/Nim/100-doors-1.nim +++ b/Task/100-doors/Nim/100-doors-1.nim @@ -1,16 +1,11 @@ -from strutils import format +from strutils import `%` -proc check_doors() = - const n = 100 - var is_open : array[1..n, bool] # auto-initialized to false - # pass over the doors n times - for pass in 1..n: - var i = pass - while i <= n: - is_open[i] = not is_open[i] - i += pass - # print the result - for door in 1..n: - echo format("door $1 is $2.", door, (if is_open[door]: "open" else: "closed")) +const numDoors = 100 +var doors: array[1..numDoors, bool] -check_doors() +for pass in 1..numDoors: + for door in countup(pass, numDoors, pass): + doors[door] = not doors[door] + +for door in 1..numDoors: + echo "Door $1 is $2." % [$door, if doors[door]: "open" else: "closed"] diff --git a/Task/100-doors/Nim/100-doors-2.nim b/Task/100-doors/Nim/100-doors-2.nim index b58f5fa2e3..70f792d212 100644 --- a/Task/100-doors/Nim/100-doors-2.nim +++ b/Task/100-doors/Nim/100-doors-2.nim @@ -1,9 +1,15 @@ -var isOpen: array[1..100, bool] +from strutils import `%` -for pass in countup(1, 100): - for door in countup(pass,100,pass): - isOpen[door] = not isOpen[door] +const numDoors = 100 +var doors {.compileTime.}: array[1..numDoors, bool] -for i in countup(1, 100): - if isOpen[i]: - echo("Door ",i," is open.") +proc calcDoors(): string = + for pass in 1..numDoors: + for door in countup(pass, numDoors, pass): + doors[door] = not doors[door] + for door in 1..numDoors: + result.add("Door $1 is $2.\n" % [$door, if doors[door]: "open" else: "closed"]) + +const outputString: string = calcDoors() + +echo outputString diff --git a/Task/100-doors/Oforth/100-doors.oforth b/Task/100-doors/Oforth/100-doors.oforth index 34534cf445..e66df29315 100644 --- a/Task/100-doors/Oforth/100-doors.oforth +++ b/Task/100-doors/Oforth/100-doors.oforth @@ -1,7 +1,7 @@ : doors | i j l | - 100 #[ false ] Array init dup ->l + 100 false Array newWith dup ->l 100 loop: i [ - i 100 i step: j [ l put(j, l at(j) not) ] + i 100 i step: j [ l put ( j , j l at not ) ] ] - l . ; +; diff --git a/Task/100-doors/Perl-6/100-doors-3.pl6 b/Task/100-doors/Perl-6/100-doors-3.pl6 index b0b47a8762..bad238c11d 100644 --- a/Task/100-doors/Perl-6/100-doors-3.pl6 +++ b/Task/100-doors/Perl-6/100-doors-3.pl6 @@ -1 +1 @@ - say "Door $_ is open" for 1..10 X** 2; +say 'Door $_ is open' for (1..10)»²; diff --git a/Task/100-doors/Perl-6/100-doors-4.pl6 b/Task/100-doors/Perl-6/100-doors-4.pl6 index 820f5459cd..b0b47a8762 100644 --- a/Task/100-doors/Perl-6/100-doors-4.pl6 +++ b/Task/100-doors/Perl-6/100-doors-4.pl6 @@ -1 +1 @@ -say "Door $_ is ", [.sqrt == .sqrt.floor] for 1..100; + say "Door $_ is open" for 1..10 X** 2; diff --git a/Task/100-doors/Perl-6/100-doors-5.pl6 b/Task/100-doors/Perl-6/100-doors-5.pl6 index 5dbedccd7c..820f5459cd 100644 --- a/Task/100-doors/Perl-6/100-doors-5.pl6 +++ b/Task/100-doors/Perl-6/100-doors-5.pl6 @@ -1,26 +1 @@ -sub output( @arr, $max ) { - my $output = 1; - for 1..^$max -> $index { - if @arr[$index] { - printf "%4d", $index; - say '' if $output++ %% 10; - } - } - say ''; -} - -sub MAIN ( Int :$doors = 100 ) { - my $doorcount = $doors + 1; - my @door[$doorcount] = 0 xx ($doorcount); - - INDEX: - for 1...^$doorcount -> $index { - # flip door $index & its multiples, up to last door. - # - for ($index, * + $index ... *)[^$doors] -> $multiple { - next INDEX if $multiple > $doors; - @door[$multiple] = @door[$multiple] ?? 0 !! 1; - } - } - output @door, $doors+1; -} +say "Door $_ is ", [.sqrt == .sqrt.floor] for 1..100; diff --git a/Task/100-doors/Perl-6/100-doors-6.pl6 b/Task/100-doors/Perl-6/100-doors-6.pl6 new file mode 100644 index 0000000000..5dbedccd7c --- /dev/null +++ b/Task/100-doors/Perl-6/100-doors-6.pl6 @@ -0,0 +1,26 @@ +sub output( @arr, $max ) { + my $output = 1; + for 1..^$max -> $index { + if @arr[$index] { + printf "%4d", $index; + say '' if $output++ %% 10; + } + } + say ''; +} + +sub MAIN ( Int :$doors = 100 ) { + my $doorcount = $doors + 1; + my @door[$doorcount] = 0 xx ($doorcount); + + INDEX: + for 1...^$doorcount -> $index { + # flip door $index & its multiples, up to last door. + # + for ($index, * + $index ... *)[^$doors] -> $multiple { + next INDEX if $multiple > $doors; + @door[$multiple] = @door[$multiple] ?? 0 !! 1; + } + } + output @door, $doors+1; +} diff --git a/Task/100-doors/Retro/100-doors.retro b/Task/100-doors/Retro/100-doors.retro index a3c29ee33f..782882a047 100644 --- a/Task/100-doors/Retro/100-doors.retro +++ b/Task/100-doors/Retro/100-doors.retro @@ -1,3 +1,2 @@ -: squared ( n-n ) dup * ; -: doors ( n- ) [ 1 repeat 2over squared > 0; drop dup squared putn space 1+ again ] do 2drop ; -100 doors +:doors (n-) [ #1 repeat dup-pair n:square gt? 0; drop dup n:square n:put sp n:inc again ] do drop-pair ; +#100 doors diff --git a/Task/100-doors/V/100-doors.v b/Task/100-doors/V/100-doors.v new file mode 100644 index 0000000000..58b6aa785b --- /dev/null +++ b/Task/100-doors/V/100-doors.v @@ -0,0 +1,30 @@ +fn main() { + mut is_open := [false].repeat(100) + + // do 100 passes + for pass := 0; pass < 100; pass++ { + for door := pass; door < 100; door += pass + 1 { + // there is no NOT operator in V. + is_open[door] = match is_open[door] { + true { false } + false { true } + else { false } + } + } + } + + // output results + for door := 0; door < 100; door ++ { + print( "door #" ) + print( door + 1 ) + print( + if is_open[door] { + " is open." + } + else { + " is closed." + } + ) + println("") + } +} diff --git a/Task/24-game/Elena/24-game.elena b/Task/24-game/Elena/24-game.elena index 2581fba5d5..ef481696de 100644 --- a/Task/24-game/Elena/24-game.elena +++ b/Task/24-game/Elena/24-game.elena @@ -3,6 +3,8 @@ import system'collections; import system'dynamic; import extensions; +// --- Expression --- + class ExpressionTree { object theTree; @@ -68,7 +70,7 @@ class ExpressionTree var op := node.Operation; - ^ mixin op(left).eval:right + ^ op(left, right); } } @@ -80,8 +82,6 @@ class ExpressionTree if (nil == node) { InvalidArgumentException.raise() }; - var s := subjconst Leaf; - if (node.containsProperty(subjconst Leaf)) { list.append(node.Leaf) @@ -97,6 +97,8 @@ class ExpressionTree <= readLeaves(list,theTree); } +// --- Game --- + class TwentyFourGame { object theNumbers; @@ -109,12 +111,12 @@ class TwentyFourGame newPuzzle() { theNumbers := new object[] - { - 1 + randomGenerator.eval:9, - 1 + randomGenerator.eval:9, - 1 + randomGenerator.eval:9, - 1 + randomGenerator.eval:9 - } + { + 1 + randomGenerator.eval:9, + 1 + randomGenerator.eval:9, + 1 + randomGenerator.eval:9, + 1 + randomGenerator.eval:9 + } } help() diff --git a/Task/24-game/Objeck/24-game.objeck b/Task/24-game/Objeck/24-game.objeck new file mode 100644 index 0000000000..bb740c3f42 --- /dev/null +++ b/Task/24-game/Objeck/24-game.objeck @@ -0,0 +1,101 @@ +use Collection.Generic; +use System.Matrix; + +class RPNParser { + @stk : Stack; + @digits : List; + + function : Main(args : String[]) ~ Nil { + digits := List->New(); + "Make 24 with the digits: "->Print(); + for(i := 0; i < 4; i += 1;) { + n : Int := Int->Random(1, 9); + " {$n}"->Print(); + digits->AddBack(n); + }; + '\n'->Print(); + + parser := RPNParser->New(); + if(parser->Parse(System.IO.Console->ReadString(), digits)) { + result := parser->GetResult(); + if(result = 24) { + "Good job!"->PrintLine(); + } + else { + "{$result}, Try again."->PrintLine(); + }; + } + else { + "Invalid sequence"->PrintLine(); + }; + } + + New() { + @stk := Stack->New(); + @digits := List->New(); + } + + method : Op(f : \Func->Calc) ~ Nil { + if(@stk->Size() < 2) { "Improperly written expression"->ErrorLine(); Runtime->Exit(1); }; + b := @stk->Pop(); + a := @stk->Pop(); + @stk->Push(f(a, b)); + } + + method : Parse(c : Char) ~ Nil { + if(c >= '0' & c <= '9') { + value : Int := c - '0'; + @stk->Push(value); + @digits->AddBack(value); + } + else if(c = '+') { + Op(\Func->Calc : (a, b) => a + b); + } + else if(c = '-') { + Op(\Func->Calc : (a, b) => a - b); + } + else if(c = '*') { + Op(\Func->Calc : (a, b) => a * b); + } + else if(c = '/') { + Op(\Func->Calc : (a, b) => { if(b <> 0) { return a / b; } else { return 0; }; }); + }; + } + + method : GetResult() ~ Int { + if(@stk->Size() = 1) { + return @stk->Top(); + }; + + return 0; + } + + method : Parse(s : String, digits : List) ~ Bool { + each(i : s) { + Parse(s->Get(i)); + }; + + @digits->Rewind(); + while(@digits->More()) { + left := @digits->Get()->Get(); + digits->Rewind(); + found := false; + while(digits->More() & found = false) { + right := digits->Get()->Get(); + if(left = right) { + digits->Remove(); found := true; + } + else { + digits->Next(); + }; + }; + @digits->Next(); + }; + + return digits->IsEmpty(); + } +} + +alias Func { + Calc : (IntHolder, IntHolder) ~ IntHolder +} diff --git a/Task/9-billion-names-of-God-the-integer/Dart/9-billion-names-of-god-the-integer-1.dart b/Task/9-billion-names-of-God-the-integer/Dart/9-billion-names-of-god-the-integer-1.dart new file mode 100644 index 0000000000..c3cad0529f --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Dart/9-billion-names-of-god-the-integer-1.dart @@ -0,0 +1,34 @@ +import 'dart:math'; + +List partitions(int n) { + var cache = List>.filled(1, List.filled(1, BigInt.from(1)), growable: true); + for(int length = cache.length; length < n + 1; length++) { + var row = List.filled(1, BigInt.from(0), growable: true); + for(int index = 1; index < length + 1; index++) { + var partAtIndex = row[row.length - 1] + cache[length - index][min(index, length - index)]; + row.add(partAtIndex); + } + cache.add(row); + } + return cache[n]; +} + +List row(int n) { + var parts = partitions(n); + return List.generate(n, (int index) => parts[index + 1] - parts[index]); +} + +void printRows({int min = 1, int max = 11}) { + int maxDigits = max.toString().length; + print('Rows:'); + for(int i in List.generate(max - min, (int index) => index + min)) { + print((' ' * (maxDigits - i.toString().length)) + '$i: ${row(i)}'); + } +} + +void printSums(List args) { + print('Sums:'); + for(int i in args) { + print('$i: ${partitions(i)[i]}'); + } +} diff --git a/Task/9-billion-names-of-God-the-integer/Dart/9-billion-names-of-god-the-integer-2.dart b/Task/9-billion-names-of-God-the-integer/Dart/9-billion-names-of-god-the-integer-2.dart new file mode 100644 index 0000000000..2c657b908f --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Dart/9-billion-names-of-god-the-integer-2.dart @@ -0,0 +1,6 @@ + import 'package:DD1_NamesOfGod/DD1_NamesOfGod.dart' as names_of_god; + +main(List arguments) { + names_of_god.printRows(min: 1, max: 11); + names_of_god.printSums([23, 123, 1234, 12345]); +} diff --git a/Task/9-billion-names-of-God-the-integer/Factor/9-billion-names-of-god-the-integer.factor b/Task/9-billion-names-of-God-the-integer/Factor/9-billion-names-of-god-the-integer.factor new file mode 100644 index 0000000000..a17f2e14d4 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Factor/9-billion-names-of-god-the-integer.factor @@ -0,0 +1,21 @@ +USING: combinators io kernel math math.ranges memoize prettyprint +sequences ; + +MEMO: p ( m n -- o ) + { + { [ dup zero? ] [ nip ] } + { [ 2dup = ] [ 2drop 1 ] } + { [ 2dup < ] [ 2drop 0 ] } + [ [ [ 1 - ] bi@ p ] [ [ - ] [ ] bi p + ] 2bi ] + } cond ; + +: row ( n -- seq ) dup [1,b] [ p ] with map ; + +: .row ( n -- ) row [ pprint bl ] each nl ; + +: .triangle ( n -- ) [1,b] [ .row ] each ; + +: G ( n -- sum ) row sum ; + +25 .triangle nl +"Sums:" print { 23 123 1234 12345 } [ dup pprint bl G . ] each 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 362e502616..eeef1e1ab9 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 @@ -6,11 +6,11 @@ import extensions'text; extension bottleOp { bottleDescription() - = self.Printable + (self != 1).iif(" bottles"," bottle"); + = self.toPrintable() + (self != 1).iif(" bottles"," bottle"); bottleEnumerator() = new Variable(self).doWith:(n) { - ^ new Enumerator: + ^ new Enumerator { bool next() = n > 0; diff --git a/Task/99-Bottles-of-Beer/Euphoria/99-bottles-of-beer.euphoria b/Task/99-Bottles-of-Beer/Euphoria/99-bottles-of-beer-1.euphoria similarity index 100% rename from Task/99-Bottles-of-Beer/Euphoria/99-bottles-of-beer.euphoria rename to Task/99-Bottles-of-Beer/Euphoria/99-bottles-of-beer-1.euphoria diff --git a/Task/99-Bottles-of-Beer/Euphoria/99-bottles-of-beer-2.euphoria b/Task/99-Bottles-of-Beer/Euphoria/99-bottles-of-beer-2.euphoria new file mode 100644 index 0000000000..87fadd640a --- /dev/null +++ b/Task/99-Bottles-of-Beer/Euphoria/99-bottles-of-beer-2.euphoria @@ -0,0 +1,17 @@ +-- An alternate version + +include std/console.e + +sequence howmany = {"No more bottles","%d bottle","","s"} + +for beer = 99 to 1 by -1 do + display(` + [1] bottles of beer on the wall, + [1] bottles of beer. + Take one down, drink it right down, + [2][3] of beer. + `,{beer, + sprintf(howmany[(beer>1)+1],beer-1), + howmany[(beer>2)+3] + }) +end for diff --git a/Task/99-Bottles-of-Beer/Phix/99-bottles-of-beer.phix b/Task/99-Bottles-of-Beer/Phix/99-bottles-of-beer.phix index ade02cad76..064ce01737 100644 --- a/Task/99-Bottles-of-Beer/Phix/99-bottles-of-beer.phix +++ b/Task/99-Bottles-of-Beer/Phix/99-bottles-of-beer.phix @@ -19,12 +19,12 @@ end function string this = bob(ninetynine) string that = "Take one down, pass it around,\n" - for i=ninetynine to 0 by -1 do - puts(1,up1(this)&" on the wall,\n") - puts(1,this&".\n") - if i=0 then that = "Go to the store, buy some more,\n" - elsif i=1 then that[6..8] = "it" end if - this = bob(i-1) - puts(1,that&this&" on the wall.\n\n") - end for - if getc(0) then end if +for i=ninetynine to 0 by -1 do + puts(1,up1(this)&" on the wall,\n") + puts(1,this&".\n") + if i=0 then that = "Go to the store, buy some more,\n" + elsif i=1 then that[6..8] = "it" end if + this = bob(i-1) + puts(1,that&this&" on the wall.\n\n") +end for +{} = wait_key() diff --git a/Task/99-Bottles-of-Beer/Pony/99-bottles-of-beer-1.pony b/Task/99-Bottles-of-Beer/Pony/99-bottles-of-beer-1.pony new file mode 100644 index 0000000000..bba48bf07c --- /dev/null +++ b/Task/99-Bottles-of-Beer/Pony/99-bottles-of-beer-1.pony @@ -0,0 +1,20 @@ +actor Main + let _env: Env + new create(env: Env) => + _env = env + bottles(99) + + be bottles(n: U32) => + if n == 0 then + _env.out.print("No more bottles of beer on the wall, no more bottles of beer.") + _env.out.print("Go to the store and buy some more, 99 bottles of beer on the wall.") + else + if n == 1 then + _env.out.print("1 bottle of beer on the wall, 1 bottle of beer.") + _env.out.print("Take one down and pass it around, no more bottles of beer on the wall.\n") + else + _env.out.print(n.string() + " bottles of beer on the wall, " + n.string() + " bottles of beer.") + _env.out.print("Take one down and pass it around, "+ (n - 1).string() +" bottles of beer on the wall.\n") + end + bottles(n-1) + end diff --git a/Task/99-Bottles-of-Beer/Pony/99-bottles-of-beer-2.pony b/Task/99-Bottles-of-Beer/Pony/99-bottles-of-beer-2.pony new file mode 100644 index 0000000000..3ec3875b13 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Pony/99-bottles-of-beer-2.pony @@ -0,0 +1,18 @@ +actor Main + let _env: Env + new create(env: Env) => + _env = env + var n: I32 = 99 + repeat + if n == 0 then + _env.out.print("No more bottles of beer on the wall, no more bottles of beer.") + _env.out.print("Go to the store and buy some more, 99 bottles of beer on the wall.") + elseif n == 1 then + _env.out.print("1 bottle of beer on the wall, 1 bottle of beer.") + _env.out.print("Take one down and pass it around, no more bottles of beer on the wall.\n") + else + _env.out.print(n.string() + " bottles of beer on the wall, " + n.string() + " bottles of beer.") + _env.out.print("Take one down and pass it around, "+ (n - 1).string() +" bottles of beer on the wall.\n") + end + n = n - 1 + until n < 0 end diff --git a/Task/99-Bottles-of-Beer/Processing/99-bottles-of-beer b/Task/99-Bottles-of-Beer/Processing/99-bottles-of-beer deleted file mode 100644 index f10588ecf0..0000000000 --- a/Task/99-Bottles-of-Beer/Processing/99-bottles-of-beer +++ /dev/null @@ -1,3 +0,0 @@ -for (int i = 99; i > 0; i--) { - print(i + " bottles of beer on the wall\n" + i + " bottles of beer\nTake one down, pass it around\n" + (i - 1) + " bottles of beer on the wall\n\n"); -} diff --git a/Task/99-Bottles-of-Beer/Processing/99-bottles-of-beer-1 b/Task/99-Bottles-of-Beer/Processing/99-bottles-of-beer-1 new file mode 100644 index 0000000000..3196fbfdfc --- /dev/null +++ b/Task/99-Bottles-of-Beer/Processing/99-bottles-of-beer-1 @@ -0,0 +1,5 @@ +for (int i = 99; i > 0; i--) { + print(i + " bottles of beer on the wall\n" + + i + " bottles of beer\nTake one down, pass it around\n" + + (i - 1) + " bottles of beer on the wall\n\n"); +} diff --git a/Task/99-Bottles-of-Beer/Processing/99-bottles-of-beer-2 b/Task/99-Bottles-of-Beer/Processing/99-bottles-of-beer-2 new file mode 100644 index 0000000000..e9d2270fe6 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Processing/99-bottles-of-beer-2 @@ -0,0 +1,18 @@ +int i = 99; +void setup() { + size(200, 140); +} +void draw() { + background(0); + text(i + " bottles of beer on the wall\n" + + i + " bottles of beer\nTake one down, pass it around\n" + + (i - 1) + " bottles of beer on the wall\n\n", + 10, 20); + if (frameCount%240==239) next(); // auto-advance every 4 secs +} +void mouseReleased() { + next(); // manual advance +} +void next() { + i = max(i-1, 1); // stop decreasing at 1-0 bottles +} diff --git a/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-1.py b/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-1.py index 5050e6e77d..f10bd37a4f 100644 --- a/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-1.py +++ b/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-1.py @@ -1,28 +1,10 @@ -"""Pythonic 99 beer song (readability counts).""" +catchphrase = "%d bottles of beer on the wall" -regular_verse = '''\ -{n} bottles of beer on the wall, {n} bottles of beer -Take one down and pass it around, {n_minus_1} bottles of beer on the wall. +strofas = ("\n".join(( + catchphrase % n, + catchphrase[:18] % n, + "Take one down and pass it around", + catchphrase % (n-1) +)) for n in range(99, 0, -1)) -''' - -ending_verses = '''\ -2 bottles of beer on the wall, 2 bottles of beer. -Take one down and pass it around, 1 bottle of beer on the wall. - -1 bottle of beer on the wall, 1 bottle of beer. -Take one down and pass it around, no more 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. - -''' - -# @todo: It is possible to refactor the code to avoid n-1 in the code, -# notice that the last line of any verse and the first line of the next -# verse share the same number of bottles. Nevertheless the code -# would be less readliable. - -for n in range(99, 2, -1): - print(regular_verse.format(n=n, n_minus_1=n - 1)) -print(ending_verses) +print("\n\n".join(strofas)) diff --git a/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-2.py b/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-2.py index a5518fdf9b..5bc8294b7d 100644 --- a/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-2.py +++ b/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-2.py @@ -1,16 +1,17 @@ -"""Pythonic 99 beer song (readability counts).""" +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- -first = '''\ -99 bottles of beer on the wall, 99 bottles of beer -''' +"""Pythonic 99 beer song (maybe the simplest naive implementation in Python 3).""" -middle = '''\ -Take one down and pass it around, {n} bottles of beer on the wall. +REGULAR_VERSE = '''\ {n} bottles of beer on the wall, {n} bottles of beer +Take one down and pass it around, {n_minus_1} bottles of beer on the wall. + ''' -last = '''\ +ENDING_VERSES = '''\ +2 bottles of beer on the wall, 2 bottles of beer. Take one down and pass it around, 1 bottle of beer on the wall. 1 bottle of beer on the wall, 1 bottle of beer. @@ -18,9 +19,10 @@ Take one down and pass it around, no more 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. + ''' -print(first) -for n in range(98, 1, -1): - print(middle.format(n=n)) -print(last) + +for n in range(99, 2, -1): + print(REGULAR_VERSE.format(n=n, n_minus_1=n - 1)) +print(ENDING_VERSES) diff --git a/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-4.py b/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-4.py index 2effd00e49..97ac0c47fe 100644 --- a/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-4.py +++ b/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-4.py @@ -1,23 +1,34 @@ -"""99 Bottles of Beer on the Wall made functional""" +""" + 99 Bottles of Beer on the Wall made functional + + Main function accepts a number of parameters, so you can specify a name of + the drink, its container and other things. English only. +""" + from functools import partial from typing import Callable def regular_plural(noun: str) -> str: - """Regular rule to get the plural form of a word""" + """English rule to get the plural form of a word""" + if noun[-1] == "s": + return noun + "es" + return noun + "s" -def beer_song(*, - location: str = 'on the wall', - distribution: str = 'Take one down, pass it around', - solution: str = 'Better go to the store to buy some more!', - container: str = 'bottle', - plurifier: Callable[[str], str] = regular_plural, - liquid: str = "beer", - initial_count: int = 99) -> None: +def beer_song( + *, + location: str = 'on the wall', + distribution: str = 'Take one down, pass it around', + solution: str = 'Better go to the store to buy some more!', + container: str = 'bottle', + plurifier: Callable[[str], str] = regular_plural, + liquid: str = "beer", + initial_count: int = 99, +) -> str: """ - Displays the lyrics of the beer song + Return the lyrics of the beer song :param location: initial location of the drink :param distribution: specifies the process of its distribution :param solution: what happens when we run out of drinks @@ -26,68 +37,92 @@ def beer_song(*, :param liquid: the name of the drink in the given container :param initial_count: how many containers available initially """ - verse = partial(get_verse, - location=location, - distribution=distribution, - solution=solution, - container=container, - plurifier=plurifier, - liquid=liquid) + + verse = partial( + get_verse, + initial_count = initial_count, + location = location, + distribution = distribution, + solution = solution, + container = container, + plurifier = plurifier, + liquid = liquid, + ) + verses = map(verse, range(initial_count, -1, -1)) - print(*verses, sep='\n\n') + return '\n\n'.join(verses) -def get_verse(count: int, - *, - location: str, - distribution: str, - solution: str, - container: str, - plurifier: Callable[[str], str], - liquid: str) -> str: - """Returns the verse for the given initial amount of drinks""" - inventory = partial(get_inventory, - location=location) - asset = partial(get_asset, - container=container, - plurifier=plurifier, - liquid=liquid) - initial_asset = asset(count) - final_asset = asset(count - 1) - standard_verse = '\n'.join([inventory(initial_asset), - initial_asset, - distribution, - inventory(final_asset)]) - return solution if count == 0 else standard_verse +def get_verse( + count: int, + *, + initial_count: str, + location: str, + distribution: str, + solution: str, + container: str, + plurifier: Callable[[str], str], + liquid: str, +) -> str: + """Returns the verse for the given amount of drinks""" + + asset = partial( + get_asset, + container = container, + plurifier = plurifier, + liquid = liquid, + ) + + current_asset = asset(count) + next_number = count - 1 if count else initial_count + next_asset = asset(next_number) + action = distribution if count else solution + + inventory = partial( + get_inventory, + location = location, + ) + + return '\n'.join(( + inventory(current_asset), + current_asset, + action, + inventory(next_asset), + )) -def get_inventory(asset: str, - *, - location: str) -> str: +def get_inventory( + asset: str, + *, + location: str, +) -> str: """ Used to return the first or the fourth line of the verse >>> get_inventory("10 bottles of beer", location="on the wall") "10 bottles of beer on the wall" """ - return ' '.join([asset, location]) + return ' '.join((asset, location)) -def get_asset(count: int, - *, - container: str, - plurifier: Callable[[str], str], - liquid: str) -> str: +def get_asset( + count: int, + *, + container: str, + plurifier: Callable[[str], str], + liquid: str, +) -> str: """ Quantified asset >>> get_asset(0, container="jar", plurifier=regular_plural, liquid='milk') "No more jars of milk" """ - containers = container if count == 1 else plurifier(container) - spelled_out_quantity = "No more" if count == 0 else str(count) - return ' '.join([spelled_out_quantity, containers, "of", liquid]) + + containers = plurifier(container) if count != 1 else container + spelled_out_quantity = str(count) if count else "No more" + return ' '.join((spelled_out_quantity, containers, "of", liquid)) if __name__ == '__main__': - beer_song() + print(beer_song()) diff --git a/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-5.py b/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-5.py new file mode 100644 index 0000000000..718e4b23ee --- /dev/null +++ b/Task/99-Bottles-of-Beer/Python/99-bottles-of-beer-5.py @@ -0,0 +1,256 @@ +""" +Excercise of style. An overkill for the task :-D + +1. OOP, with abstract class and implementation with much common magic methods +2. you can customize: + a. the initial number + b. the name of the item and its plural + c. the string to display when there's no more items + d. the normal action + e. the final action + f. the template used, for foreign languages +3. strofas of the song are created with multiprocessing +4. when you launch it as a script, you can specify an optional parameter for + the number of initial items +""" + +from string import Template +from abc import ABC, abstractmethod +from multiprocessing.pool import Pool as ProcPool +from functools import partial +import sys + +class Song(ABC): + @abstractmethod + def sing(self): + """ + it must return the song as a text-like object + """ + + pass + +class MuchItemsSomewhere(Song): + eq_attrs = ( + "initial_number", + "zero_items", + "action1", + "action2", + "item", + "items", + "strofa_tpl" + ) + + hash_attrs = eq_attrs + repr_attrs = eq_attrs + + __slots__ = eq_attrs + ("_repr", "_hash") + + def __init__( + self, + items = "bottles of beer", + item = "bottle of beer", + where = "on the wall", + initial_number = None, + zero_items = "No more", + action1 = "Take one down, pass it around", + action2 = "Go to the store, buy some more", + template = None, + ): + initial_number_true = 99 if initial_number is None else initial_number + + try: + is_initial_number_int = (initial_number_true % 1) == 0 + except Exception: + is_initial_number_int = False + + if not is_initial_number_int: + raise ValueError("`initial_number` parameter must be None or a int-like object") + + if initial_number_true < 0: + raise ValueError("`initial_number` parameter must be >=0") + + + true_tpl = template or """\ +$i $items1 $where +$i $items1 +$action +$j $items2 $where""" + + strofa_tpl_tmp = Template(true_tpl) + strofa_tpl = Template(strofa_tpl_tmp.safe_substitute(where=where)) + + self.zero_items = zero_items + self.action1 = action1 + self.action2 = action2 + self.initial_number = initial_number_true + self.item = item + self.items = items + self.strofa_tpl = strofa_tpl + self._hash = None + self._repr = None + + def strofa(self, number): + zero_items = self.zero_items + item = self.item + items = self.items + + if number == 0: + i = zero_items + action = self.action2 + j = self.initial_number + else: + i = number + action = self.action1 + j = i - 1 + + if i == 1: + items1 = item + j = zero_items + else: + items1 = items + + if j == 1: + items2 = item + else: + items2 = items + + return self.strofa_tpl.substitute( + i = i, + j = j, + action = action, + items1 = items1, + items2 = items2 + ) + + def sing(self): + with ProcPool() as proc_pool: + strofa = self.strofa + initial_number = self.initial_number + args = range(initial_number, -1, -1) + return "\n\n".join(proc_pool.map(strofa, args)) + + def __copy__(self, *args, **kwargs): + return self + + def __deepcopy__(self, *args, **kwargs): + return self + + def __eq__(self, other, *args, **kwargs): + if self is other: + return True + + getmyattr = partial(getattr, self) + getotherattr = partial(getattr, other) + eq_attrs = self.eq_attrs + + for attr in eq_attrs: + val = getmyattr(attr) + + try: + val2 = getotherattr(attr) + except Exception: + return False + + if attr == "strofa_tpl": + val_true = val.safe_substitute() + val2_true = val.safe_substitute() + else: + val_true = val + val2_true = val + + if val_true != val2_true: + return False + + return True + + def __hash__(self, *args, **kwargs): + _hash = self._hash + + if _hash is None: + getmyattr = partial(getattr, self) + attrs = self.hash_attrs + hash_true = self._hash = hash(tuple(map(getmyattr, attrs))) + else: + hash_true = _hash + + return hash_true + + def __repr__(self, *args, **kwargs): + _repr = self._repr + + if _repr is None: + repr_attrs = self.repr_attrs + getmyattr = partial(getattr, self) + + attrs = [] + + for attr in repr_attrs: + val = getmyattr(attr) + + if attr == "strofa_tpl": + val_true = val.safe_substitute() + else: + val_true = val + + attrs.append(f"{attr}={repr(val_true)}") + + repr_true = self._repr = f"{self.__class__.__name__}({', '.join(attrs)})" + else: + repr_true = _repr + + return repr_true + +def muchBeersOnTheWall(num): + song = MuchItemsSomewhere(initial_number=num) + + return song.sing() + +def balladOfProgrammer(num): + """ + Prints + "99 Subtle Bugs in Production" + or + "The Ballad of Programmer" + """ + + song = MuchItemsSomewhere( + initial_number = num, + items = "subtle bugs", + item = "subtle bug", + where = "in Production", + action1 = "Debug and catch, commit a patch", + action2 = "Release the fixes, wait for some tickets", + zero_items = "Zarro", + ) + + return song.sing() + +def main(num): + print(f"### {num} Bottles of Beers on the Wall ###") + print() + print(muchBeersOnTheWall(num)) + print() + print() + print('### "The Ballad of Programmer", by Marco Sulla') + print() + print(balladOfProgrammer(num)) + +if __name__ == "__main__": + # Ok, argparse is **really** too much + argv = sys.argv + + if len(argv) == 1: + num = None + elif len(argv) == 2: + try: + num = int(argv[1]) + except Exception: + raise ValueError( + f"{__file__} parameter must be an integer, or can be omitted" + ) + else: + raise RuntimeError(f"{__file__} takes one parameter at max") + + main(num) + +__all__ = (Song.__name__, MuchItemsSomewhere.__name__, muchBeersOnTheWall.__name__, balladOfProgrammer.__name__) diff --git a/Task/A+B/ARM-Assembly/a+b-1.arm b/Task/A+B/ARM-Assembly/a+b-1.arm index e36fc885d4..33c40fcd0c 100644 --- a/Task/A+B/ARM-Assembly/a+b-1.arm +++ b/Task/A+B/ARM-Assembly/a+b-1.arm @@ -1,2 +1 @@ -as -o ab.o ab.S -ld -o a.out ab.o +arm-linux-gnueabi-as src.s -o src.o && arm-linux-gnueabi-gcc -static src.o -o run && qemu-arm run diff --git a/Task/A+B/ARM-Assembly/a+b-2.arm b/Task/A+B/ARM-Assembly/a+b-2.arm index 336c349126..abfe25489b 100644 --- a/Task/A+B/ARM-Assembly/a+b-2.arm +++ b/Task/A+B/ARM-Assembly/a+b-2.arm @@ -1,513 +1,27 @@ -.data - .align 2 - .code 32 - -.section .rodata - .align 2 - .code 32 - -overflow_msg: .ascii "Invalid number. Overflow.\n" -overflow_msglen = . - overflow_msg -bad_input_msg: .ascii "Invalid input. NaN.\n" -bad_input_msglen = . - bad_input_msg -range_err_msg: .ascii "Value out of range.\n" -range_err_msglen = . - range_err_msg -io_error_msg: .ascii "I/O error.\n" -io_error_msglen = . - range_err_msg - -sys_exit = 1 -sys_read = 3 -sys_write = 4 -max_rd_buf = 14 -lf = 10 -m10_9 = 0x3b9aca00 -maxval = 1000 -minval = -1000 - .text +.global main +.extern printf +.extern scanf -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ -@@ void main() -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - .align 2 - .code 32 - .type _start STT_FUNC - .global _start -_start: - stmfd sp!, {r4,r5,lr} +main: + push {lr} + ldr r0, =scanf_lit + ldr r1, =num_a + ldr r2, =num_b + bl scanf // scanf("%d %d", &num_a, &num_b); + ldr r0, =printf_lit + ldr r1, =num_a + ldr r1, [r1] + ldr r2, =num_b + ldr r2, [r2] + add r1, r1, r2 + bl printf // printf("%d\n", num_a + num_b); + pop {pc} -.read_lhs: - ldr r0, =max_rd_buf - bl readint - mov r4, r0 - bl printint - mov r0, r4 - bl range_check - -.read_rhs: - ldr r0, =max_rd_buf - bl readint - mov r5, r0 - bl printint - mov r0, r5 - bl range_check - -.sum_and_print: - adds r0, r4, r5 - bvs overflow - bl printint - -.main_exit: - mov r0, #0 - bl exit - ldmfd sp!, {r4,r5,pc} - -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ -@@ Read from stdin until we encounter a non-digit, or we have read bytes2rd digits. -@@ Ignore leading spaces. -@@ Return value to the caller converted to a signed int. -@@ We read positive values, but if we read a leading '-' sign, we convert the -@@ return value to two's complement. -@@ The argument is max number of bytes to read from stdin. -@@ int readint(int bytes2rd) -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - .align 2 - .code 32 - .type readint STT_FUNC - .global readint -readint: - stmfd sp!, {r4,r5,r6,r7,lr} - @@@@@@@@@@@@@@@ - @@ r0 : #0 for stdin arg to read. - @@ r1 : ptr to current pos in local buffer. - @@ r2 : #1 to read one byte at a time. - @@ r3,r7 : tmp. - @@ r4 : number of bytes read. - @@ r5 : value of current byte. - @@ r6 : 0 while we are reading leading spaces. - @@@@@@@@@@@@@@@ - sub sp, sp, r0 - mov r1, sp - mov r3, #0 - push {r3} @ sp,#4: local var @isnegative. return in r1. Default value is 0/false. Positive number. - push {r0} @ sp,#0: local var @maxbytes. const. - mov r2, #1 - mov r4, #0 - - mov r6, #0 - b .rd -@ we get here if r6 is 0. -@ if space, goto .rd. -@ else set r6 to 1 and goto .noleading. -.leadchk: - mov r0, r5 - bl isspace - cmp r0, #1 - beq .rd - -.sign_chk: - mov r0, r5 - push {r1} - bl issign - cmp r0, #1 - streq r0, [sp,#8] @ sp,#4 + 4 for the pushed r1. - movhi r1, #0 - strhi r1, [sp,#8] @ sp,#4 + 4 for the pushed r1. - pop {r1} - bhs .rd - - mov r6, #1 - b .noleading - -.rd: - mov r0, #0 - bl read - cmp r0, #1 - bne .sum_digits_eof @ eof - mov r5, #0 - ldrb r5, [r1] - cmp r6, #0 - beq .leadchk - -.noleading: - mov r0, r5 - bl isdigit - cmp r0, #1 - bne .sum_digits_nan @ r5 is non-digit - - add r4, r4, #1 - add r1, r1, #1 - @ max chars to read is received in arg[0], stored in local var at sp. - @ Only 10 can be valid, so the default of 12 leaves space for separator. - ldr r3, [sp] - cmp r4, r3 - beq .sum_digits_maxrd @ max bytes read. - b .rd - - - @@@@@@@@@@@@@@@ - @ We have read r4 (0..arg[0](default 12)) digits when we get here. Go through them - @ and add/mul them together to calculate a number. - @ We multiply and add the digits in reverse order to simplify the multiplication. - @@@@@@@@@@@@@@@ - @ r0: return value. - @ r1: local variable for read buffer. - @ r2: tmp for conversion. - @ r3,r6,r7: tmp - @ r4: number of chars we have read. - @ r5: multiplier 1,10,100. - @@@@@@@@@@@@@@@ -.sum_digits_nan: - mov r0, r5 - bl isspace - cmp r0, #1 - bne bad_input -.sum_digits_maxrd: -.sum_digits_eof: - mov r0, #0 - mov r5, #1 -.count: - cmp r4, #0 - beq .readint_ret - sub r4, r4, #1 - sub r1, #1 - ldrb r2, [r1] - sub r2, r2, #48 - mov r3, r2 - - @ multiply r3 (char value of digit) with r5 (multiplier). - @ possible overflow. - @ MI means negative. - @ smulls multiples two signed 32 bit vals and returns a 64 bit result. - @ If we get anything in r7, the value has overflowed. - @ having r2[31] set is overflow too. - smulls r2, r7, r3, r5 - cmp r7, #0 - bne overflow - cmp r2, #0 - bmi overflow - - @@ possible overflow. - adds r0, r0, r2 - bvs overflow - bmi overflow - - @@ end of array check. - @@ check is needed here too, for large numbers, since 10 billion is not a valid 32 bit val. - cmp r4, #0 - beq .readint_ret - - @@ multiple multiplier by 10. - @@ possible overflow. - @@ too many digits is input. happens if input is more than 10 digits. - mov r3, #10 - mov r6, r5 - smulls r5, r7, r3, r6 - cmp r7, #0 - bne overflow - cmp r5, #0 - bmi overflow - b .count - -.readint_ret: - ldr r1, [sp,#4] @ read isnegative value. - cmp r1, #0 - rsbne r0, r0, #0 - pop {r2} - add sp, sp, #4 - add sp, sp, r2 - ldmfd sp!, {r4,r5,r6,r7,pc} - -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ -@@ int isdigit(int) -@@ #48..#57 ascii range for '0'..'9'. -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - .align 2 - .code 32 - .type isdigit STT_FUNC - .global isdigit -isdigit: - stmfd sp!, {r1,lr} - cmp r0, #48 - blo .o_range - cmp r0, #57 - bhi .o_range - mov r0, #1 - ldmfd sp!, {r1,pc} -.o_range: - mov r0, #0 - ldmfd sp!, {r1,pc} - -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ -@@ int isspace(int) -@@ ascii space = 32, tab = 9, newline 10, cr = 13. -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - .align 2 - .code 32 - .type isspace STT_FUNC - .global isspace -isspace: - stmfd sp!, {lr} - cmp r0, #32 - cmpne r0, #9 - cmpne r0, #10 - cmpne r0, #13 - beq .is_space - mov r0, #0 - ldmfd sp!, {pc} -.is_space: - mov r0, #1 - ldmfd sp!, {pc} - -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ -@@ Return value is 1 for '-' 2 for '+'. -@@ int isspace(int) -@@ '+' = 43 and '-' = 45. -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - .align 2 - .code 32 - .type issign STT_FUNC - .global issign -issign: - stmfd sp!, {lr} - cmp r0, #43 - beq .plus_sign - cmp r0, #45 - beq .minus_sign - mov r0, #0 - ldmfd sp!, {pc} -.plus_sign: - mov r0, #2 - ldmfd sp!, {pc} -.minus_sign: - mov r0, #1 - ldmfd sp!, {pc} - -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ -@@ ARGS: -@@ r0 : in out arg (current int value) -@@ r1 : in out arg (ptr to current pos in buffer) -@@ r2 : in arg (const increment. 1000_000_000, 100_000_000, 10_000_000, 1000_000, 100_000, 10_000, 1000, 100, 10, 1.) -@@ -@@ r4 : tmp local. Outer scope must init to #10 and count down to #0. -@@ Special case is INTMAX. Must init to 5 if r4 >= 1000_000_000 (0x3b9aca00 = m10_9). -@@ r5: tmp -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - .align 2 - .code 32 - .type get_digit STT_FUNC - .global get_digit -get_digit: - stmfd sp!, {r2,r4,r5,lr} - ldr r5, =m10_9 - cmp r2, r5 - movlo r4, #10 - movhs r4, #5 -.get_digit_loop: - sub r4, #1 - mul r5, r4, r2 - cmp r0, r5 - blo .get_digit_loop - sub r0, r5 - add r4, r4, #48 - strb r4, [r1], #1 - ldmfd sp!, {r2,r4,r5,pc} - -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ -@@ A quick way to divide (numbers evenly divisible by 10) by 10. -@@ Most ARM cpus don't have a divide instruction, -@@ so this will always work. -@@ A generic div function is long and not needed here. -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - .align 2 -.div_r2_10: - stmfd sp!, {r0,r1,r3,lr} - mov r0, #1 - mov r1, #10 -.find_x: - mul r3, r0, r1; - cmp r3, r2 - movlo r0, r3 - blo .find_x - mov r2, r0 - ldmfd sp!, {r0,r1,r3,pc} - -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ -@@ -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - .align 2 -.print_neg_sign: - stmfd sp!, {r0,r1,r2,lr} - @ 45 = '-' - mov r1, #45 - push {r1} - mov r2, #1 - @ r1 is ptr to our local variable (holding '-'). - mov r1, sp - mov r0, #1 - bl write - cmp r0, #0 - blne io_error - pop {r1} - ldmfd sp!, {r0,r1,r2,pc} - -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ -@@ void printint(int val) -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - .align 2 - .code 32 - .type printint STT_FUNC - .global printint -printint: - stmfd sp!, {r4,r5,r6,lr} - mov r1, #1 - ands r1, r1, r0, LSR #31 - rsbne r0, r0, #0 - blne .print_neg_sign - sub sp, sp, #20 - mov r1, sp - mov r3, sp - - ldr r2, =m10_9 -.getc_loop: - bl get_digit - cmp r2, #1 - beq .exit_getc_loop - bl .div_r2_10 - b .getc_loop -.exit_getc_loop: - ldr r0, =lf - strb r0, [r1], #1 - - sub r2, r1, r3 - mov r1, r3 - mov r0, #1 - bl write - cmp r0, #0 - blne io_error - add sp, sp, #20 - ldmfd sp!, {r4,r5,r6,pc} - -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ -@@ -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - .align 2 -range_check: - stmfd sp!, {r4,r5,lr} - ldr r4, =minval - ldr r5, =maxval - cmp r4, #0 - cmpeq r5, #0 - beq .skip_range_check - cmp r0, r4 - bllt range_err - cmp r0, r5 - blgt range_err -.skip_range_check: - ldmfd sp!, {r4,r5,pc} - -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ -@ void range_err() -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - .align 2 -range_err: - stmfd sp!, {lr} - ldr r2, =range_err_msglen - ldr r1, =range_err_msg - mov r0, #2 - bl write - mov r0, #-1 - bl exit - ldmfd sp!, {pc} - -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ -@ void overflow() -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - .align 2 -overflow: - stmfd sp!, {lr} - ldr r2, =overflow_msglen - ldr r1, =overflow_msg - mov r0, #2 - bl write - mov r0, #-1 - bl exit - ldmfd sp!, { pc} - -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ -@ void bad_input() -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - .align 2 -bad_input: - stmfd sp!, {lr} - ldr r2, =bad_input_msglen - ldr r1, =bad_input_msg - mov r0, #2 - bl write - mov r0, #-1 - bl exit - ldmfd sp!, {pc} - -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ -@ void io_error() -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - .align 2 -io_error: - stmfd sp!, {lr} - ldr r2, =io_error_msglen - ldr r1, =io_error_msg - mov r0, #2 - bl write - mov r0, #-1 - bl exit - ldmfd sp!, {pc} - -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ -@ void exit(int) -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - .align 2 - .code 32 - .type _start STT_FUNC - .global exit -exit: - stmfd sp!, {r7, lr} - ldr r7, =sys_exit - svc #0 - ldmfd sp!, {r7, pc} - -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ -@ int write(int fd,char*buf,int len) -@ Return 0 if we successfully write all bytes. Otherwise return the error code. -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - .align 2 - .code 32 - .type _start STT_FUNC - .global write -write: - stmfd sp!, {r4,r7, lr} - mov r4, r2 -.wr_loop: - ldr r7, =sys_write - svc #0 - @ If r0 is negative, it is more than r4 with LO (unsigned <). - cmp r0, r4 - sublo r4, r0 - blo .wr_loop - moveq r0, #0 - ldmfd sp!, {r4,r7, pc} - -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ -@ int read(int fd,char*buf,int len) -@ Return number of bytes successfully read. Ignore errors. -@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ - .align 2 - .code 32 - .type _start STT_FUNC - .global read -read: - stmfd sp!, {r7, lr} - ldr r7, =sys_read - svc #0 - cmp r0, #0 - movlt r0, #0 - ldmfd sp!, {r7, pc} +.data +scanf_lit: .asciz "%d %d" +printf_lit: .asciz "%d\n" +.align 4 +.bss +num_a: .skip 4 +num_b: .skip 4 diff --git a/Task/A+B/ARM-Assembly/a+b-3.arm b/Task/A+B/ARM-Assembly/a+b-3.arm new file mode 100644 index 0000000000..e36fc885d4 --- /dev/null +++ b/Task/A+B/ARM-Assembly/a+b-3.arm @@ -0,0 +1,2 @@ +as -o ab.o ab.S +ld -o a.out ab.o diff --git a/Task/A+B/ARM-Assembly/a+b-4.arm b/Task/A+B/ARM-Assembly/a+b-4.arm new file mode 100644 index 0000000000..336c349126 --- /dev/null +++ b/Task/A+B/ARM-Assembly/a+b-4.arm @@ -0,0 +1,513 @@ +.data + .align 2 + .code 32 + +.section .rodata + .align 2 + .code 32 + +overflow_msg: .ascii "Invalid number. Overflow.\n" +overflow_msglen = . - overflow_msg +bad_input_msg: .ascii "Invalid input. NaN.\n" +bad_input_msglen = . - bad_input_msg +range_err_msg: .ascii "Value out of range.\n" +range_err_msglen = . - range_err_msg +io_error_msg: .ascii "I/O error.\n" +io_error_msglen = . - range_err_msg + +sys_exit = 1 +sys_read = 3 +sys_write = 4 +max_rd_buf = 14 +lf = 10 +m10_9 = 0x3b9aca00 +maxval = 1000 +minval = -1000 + +.text + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@ void main() +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 + .code 32 + .type _start STT_FUNC + .global _start +_start: + stmfd sp!, {r4,r5,lr} + +.read_lhs: + ldr r0, =max_rd_buf + bl readint + mov r4, r0 + bl printint + mov r0, r4 + bl range_check + +.read_rhs: + ldr r0, =max_rd_buf + bl readint + mov r5, r0 + bl printint + mov r0, r5 + bl range_check + +.sum_and_print: + adds r0, r4, r5 + bvs overflow + bl printint + +.main_exit: + mov r0, #0 + bl exit + ldmfd sp!, {r4,r5,pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@ Read from stdin until we encounter a non-digit, or we have read bytes2rd digits. +@@ Ignore leading spaces. +@@ Return value to the caller converted to a signed int. +@@ We read positive values, but if we read a leading '-' sign, we convert the +@@ return value to two's complement. +@@ The argument is max number of bytes to read from stdin. +@@ int readint(int bytes2rd) +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 + .code 32 + .type readint STT_FUNC + .global readint +readint: + stmfd sp!, {r4,r5,r6,r7,lr} + @@@@@@@@@@@@@@@ + @@ r0 : #0 for stdin arg to read. + @@ r1 : ptr to current pos in local buffer. + @@ r2 : #1 to read one byte at a time. + @@ r3,r7 : tmp. + @@ r4 : number of bytes read. + @@ r5 : value of current byte. + @@ r6 : 0 while we are reading leading spaces. + @@@@@@@@@@@@@@@ + sub sp, sp, r0 + mov r1, sp + mov r3, #0 + push {r3} @ sp,#4: local var @isnegative. return in r1. Default value is 0/false. Positive number. + push {r0} @ sp,#0: local var @maxbytes. const. + mov r2, #1 + mov r4, #0 + + mov r6, #0 + b .rd +@ we get here if r6 is 0. +@ if space, goto .rd. +@ else set r6 to 1 and goto .noleading. +.leadchk: + mov r0, r5 + bl isspace + cmp r0, #1 + beq .rd + +.sign_chk: + mov r0, r5 + push {r1} + bl issign + cmp r0, #1 + streq r0, [sp,#8] @ sp,#4 + 4 for the pushed r1. + movhi r1, #0 + strhi r1, [sp,#8] @ sp,#4 + 4 for the pushed r1. + pop {r1} + bhs .rd + + mov r6, #1 + b .noleading + +.rd: + mov r0, #0 + bl read + cmp r0, #1 + bne .sum_digits_eof @ eof + mov r5, #0 + ldrb r5, [r1] + cmp r6, #0 + beq .leadchk + +.noleading: + mov r0, r5 + bl isdigit + cmp r0, #1 + bne .sum_digits_nan @ r5 is non-digit + + add r4, r4, #1 + add r1, r1, #1 + @ max chars to read is received in arg[0], stored in local var at sp. + @ Only 10 can be valid, so the default of 12 leaves space for separator. + ldr r3, [sp] + cmp r4, r3 + beq .sum_digits_maxrd @ max bytes read. + b .rd + + + @@@@@@@@@@@@@@@ + @ We have read r4 (0..arg[0](default 12)) digits when we get here. Go through them + @ and add/mul them together to calculate a number. + @ We multiply and add the digits in reverse order to simplify the multiplication. + @@@@@@@@@@@@@@@ + @ r0: return value. + @ r1: local variable for read buffer. + @ r2: tmp for conversion. + @ r3,r6,r7: tmp + @ r4: number of chars we have read. + @ r5: multiplier 1,10,100. + @@@@@@@@@@@@@@@ +.sum_digits_nan: + mov r0, r5 + bl isspace + cmp r0, #1 + bne bad_input +.sum_digits_maxrd: +.sum_digits_eof: + mov r0, #0 + mov r5, #1 +.count: + cmp r4, #0 + beq .readint_ret + sub r4, r4, #1 + sub r1, #1 + ldrb r2, [r1] + sub r2, r2, #48 + mov r3, r2 + + @ multiply r3 (char value of digit) with r5 (multiplier). + @ possible overflow. + @ MI means negative. + @ smulls multiples two signed 32 bit vals and returns a 64 bit result. + @ If we get anything in r7, the value has overflowed. + @ having r2[31] set is overflow too. + smulls r2, r7, r3, r5 + cmp r7, #0 + bne overflow + cmp r2, #0 + bmi overflow + + @@ possible overflow. + adds r0, r0, r2 + bvs overflow + bmi overflow + + @@ end of array check. + @@ check is needed here too, for large numbers, since 10 billion is not a valid 32 bit val. + cmp r4, #0 + beq .readint_ret + + @@ multiple multiplier by 10. + @@ possible overflow. + @@ too many digits is input. happens if input is more than 10 digits. + mov r3, #10 + mov r6, r5 + smulls r5, r7, r3, r6 + cmp r7, #0 + bne overflow + cmp r5, #0 + bmi overflow + b .count + +.readint_ret: + ldr r1, [sp,#4] @ read isnegative value. + cmp r1, #0 + rsbne r0, r0, #0 + pop {r2} + add sp, sp, #4 + add sp, sp, r2 + ldmfd sp!, {r4,r5,r6,r7,pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@ int isdigit(int) +@@ #48..#57 ascii range for '0'..'9'. +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 + .code 32 + .type isdigit STT_FUNC + .global isdigit +isdigit: + stmfd sp!, {r1,lr} + cmp r0, #48 + blo .o_range + cmp r0, #57 + bhi .o_range + mov r0, #1 + ldmfd sp!, {r1,pc} +.o_range: + mov r0, #0 + ldmfd sp!, {r1,pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@ int isspace(int) +@@ ascii space = 32, tab = 9, newline 10, cr = 13. +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 + .code 32 + .type isspace STT_FUNC + .global isspace +isspace: + stmfd sp!, {lr} + cmp r0, #32 + cmpne r0, #9 + cmpne r0, #10 + cmpne r0, #13 + beq .is_space + mov r0, #0 + ldmfd sp!, {pc} +.is_space: + mov r0, #1 + ldmfd sp!, {pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@ Return value is 1 for '-' 2 for '+'. +@@ int isspace(int) +@@ '+' = 43 and '-' = 45. +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 + .code 32 + .type issign STT_FUNC + .global issign +issign: + stmfd sp!, {lr} + cmp r0, #43 + beq .plus_sign + cmp r0, #45 + beq .minus_sign + mov r0, #0 + ldmfd sp!, {pc} +.plus_sign: + mov r0, #2 + ldmfd sp!, {pc} +.minus_sign: + mov r0, #1 + ldmfd sp!, {pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@ ARGS: +@@ r0 : in out arg (current int value) +@@ r1 : in out arg (ptr to current pos in buffer) +@@ r2 : in arg (const increment. 1000_000_000, 100_000_000, 10_000_000, 1000_000, 100_000, 10_000, 1000, 100, 10, 1.) +@@ +@@ r4 : tmp local. Outer scope must init to #10 and count down to #0. +@@ Special case is INTMAX. Must init to 5 if r4 >= 1000_000_000 (0x3b9aca00 = m10_9). +@@ r5: tmp +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 + .code 32 + .type get_digit STT_FUNC + .global get_digit +get_digit: + stmfd sp!, {r2,r4,r5,lr} + ldr r5, =m10_9 + cmp r2, r5 + movlo r4, #10 + movhs r4, #5 +.get_digit_loop: + sub r4, #1 + mul r5, r4, r2 + cmp r0, r5 + blo .get_digit_loop + sub r0, r5 + add r4, r4, #48 + strb r4, [r1], #1 + ldmfd sp!, {r2,r4,r5,pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@ A quick way to divide (numbers evenly divisible by 10) by 10. +@@ Most ARM cpus don't have a divide instruction, +@@ so this will always work. +@@ A generic div function is long and not needed here. +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 +.div_r2_10: + stmfd sp!, {r0,r1,r3,lr} + mov r0, #1 + mov r1, #10 +.find_x: + mul r3, r0, r1; + cmp r3, r2 + movlo r0, r3 + blo .find_x + mov r2, r0 + ldmfd sp!, {r0,r1,r3,pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 +.print_neg_sign: + stmfd sp!, {r0,r1,r2,lr} + @ 45 = '-' + mov r1, #45 + push {r1} + mov r2, #1 + @ r1 is ptr to our local variable (holding '-'). + mov r1, sp + mov r0, #1 + bl write + cmp r0, #0 + blne io_error + pop {r1} + ldmfd sp!, {r0,r1,r2,pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@ void printint(int val) +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 + .code 32 + .type printint STT_FUNC + .global printint +printint: + stmfd sp!, {r4,r5,r6,lr} + mov r1, #1 + ands r1, r1, r0, LSR #31 + rsbne r0, r0, #0 + blne .print_neg_sign + sub sp, sp, #20 + mov r1, sp + mov r3, sp + + ldr r2, =m10_9 +.getc_loop: + bl get_digit + cmp r2, #1 + beq .exit_getc_loop + bl .div_r2_10 + b .getc_loop +.exit_getc_loop: + ldr r0, =lf + strb r0, [r1], #1 + + sub r2, r1, r3 + mov r1, r3 + mov r0, #1 + bl write + cmp r0, #0 + blne io_error + add sp, sp, #20 + ldmfd sp!, {r4,r5,r6,pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 +range_check: + stmfd sp!, {r4,r5,lr} + ldr r4, =minval + ldr r5, =maxval + cmp r4, #0 + cmpeq r5, #0 + beq .skip_range_check + cmp r0, r4 + bllt range_err + cmp r0, r5 + blgt range_err +.skip_range_check: + ldmfd sp!, {r4,r5,pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@ void range_err() +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 +range_err: + stmfd sp!, {lr} + ldr r2, =range_err_msglen + ldr r1, =range_err_msg + mov r0, #2 + bl write + mov r0, #-1 + bl exit + ldmfd sp!, {pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@ void overflow() +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 +overflow: + stmfd sp!, {lr} + ldr r2, =overflow_msglen + ldr r1, =overflow_msg + mov r0, #2 + bl write + mov r0, #-1 + bl exit + ldmfd sp!, { pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@ void bad_input() +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 +bad_input: + stmfd sp!, {lr} + ldr r2, =bad_input_msglen + ldr r1, =bad_input_msg + mov r0, #2 + bl write + mov r0, #-1 + bl exit + ldmfd sp!, {pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@ void io_error() +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 +io_error: + stmfd sp!, {lr} + ldr r2, =io_error_msglen + ldr r1, =io_error_msg + mov r0, #2 + bl write + mov r0, #-1 + bl exit + ldmfd sp!, {pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@ void exit(int) +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 + .code 32 + .type _start STT_FUNC + .global exit +exit: + stmfd sp!, {r7, lr} + ldr r7, =sys_exit + svc #0 + ldmfd sp!, {r7, pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@ int write(int fd,char*buf,int len) +@ Return 0 if we successfully write all bytes. Otherwise return the error code. +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 + .code 32 + .type _start STT_FUNC + .global write +write: + stmfd sp!, {r4,r7, lr} + mov r4, r2 +.wr_loop: + ldr r7, =sys_write + svc #0 + @ If r0 is negative, it is more than r4 with LO (unsigned <). + cmp r0, r4 + sublo r4, r0 + blo .wr_loop + moveq r0, #0 + ldmfd sp!, {r4,r7, pc} + +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ +@ int read(int fd,char*buf,int len) +@ Return number of bytes successfully read. Ignore errors. +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ + .align 2 + .code 32 + .type _start STT_FUNC + .global read +read: + stmfd sp!, {r7, lr} + ldr r7, =sys_read + svc #0 + cmp r0, #0 + movlt r0, #0 + ldmfd sp!, {r7, pc} diff --git a/Task/A+B/BASIC/a+b-4.basic b/Task/A+B/BASIC/a+b-4.basic index 49bc7cb413..c60a333e4e 100644 --- a/Task/A+B/BASIC/a+b-4.basic +++ b/Task/A+B/BASIC/a+b-4.basic @@ -1,4 +1,4 @@ dim a(2) input "Enter two numbers separated by a space?", t$ a = explode(t$," ") -print t$ + " " + (a[0] + a[1]) +print t$ & " " & int(a[0]) + int(a[1]) diff --git a/Task/A+B/EDSAC-order-code/a+b.edsac b/Task/A+B/EDSAC-order-code/a+b-1.edsac similarity index 100% rename from Task/A+B/EDSAC-order-code/a+b.edsac rename to Task/A+B/EDSAC-order-code/a+b-1.edsac diff --git a/Task/A+B/EDSAC-order-code/a+b-2.edsac b/Task/A+B/EDSAC-order-code/a+b-2.edsac new file mode 100644 index 0000000000..7a7763988b --- /dev/null +++ b/Task/A+B/EDSAC-order-code/a+b-2.edsac @@ -0,0 +1,108 @@ + [A + B for Rosetta Code. + Read two integers and find their sum. + EDSAC program, Initial Orders 2.] + + [Print signed number, up to 10 digits, right-justified. + Modification of library subroutine P7. + 55 locations, load at even address.] + 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@ + + [Subroutine to read signed number from input, up to 10 digits. + Partly based on library subroutine R2. Result in 4D. + Working registers: 0F = dump to clear acc + 1F < 0 if number starts with minus, = 0 if not. + 6D = character code, as double-word value] + T 120 K + G K + A 3 F [make link for return] + T 36 @ [plant in code; clear acc] + H 7 @ [mult reg := 10/32] + T 4 D [initialize result to 0] + T 1 F [no minus sign yet] + T 6 D [ensure 7F and sandwich bit are 0] + [Loop until find valid first character of integer, namely + decimal digit (char codes 0..9), plus (13), or minus (22).] + [6] I 6 F [char code from input] + [7] T F [clear acc; also serves as constant 10/32] + S 6 F [load negative of char code] + A 39 @ [add 9] + E 24 @ [if decimal digit, out] + A 38 @ [add 3] + E 6 @ [if 10..12, try again] + A 37 @ [add 1] + E 20 @ [if plus, out with acc = 0] + A 39 @ [add 9] + G 6 @ [if 23..31, try again] + S 37 @ [subtract 1] + E 6 @ [if 14..21, try again] + T 1 F [minus, acc = -1, store in sign] + [Loop to read characters after first. Assumes acc = 0 here.] + [20] I 6 F [next char from input] + S 6 F [negative to acc] + A 39 @ [add 9] + G 30 @ [finished if not digit] + [24] T F [clear acc] + V 4 D [acc := 10/32 times partial sum] + L 8 F [shift 5 left] + A 6 D [add latest digit] + T 4 D [update partial sum] + E 20 @ [loop for next char] + [Here when no more digits] + [30] T F [clear acc] + A 1 F [load sign of result] + E 36 @ [exit (with acc = 0) if >= 0] + T F [< 0, clear acc] + S 4 D [subtract number] + T 4 D [store back negated; clear acc] + [36] E F [exit with acc = 0 (EDSAC convention)] + [Constants] + [37] P D [1] + [38] P 1 D [3] + [39] P 4 D [9] + + [Main routine] + T 200 K + G K + [Variables] + [0] P F P F [integer A] + [2] P F P F [integer B] + [Constants] + [4] # F [figures] + [5] @ F [carriage return] + [6] & F [line feed] + [7] K 4096 F [null char] + [Enter with acc = 0] + [8] O 4 @ [set teleprinter to figures] + A 9 @ + G 120 F [read integer A from input] + A 4 D [load] + U #@ [save] + T D [to 0D for printing] + A 14 @ + G 56 F [print A] + O 5 @ [followed by new line] + O 6 @ + A 18 @ + G 120 F [read integer B from input] + A 4 D [load] + U 2#@ [save] + T D [to 0D for printing] + A 23 @ + G 56 F [print B] + O 5 @ [followed by new line] + O 6 @ + A #@ [load A] + A 2#@ [add B] + T D [A + B to 0D for printing] + A 30 @ + G 56 F [print A + B] + O 5 @ [followed by new line] + O 6 @ + O 7 @ [print null to flush teleprinter buffer] + Z F [stop] + E 8 Z + P F +-987.123. diff --git a/Task/A+B/Elena/a+b-1.elena b/Task/A+B/Elena/a+b-1.elena index 666edf0544..a4c98a1213 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 := new Integer(); - var B := new Integer(); + var A := Integer.new(); + var B := Integer.new(); 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 d6017ce933..0a28b451d9 100644 --- a/Task/A+B/Elena/a+b-2.elena +++ b/Task/A+B/Elena/a+b-2.elena @@ -5,6 +5,6 @@ public program() { console.printLine(console.readLine() .split() - .selectBy(__mssg toInt[0]) + .selectBy(mssgconst toInt[1]) .summarize()) } diff --git a/Task/A+B/Java/a+b-1.java b/Task/A+B/Java/a+b-1.java index 052d8ee196..0d779678af 100644 --- a/Task/A+B/Java/a+b-1.java +++ b/Task/A+B/Java/a+b-1.java @@ -1,4 +1,4 @@ -import java.util.*; +import java.util.Scanner; public class Sum2 { public static void main(String[] args) { diff --git a/Task/A+B/XQuery/a+b.xquery b/Task/A+B/XQuery/a+b.xquery new file mode 100644 index 0000000000..f136119a6d --- /dev/null +++ b/Task/A+B/XQuery/a+b.xquery @@ -0,0 +1,15 @@ +(: + Using the EXPath File Module, which is built into most XQuery processors + by default and thus does not need to get imported. Some processors bind the + namespace automatically, others require explicit declaration. +:) + +xquery version "3.1"; + +declare namespace file = 'http://expath.org/ns/file'; + +let $in := 'input.txt' +let $out := 'output.txt' +let $numbers := tokenize(file:read-text($in)) +let $result := xs:numeric($numbers[1]) + xs:numeric($numbers[2]) +return file:write-text($out, xs:string($result)) diff --git a/Task/ABC-Problem/Elena/abc-problem.elena b/Task/ABC-Problem/Elena/abc-problem.elena index 2239dd7787..41a57202a0 100644 --- a/Task/ABC-Problem/Elena/abc-problem.elena +++ b/Task/ABC-Problem/Elena/abc-problem.elena @@ -28,12 +28,12 @@ extension op public program() { - var blocks := new object[] {"BO", "XK", "DQ", "CP", "NA", + var blocks := new string[]{"BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", "JW", "HU", "VI", "AN", "OB", "ER", "FS", "LY", "PC", "ZM"}; - var words := new object[] {"", "A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "Confuse"}; + var words := new string[]{"", "A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "Confuse"}; Enumerator e := words.enumerator(); e.next(); diff --git a/Task/ABC-Problem/Julia/abc-problem.julia b/Task/ABC-Problem/Julia/abc-problem.julia index 52bf08a809..b584f8f222 100644 --- a/Task/ABC-Problem/Julia/abc-problem.julia +++ b/Task/ABC-Problem/Julia/abc-problem.julia @@ -1,3 +1,5 @@ +using Printf + function abc(str::AbstractString, list) isempty(str) && return true for i in eachindex(list) diff --git a/Task/ABC-Problem/REXX/abc-problem-1.rexx b/Task/ABC-Problem/REXX/abc-problem-1.rexx index b6ff22c338..cfb88b54ac 100644 --- a/Task/ABC-Problem/REXX/abc-problem-1.rexx +++ b/Task/ABC-Problem/REXX/abc-problem-1.rexx @@ -7,15 +7,15 @@ blocks= 'BO XK DQ CP NA GT RE TG QD FS JW HU VI AN OB ER FS LY exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ spell: procedure expose blocks; arg x /*ARG uppercases the word to be spelt.*/ - L=length(x); @.=0 /*get length of the word to be spelt. */ - do try=1 for L; z=blocks; upper z /*use a fresh copy of the "Z" blocks.*/ - do n=1 for L; y=substr(x, n, 1) /*attempt another letter in the word. */ - @.n=pos(y, z, 1 + @.n); if @.n==0 then leave /*not found? Try again*/ - z=overlay(' ', z, @.n) /*mutate the toy block ───► a onesy. */ - do q=1 for words(z); if length(word(z, q))==1 then z=delword(z, q, 1) + L= length(x); @.= 0 /*get length of the word to be spelt. */ + do try=1 for L; z= blocks; upper z /*use a fresh copy of the "Z" blocks.*/ + do n=1 for L; y= substr(x, n, 1) /*attempt another letter in the word. */ + @.n= pos(y, z, 1 + @.n); if @.n==0 then leave /*not found? Try again*/ + z= overlay(' ', z, @.n) /*mutate the toy block ───► a onesy. */ + do q=1 for words(z); if length(word(z,q))==1 then z= delword(z, q, 1) end /*q*/ /* [↑] elide any existing onesy block.*/ if n==L then leave try /*was last letter used in the spelling?*/ end /*n*/ /* [↑] end of a toy block usage. */ end /*try*/ /* [↑] end of a "TRY" permute. */ - say right(arg(1), 30) right( word( "can't can", (n==L) +1), 6) 'be spelt.' + say right( arg(1), 30) right( word( "can't can", (n==L) + 1), 6) 'be spelt.' return diff --git a/Task/ABC-Problem/XPL0/abc-problem.xpl0 b/Task/ABC-Problem/XPL0/abc-problem.xpl0 new file mode 100644 index 0000000000..e98ef226e6 --- /dev/null +++ b/Task/ABC-Problem/XPL0/abc-problem.xpl0 @@ -0,0 +1,29 @@ +string 0; + +char Side1, Side2; +def Size = 20; +char Avail(Size); + +func CanMakeWord(Word); \returns 'true' if blocks can make Word +char Word; +int I, Let; +[Let:= Word(0) & $5F; \get letter and make sure it's uppercase +if Let = 0 then return true; \if 0 then end of word; return successful +for I:= 0 to Size-1 do \scan for block that contains letter + if Avail(I) and (Side1(I) = Let or Side2(I) = Let) then + [Avail(I):= false; + if CanMakeWord(Word+1) then return true; + ]; +return false; +]; + +int I, J, Words; +[Side1:= "BXDCNGRTQFJHVAOEFLPZ"; + Side2:= "OKQPATEGDSWUINBRSYCM"; +Words:= ["A", "bark", "Book", "Treat", "Common", "Squad", "conFuse"]; +for J:= 0 to 6 do + [Text(0, "Can make ^""); Text(0, Words(J)); Text(0, "^": "); + for I:= 0 to Size-1 do Avail(I):= true; + Text(0, if CanMakeWord(Words(J)) then "True" else "False"); CrLf(0); + ]; +] diff --git a/Task/AKS-test-for-primes/Ada/aks-test-for-primes.ada b/Task/AKS-test-for-primes/Ada/aks-test-for-primes.ada new file mode 100644 index 0000000000..0ea9ed95f6 --- /dev/null +++ b/Task/AKS-test-for-primes/Ada/aks-test-for-primes.ada @@ -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/Julia/aks-test-for-primes-2.julia b/Task/AKS-test-for-primes/Julia/aks-test-for-primes-2.julia index 1cc9df25e6..e5fc3ffe81 100644 --- a/Task/AKS-test-for-primes/Julia/aks-test-for-primes-2.julia +++ b/Task/AKS-test-for-primes/Julia/aks-test-for-primes-2.julia @@ -1,3 +1,5 @@ +using Printf + function stringpoly(n::Int64) if n < 0 return "" diff --git a/Task/AKS-test-for-primes/Rust/aks-test-for-primes-1.rust b/Task/AKS-test-for-primes/Rust/aks-test-for-primes-1.rust index 11e268bfce..59f48a2e58 100644 --- a/Task/AKS-test-for-primes/Rust/aks-test-for-primes-1.rust +++ b/Task/AKS-test-for-primes/Rust/aks-test-for-primes-1.rust @@ -1,7 +1,5 @@ -use std::iter::repeat; - fn aks_coefficients(k: usize) -> Vec { - let mut coefficients = repeat(0i64).take(k + 1).collect::>(); + let mut coefficients = vec![0i64; k + 1]; coefficients[0] = 1; for i in 1..(k + 1) { coefficients[i] = -(1..i).fold(coefficients[0], |prev, j|{ @@ -18,7 +16,7 @@ fn is_prime(p: usize) -> bool { false } else { let c = aks_coefficients(p); - (1 .. (c.len() - 1) / 2 + 1).all(|i| (c[i] % (p as i64)) == 0) + (1..p / 2 + 1).all(|i| c[i] % p as i64 == 0) } } @@ -26,7 +24,7 @@ fn main() { for i in 0..8 { println!("{}: {:?}", i, aks_coefficients(i)); } - for i in (1..51).filter(|&i| is_prime(i)) { + for i in (1..=50).filter(|&i| is_prime(i)) { print!("{} ", i); } } diff --git a/Task/Abstract-type/00DESCRIPTION b/Task/Abstract-type/00DESCRIPTION index 4c49cc7690..635ed7d1da 100644 --- a/Task/Abstract-type/00DESCRIPTION +++ b/Task/Abstract-type/00DESCRIPTION @@ -9,3 +9,5 @@ It is important not to confuse this ''abstractness'' (of implementation) with on In some languages, like for example in Objective Caml which is strongly statically typed, it is also possible to have '''abstract types''' that are not OO related and are not an abstractness too. These are ''pure abstract types'' without any definition even in the implementation and can be used for example for the type algebra, or for some consistence of the type inference. For example in this area, an abstract type can be used as a phantom type to augment another type as its parameter. '''Task''': show how an abstract type can be declared in the language. If the language makes a distinction between interfaces and partially implemented types illustrate both. + +{{omit from|MiniZinc|no ability to declare new types at all}} diff --git a/Task/Abstract-type/Go/abstract-type.go b/Task/Abstract-type/Go/abstract-type-1.go similarity index 100% rename from Task/Abstract-type/Go/abstract-type.go rename to Task/Abstract-type/Go/abstract-type-1.go diff --git a/Task/Abstract-type/Go/abstract-type-2.go b/Task/Abstract-type/Go/abstract-type-2.go new file mode 100644 index 0000000000..250d18e20e --- /dev/null +++ b/Task/Abstract-type/Go/abstract-type-2.go @@ -0,0 +1,29 @@ +package main + +import "fmt" + +type Beast interface { + Cry() string +} + +type Pet struct{} +type Cat struct { + Pet +} + +func (p Pet) Name(b Beast) { + fmt.Println(b.Cry()) +} +func (p Pet) Cry() string { + return "Woof" +} +func (c Cat) Cry() string { + return "Meow" +} + +func main() { + p := Pet{} + c := Cat{} + p.Name(p) // prt Woof + c.Name(c) // prt Meow +} diff --git a/Task/Abstract-type/Vala/abstract-type.vala b/Task/Abstract-type/Vala/abstract-type.vala new file mode 100644 index 0000000000..3c83c3df34 --- /dev/null +++ b/Task/Abstract-type/Vala/abstract-type.vala @@ -0,0 +1,29 @@ +public abstract class Animal : Object { + public void eat() { + print("Chomp! Chomp!\n"); + } + + public abstract void talk(); +} + +public class Mouse : Animal { + public override void talk() { + print("Squeak! Squeak!\n"); + } +} + +public class Dog : Animal { + public override void talk() { + print("Woof! Woof!\n"); + } +} + +void main() { + Dog mike = new Dog(); + Mouse scott = new Mouse(); + + mike.talk(); + mike.eat(); + scott.talk(); + scott.eat(); +} diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Ada/abundant,-deficient-and-perfect-number-classifications.ada b/Task/Abundant,-deficient-and-perfect-number-classifications/Ada/abundant,-deficient-and-perfect-number-classifications.ada index 7f31df9a87..6f066bde65 100644 --- a/Task/Abundant,-deficient-and-perfect-number-classifications/Ada/abundant,-deficient-and-perfect-number-classifications.ada +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Ada/abundant,-deficient-and-perfect-number-classifications.ada @@ -2,29 +2,26 @@ 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); - Sum: Natural; 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 - Sum := Divisor_Sum.Process(N); - if Sum < N then - Results(Deficient) := Results(Deficient)+1; - elsif Sum = N then - Results(Perfect) := Results(Perfect)+1; - else - Results(Abundant) := Results(Abundant)+1; - end if; + Cls := Class(Divisor_Sum.Process(N), N); + Results(Cls) := Results(Cls)+1; end loop; - Sum := 0; for Class in Results'Range loop CIO.Put(Class, 12); NIO.Put(Results(Class), 8); @@ -32,7 +29,7 @@ begin end loop; Ada.Text_IO.Put_Line("--------------------"); Ada.Text_IO.Put("Sum "); - NIO.Put(Sum, 8); + 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/Erlang/abundant,-deficient-and-perfect-number-classifications-1.erl b/Task/Abundant,-deficient-and-perfect-number-classifications/Erlang/abundant,-deficient-and-perfect-number-classifications-1.erl index d0e48c4358..6f12c8a35b 100644 --- a/Task/Abundant,-deficient-and-perfect-number-classifications/Erlang/abundant,-deficient-and-perfect-number-classifications-1.erl +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Erlang/abundant,-deficient-and-perfect-number-classifications-1.erl @@ -6,15 +6,15 @@ divs(1) -> []; divs(N) -> lists:sort(divisors(1,N)). divisors(1,N) -> - [1] ++ divisors(2,N,math:sqrt(N)). + divisors(2,N,math:sqrt(N),[1]). -divisors(K,_N,Q) when K > Q -> []; -divisors(K,N,_Q) when N rem K =/= 0 -> - [] ++ divisors(K+1,N,math:sqrt(N)); -divisors(K,N,_Q) when K * K == N -> - [K] ++ divisors(K+1,N,math:sqrt(N)); -divisors(K,N,_Q) -> - [K, N div K] ++ divisors(K+1,N,math:sqrt(N)). +divisors(K,_N,Q,L) when K > Q -> L; +divisors(K,N,_Q,L) when N rem K =/= 0 -> + divisors(K+1,N,_Q,L); +divisors(K,N,_Q,L) when K * K =:= N -> + divisors(K+1,N,_Q,[K|L]); +divisors(K,N,_Q,L) -> + divisors(K+1,N,_Q,[N div K, K|L]). sumdivs(N) -> lists:sum(divs(N)). diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Frink/abundant,-deficient-and-perfect-number-classifications.frink b/Task/Abundant,-deficient-and-perfect-number-classifications/Frink/abundant,-deficient-and-perfect-number-classifications.frink new file mode 100644 index 0000000000..667b899fc1 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Frink/abundant,-deficient-and-perfect-number-classifications.frink @@ -0,0 +1,11 @@ +d = new dict +for n = 1 to 20000 +{ + s = sum[allFactors[n, true, false, true], 0] + rel = s <=> n + d.increment[rel, 1] +} + +println["Deficient: " + d@(-1)] +println["Perfect: " + d@0] +println["Abundant: " + d@1] diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Haskell/abundant,-deficient-and-perfect-number-classifications.hs b/Task/Abundant,-deficient-and-perfect-number-classifications/Haskell/abundant,-deficient-and-perfect-number-classifications-1.hs similarity index 100% rename from Task/Abundant,-deficient-and-perfect-number-classifications/Haskell/abundant,-deficient-and-perfect-number-classifications.hs rename to Task/Abundant,-deficient-and-perfect-number-classifications/Haskell/abundant,-deficient-and-perfect-number-classifications-1.hs diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Haskell/abundant,-deficient-and-perfect-number-classifications-2.hs b/Task/Abundant,-deficient-and-perfect-number-classifications/Haskell/abundant,-deficient-and-perfect-number-classifications-2.hs new file mode 100644 index 0000000000..ff861feac3 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Haskell/abundant,-deficient-and-perfect-number-classifications-2.hs @@ -0,0 +1,27 @@ +import Data.Numbers.Primes (primeFactors) +import Data.List (group, sort) +import Data.Bool (bool) + +deficientPerfectAbundantCountsUpTo :: Int -> (Int, Int, Int) +deficientPerfectAbundantCountsUpTo n = + foldr + (\x (deficient, perfect, abundant) -> + let divisorSum = sum $ properDivisors x + in bool + (bool + (deficient, succ perfect, abundant) + (deficient, perfect, succ abundant) + (divisorSum > x)) + (succ deficient, perfect, abundant) + (divisorSum < x)) + (0, 0, 0) + [1 .. n :: Int] + +properDivisors :: Int -> [Int] +properDivisors = + init . sort . foldr ( + flip ((<*>) . fmap (*)) . scanl (*) 1 + ) [1] . group . primeFactors + +main :: IO () +main = print $ deficientPerfectAbundantCountsUpTo 20000 diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications.py b/Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications-1.py similarity index 100% rename from Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications.py rename to Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications-1.py diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications-2.py b/Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications-2.py new file mode 100644 index 0000000000..3a7603f5e4 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications-2.py @@ -0,0 +1,109 @@ +'''Abundant, deficient and perfect number classifications''' + +from itertools import accumulate, chain, groupby, product +from functools import reduce +from math import floor, sqrt +from operator import mul + + +# deficientPerfectAbundantCountsUpTo :: Int -> (Int, Int, Int) +def deficientPerfectAbundantCountsUpTo(n): + '''Counts of deficient, perfect, and abundant + integers in the range [1..n]. + ''' + def go(dpa, x): + deficient, perfect, abundant = dpa + divisorSum = sum(properDivisors(x)) + return ( + succ(deficient), perfect, abundant + ) if x > divisorSum else ( + deficient, perfect, succ(abundant) + ) if x < divisorSum else ( + deficient, succ(perfect), abundant + ) + return reduce(go, range(1, 1 + n), (0, 0, 0)) + + +# --------------------------TEST-------------------------- +# main :: IO () +def main(): + '''Size of each sub-class of integers drawn from [1..20000]:''' + + print(main.__doc__) + print( + '\n'.join(map( + lambda a, b: a.rjust(10) + ' -> ' + str(b), + ['Deficient', 'Perfect', 'Abundant'], + deficientPerfectAbundantCountsUpTo(20000) + )) + ) + + +# ------------------------GENERIC------------------------- + +# primeFactors :: Int -> [Int] +def primeFactors(n): + '''A list of the prime factors of n. + ''' + def f(qr): + r = qr[1] + return step(r), 1 + r + + def step(x): + return 1 + (x << 2) - ((x >> 1) << 1) + + def go(x): + root = floor(sqrt(x)) + + def p(qr): + q = qr[0] + return root < q or 0 == (x % q) + + q = until(p)(f)( + (2 if 0 == x % 2 else 3, 1) + )[0] + return [x] if q > root else [q] + go(x // q) + + return go(n) + + +# properDivisors :: Int -> [Int] +def properDivisors(n): + '''The ordered divisors of n, excluding n itself. + ''' + def go(a, x): + return [a * b for a, b in product( + a, + accumulate(chain([1], x), mul) + )] + return sorted( + reduce(go, [ + list(g) for _, g in groupby(primeFactors(n)) + ], [1]) + )[:-1] if 1 < n else [] + + +# succ :: Int -> Int +def succ(x): + '''The successor of a value. + For numeric types, (1 +). + ''' + return 1 + x + + +# until :: (a -> Bool) -> (a -> a) -> a -> a +def until(p): + '''The result of repeatedly applying f until p holds. + The initial seed value is x. + ''' + def go(f, x): + v = x + while not p(v): + v = f(v) + return v + return lambda f: lambda x: go(f, x) + + +# MAIN --- +if __name__ == '__main__': + main() diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications-3.py b/Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications-3.py new file mode 100644 index 0000000000..396cf2d3ff --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications-3.py @@ -0,0 +1,11 @@ +# nthArrow :: (a -> b) -> Tuple -> Int -> Tuple +def nthArrow(f): + '''A simple function lifted to one which applies to a + tuple, transforming only its nth value. + ''' + def go(v, n): + m = n - 1 + return v if n > len(v) else [ + x if m != i else f(x) for i, x in enumerate(v) + ] + return lambda tpl: lambda n: tuple(go(tpl, n)) diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications-4.py b/Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications-4.py new file mode 100644 index 0000000000..0dbd88ba9c --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Python/abundant,-deficient-and-perfect-number-classifications-4.py @@ -0,0 +1,13 @@ +# deficientPerfectAbundantCountsUpTo :: Int -> (Int, Int, Int) +def deficientPerfectAbundantCountsUpTo(n): + '''Counts of deficient, perfect, and abundant + integers in the range [1..n]. + ''' + def go(dpa, x): + divisorSum = sum(properDivisors(x)) + return nthArrow(succ)(dpa)( + 1 if x > divisorSum else ( + 3 if x < divisorSum else 2 + ) + ) + return reduce(go, range(1, 1 + n), (0, 0, 0)) diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Vala/abundant,-deficient-and-perfect-number-classifications.vala b/Task/Abundant,-deficient-and-perfect-number-classifications/Vala/abundant,-deficient-and-perfect-number-classifications.vala new file mode 100644 index 0000000000..260b68b28c --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Vala/abundant,-deficient-and-perfect-number-classifications.vala @@ -0,0 +1,35 @@ +enum Classification { + DEFICIENT, + PERFECT, + ABUNDANT +} + +void main() { + var i = 0; var j = 0; + var sum = 0; var try_max = 0; + int[] count_list = {1, 0, 0}; + for (i = 2; i <= 20000; i++) { + try_max = i / 2; + sum = 1; + for (j = 2; j < try_max; j++) { + if (i % j != 0) + continue; + try_max = i / j; + sum += j; + if (j != try_max) + sum += try_max; + } + if (sum < i) { + count_list[Classification.DEFICIENT]++; + continue; + } + if (sum > i) { + count_list[Classification.ABUNDANT]++; + continue; + } + count_list[Classification.PERFECT]++; + } + print(@"There are $(count_list[Classification.DEFICIENT]) deficient,"); + print(@" $(count_list[Classification.PERFECT]) perfect,"); + print(@" $(count_list[Classification.ABUNDANT]) abundant numbers between 1 and 20000.\n"); +} diff --git a/Task/Accumulator-factory/Retro/accumulator-factory.retro b/Task/Accumulator-factory/Retro/accumulator-factory.retro new file mode 100644 index 0000000000..ceb402d4de --- /dev/null +++ b/Task/Accumulator-factory/Retro/accumulator-factory.retro @@ -0,0 +1,2 @@ +:acc (ns-) + d:create , [ [ fetch ] [ v:inc ] bi ] does ; diff --git a/Task/Ackermann-function/00DESCRIPTION b/Task/Ackermann-function/00DESCRIPTION index cbf33306bc..f67beb6334 100644 --- a/Task/Ackermann-function/00DESCRIPTION +++ b/Task/Ackermann-function/00DESCRIPTION @@ -15,8 +15,10 @@ The Ackermann function is usually defined as follows: -Its arguments are never negative and it always terminates. Write a function which returns the value of A(m, n). Arbitrary precision is preferred (since the function grows so quickly), but not required. +Its arguments are never negative and it always terminates. +;Task: +Write a function which returns the value of A(m, n). Arbitrary precision is preferred (since the function grows so quickly), but not required. ;See also: * [[wp:Conway_chained_arrow_notation#Ackermann_function|Conway chained arrow notation]] for the Ackermann function. diff --git a/Task/Ackermann-function/JavaScript/ackermann-function.js b/Task/Ackermann-function/JavaScript/ackermann-function-1.js similarity index 100% rename from Task/Ackermann-function/JavaScript/ackermann-function.js rename to Task/Ackermann-function/JavaScript/ackermann-function-1.js diff --git a/Task/Ackermann-function/JavaScript/ackermann-function-2.js b/Task/Ackermann-function/JavaScript/ackermann-function-2.js new file mode 100644 index 0000000000..1f85df2e13 --- /dev/null +++ b/Task/Ackermann-function/JavaScript/ackermann-function-2.js @@ -0,0 +1,6 @@ +function ack(M,N) { + for (; M > 0; M--) { + N = N === 0 ? 1 : ack(M,N-1); + } + return N+1; +} diff --git a/Task/Ackermann-function/JavaScript/ackermann-function-3.js b/Task/Ackermann-function/JavaScript/ackermann-function-3.js new file mode 100644 index 0000000000..51a247711a --- /dev/null +++ b/Task/Ackermann-function/JavaScript/ackermann-function-3.js @@ -0,0 +1,20 @@ +function stackermann(M, N) { + const stack = []; + for (;;) { + if (M === 0) { + N++; + if (stack.length === 0) return N; + const r = stack[stack.length-1]; + if (r[1] === 1) stack.length--; + else r[1]--; + M = r[0]; + } else if (N === 0) { + M--; + N = 1; + } else { + M-- + stack.push([M, N]); + N = 1; + } + } +} diff --git a/Task/Ackermann-function/JavaScript/ackermann-function-4.js b/Task/Ackermann-function/JavaScript/ackermann-function-4.js new file mode 100644 index 0000000000..bca6a8dc8a --- /dev/null +++ b/Task/Ackermann-function/JavaScript/ackermann-function-4.js @@ -0,0 +1,26 @@ +#!/usr/bin/env nodejs +function ack(M, N){ + const next = new Float64Array(M + 1); + const goal = new Float64Array(M + 1).fill(1, 0, M); + const n = N + 1; + + // This serves as a sentinel value; + // next[M] never equals goal[M] == -1, + // so we don't need an extra check for + // loop termination below. + goal[M] = -1; + + let v; + do { + v = next[0] + 1; + let m = 0; + while (next[m] === goal[m]) { + goal[m] = v; + next[m++]++; + } + next[m]++; + } while (next[M] !== n); + return v; +} +var args = process.argv; +console.log(ack(parseInt(args[2]), parseInt(args[3]))); diff --git a/Task/Ackermann-function/JavaScript/ackermann-function-5.js b/Task/Ackermann-function/JavaScript/ackermann-function-5.js new file mode 100644 index 0000000000..6d169b0aaa --- /dev/null +++ b/Task/Ackermann-function/JavaScript/ackermann-function-5.js @@ -0,0 +1,38 @@ +(() => { + 'use strict'; + + // ackermann :: Int -> Int -> Int + const ackermann = m => n => { + const go = (m, n) => + 0 === m ? ( + succ(n) + ) : go(pred(m), 0 === n ? ( + 1 + ) : go(m, pred(n))); + return go(m, n); + }; + + // TEST ----------------------------------------------- + const main = () => console.log(JSON.stringify( + [0, 1, 2, 3].map( + flip(ackermann)(3) + ) + )); + + + // GENERAL FUNCTIONS ---------------------------------- + + // flip :: (a -> b -> c) -> b -> a -> c + const flip = f => + x => y => f(y)(x); + + // pred :: Enum a => a -> a + const pred = x => x - 1; + + // succ :: Enum a => a -> a + const succ = x => 1 + x; + + + // MAIN --- + return main(); +})(); diff --git a/Task/Ackermann-function/Lua/ackermann-function.lua b/Task/Ackermann-function/Lua/ackermann-function-1.lua similarity index 100% rename from Task/Ackermann-function/Lua/ackermann-function.lua rename to Task/Ackermann-function/Lua/ackermann-function-1.lua diff --git a/Task/Ackermann-function/Lua/ackermann-function-2.lua b/Task/Ackermann-function/Lua/ackermann-function-2.lua new file mode 100644 index 0000000000..959f548fd6 --- /dev/null +++ b/Task/Ackermann-function/Lua/ackermann-function-2.lua @@ -0,0 +1,38 @@ +#!/usr/bin/env luajit +local gmp = require 'gmp' ('libgmp') +local mpz, z_mul, z_add, z_add_ui, z_set_d = + gmp.types.z, gmp.z_mul, gmp.z_add, gmp.z_add_ui, gmp.z_set_d +local z_cmp, z_cmp_ui, z_init_d, z_set= + gmp.z_cmp, gmp.z_cmp_ui, gmp.z_init_set_d, gmp.z_set +local printf = gmp.printf + +local function ack(i,n) + local nxt=setmetatable({}, {__index=function(t,k) local z=mpz() z_init_d(z, 0) t[k]=z return z end}) + local goal=setmetatable({}, {__index=function(t,k) local o=mpz() z_init_d(o, 1) t[k]=o return o end}) + goal[i]=mpz() z_init_d(goal[i], -1) + local v=mpz() z_init_d(v, 0) + local ic + local END=n+1 + local ntmp,gtmp + repeat + ic=0 + ntmp,gtmp=nxt[ic], goal[ic] + z_add_ui(v, ntmp, 1) + while z_cmp(ntmp, gtmp) == 0 do + z_set(gtmp,v) + z_add_ui(ntmp, ntmp, 1) + nxt[ic], goal[ic]=ntmp, gtmp + ic=ic+1 + ntmp,gtmp=nxt[ic], goal[ic] + end + z_add_ui(ntmp, ntmp, 1) + nxt[ic]=ntmp + until z_cmp_ui(nxt[i], END) == 0 + return v +end + +if #arg<1 then + print("Ackermann: "..arg[0].." [num2]") +else + printf("%Zd\n", ack(tonumber(arg[1]), arg[2] and tonumber(arg[2]) or 0)) +end diff --git a/Task/Ackermann-function/Processing/ackermann-function b/Task/Ackermann-function/Processing/ackermann-function index 8b381fa09a..b35ab10da7 100644 --- a/Task/Ackermann-function/Processing/ackermann-function +++ b/Task/Ackermann-function/Processing/ackermann-function @@ -1,9 +1,19 @@ -int ackermann(int m, n) -{ - if (m == 0) - return n + 1; - else if (m > 0 && n == 0) - return ackermann(m - 1, 1); - else - return ackermann( m - 1, ackermann(m, n - 1) ); +int ackermann(int m, int n) { + if (m == 0) + return n + 1; + else if (m > 0 && n == 0) + return ackermann(m - 1, 1); + else + return ackermann( m - 1, ackermann(m, n - 1) ); +} + +// Call function to produce output: +// the first 4x7 Ackermann numbers +void setup() { + for (int m=0; m<4; m++) { + for (int n=0; n<7; n++) { + print(ackermann(m, n), " "); + } + println(); + } } diff --git a/Task/Ackermann-function/Vala/ackermann-function.vala b/Task/Ackermann-function/Vala/ackermann-function.vala new file mode 100644 index 0000000000..8315a52dad --- /dev/null +++ b/Task/Ackermann-function/Vala/ackermann-function.vala @@ -0,0 +1,13 @@ +uint64 ackermann(uint64 m, uint64 n) { + if (m == 0) return n + 1; + if (n == 0) return ackermann(m - 1, 1); + return ackermann(m - 1, ackermann(m, n - 1)); +} + +void main () { + for (uint64 m = 0; m < 4; ++m) { + for (uint64 n = 0; n < 10; ++n) { + print(@"A($m,$n) = $(ackermann(m,n))\n"); + } + } +} diff --git a/Task/Ackermann-function/X86-Assembly/ackermann-function.x86 b/Task/Ackermann-function/X86-Assembly/ackermann-function.x86 new file mode 100644 index 0000000000..ffe46ad920 --- /dev/null +++ b/Task/Ackermann-function/X86-Assembly/ackermann-function.x86 @@ -0,0 +1,29 @@ +section .text + +global _main +_main: + mov eax, 3 ;m + mov ebx, 4 ;n + call ack ;returns number in ebx + ret + +ack: + cmp eax, 0 + je M0 ;if M == 0 + cmp ebx, 0 + je N0 ;if N == 0 + dec ebx ;else N-1 + push eax ;save M + call ack1 ;ack(m,n) -> returned in ebx so no further instructions needed + pop eax ;restore M + dec eax ;M - 1 + call ack1 ;return ack(m-1,ack(m,n-1)) + ret + M0: + inc ebx ;return n + 1 + ret + N0: + dec eax + inc ebx ;ebx always 0: inc -> ebx = 1 + call ack1 ;return ack(M-1,1) + ret diff --git a/Task/Active-Directory-Search-for-a-user/PowerShell/active-directory-search-for-a-user.psh b/Task/Active-Directory-Search-for-a-user/PowerShell/active-directory-search-for-a-user.psh new file mode 100644 index 0000000000..63a5c8a5cf --- /dev/null +++ b/Task/Active-Directory-Search-for-a-user/PowerShell/active-directory-search-for-a-user.psh @@ -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-object/Phix/active-object-1.phix b/Task/Active-object/Phix/active-object-1.phix new file mode 100644 index 0000000000..7e882c82dd --- /dev/null +++ b/Task/Active-object/Phix/active-object-1.phix @@ -0,0 +1,65 @@ +integer xlock = init_cs() + +class integrator +-- +-- Integrates input function f over time +-- v + (t1 - t0) * (f(t1) + f(t0)) / 2 +-- + integer f -- function f(atom t); (see note) + atom interval, t0, k0 = 0, v = 0 + bool running + public integer id + + procedure set_func(integer rid) + this.f = rid + end procedure + + procedure update() + enter_cs(xlock) + integer f = this.f -- (nb: no "this") + atom t1 = time(), + k1 = f(t1) +-- (oops, '+=' not yet properly supported on class fields...) +-- v += (t1 - t0) * (k1 + k0) / 2 + v = v + (t1 - t0) * (k1 + k0) / 2 + t0 = t1 + k0 = k1 + leave_cs(xlock) + end procedure + + procedure tick() + running = true + while running do + sleep(interval) + update() + end while + end procedure + + procedure stop() + running = false + wait_thread(id) + end procedure + + function get_output() + return v + end function + +end class + +function new_integrator(integer rid, atom interval) + integrator i = new({rid,interval,time()}) + i.update() + i.id = create_thread(i.tick,{i}) + return i +end function + +function zero(atom /*t*/) return 0 end function +function sine(atom t) return sin(2*PI*0.5*t) end function + +integrator i = new_integrator(sine,0.01); +sleep(2) +?i.get_output() +i.set_func(zero) +sleep(0.5) +i.stop() +?i.get_output() diff --git a/Task/Active-object/Phix/active-object.phix b/Task/Active-object/Phix/active-object-2.phix similarity index 100% rename from Task/Active-object/Phix/active-object.phix rename to Task/Active-object/Phix/active-object-2.phix diff --git a/Task/Address-of-a-variable/Julia/address-of-a-variable-1.julia b/Task/Address-of-a-variable/Julia/address-of-a-variable-1.julia index c9fc3dad9b..455faff55d 100644 --- a/Task/Address-of-a-variable/Julia/address-of-a-variable-1.julia +++ b/Task/Address-of-a-variable/Julia/address-of-a-variable-1.julia @@ -1,5 +1,8 @@ -julia> x = 3 +julia> x = [1, 2, 3] julia> ptr = pointer_from_objref(x) Ptr{Void} @0x000000010282e4a0 julia> unsafe_pointer_to_objref(ptr) -3 +3-element Array{Int64,1}: + 1 + 2 + 3 diff --git a/Task/Address-of-a-variable/Perl/address-of-a-variable-1.pl b/Task/Address-of-a-variable/Perl/address-of-a-variable-1.pl index 8ae7e23582..bf803da907 100644 --- a/Task/Address-of-a-variable/Perl/address-of-a-variable-1.pl +++ b/Task/Address-of-a-variable/Perl/address-of-a-variable-1.pl @@ -1,2 +1,2 @@ use Scalar::Util qw(refaddr); -print refaddr(\my $v), "\n"; # 135691508 +print refaddr(\my $v), "\n"; # 140502490125712 diff --git a/Task/Address-of-a-variable/Perl/address-of-a-variable-2.pl b/Task/Address-of-a-variable/Perl/address-of-a-variable-2.pl index 85557b3156..9d97b42bb4 100644 --- a/Task/Address-of-a-variable/Perl/address-of-a-variable-2.pl +++ b/Task/Address-of-a-variable/Perl/address-of-a-variable-2.pl @@ -1,4 +1 @@ -my $a = 12; -my $b = \$a; # get reference -$$b = $$b + 30; # access referenced value -print $a; # prints 42 +printf "%p", $v; # 7fc949039590 diff --git a/Task/Address-of-a-variable/Perl/address-of-a-variable-3.pl b/Task/Address-of-a-variable/Perl/address-of-a-variable-3.pl index ca3818d25a..85557b3156 100644 --- a/Task/Address-of-a-variable/Perl/address-of-a-variable-3.pl +++ b/Task/Address-of-a-variable/Perl/address-of-a-variable-3.pl @@ -1,6 +1,4 @@ my $a = 12; -our $b; # you can overlay only global variables (this line is only for strictness) -*b = \$a; -print $b; # prints 12 -$b++; -print $a; # prints 13 +my $b = \$a; # get reference +$$b = $$b + 30; # access referenced value +print $a; # prints 42 diff --git a/Task/Address-of-a-variable/Perl/address-of-a-variable-4.pl b/Task/Address-of-a-variable/Perl/address-of-a-variable-4.pl new file mode 100644 index 0000000000..ca3818d25a --- /dev/null +++ b/Task/Address-of-a-variable/Perl/address-of-a-variable-4.pl @@ -0,0 +1,6 @@ +my $a = 12; +our $b; # you can overlay only global variables (this line is only for strictness) +*b = \$a; +print $b; # prints 12 +$b++; +print $a; # prints 13 diff --git a/Task/Address-of-a-variable/R/address-of-a-variable-1.r b/Task/Address-of-a-variable/R/address-of-a-variable-1.r new file mode 100644 index 0000000000..900a01d6fe --- /dev/null +++ b/Task/Address-of-a-variable/R/address-of-a-variable-1.r @@ -0,0 +1,9 @@ +x <- 5 +y <- x +pryr::address(x) +pryr::address(y) + +y <- y + 1 + +pryr::address(x) +pryr::address(y) diff --git a/Task/Address-of-a-variable/R/address-of-a-variable-2.r b/Task/Address-of-a-variable/R/address-of-a-variable-2.r new file mode 100644 index 0000000000..098f7e1a7e --- /dev/null +++ b/Task/Address-of-a-variable/R/address-of-a-variable-2.r @@ -0,0 +1,12 @@ +address <- function(obj) { + paste0("0x", substring(sub(" .*$","",capture.output(.Internal(inspect(obj)))),2)) +} + +x <- 5 +y <- x +address(x) +address(y) + +y <- y + 1 +address(x) +address(y) diff --git a/Task/Align-columns/Python/align-columns-1.py b/Task/Align-columns/Python/align-columns-1.py index b6ae3b9a42..708282b3a2 100644 --- a/Task/Align-columns/Python/align-columns-1.py +++ b/Task/Align-columns/Python/align-columns-1.py @@ -1,45 +1,19 @@ -from StringIO import StringIO +from itertools import zip_longest -textinfile = '''Given$a$text$file$of$many$lines,$where$fields$within$a$line$ +txt = """Given$a$txt$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.''' +justified,$right$justified,$or$center$justified$within$its$column.""" -j2justifier = dict(L=str.ljust, R=str.rjust, C=str.center) +parts = [line.rstrip("$").split("$") for line in txt.splitlines()] +widths = [max(len(word) for word in col) + for col in zip_longest(*parts, fillvalue='')] -def aligner(infile, justification = 'L'): - ''' \ - Justify columns of textual tabular input where the row separator is the newline - and the field separator is a 'dollar' character. - justification can be L, R, or C; (Left, Right, or Centered). - - Return the justified output as a string - ''' - assert justification in j2justifier, "justification can be L, R, or C; (Left, Right, or Centered)." - justifier = j2justifier[justification] - - fieldsbyrow= [line.strip().split('$') for line in infile] - # pad to same number of fields per row - maxfields = max(len(row) for row in fieldsbyrow) - fieldsbyrow = [fields + ['']*(maxfields - len(fields)) - for fields in fieldsbyrow] - # rotate - fieldsbycolumn = zip(*fieldsbyrow) - # calculate max fieldwidth per column - colwidths = [max(len(field) for field in column) - for column in fieldsbycolumn] - # pad fields in columns to colwidth with spaces - fieldsbycolumn = [ [justifier(field, width) for field in column] - for width, column in zip(colwidths, fieldsbycolumn) ] - # rotate again - fieldsbyrow = zip(*fieldsbycolumn) - - return "\n".join( " ".join(row) for row in fieldsbyrow) - - -for align in 'Left Right Center'.split(): - infile = StringIO(textinfile) - print "\n# %s Column-aligned output:" % align - print aligner(infile, align[0]) +for justify in "<_Left ^_Center >_Right".split(): + j, jtext = justify.split('_') + print(f"{jtext} column-aligned output:\n") + for line in parts: + print(' '.join(f"{wrd:{j}{wdth}}" for wdth, wrd in zip(widths, line))) + print("- " * 52) diff --git a/Task/Align-columns/Python/align-columns-2.py b/Task/Align-columns/Python/align-columns-2.py index ac4daedcdb..b6ae3b9a42 100644 --- a/Task/Align-columns/Python/align-columns-2.py +++ b/Task/Align-columns/Python/align-columns-2.py @@ -1,18 +1,45 @@ -''' -cat <<'EOF' > align_columns.dat -Given$a$text$file$of$many$lines,$where$fields$within$a$line$ +from StringIO import StringIO + +textinfile = '''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. -EOF -''' +justified,$right$justified,$or$center$justified$within$its$column.''' -for align in '<^>': - rows = [ line.strip().split('$') for line in open('align_columns.dat') ] - fmts = [ '{:%s%d}' % (align, max( len(row[i]) if i < len(row) else 0 for row in rows )) - for i in range(max(map(len, rows))) ] - for row in rows: - print(' '.join(fmts).format(*(row + [''] * len(fmts)))) - print('') +j2justifier = dict(L=str.ljust, R=str.rjust, C=str.center) + +def aligner(infile, justification = 'L'): + ''' \ + Justify columns of textual tabular input where the row separator is the newline + and the field separator is a 'dollar' character. + justification can be L, R, or C; (Left, Right, or Centered). + + Return the justified output as a string + ''' + assert justification in j2justifier, "justification can be L, R, or C; (Left, Right, or Centered)." + justifier = j2justifier[justification] + + fieldsbyrow= [line.strip().split('$') for line in infile] + # pad to same number of fields per row + maxfields = max(len(row) for row in fieldsbyrow) + fieldsbyrow = [fields + ['']*(maxfields - len(fields)) + for fields in fieldsbyrow] + # rotate + fieldsbycolumn = zip(*fieldsbyrow) + # calculate max fieldwidth per column + colwidths = [max(len(field) for field in column) + for column in fieldsbycolumn] + # pad fields in columns to colwidth with spaces + fieldsbycolumn = [ [justifier(field, width) for field in column] + for width, column in zip(colwidths, fieldsbycolumn) ] + # rotate again + fieldsbyrow = zip(*fieldsbycolumn) + + return "\n".join( " ".join(row) for row in fieldsbyrow) + + +for align in 'Left Right Center'.split(): + infile = StringIO(textinfile) + print "\n# %s Column-aligned output:" % align + print aligner(infile, align[0]) diff --git a/Task/Align-columns/Python/align-columns-3.py b/Task/Align-columns/Python/align-columns-3.py index 6f409cc691..ac4daedcdb 100644 --- a/Task/Align-columns/Python/align-columns-3.py +++ b/Task/Align-columns/Python/align-columns-3.py @@ -1,21 +1,18 @@ -txt = """Given$a$txt$file$of$many$lines,$where$fields$within$a$line$ +''' +cat <<'EOF' > align_columns.dat +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.""" +justified,$right$justified,$or$center$justified$within$its$column. +EOF +''' -parts = [line.rstrip("$").split("$") for line in txt.splitlines()] - -max_widths = {} -for line in parts: - for i, word in enumerate(line): - max_widths[i] = max(max_widths.get(i, 0), len(word)) - -for i, justify in enumerate([str.ljust, str.center, str.rjust]): - print ["Left", "Center", "Right"][i], " column-aligned output:\n" - for line in parts: - for j, word in enumerate(line): - print justify(word, max_widths[j]), - print - print "- " * 52 +for align in '<^>': + rows = [ line.strip().split('$') for line in open('align_columns.dat') ] + fmts = [ '{:%s%d}' % (align, max( len(row[i]) if i < len(row) else 0 for row in rows )) + for i in range(max(map(len, rows))) ] + for row in rows: + print(' '.join(fmts).format(*(row + [''] * len(fmts)))) + print('') diff --git a/Task/Align-columns/Python/align-columns-4.py b/Task/Align-columns/Python/align-columns-4.py index 64061d0e0c..89d9a5796a 100644 --- a/Task/Align-columns/Python/align-columns-4.py +++ b/Task/Align-columns/Python/align-columns-4.py @@ -1,75 +1,21 @@ -'''Variously aligned columns - from delimited text. -''' - -from functools import reduce -from itertools import repeat - - -# TEST ---------------------------------------------------- -# main :: IO () -def main(): - '''Test of three alignments.''' - - txt = '''Given$a$text$file$of$many$lines,$where$fields$within$a$line$ +txt = """Given$a$txt$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.''' +justified,$right$justified,$or$center$justified$within$its$column.""" - rows = [x.split('$') for x in txt.splitlines()] - table = paddedRows(max(map(len, rows)))('')(rows) +parts = [line.rstrip("$").split("$") for line in txt.splitlines()] - print('\n\n'.join(map( - alignedTable(table)(' '), - [-1, 0, 1] # Left, Center, Right - ))) +max_widths = {} +for line in parts: + for i, word in enumerate(line): + max_widths[i] = max(max_widths.get(i, 0), len(word)) - -# alignedTable :: [[String]] -> Alignment -> String -> String -def alignedTable(rows): - '''Tabulation of rows of cells, with cell alignment - specified by: - eAlign -1 = left - eAlign 0 = center - eAlign 1 = right - and separator between columns - supplied by the `sep` argument. - ''' - def go(sep, eAlign): - lcr = ['ljust', 'center', 'rjust'][1 + eAlign] - - # nextAlignedCol :: [[String]] -> [String] -> [[String]] - def nextAlignedCol(cols, col): - w = max(len(cell) for cell in col) - return cols + [ - [getattr(s, lcr)(w, ' ') for s in col] - ] - - return '\n'.join([ - sep.join(cells) for cells in - zip(*reduce(nextAlignedCol, zip(*rows), [])) - ]) - return lambda sep: lambda eAlign: go(sep, eAlign) - - -# GENERIC ------------------------------------------------- - -# paddedRows :: Int -> a -> [[a]] -> [[a]] -def paddedRows(n): - '''A list of rows of even length, - in which each may be padded (but - not truncated) to length n with - appended copies of value v.''' - def go(v, xs): - def pad(x): - d = n - len(x) - return (x + list(repeat(v, d))) if 0 < d else x - return [pad(row) for row in xs] - return lambda v: lambda xs: go(v, xs) if xs else [] - - -# MAIN --- -if __name__ == '__main__': - main() +for i, justify in enumerate([str.ljust, str.center, str.rjust]): + print(["Left", "Center", "Right"][i], " column-aligned output:\n") + for line in parts: + for j, word in enumerate(line): + print(justify(word, max_widths[j]), end=' ') + print() + print("- " * 52) diff --git a/Task/Align-columns/Python/align-columns-5.py b/Task/Align-columns/Python/align-columns-5.py new file mode 100644 index 0000000000..64061d0e0c --- /dev/null +++ b/Task/Align-columns/Python/align-columns-5.py @@ -0,0 +1,75 @@ +'''Variously aligned columns + from delimited text. +''' + +from functools import reduce +from itertools import repeat + + +# TEST ---------------------------------------------------- +# main :: IO () +def main(): + '''Test of three alignments.''' + + txt = '''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.''' + + rows = [x.split('$') for x in txt.splitlines()] + table = paddedRows(max(map(len, rows)))('')(rows) + + print('\n\n'.join(map( + alignedTable(table)(' '), + [-1, 0, 1] # Left, Center, Right + ))) + + +# alignedTable :: [[String]] -> Alignment -> String -> String +def alignedTable(rows): + '''Tabulation of rows of cells, with cell alignment + specified by: + eAlign -1 = left + eAlign 0 = center + eAlign 1 = right + and separator between columns + supplied by the `sep` argument. + ''' + def go(sep, eAlign): + lcr = ['ljust', 'center', 'rjust'][1 + eAlign] + + # nextAlignedCol :: [[String]] -> [String] -> [[String]] + def nextAlignedCol(cols, col): + w = max(len(cell) for cell in col) + return cols + [ + [getattr(s, lcr)(w, ' ') for s in col] + ] + + return '\n'.join([ + sep.join(cells) for cells in + zip(*reduce(nextAlignedCol, zip(*rows), [])) + ]) + return lambda sep: lambda eAlign: go(sep, eAlign) + + +# GENERIC ------------------------------------------------- + +# paddedRows :: Int -> a -> [[a]] -> [[a]] +def paddedRows(n): + '''A list of rows of even length, + in which each may be padded (but + not truncated) to length n with + appended copies of value v.''' + def go(v, xs): + def pad(x): + d = n - len(x) + return (x + list(repeat(v, d))) if 0 < d else x + return [pad(row) for row in xs] + return lambda v: lambda xs: go(v, xs) if xs else [] + + +# MAIN --- +if __name__ == '__main__': + main() diff --git a/Task/Aliquot-sequence-classifications/Julia/aliquot-sequence-classifications-3.julia b/Task/Aliquot-sequence-classifications/Julia/aliquot-sequence-classifications-3.julia index 2969255cbd..60838d0461 100644 --- a/Task/Aliquot-sequence-classifications/Julia/aliquot-sequence-classifications-3.julia +++ b/Task/Aliquot-sequence-classifications/Julia/aliquot-sequence-classifications-3.julia @@ -1,3 +1,5 @@ +using Printf + println("Classification Tests:") tests = [1:12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488] for i in tests diff --git a/Task/Almost-prime/Delphi/almost-prime.delphi b/Task/Almost-prime/Delphi/almost-prime.delphi new file mode 100644 index 0000000000..d573d4fb37 --- /dev/null +++ b/Task/Almost-prime/Delphi/almost-prime.delphi @@ -0,0 +1,40 @@ +program AlmostPrime; + +{$APPTYPE CONSOLE} + +function IsKPrime(const n, k: Integer): Boolean; +var + p, f, v: Integer; +begin + f := 0; + p := 2; + v := n; + while (f < k) and (p*p <= n) do begin + while (v mod p) = 0 do begin + v := v div p; + Inc(f); + end; + Inc(p); + end; + if v > 1 then Inc(f); + Result := f = k; +end; + +var + i, c, k: Integer; + +begin + for k := 1 to 5 do begin + Write('k = ', k, ':'); + c := 0; + i := 2; + while c < 10 do begin + if IsKPrime(i, k) then begin + Write(' ', i); + Inc(c); + end; + Inc(i); + end; + WriteLn; + end; +end. diff --git a/Task/Almost-prime/Julia/almost-prime.julia b/Task/Almost-prime/Julia/almost-prime.julia new file mode 100644 index 0000000000..29287e2ccc --- /dev/null +++ b/Task/Almost-prime/Julia/almost-prime.julia @@ -0,0 +1,17 @@ +using Primes + +isalmostprime(n::Integer, k::Integer) = sum(values(factor(n))) == k + +function almostprimes(N::Integer, k::Integer) # return first N almost-k primes + P = Vector{typeof(k)}(undef,N) + i = 0; n = 2 + while i < N + if isalmostprime(n, k) P[i += 1] = n end + n += 1 + end + return P +end + +for k in 1:5 + println("$k-Almost-primes: ", join(almostprimes(10, k), ", "), "...") +end diff --git a/Task/Almost-prime/Swift/almost-prime.swift b/Task/Almost-prime/Swift/almost-prime.swift new file mode 100644 index 0000000000..985d7fb70c --- /dev/null +++ b/Task/Almost-prime/Swift/almost-prime.swift @@ -0,0 +1,35 @@ +struct KPrimeGen: Sequence, IteratorProtocol { + let k: Int + private(set) var n: Int + + private func isKPrime() -> Bool { + var primes = 0 + var f = 2 + var rem = n + + while primes < k && rem > 1 { + while rem % f == 0 && rem > 1 { + rem /= f + primes += 1 + } + + f += 1 + } + + return rem == 1 && primes == k + } + + mutating func next() -> Int? { + n += 1 + + while !isKPrime() { + n += 1 + } + + return n + } +} + +for k in 1..<6 { + print("\(k): \(Array(KPrimeGen(k: k, n: 1).lazy.prefix(10)))") +} diff --git a/Task/Amb/Elena/amb.elena b/Task/Amb/Elena/amb.elena index 880f9ca7d0..4e4bfb2b1c 100644 --- a/Task/Amb/Elena/amb.elena +++ b/Task/Amb/Elena/amb.elena @@ -68,7 +68,8 @@ public program() try { ambOperator - .for(new {"the","that","a"},new {"frog", "elephant", "thing"},new {"walked", "treaded", "grows"}, new {"slowly", "quickly"}) + .for(new::("the","that","a"),new::("frog", "elephant", "thing"),new::("walked", "treaded", "grows"), + new::("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) } } diff --git a/Task/Amb/Haskell/amb-1.hs b/Task/Amb/Haskell/amb-1.hs index ee620710f3..962cbc6ed7 100644 --- a/Task/Amb/Haskell/amb-1.hs +++ b/Task/Amb/Haskell/amb-1.hs @@ -9,7 +9,7 @@ example = do w2 <- amb ["frog", "elephant", "thing"] w3 <- amb ["walked", "treaded", "grows"] w4 <- amb ["slowly", "quickly"] - unless (joins w1 w2) (amb []) - unless (joins w2 w3) (amb []) - unless (joins w3 w4) (amb []) - return (unwords [w1, w2, w3, w4]) + guard (w1 `joins` w2) + guard (w2 `joins` w3) + guard (w3 `joins` w4) + pure $ unwords [w1, w2, w3, w4] diff --git a/Task/Amicable-pairs/Elena/amicable-pairs-1.elena b/Task/Amicable-pairs/Elena/amicable-pairs-1.elena index 3f51512276..2d7ae848dd 100644 --- a/Task/Amicable-pairs/Elena/amicable-pairs-1.elena +++ b/Task/Amicable-pairs/Elena/amicable-pairs-1.elena @@ -24,7 +24,7 @@ extension op var sum := divsums[i]; ^ (i < sum) && (sum < divsums.Length) && (divsums[sum] == i) } - .selectBy:(i => new:{ Item1 = i; Item2 = divsums[i]; }) + .selectBy:(i => new::{ Item1 = i; Item2 = divsums[i]; }) } } diff --git a/Task/Amicable-pairs/Haskell/amicable-pairs-2.hs b/Task/Amicable-pairs/Haskell/amicable-pairs-2.hs index d3f08d232e..1ce319c29c 100644 --- a/Task/Amicable-pairs/Haskell/amicable-pairs-2.hs +++ b/Task/Amicable-pairs/Haskell/amicable-pairs-2.hs @@ -1,31 +1,21 @@ +import Data.Bool (bool) + amicablePairsUpTo :: Int -> [(Int, Int)] amicablePairsUpTo n = - foldl - (\a x -> - let y = sigma x - in if (x < y) && (sigma y == x) - then a ++ [(x, y)] - else a) - [] - [1 .. n] + let sigma = sum . properDivisors + in [1 .. n] >>= + (\x -> + let y = sigma x + in bool [] [(x, y)] (x < y && x == sigma y)) -sigma :: Int -> Int -sigma = sum . propDivs - where - propDivs :: Int -> [Int] - propDivs n - | n < 2 = [] - | otherwise = - lows ++ - drop - (if isPerfect - then 1 - else 0) - (reverse (quot n <$> tail lows)) - where - iRoot = floor (sqrt $ fromIntegral n) - isPerfect = iRoot * iRoot == n - lows = filter ((== 0) . rem n) [1 .. iRoot] +properDivisors + :: Integral a + => a -> [a] +properDivisors n = + let root = (floor . sqrt) (fromIntegral n :: Double) + lows = filter ((0 ==) . rem n) [1 .. root] + in init $ + lows ++ drop (bool 0 1 (root * root == n)) (reverse (quot n <$> lows)) main :: IO () main = mapM_ print $ amicablePairsUpTo 20000 diff --git a/Task/Amicable-pairs/JavaScript/amicable-pairs-3.js b/Task/Amicable-pairs/JavaScript/amicable-pairs-3.js index 928e889293..6814de393e 100644 --- a/Task/Amicable-pairs/JavaScript/amicable-pairs-3.js +++ b/Task/Amicable-pairs/JavaScript/amicable-pairs-3.js @@ -1,46 +1,61 @@ -(max => { +(() => { + 'use strict'; // amicablePairsUpTo :: Int -> [(Int, Int)] - let amicablePairsUpTo = max => - range(1, max) - .map(x => properDivisors(x) - .reduce((a, b) => a + b, 0)) - .reduce((a, m, i, lst) => { - let n = i + 1; + const amicablePairsUpTo = n => { + const sigma = compose(sum, properDivisors); + return enumFromTo(1)(n).flatMap(x => { + const y = sigma(x); + return x < y && x === sigma(y) ? ([ + [x, y] + ]) : []; + }); + }; - return (m > n) && lst[m - 1] === n ? - a.concat([[n, m]]) : a; - }, []), + // properDivisors :: Int -> [Int] + const properDivisors = n => { + const + rRoot = Math.sqrt(n), + intRoot = Math.floor(rRoot), + lows = enumFromTo(1)(intRoot) + .filter(x => 0 === (n % x)); + return lows.concat(lows.map(x => n / x) + .reverse() + .slice((rRoot === intRoot) | 0, -1)); + }; - // properDivisors :: Int -> [Int] - properDivisors = n => { - if (n < 2) return []; - else { - let rRoot = Math.sqrt(n), - intRoot = Math.floor(rRoot), - blnPerfectSquare = rRoot === intRoot, + // TEST ----------------------------------------------- - lows = range(1, intRoot) - .filter(x => (n % x) === 0); - - return lows.concat(lows.slice(1) - .map(x => n / x) - .reverse() - .slice(blnPerfectSquare | 0)); - } - }, - - // Int -> Int -> Maybe Int -> [Int] - range = (m, n, step) => { - let d = (step || 1) * (n >= m ? 1 : -1); - - return Array.from({ - length: Math.floor((n - m) / d) + 1 - }, (_, i) => m + (i * d)); - } + // main :: IO () + const main = () => + console.log(unlines( + amicablePairsUpTo(20000).map(JSON.stringify) + )); - return amicablePairsUpTo(max); + // GENERIC FUNCTIONS ---------------------------------- -})(20000); + // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c + const compose = (...fs) => + x => fs.reduceRight((a, f) => f(a), x); + + + // enumFromTo :: Int -> Int -> [Int] + const enumFromTo = m => n => + Array.from({ + length: 1 + n - m + }, (_, i) => m + i); + + + // sum :: [Num] -> Num + const sum = xs => xs.reduce((a, x) => a + x, 0); + + + // unlines :: [String] -> String + const unlines = xs => xs.join('\n'); + + + // MAIN --- + return main(); +})(); diff --git a/Task/Amicable-pairs/MATLAB/amicable-pairs.m b/Task/Amicable-pairs/MATLAB/amicable-pairs.m new file mode 100644 index 0000000000..ae3e5618e5 --- /dev/null +++ b/Task/Amicable-pairs/MATLAB/amicable-pairs.m @@ -0,0 +1,35 @@ +function amicable + tic + N=2:1:20000; aN=[]; + N(isprime(N))=[]; %erase prime numbers + I=1; + a=N(1); b=sum(pd(a)); + while length(N)>1 + if a==b %erase perfect numbers; + N(N==a)=[]; a=N(1); b=sum(pd(a)); + elseif b [(Int, Int)] +def amicablePairsUpTo(n): + '''List of all amicable pairs + of integers below n. + ''' + sigma = compose(sum)(properDivisors) + + def amicable(x): + y = sigma(x) + return [(x, y)] if (x < y and x == sigma(y)) else [] + + return concatMap(amicable)( + enumFromTo(1)(n) + ) + + +# TEST ---------------------------------------------------- +# main :: IO () +def main(): + '''Amicable pairs of integers up to 20000''' + + for x in amicablePairsUpTo(20000): + print(x) + + +# GENERIC ------------------------------------------------- + +# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c +def compose(g): + '''Right to left function composition.''' + return lambda f: lambda x: g(f(x)) + + +# concatMap :: (a -> [b]) -> [a] -> [b] +def concatMap(f): + '''A concatenated list or string over which a function f + has been mapped. + The list monad can be derived by using an (a -> [b]) + function which wraps its output in a list (using an + empty list to represent computational failure). + ''' + return lambda xs: (''.join if isinstance(xs, str) else list)( + chain.from_iterable(map(f, xs)) + ) + + +# enumFromTo :: Int -> Int -> [Int] +def enumFromTo(m): + '''Enumeration of integer values [m..n]''' + def go(n): + return list(range(m, 1 + n)) + return lambda n: go(n) + + +# properDivisors :: Int -> [Int] +def properDivisors(n): + '''Positive divisors of n, excluding n itself''' + root_ = sqrt(n) + intRoot = int(root_) + blnSqr = root_ == intRoot + lows = [x for x in range(1, 1 + intRoot) if 0 == n % x] + return lows + [ + n // x for x in reversed( + lows[1:-1] if blnSqr else lows[1:] + ) + ] + + +# MAIN --- +if __name__ == '__main__': + main() diff --git a/Task/Amicable-pairs/Ruby/amicable-pairs.rb b/Task/Amicable-pairs/Ruby/amicable-pairs.rb index 0ea7867a77..4f4f75739e 100644 --- a/Task/Amicable-pairs/Ruby/amicable-pairs.rb +++ b/Task/Amicable-pairs/Ruby/amicable-pairs.rb @@ -1,5 +1,5 @@ h = {} -(1..20_000).each{|n| h[n] = n.proper_divisors.inject(:+)} +(1..20_000).each{|n| h[n] = n.proper_divisors.sum } h.select{|k,v| h[v] == k && k < v}.each do |key,val| # k TECTONICS - *> wget http://www.puzzlers.org/pub/wordlists/unixdict.txt + *> wget http://wiki.puzzlers.org/pub/wordlists/unixdict.txt *> or visit https://sourceforge.net/projects/souptonuts/files *> or snag ftp://ftp.openwall.com/pub/wordlists/all.gz *> for a 5 million all language word file (a few phrases) diff --git a/Task/Anagrams/Clojure/anagrams-2.clj b/Task/Anagrams/Clojure/anagrams-2.clj index 7ca2a423c4..acf5002180 100644 --- a/Task/Anagrams/Clojure/anagrams-2.clj +++ b/Task/Anagrams/Clojure/anagrams-2.clj @@ -1,4 +1,4 @@ -(->> (slurp "http://www.puzzlers.org/pub/wordlists/unixdict.txt") +(->> (slurp "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt") clojure.string/split-lines (group-by sort) vals diff --git a/Task/Anagrams/CoffeeScript/anagrams-1.coffee b/Task/Anagrams/CoffeeScript/anagrams-1.coffee index 5e93433fae..4da2fce96b 100644 --- a/Task/Anagrams/CoffeeScript/anagrams-1.coffee +++ b/Task/Anagrams/CoffeeScript/anagrams-1.coffee @@ -17,7 +17,7 @@ show_large_anagram_sets = (word_lst) -> get_word_list = (process) -> options = - host: "www.puzzlers.org" + host: "wiki.puzzlers.org" path: "/pub/wordlists/unixdict.txt" req = http.request options, (res) -> diff --git a/Task/Anagrams/Common-Lisp/anagrams-1.lisp b/Task/Anagrams/Common-Lisp/anagrams-1.lisp index 7ed43ea4d5..fbf820fc6f 100644 --- a/Task/Anagrams/Common-Lisp/anagrams-1.lisp +++ b/Task/Anagrams/Common-Lisp/anagrams-1.lisp @@ -1,4 +1,4 @@ -(defun anagrams (&optional (url "http://www.puzzlers.org/pub/wordlists/unixdict.txt")) +(defun anagrams (&optional (url "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")) (let ((words (drakma:http-request url :want-stream t)) (wordsets (make-hash-table :test 'equalp))) ;; populate the wordsets and close stream diff --git a/Task/Anagrams/E/anagrams.e b/Task/Anagrams/E/anagrams.e index f041514dae..0a23841f8e 100644 --- a/Task/Anagrams/E/anagrams.e +++ b/Task/Anagrams/E/anagrams.e @@ -1,5 +1,5 @@ println("Downloading...") -when (def wordText := <- getText()) -> { +when (def wordText := <- getText()) -> { def words := wordText.split("\n") def storage := [].asMap().diverge() diff --git a/Task/Anagrams/Frink/anagrams.frink b/Task/Anagrams/Frink/anagrams.frink index 8ba2f436ae..ebb5fd075a 100644 --- a/Task/Anagrams/Frink/anagrams.frink +++ b/Task/Anagrams/Frink/anagrams.frink @@ -1,5 +1,5 @@ d = new dict -for w = lines["http://www.puzzlers.org/pub/wordlists/unixdict.txt"] +for w = lines["http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"] { sorted = sort[charList[w]] curr = d@sorted diff --git a/Task/Anagrams/Go/anagrams-1.go b/Task/Anagrams/Go/anagrams-1.go index 938ca53e8c..e72f91f4af 100644 --- a/Task/Anagrams/Go/anagrams-1.go +++ b/Task/Anagrams/Go/anagrams-1.go @@ -9,7 +9,7 @@ import ( ) func main() { - r, err := http.Get("http://www.puzzlers.org/pub/wordlists/unixdict.txt") + r, err := http.Get("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt") if err != nil { fmt.Println(err) return diff --git a/Task/Anagrams/Go/anagrams-2.go b/Task/Anagrams/Go/anagrams-2.go index 55618fcaee..054de4d674 100644 --- a/Task/Anagrams/Go/anagrams-2.go +++ b/Task/Anagrams/Go/anagrams-2.go @@ -1,4 +1,4 @@ -def words = new URL('http://www.puzzlers.org/pub/wordlists/unixdict.txt').text.readLines() +def words = new URL('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt').text.readLines() def groups = words.groupBy{ it.toList().sort() } def bigGroupSize = groups.collect{ it.value.size() }.max() def isBigAnagram = { it.value.size() == bigGroupSize } diff --git a/Task/Anagrams/Java/anagrams-1.java b/Task/Anagrams/Java/anagrams-1.java index 603b714186..5ab4d13f4b 100644 --- a/Task/Anagrams/Java/anagrams-1.java +++ b/Task/Anagrams/Java/anagrams-1.java @@ -4,7 +4,7 @@ import java.util.*; public class WordsOfEqChars { public static void main(String[] args) throws IOException { - URL url = new URL("http://www.puzzlers.org/pub/wordlists/unixdict.txt"); + URL url = new URL("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"); InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader reader = new BufferedReader(isr); diff --git a/Task/Anagrams/Java/anagrams-2.java b/Task/Anagrams/Java/anagrams-2.java index 0dd4bcf144..9277fdf9ed 100644 --- a/Task/Anagrams/Java/anagrams-2.java +++ b/Task/Anagrams/Java/anagrams-2.java @@ -25,7 +25,7 @@ public interface Anagram { () -> new BufferedReader( new InputStreamReader( new URL( - "http://www.puzzlers.org/pub/wordlists/unixdict.txt" + "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt" ).openStream() ) ), diff --git a/Task/Anagrams/Julia/anagrams.julia b/Task/Anagrams/Julia/anagrams.julia index 9585079109..ec285d4bec 100644 --- a/Task/Anagrams/Julia/anagrams.julia +++ b/Task/Anagrams/Julia/anagrams.julia @@ -1,4 +1,4 @@ -url = "http://www.puzzlers.org/pub/wordlists/unixdict.txt" +url = "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt" wordlist = open(readlines, download(url)) wsort(word::AbstractString) = join(sort(collect(word))) diff --git a/Task/Anagrams/Kotlin/anagrams.kotlin b/Task/Anagrams/Kotlin/anagrams.kotlin index ef6c63a1c4..c636e815c4 100644 --- a/Task/Anagrams/Kotlin/anagrams.kotlin +++ b/Task/Anagrams/Kotlin/anagrams.kotlin @@ -1,9 +1,10 @@ import java.io.BufferedReader import java.io.InputStreamReader import java.net.URL +import kotlin.math.max -fun main(args: Array) { - val url = URL("http://www.puzzlers.org/pub/wordlists/unixdict.txt") +fun main() { + val url = URL("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt") val isr = InputStreamReader(url.openStream()) val reader = BufferedReader(isr) val anagrams = mutableMapOf>() @@ -13,9 +14,9 @@ fun main(args: Array) { val chars = word.toCharArray() chars.sort() val key = chars.joinToString("") - if (!anagrams.containsKey(key)) anagrams.put(key, mutableListOf()) - anagrams[key]!!.add(word) - count = Math.max(count, anagrams[key]!!.size) + if (!anagrams.containsKey(key)) anagrams[key] = mutableListOf() + anagrams[key]?.add(word) + count = max(count, anagrams[key]?.size ?: 0) word = reader.readLine() } reader.close() diff --git a/Task/Anagrams/Lasso/anagrams.lasso b/Task/Anagrams/Lasso/anagrams.lasso index ff7a56e17b..3ab06b88c4 100644 --- a/Task/Anagrams/Lasso/anagrams.lasso +++ b/Task/Anagrams/Lasso/anagrams.lasso @@ -1,6 +1,6 @@ local( anagrams = map, - words = include_url('http://www.puzzlers.org/pub/wordlists/unixdict.txt')->split('\n'), + words = include_url('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt')->split('\n'), key, max = 0, findings = array diff --git a/Task/Anagrams/LiveCode/anagrams.livecode b/Task/Anagrams/LiveCode/anagrams.livecode index ebe452f7a7..48ff3352ca 100644 --- a/Task/Anagrams/LiveCode/anagrams.livecode +++ b/Task/Anagrams/LiveCode/anagrams.livecode @@ -1,5 +1,5 @@ on mouseUp - put mostCommonAnagrams(url "http://www.puzzlers.org/pub/wordlists/unixdict.txt") + put mostCommonAnagrams(url "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt") end mouseUp function mostCommonAnagrams X diff --git a/Task/Anagrams/Maple/anagrams-1.maple b/Task/Anagrams/Maple/anagrams-1.maple index 3b4d54e6d8..c247517fc4 100644 --- a/Task/Anagrams/Maple/anagrams-1.maple +++ b/Task/Anagrams/Maple/anagrams-1.maple @@ -1,4 +1,4 @@ -words := HTTP:-Get( "http://www.puzzlers.org/pub/wordlists/unixdict.txt" )[2]: # ignore errors +words := HTTP:-Get( "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt" )[2]: # ignore errors use StringTools, ListTools in T := Classify( Sort, map( Trim, Split( words ) ) ) end use: diff --git a/Task/Anagrams/Mathematica/anagrams-1.math b/Task/Anagrams/Mathematica/anagrams-1.math index 254a3f2cd2..c386247222 100644 --- a/Task/Anagrams/Mathematica/anagrams-1.math +++ b/Task/Anagrams/Mathematica/anagrams-1.math @@ -1,4 +1,4 @@ -list=Import["http://www.puzzlers.org/pub/wordlists/unixdict.txt","Lines"]; +list=Import["http://wiki.puzzlers.org/pub/wordlists/unixdict.txt","Lines"]; text={#,StringJoin@@Sort[Characters[#]]}&/@list; text=SortBy[text,#[[2]]&]; splits=Split[text,#1[[2]]==#2[[2]]&][[All,All,1]]; diff --git a/Task/Anagrams/Mathematica/anagrams-5.math b/Task/Anagrams/Mathematica/anagrams-5.math index 9f23ae41ca..6431ce1791 100644 --- a/Task/Anagrams/Mathematica/anagrams-5.math +++ b/Task/Anagrams/Mathematica/anagrams-5.math @@ -1,2 +1,2 @@ -list=Import["http://www.puzzlers.org/pub/wordlists/unixdict.txt","Lines"]; +list=Import["http://wiki.puzzlers.org/pub/wordlists/unixdict.txt","Lines"]; MaximalBy[GatherBy[list, Sort@*Characters], Length] diff --git a/Task/Anagrams/NetRexx/anagrams-1.netrexx b/Task/Anagrams/NetRexx/anagrams-1.netrexx index b920534d1e..28e2d5e2eb 100644 --- a/Task/Anagrams/NetRexx/anagrams-1.netrexx +++ b/Task/Anagrams/NetRexx/anagrams-1.netrexx @@ -8,7 +8,7 @@ class RAnagramsV01 public parse arg localFile . isr = Reader if localFile = '' then do - durl = URL("http://www.puzzlers.org/pub/wordlists/unixdict.txt") + durl = URL("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt") dictFrom = durl.toString() isr = InputStreamReader(durl.openStream()) end diff --git a/Task/Anagrams/NetRexx/anagrams-2.netrexx b/Task/Anagrams/NetRexx/anagrams-2.netrexx index 0df963757e..ba3227d87b 100644 --- a/Task/Anagrams/NetRexx/anagrams-2.netrexx +++ b/Task/Anagrams/NetRexx/anagrams-2.netrexx @@ -9,7 +9,7 @@ method findMostAnagrams(arg) public static signals MalformedURLException, IOExce parse arg localFile . isr = Reader if localFile = '' then do - durl = URL("http://www.puzzlers.org/pub/wordlists/unixdict.txt") + durl = URL("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt") dictFrom = durl.toString() isr = InputStreamReader(durl.openStream()) end diff --git a/Task/Anagrams/Objeck/anagrams.objeck b/Task/Anagrams/Objeck/anagrams.objeck index e6c8c84a18..66a2dc3f09 100644 --- a/Task/Anagrams/Objeck/anagrams.objeck +++ b/Task/Anagrams/Objeck/anagrams.objeck @@ -3,7 +3,7 @@ use Collection; class Anagrams { function : Main(args : String[]) ~ Nil { - lines := HttpClient->New()->Get("http://www.puzzlers.org/pub/wordlists/unixdict.txt"); + lines := HttpClient->New()->Get("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"); anagrams := StringMap->New(); count := 0; if(lines->Size() = 1) { diff --git a/Task/Anagrams/PHP/anagrams.php b/Task/Anagrams/PHP/anagrams.php index a87048da7b..9ab64c41e9 100644 --- a/Task/Anagrams/PHP/anagrams.php +++ b/Task/Anagrams/PHP/anagrams.php @@ -1,5 +1,5 @@ >> import urllib.request >>> from collections import defaultdict ->>> words = urllib.request.urlopen('http://www.puzzlers.org/pub/wordlists/unixdict.txt').read().split() +>>> words = urllib.request.urlopen('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt').read().split() >>> anagram = defaultdict(list) # map sorted chars to anagrams >>> for word in words: anagram[tuple(sorted(word))].append( word ) diff --git a/Task/Anagrams/Python/anagrams-2.py b/Task/Anagrams/Python/anagrams-2.py index 0a7705f4f0..afffe549b0 100644 --- a/Task/Anagrams/Python/anagrams-2.py +++ b/Task/Anagrams/Python/anagrams-2.py @@ -1,6 +1,6 @@ >>> import urllib >>> from collections import defaultdict ->>> words = urllib.urlopen('http://www.puzzlers.org/pub/wordlists/unixdict.txt').read().split() +>>> words = urllib.urlopen('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt').read().split() >>> len(words) 25104 >>> anagram = defaultdict(list) # map sorted chars to anagrams diff --git a/Task/Anagrams/Python/anagrams-3.py b/Task/Anagrams/Python/anagrams-3.py index fc284a8617..4ba10d32b8 100644 --- a/Task/Anagrams/Python/anagrams-3.py +++ b/Task/Anagrams/Python/anagrams-3.py @@ -1,5 +1,5 @@ >>> import urllib, itertools ->>> words = urllib.urlopen('http://www.puzzlers.org/pub/wordlists/unixdict.txt').read().split() +>>> words = urllib.urlopen('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt').read().split() >>> len(words) 25104 >>> anagrams = [list(g) for k,g in itertools.groupby(sorted(words, key=sorted), key=sorted)] diff --git a/Task/Anagrams/R/anagrams.r b/Task/Anagrams/R/anagrams.r index 428f07e981..3a0f21133e 100644 --- a/Task/Anagrams/R/anagrams.r +++ b/Task/Anagrams/R/anagrams.r @@ -1,4 +1,4 @@ -words <- readLines("http://www.puzzlers.org/pub/wordlists/unixdict.txt") +words <- readLines("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt") word_group <- sapply( strsplit(words, split=""), # this will split all words to single letters... function(x) paste(sort(x), collapse="") # ...which we sort and paste again diff --git a/Task/Anagrams/Racket/anagrams.rkt b/Task/Anagrams/Racket/anagrams.rkt index b6a10447e4..a9ac4a6a82 100644 --- a/Task/Anagrams/Racket/anagrams.rkt +++ b/Task/Anagrams/Racket/anagrams.rkt @@ -18,4 +18,4 @@ (define max-keys (filter (λ (k) (= (length (hash-ref h k)) max-ws)) (hash-keys h))) (map (λ (k) (hash-ref h k)) max-keys)) -(get-maxes (hash-words (get-lines "http://www.puzzlers.org/pub/wordlists/unixdict.txt"))) +(get-maxes (hash-words (get-lines "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt"))) diff --git a/Task/Anagrams/Rascal/anagrams-1.rascal b/Task/Anagrams/Rascal/anagrams-1.rascal index f35ca15b24..23124521c2 100644 --- a/Task/Anagrams/Rascal/anagrams-1.rascal +++ b/Task/Anagrams/Rascal/anagrams-1.rascal @@ -4,7 +4,7 @@ list[str] OrderedRep(str word){ return sort([word[i] | i <- [0..size(word)-1]]); } public list[set[str]] anagram(){ - allwords = readFileLines(|http://www.puzzlers.org/pub/wordlists/unixdict.txt|); + allwords = readFileLines(|http://wiki.puzzlers.org/pub/wordlists/unixdict.txt|); AnagramMap = invert((word : OrderedRep(word) | word <- allwords)); longest = max([size(group) | group <- range(AnagramMap)]); return [AnagramMap[rep]| rep <- AnagramMap, size(AnagramMap[rep]) == longest]; diff --git a/Task/Anagrams/Red/anagrams.red b/Task/Anagrams/Red/anagrams.red index a45eb79b65..4742495d0a 100644 --- a/Task/Anagrams/Red/anagrams.red +++ b/Task/Anagrams/Red/anagrams.red @@ -3,7 +3,7 @@ Red [] m: make map! [] 25000 maxx: 0 -foreach word read/lines http://www.puzzlers.org/pub/wordlists/unixdict.txt [ +foreach word read/lines http://wiki.puzzlers.org/pub/wordlists/unixdict.txt [ sword: sort copy word ;; sorted characters of word either find m sword [ diff --git a/Task/Anagrams/Ruby/anagrams-1.rb b/Task/Anagrams/Ruby/anagrams-1.rb index af3ba231c1..5f6ae49a1b 100644 --- a/Task/Anagrams/Ruby/anagrams-1.rb +++ b/Task/Anagrams/Ruby/anagrams-1.rb @@ -2,7 +2,7 @@ require 'open-uri' anagram = Hash.new {|hash, key| hash[key] = []} # map sorted chars to anagrams -open('http://www.puzzlers.org/pub/wordlists/unixdict.txt') do |f| +open('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt') do |f| words = f.read.split for word in words anagram[word.split('').sort] << word diff --git a/Task/Anagrams/Ruby/anagrams-2.rb b/Task/Anagrams/Ruby/anagrams-2.rb index 9cf7089876..0eb689a660 100644 --- a/Task/Anagrams/Ruby/anagrams-2.rb +++ b/Task/Anagrams/Ruby/anagrams-2.rb @@ -1,4 +1,4 @@ require 'open-uri' -anagrams = open('http://www.puzzlers.org/pub/wordlists/unixdict.txt'){|f| f.read.split.group_by{|w| w.each_char.sort} } +anagrams = open('http://wiki.puzzlers.org/pub/wordlists/unixdict.txt'){|f| f.read.split.group_by{|w| w.each_char.sort} } anagrams.values.group_by(&:size).max.last.each{|group| puts group.join(", ") } diff --git a/Task/Anagrams/Run-BASIC/anagrams.run b/Task/Anagrams/Run-BASIC/anagrams.run index feb89f6a37..d940ce3d49 100644 --- a/Task/Anagrams/Run-BASIC/anagrams.run +++ b/Task/Anagrams/Run-BASIC/anagrams.run @@ -3,7 +3,7 @@ mem$ = "CREATE TABLE anti(gram,ordr); CREATE INDEX ord ON anti(ordr)" #mem execute(mem$) ' read the file -a$ = httpGet$("http://www.puzzlers.org/pub/wordlists/unixdict.txt") +a$ = httpGet$("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt") ' break the file words apart i = 1 diff --git a/Task/Anagrams/Scala/anagrams-1.scala b/Task/Anagrams/Scala/anagrams-1.scala index 580e0b4d89..8bc5787a44 100644 --- a/Task/Anagrams/Scala/anagrams-1.scala +++ b/Task/Anagrams/Scala/anagrams-1.scala @@ -1,4 +1,4 @@ -val src = io.Source fromURL "http://www.puzzlers.org/pub/wordlists/unixdict.txt" +val src = io.Source fromURL "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt" val vls = src.getLines.toList.groupBy(_.sorted).values val max = vls.map(_.size).max vls filter (_.size == max) map (_ mkString " ") mkString "\n" diff --git a/Task/Anagrams/Scala/anagrams-2.scala b/Task/Anagrams/Scala/anagrams-2.scala index 0f6520d1ef..1b56552b1b 100644 --- a/Task/Anagrams/Scala/anagrams-2.scala +++ b/Task/Anagrams/Scala/anagrams-2.scala @@ -1,5 +1,5 @@ Source - .fromURL("http://www.puzzlers.org/pub/wordlists/unixdict.txt").getLines.toList + .fromURL("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt").getLines.toList .groupBy(_.sorted).values .groupBy(_.size).maxBy(_._1)._2 .map(_.mkString("\t")) diff --git a/Task/Anagrams/Seed7/anagrams.seed7 b/Task/Anagrams/Seed7/anagrams.seed7 index b9083d0fb8..38a87c13a0 100644 --- a/Task/Anagrams/Seed7/anagrams.seed7 +++ b/Task/Anagrams/Seed7/anagrams.seed7 @@ -33,7 +33,7 @@ const proc: main is func var integer: length is 0; var integer: maxLength is 0; begin - dictFile := openStrifile(getHttp("www.puzzlers.org/pub/wordlists/unixdict.txt")); + dictFile := openStrifile(getHttp("wiki.puzzlers.org/pub/wordlists/unixdict.txt")); while hasNext(dictFile) do readln(dictFile, word); sortedLetters := sort(word); diff --git a/Task/Anagrams/Smalltalk/anagrams-3.st b/Task/Anagrams/Smalltalk/anagrams-3.st index ed608bdeac..525f2c667a 100644 --- a/Task/Anagrams/Smalltalk/anagrams-3.st +++ b/Task/Anagrams/Smalltalk/anagrams-3.st @@ -1 +1 @@ -'http://www.puzzlers.org/pub/wordlists/unixdict.txt' asURI contents asCollectionOfLines do:[:eachWord | ... +'http://wiki.puzzlers.org/pub/wordlists/unixdict.txt' asURI contents asCollectionOfLines do:[:eachWord | ... diff --git a/Task/Anagrams/Stata/anagrams.stata b/Task/Anagrams/Stata/anagrams.stata index 1469f3471b..1045cdd860 100644 --- a/Task/Anagrams/Stata/anagrams.stata +++ b/Task/Anagrams/Stata/anagrams.stata @@ -1,4 +1,4 @@ -import delimited http://www.puzzlers.org/pub/wordlists/unixdict.txt, clear +import delimited http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, clear mata a=st_sdata(.,.) n=rows(a) diff --git a/Task/Anagrams/Swift/anagrams.swift b/Task/Anagrams/Swift/anagrams.swift index 8345eef64d..fcdb38765d 100644 --- a/Task/Anagrams/Swift/anagrams.swift +++ b/Task/Anagrams/Swift/anagrams.swift @@ -1,6 +1,6 @@ import Foundation -let wordsURL = NSURL(string: "http://www.puzzlers.org/pub/wordlists/unixdict.txt")! +let wordsURL = NSURL(string: "http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")! let wordsstring = try NSString(contentsOfURL:wordsURL , encoding: NSUTF8StringEncoding) let allwords = wordsstring.componentsSeparatedByString("\n") diff --git a/Task/Anagrams/TUSCRIPT/anagrams.tu b/Task/Anagrams/TUSCRIPT/anagrams.tu index 37eeb987ec..3f3c0b3e89 100644 --- a/Task/Anagrams/TUSCRIPT/anagrams.tu +++ b/Task/Anagrams/TUSCRIPT/anagrams.tu @@ -1,5 +1,5 @@ $$ MODE TUSCRIPT,{} -requestdata = REQUEST ("http://www.puzzlers.org/pub/wordlists/unixdict.txt") +requestdata = REQUEST ("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt") DICT anagramm CREATE 99999 diff --git a/Task/Anagrams/Tcl/anagrams.tcl b/Task/Anagrams/Tcl/anagrams.tcl index aca6f55177..59a0606e6b 100644 --- a/Task/Anagrams/Tcl/anagrams.tcl +++ b/Task/Anagrams/Tcl/anagrams.tcl @@ -1,7 +1,7 @@ package require Tcl 8.5 package require http -set url http://www.puzzlers.org/pub/wordlists/unixdict.txt +set url http://wiki.puzzlers.org/pub/wordlists/unixdict.txt set response [http::geturl $url] set data [http::data $response] http::cleanup $response diff --git a/Task/Anagrams/UNIX-Shell/anagrams.sh b/Task/Anagrams/UNIX-Shell/anagrams.sh index d9a0f67802..3b508ffb78 100644 --- a/Task/Anagrams/UNIX-Shell/anagrams.sh +++ b/Task/Anagrams/UNIX-Shell/anagrams.sh @@ -18,7 +18,7 @@ declare -A wordlist while read -r word; do uniq_letters=( $(for ((i=0; i<${#word}; i++)); do echo "${word:i:1}"; done | sort) ) wordlist["${uniq_letters[*]}"]+="$word " -done < <( http_get_body www.puzzlers.org /pub/wordlists/unixdict.txt ) +done < <( http_get_body wiki.puzzlers.org /pub/wordlists/unixdict.txt ) maxlen=0 maxwords=() diff --git a/Task/Anonymous-recursion/Go/anonymous-recursion.go b/Task/Anonymous-recursion/Go/anonymous-recursion.go index e5e4355f1e..783be8c615 100644 --- a/Task/Anonymous-recursion/Go/anonymous-recursion.go +++ b/Task/Anonymous-recursion/Go/anonymous-recursion.go @@ -36,9 +36,7 @@ type fx func(fx) fn func yc(f ff) fn { return func(x fx) fn { - return f(func(a1, a2, a3 int) int { - return x(x)(a1, a2, a3) - }) + return x(x) }(func(x fx) fn { return f(func(a1, a2, a3 int) int { return x(x)(a1, a2, a3) diff --git a/Task/Anonymous-recursion/Phix/anonymous-recursion-1.phix b/Task/Anonymous-recursion/Phix/anonymous-recursion-1.phix new file mode 100644 index 0000000000..4b8974da57 --- /dev/null +++ b/Task/Anonymous-recursion/Phix/anonymous-recursion-1.phix @@ -0,0 +1,18 @@ +class Fib + private function fib_i(integer n) + return iff(n<2?n:this.fib_i(n-1)+this.fib_i(n-2)) + end function + public function fib(integer n) + if n<0 then throw("constraint error") end if + return this.fib_i(n) + end function +end class +Fib f = new() + +function fib_i(integer i) + return sprintf("this is not the fib_i(%d) you are looking for\n",i) +end function + +?f.fib(10) +--?f.fib_i(10) -- illegal +?fib_i(10) diff --git a/Task/Anonymous-recursion/Phix/anonymous-recursion-2.phix b/Task/Anonymous-recursion/Phix/anonymous-recursion-2.phix new file mode 100644 index 0000000000..4bb77ae889 --- /dev/null +++ b/Task/Anonymous-recursion/Phix/anonymous-recursion-2.phix @@ -0,0 +1,10 @@ +function erm(integer n, f) + return f(n,f) +end function + +function fib(integer n) + if n<0 then throw("constraint error") end if + return erm(n,function(integer n,f) return iff(n<2?n:f(n-1,f)+f(n-2,f)) end function) +end function + +?fib(10) diff --git a/Task/Anonymous-recursion/Python/anonymous-recursion-5.py b/Task/Anonymous-recursion/Python/anonymous-recursion-5.py new file mode 100644 index 0000000000..2ee943c4a6 --- /dev/null +++ b/Task/Anonymous-recursion/Python/anonymous-recursion-5.py @@ -0,0 +1,4 @@ +>>> Y = lambda f: lambda n: f(f,n) +>>> fib = lambda f, n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(f,n-1) + f(f,n-2))) #same as the first three implementations +>>> [ Y(fib)(i) for i in range(-2, 10) ] +[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34] diff --git a/Task/Anonymous-recursion/Python/anonymous-recursion-6.py b/Task/Anonymous-recursion/Python/anonymous-recursion-6.py new file mode 100644 index 0000000000..ebb7f83f08 --- /dev/null +++ b/Task/Anonymous-recursion/Python/anonymous-recursion-6.py @@ -0,0 +1,3 @@ +>>> fib_func = (lambda f: lambda n: f(f,n))(lambda f, n: None if n < 0 else (0 if n == 0 else (1 if n == 1 else f(f,n-1) + f(f,n-2)))) +>>> [ fib_func(i) for i in range(-2, 10) ] +[None, None, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34] diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/PHP/append-a-record-to-the-end-of-a-text-file.php b/Task/Append-a-record-to-the-end-of-a-text-file/PHP/append-a-record-to-the-end-of-a-text-file.php new file mode 100644 index 0000000000..ba15303a2f --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/PHP/append-a-record-to-the-end-of-a-text-file.php @@ -0,0 +1,19 @@ + fin routine */ + mov r2,#10 /* facteur */ + mov r3,#0 /* compteur */ + mov r4,r0 /* save de l adresse dans r4 */ + mov r6,#0 /* signe positif par defaut */ + mov r0,#0 /* initialisation à 0 */ +1: /* boucle d élimination des blancs du debut */ + ldrb r5,[r4,r3] /* chargement dans r5 de l octet situé au debut + la position */ + cmp r5,#0 /* fin de chaine -> fin routine */ beq 100f - cmp r5,#0x0A /* fin de chaine -> fin routine */ + cmp r5,#0x0A /* fin de chaine -> fin routine */ beq 100f - cmp r5,#' ' /* blanc au début */ - bne 1f /* non on continue */ + cmp r5,#' ' /* blanc au début */ + bne 1f /* non on continue */ add r3,r3,#1 /* oui on boucle en avançant d un octet */ b 1b 1: - cmp r5,#'-' /* premier caracteres est - */ - moveq r6,#1 /* maj du registre r6 avec 1 */ - beq 3f /* puis on avance à la position suivante */ -2: /* debut de boucle de traitement des chiffres */ - cmp r5,#'0' /* caractere n est pas un chiffre */ + cmp r5,#'-' /* premier caracteres est - */ + moveq r6,#1 /* maj du registre r6 avec 1 */ + beq 3f /* puis on avance à la position suivante */ +2: /* debut de boucle de traitement des chiffres */ + cmp r5,#'0' /* caractere n est pas un chiffre */ blt 3f - cmp r5,#'9' /* caractere n est pas un chiffre */ + cmp r5,#'9' /* caractere n est pas un chiffre */ bgt 3f - /* caractère est un chiffre */ + /* caractère est un chiffre */ sub r5,#48 - ldr r1,iMaxi /*verifier le dépassement du registre */ + ldr r1,iMaxi /*verifier le dépassement du registre */ cmp r0,r1 bgt 99f - mul r0,r2,r0 /* multiplier par facteur */ - add r0,r5 /* ajout à r0 */ + mul r0,r2,r0 /* multiplier par facteur */ + add r0,r5 /* ajout à r0 */ 3: - add r3,r3,#1 /* avance à la position suivante */ + add r3,r3,#1 /* avance à la position suivante */ ldrb r5,[r4,r3] /* chargement de l octet */ cmp r5,#0 /* fin de chaine -> fin routine */ beq 4f - cmp r5,#10 /* fin de chaine -> fin routine */ + cmp r5,#10 /* fin de chaine -> fin routine */ beq 4f - b 2b /* boucler */ + b 2b /* boucler */ 4: - cmp r6,#1 /* test du registre r6 pour le signe */ + cmp r6,#1 /* test du registre r6 pour le signe */ bne 100f mov r1,#-1 - mul r0,r1,r0 /* si negatif, on multiplie par -1 */ + mul r0,r1,r0 /* si negatif, on multiplie par -1 */ b 100f -99: /* erreur de dépassement */ +99: /* erreur de dépassement */ ldr r1,=szMessErrDep bl afficheerreur - mov r0,#0 /* en cas d'erreur on retourne toujours zero */ + mov r0,#0 /* en cas d erreur on retourne toujours zero */ 100: pop {r1-r7} /* restaur des autres registres */ - pop {fp,lr} /* restaur des 2 registres */ + pop {fp,lr} /* restaur des 2 registres */ bx lr /* retour procedure */ /* constante programme */ iMaxi: .int 1073741824 @@ -268,9 +268,9 @@ division: /* r2 contains Q */ /* r3 contains R */ push {r4, lr} - mov r2, #0 /* r2 ? 0 */ - mov r3, #0 /* r3 ? 0 */ - mov r4, #32 /* r4 ? 32 */ + mov r2, #0 /* r2 ? 0 */ + mov r3, #0 /* r3 ? 0 */ + mov r4, #32 /* r4 ? 32 */ b 2f 1: movs r0, r0, LSL #1 /* r0 ? r0 << 1 updating cpsr (sets C if 31st bit of r0 was 1) */ @@ -281,7 +281,7 @@ division: adc r2, r2, r2 /* r2 ? r2 + r2 + C. This is equivalent to r2 ? (r2 << 1) + C */ 2: subs r4, r4, #1 /* r4 ? r4 - 1 */ - bpl 1b /* if r4 >= 0 (N=0) then branch to .Lloop1 */ + bpl 1b /* if r4 >= 0 (N=0) then branch to .Lloop1 */ pop {r4, lr} bx lr diff --git a/Task/Arithmetic-Integer/Retro/arithmetic-integer.retro b/Task/Arithmetic-Integer/Retro/arithmetic-integer.retro index 73d78c3282..3aa131a3fc 100644 --- a/Task/Arithmetic-Integer/Retro/arithmetic-integer.retro +++ b/Task/Arithmetic-Integer/Retro/arithmetic-integer.retro @@ -1,8 +1,8 @@ -: arithmetic ( ab- ) - over "\na = %d" puts - dup "\nb = %d" puts - 2over + "\na + b = %d" puts - 2over - "\na - b = %d" puts - 2over * "\na * b = %d" puts - /mod "\na / b = %d" puts - "\na mod b = %d\n" puts ; +:arithmetic (ab-) + over '\na_______=_%n s:put + dup '\nb_______=_%n s:put + dup-pair + '\na_+_b___=_%n s:put + dup-pair - '\na_-_b___=_%n s:put + dup-pair * '\na_*_b___=_%n s:put + /mod '\na_/_b___=_%n s:put + '\na_mod_b_=_%n\n" s:put ; diff --git a/Task/Arithmetic-Rational/Julia/arithmetic-rational.julia b/Task/Arithmetic-Rational/Julia/arithmetic-rational.julia index 0806369652..c0fa4525d2 100644 --- a/Task/Arithmetic-Rational/Julia/arithmetic-rational.julia +++ b/Task/Arithmetic-Rational/Julia/arithmetic-rational.julia @@ -1,24 +1,7 @@ -function isperfect{T<:Integer}(n::T) - !isprime(n) || return false - tal = 1//n - hi = isqrt(n) - if hi^2 == n - tal += 1//hi - hi -= 1 - end - for i in 2:hi - (d, r) = divrem(n, i) - if r == 0 - tal += (1//i + 1//d) - end - end - return tal == 1//1 -end +using Primes +divisors(n) = foldl((a, (p, e)) -> vcat((a * [p^i for i in 0:e]')...), factor(n), init=[1]) -lo = 2 -hi = 2^19 -println("Searching for perfect numbers from ", lo, " to ", hi, ".") -for i in 2:2^19 - isperfect(i) || continue - println(@sprintf("%8d", i)) -end +isperfect(n) = sum(1 // d for d in divisors(n)) == 2 + +lo, hi = 2, 2^19 +println("Perfect numbers between ", lo, " and ", hi, ": ", collect(filter(isperfect, lo:hi))) diff --git a/Task/Arithmetic-Rational/Swift/arithmetic-rational.swift b/Task/Arithmetic-Rational/Swift/arithmetic-rational.swift new file mode 100644 index 0000000000..7de94b1ab7 --- /dev/null +++ b/Task/Arithmetic-Rational/Swift/arithmetic-rational.swift @@ -0,0 +1,156 @@ +import Foundation + +extension BinaryInteger { + @inlinable + public func gcd(with other: Self) -> Self { + var gcd = self + var b = other + + while b != 0 { + (gcd, b) = (b, gcd % b) + } + + return gcd + } + + @inlinable + public func lcm(with other: Self) -> Self { + let g = gcd(with: other) + + return self / g * other + } +} + +public struct Frac: Equatable { + @usableFromInline + var _num: NumType + + @usableFromInline + var _dom: NumType + + @usableFromInline + init(_num: NumType, _dom: NumType) { + self._num = _num + self._dom = _dom + } + + @inlinable + public init(numerator: NumType, denominator: NumType) { + let divisor = numerator.gcd(with: denominator) + + self._num = numerator / divisor + self._dom = denominator / divisor + } + + @inlinable + public static func + (lhs: Frac, rhs: Frac) -> Frac { + let multiplier = lhs._dom.lcm(with: rhs.denominator) + + return Frac( + numerator: lhs._num * multiplier / lhs._dom + rhs._num * multiplier / rhs._dom, + denominator: multiplier + ) + } + + @inlinable + public static func += (lhs: inout Frac, rhs: Frac) { + lhs = lhs + rhs + } + + @inlinable + public static func - (lhs: Frac, rhs: Frac) -> Frac { + return lhs + -rhs + } + + @inlinable + public static func -= (lhs: inout Frac, rhs: Frac) { + lhs = lhs + -rhs + } + + @inlinable + public static func * (lhs: Frac, rhs: Frac) -> Frac { + return Frac(numerator: lhs._num * rhs._num, denominator: lhs._dom * rhs._dom) + } + + @inlinable + public static func *= (lhs: inout Frac, rhs: Frac) { + lhs = lhs * rhs + } + + @inlinable + public static func / (lhs: Frac, rhs: Frac) -> Frac { + return lhs * Frac(_num: rhs._dom, _dom: rhs._num) + } + + @inlinable + public static func /= (lhs: inout Frac, rhs: Frac) { + lhs = lhs / rhs + } + + @inlinable + prefix static func - (rhs: Frac) -> Frac { + return Frac(_num: -rhs._num, _dom: rhs._dom) + } +} + +extension Frac { + @inlinable + public var numerator: NumType { + get { _num } + set { + let divisor = newValue.gcd(with: denominator) + + _num = newValue / divisor + _dom = denominator / divisor + } + } + + @inlinable + public var denominator: NumType { + get { _dom } + set { + let divisor = newValue.gcd(with: numerator) + + _num = numerator / divisor + _dom = newValue / divisor + } + } +} + +extension Frac: CustomStringConvertible { + public var description: String { + let neg = numerator < 0 || denominator < 0 + + return "Frac(\(neg ? "-" : "")\(abs(numerator)) / \(abs(denominator)))" + } +} + +extension Frac: Comparable { + @inlinable + public static func <(lhs: Frac, rhs: Frac) -> Bool { + return lhs._num * rhs._dom < lhs._dom * rhs._num + } +} + +extension Frac: ExpressibleByIntegerLiteral { + public init(integerLiteral value: Int) { + self._num = NumType(value) + self._dom = 1 + } +} + + +for candidate in 2..<1<<19 { + var sum = Frac(numerator: 1, denominator: candidate) + + let m = Int(ceil(Double(candidate).squareRoot())) + + for factor in 2.. a -> a -> ((a, a) -> Bool) -> a -agm a g eq = snd . head . dropWhile (not . eq) $ iterate step (a, g) - where step (a, g) = ((a + g) / 2, sqrt (a * g)) +agm a g eq = snd $ until eq step (a, g) + where + step (a, g) = ((a + g) / 2, sqrt (a * g)) -- Return the relative difference of the pair. We assume that at least one of -- the values is far enough from 0 to not cause problems. relDiff :: (Fractional a) => (a, a) -> a -relDiff (x, y) = let n = abs (x - y) - d = ((abs x) + (abs y)) / 2 - in n / d +relDiff (x, y) = + let n = abs (x - y) + d = (abs x + abs y) / 2 + in n / d +main :: IO () main = do let equal = (< 0.000000001) . relDiff print $ agm 1 (1 / sqrt 2) equal diff --git a/Task/Arithmetic-geometric-mean/Julia/arithmetic-geometric-mean.julia b/Task/Arithmetic-geometric-mean/Julia/arithmetic-geometric-mean.julia index cd90bb50da..7c0ca71d51 100644 --- a/Task/Arithmetic-geometric-mean/Julia/arithmetic-geometric-mean.julia +++ b/Task/Arithmetic-geometric-mean/Julia/arithmetic-geometric-mean.julia @@ -1,21 +1,20 @@ -function agm(x::T, y::T, e::Real = 5) where T<:AbstractFloat - if x ≤ 0 || y ≤ 0 || e ≤ 0 throw(DomainError("x, y must be strictly positive")) end - err = e * eps(x) +function agm(x, y, e::Real = 5) + (x ≤ 0 || y ≤ 0 || e ≤ 0) && throw(DomainError("x, y must be strictly positive")) g, a = minmax(x, y) - while err < (a - g) + while e * eps(x) < a - g a, g = (a + g) / 2, sqrt(a * g) end - return a + a end -x = 1.0 -y = 1 / √2 - +x, y = 1.0, 1 / √2 println("# Using literal-precision float numbers:") @show agm(x, y) + println("# Using half-precision float numbers:") x, y = Float32(x), Float32(y) @show agm(x, y) + println("# Using ", precision(BigFloat), "-bit float numbers:") x, y = big(1.0), 1 / √big(2.0) @show agm(x, y) diff --git a/Task/Array-concatenation/Elena/array-concatenation.elena b/Task/Array-concatenation/Elena/array-concatenation.elena index 4d412e7dbb..1bd17f94da 100644 --- a/Task/Array-concatenation/Elena/array-concatenation.elena +++ b/Task/Array-concatenation/Elena/array-concatenation.elena @@ -2,8 +2,8 @@ import extensions; public program() { - var a := new int[]{1,2,3}; - var b := new int[]{4,5}; + var a := new int[]::(1,2,3); + var b := new int[]::(4,5); console.printLine( "(",a.asEnumerable(),") + (",b.asEnumerable(), diff --git a/Task/Array-concatenation/Retro/array-concatenation.retro b/Task/Array-concatenation/Retro/array-concatenation.retro index 5a1edc2bf6..822a366317 100644 --- a/Task/Array-concatenation/Retro/array-concatenation.retro +++ b/Task/Array-concatenation/Retro/array-concatenation.retro @@ -1,3 +1 @@ -needs array' - -^array'new{ 1 2 3 } ^array'new{ 4 5 6 } ^array'append +{ #1 #2 #3 } { #4 #5 #6 } a:append diff --git a/Task/Arrays/C/arrays-10.c b/Task/Arrays/C/arrays-10.c new file mode 100644 index 0000000000..b08b7db9ae --- /dev/null +++ b/Task/Arrays/C/arrays-10.c @@ -0,0 +1,59 @@ +#include +#include +typedef struct node{ + char value; + struct node* next; +} node; +typedef struct charList{ + node* first; + int size; +} charList; + +charList createList(){ + charList foo = {.first = NULL, .size = 0}; + return foo; +} +int addEl(charList* list, char c){ + if(list != NULL){ + node* foo = (node*)malloc(sizeof(node)); + if(foo == NULL) return -1; + foo->value = c; foo->next = NULL; + if(list->first == NULL){ + list->first = foo; + }else{ + node* it= list->first; + while(it->next != NULL)it = it->next; + it->next = foo; + } + list->size = list->size+1; + return 0; + }else return -1; +} +int removeEl(charList* list, int index){ + if(list != NULL && list->size > index){ + node* it = list->first; + for(int i = 0; i < index-1; i++) it = it->next; + node* el = it->next; + it->next = el->next; + free(el); + list->size--; + return 0; + }else return -1; +} +char getEl(charList* list, int index){ + if(list != NULL && list->size > index){ + node* it = list->first; + for(int i = 0; i < index; i++) it = it->next; + return it->value; + }else return '\0'; +} +static void cleanHelp(node* el){ + if(el != NULL){ + if(el->next != NULL) cleanHelp(el->next); + free(el); + } +} +void clean(charList* list){ + cleanHelp(list->first); + list->size = 0; +} diff --git a/Task/Arrays/Elena/arrays-1.elena b/Task/Arrays/Elena/arrays-1.elena index c784dc8ae5..fa4af4b2ce 100644 --- a/Task/Arrays/Elena/arrays-1.elena +++ b/Task/Arrays/Elena/arrays-1.elena @@ -1 +1 @@ - var staticArray := new int[]{1, 2, 3}; + var staticArray := new int[]::(1, 2, 3); diff --git a/Task/Arrays/LOLCODE/arrays.lol b/Task/Arrays/LOLCODE/arrays.lol new file mode 100644 index 0000000000..80e77ef527 --- /dev/null +++ b/Task/Arrays/LOLCODE/arrays.lol @@ -0,0 +1,18 @@ +HAI 1.4 +BTW declaring array +I HAS A array ITZ A BUKKIT +BTW store values in array +array HAS A one ITZ 1 +array HAS A two ITZ 2 +array HAS A three ITZ 3 +array HAS A string ITZ "MEOW" +OBTW +there is no way to get an element of an array at a specified index in LOLCODE +therefore, you can't really iterate through an array +TLDR +BTW get the element of array +VISIBLE array'Z one +VISIBLE array'Z two +VISIBLE array'Z three +VISIBLE array'Z string +KTHXBYE diff --git a/Task/Assertions/Julia/assertions.julia b/Task/Assertions/Julia/assertions.julia index c811a0e89d..2bb3f376a2 100644 --- a/Task/Assertions/Julia/assertions.julia +++ b/Task/Assertions/Julia/assertions.julia @@ -1,14 +1,11 @@ -# assert() function takes expression as 1st argument, failed-assertion message -# as optional 2nd argument -assert(x == 42) -# ERROR: assertion failed: x is not 42 +const x = 5 # @assert macro checks the supplied conditional expression, with the expression # returned in the failed-assertion message @assert x == 42 -# ERROR: assertion failed: :((x == 42)) +# ERROR: LoadError: AssertionError: x == 42 # Julia also has type assertions of the form, x::Type which can be appended to # variable for type-checking at any point x::String -# ERROR: type: typeassert: expected String, got Int32 +# ERROR: LoadError: TypeError: in typeassert, expected String, got Int64 diff --git a/Task/Assertions/REXX/assertions.rexx b/Task/Assertions/REXX/assertions-1.rexx similarity index 100% rename from Task/Assertions/REXX/assertions.rexx rename to Task/Assertions/REXX/assertions-1.rexx diff --git a/Task/Assertions/REXX/assertions-2.rexx b/Task/Assertions/REXX/assertions-2.rexx new file mode 100644 index 0000000000..7bcd79e3c9 --- /dev/null +++ b/Task/Assertions/REXX/assertions-2.rexx @@ -0,0 +1,15 @@ +/*REXX program implements a simple ASSERT function; the expression can be compound. */ + a = 1 /*assign a value to the A variable.*/ + b = -2 /* " " " " " B " */ +gee = 7.00 /* " " " " " GEE " */ +zee = 26 /* " " " " " ZEE " */ + +call assert (a = 1) +call assert (b > 0) +call assert (gee = 7) +call assert (zee = a & zee>b) +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +assert: if arg(1)=1 then return; parse value sourceline(sigl) with x; say + say '===== ASSERT failure in REXX line' sigl", the statement is:"; say '=====' x + say; return diff --git a/Task/Associative-array-Creation/Ol/associative-array-creation.ol b/Task/Associative-array-Creation/Ol/associative-array-creation.ol index d4fdaa1eee..3304b1e7ef 100644 --- a/Task/Associative-array-Creation/Ol/associative-array-creation.ol +++ b/Task/Associative-array-Creation/Ol/associative-array-creation.ol @@ -7,15 +7,15 @@ (define empty-map #empty) ;;; creating associative array with values -(define my-map (list->ff '( +(define my-map (pairs->ff '( (1 . 100) (2 . 200) (7 . 777)))) ;;; or in short form (available from Ol version 2.1) -(define my-map '{ - (1 . 100) - (2 . 200) - (7 . 777)}) +(define my-map { + 1 100 + 2 200 + 7 777}) ;;; add new key-value pair to the existing associative array (define my-new-map (put my-map 'the-key 'the-value)) diff --git a/Task/Associative-array-Creation/Pike/associative-array-creation-1.pike b/Task/Associative-array-Creation/Pike/associative-array-creation-1.pike new file mode 100644 index 0000000000..df786dc19c --- /dev/null +++ b/Task/Associative-array-Creation/Pike/associative-array-creation-1.pike @@ -0,0 +1,5 @@ +mapping m = ([ "apple": "fruit", 17: "seventeen" ]); +write("indices: %O\nvalues: %O\n17: %O\n", + indices(m), + values(m), + m[17]); diff --git a/Task/Associative-array-Creation/Pike/associative-array-creation-2.pike b/Task/Associative-array-Creation/Pike/associative-array-creation-2.pike new file mode 100644 index 0000000000..bfd2eaf3aa --- /dev/null +++ b/Task/Associative-array-Creation/Pike/associative-array-creation-2.pike @@ -0,0 +1,4 @@ +mapping m2 = ([ "car": ([ "ford":17, "volvo":42 ]) ]); +write("#ford: %O, #volvo: %O\n", + m2->car->ford, + m2["car"]["volvo"]); diff --git a/Task/Average-loop-length/Factor/average-loop-length.factor b/Task/Average-loop-length/Factor/average-loop-length.factor new file mode 100644 index 0000000000..5f8f24a564 --- /dev/null +++ b/Task/Average-loop-length/Factor/average-loop-length.factor @@ -0,0 +1,25 @@ +USING: formatting fry io kernel locals math math.factorials +math.functions math.ranges random sequences ; + +: (analytical) ( m n -- x ) + [ drop factorial ] [ ^ /f ] [ - factorial / ] 2tri ; + +: analytical ( n -- x ) + dup [1,b] [ (analytical) ] with map-sum ; + +: loop-length ( n -- x ) + [ 0 0 1 [ 2dup bitand zero? ] ] dip + '[ [ 1 + ] 2dip bitor 1 _ random shift ] while 2drop ; + +:: average-loop-length ( n #tests -- x ) + 0 #tests [ n loop-length + ] times #tests / ; + +: stats ( n -- avg exp ) + [ 1,000,000 average-loop-length ] [ analytical ] bi ; + +: .line ( n -- ) + dup stats 2dup / 1 - 100 * + "%2d %8.4f %8.4f %6.3f%%\n" printf ; + +" n\tavg\texp.\tdiff\n-------------------------------" print +20 [1,b] [ .line ] each diff --git a/Task/Average-loop-length/Julia/average-loop-length.julia b/Task/Average-loop-length/Julia/average-loop-length.julia index ea5a677bc5..215526cfe0 100644 --- a/Task/Average-loop-length/Julia/average-loop-length.julia +++ b/Task/Average-loop-length/Julia/average-loop-length.julia @@ -1,4 +1,5 @@ -# Version 5.2 +using Printf + analytical(n::Integer) = sum(factorial(n) / big(n) ^ i / factorial(n - i) for i = 1:n) function test(n::Integer, times::Integer = 1000000) diff --git a/Task/Average-loop-length/Scala/average-loop-length.scala b/Task/Average-loop-length/Scala/average-loop-length.scala index 10eda602c8..268a3a7f4d 100644 --- a/Task/Average-loop-length/Scala/average-loop-length.scala +++ b/Task/Average-loop-length/Scala/average-loop-length.scala @@ -2,11 +2,17 @@ import scala.util.Random object AverageLoopLength extends App { - val factorial: Stream[Double] = 1 #:: factorial.zip(Stream.from(1)).map(n => n._2 * factorial(n._2 - 1)) + val factorial: LazyList[Double] = 1 #:: factorial.zip(LazyList.from(1)).map(n => n._2 * factorial(n._2 - 1)) + val results = for (n <- 1 to 20; + avg = tested(n, 1000000); + theory = expected(n) + ) yield (n, avg, theory, (avg / theory - 1) * 100) - def expected(n: Int) = (for (i <- 1 to n) yield factorial(n) / Math.pow(n, i) / factorial(n - i)).sum + def expected(n: Int): Double = (for (i <- 1 to n) yield factorial(n) / Math.pow(n, i) / factorial(n - i)).sum - def trial(n: Int):Double = { + def tested(n: Int, times: Int): Double = (for (i <- 1 to times) yield trial(n)).sum / times + + def trial(n: Int): Double = { var count = 0 var x = 1 var bits = 0 @@ -19,19 +25,12 @@ object AverageLoopLength extends App { count } - def tested(n: Int, times: Int) = (for (i <- 1 to times) yield trial(n)).sum / times - - val results = for (n <- 1 to 20; - avg = tested(n, 1000000); - theory = expected(n) - ) yield (n, avg, theory, (avg / theory - 1) * 100) - println("n avg exp diff") println("------------------------------------") results foreach { n => { - println(f"${n._1}%2d ${n._2}%2.6f ${n._3}%2.6f ${n._4}%2.3f%%") - } + println(f"${n._1}%2d ${n._2}%2.6f ${n._3}%2.6f ${n._4}%2.3f%%") + } } } diff --git a/Task/Average-loop-length/Sidef/average-loop-length.sidef b/Task/Average-loop-length/Sidef/average-loop-length.sidef new file mode 100644 index 0000000000..7d31c8a2eb --- /dev/null +++ b/Task/Average-loop-length/Sidef/average-loop-length.sidef @@ -0,0 +1,22 @@ +func find_loop(n) { + var seen = Hash() + loop { + with (irand(1, n)) { |r| + seen.has(r) ? (return seen.len) : (seen{r} = true) + } + } +} + +print " N empiric theoric (error)\n"; +print "=== ========= ============ =========\n"; + +define MAX = 20 +define TRIALS = 1000 + +for n in (1..MAX) { + var empiric = (1..TRIALS -> sum { find_loop(n) } / TRIALS) + var theoric = (1..n -> sum {|k| prod(n - k + 1 .. n) * k**2 / n**(k+1) }) + + printf("%3d %9.4f %12.4f (%5.2f%%)\n", + n, empiric, theoric, 100*(empiric-theoric)/theoric) +} diff --git a/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena b/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena index 4fe7752986..211bc6fc42 100644 --- a/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena +++ b/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena @@ -21,7 +21,7 @@ extension op public program() { - var array := new int[]{1, 2, 3, 4, 5, 6, 7, 8}; + 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/Julia/averages-arithmetic-mean.julia b/Task/Averages-Arithmetic-mean/Julia/averages-arithmetic-mean.julia index 3219e3d96a..f97e5a9774 100644 --- a/Task/Averages-Arithmetic-mean/Julia/averages-arithmetic-mean.julia +++ b/Task/Averages-Arithmetic-mean/Julia/averages-arithmetic-mean.julia @@ -1,4 +1,4 @@ -julia> mean([1,2,3]) +julia> using Statistics; mean([1,2,3]) 2.0 julia> mean(1:10) 5.5 diff --git a/Task/Averages-Mean-angle/Julia/averages-mean-angle-1.julia b/Task/Averages-Mean-angle/Julia/averages-mean-angle-1.julia index fc73f2d9d0..98cce3ccb6 100644 --- a/Task/Averages-Mean-angle/Julia/averages-mean-angle-1.julia +++ b/Task/Averages-Mean-angle/Julia/averages-mean-angle-1.julia @@ -1 +1,2 @@ +using Statistics meandegrees(degrees) = radians2degrees(atan2(mean(sind(degrees)), mean(cosd(degrees)))) diff --git a/Task/Averages-Mean-angle/Swift/averages-mean-angle.swift b/Task/Averages-Mean-angle/Swift/averages-mean-angle.swift new file mode 100644 index 0000000000..4fe21a1155 --- /dev/null +++ b/Task/Averages-Mean-angle/Swift/averages-mean-angle.swift @@ -0,0 +1,21 @@ +import Foundation + +@inlinable public func d2r(_ f: T) -> T { f * .pi / 180 } +@inlinable public func r2d(_ f: T) -> T { f * 180 / .pi } + +public func meanOfAngles(_ angles: [Double]) -> Double { + let cInv = 1 / Double(angles.count) + let (s, c) = + angles.lazy + .map(d2r) + .map({ (sin($0), cos($0)) }) + .reduce(into: (0.0, 0.0), { $0.0 += $1.0; $0.1 += $1.1 }) + + return r2d(atan2(cInv * s, cInv * c)) +} + +let fmt = { String(format: "%lf", $0) } + +print("Mean of angles (350, 10) => \(fmt(meanOfAngles([350, 10])))") +print("Mean of angles (90, 180, 270, 360) => \(fmt(meanOfAngles([90, 180, 270, 360])))") +print("Mean of angles (10, 20, 30) => \(fmt(meanOfAngles([10, 20, 30])))") diff --git a/Task/Averages-Mean-angle/Vala/averages-mean-angle.vala b/Task/Averages-Mean-angle/Vala/averages-mean-angle.vala new file mode 100644 index 0000000000..e0f3a8e662 --- /dev/null +++ b/Task/Averages-Mean-angle/Vala/averages-mean-angle.vala @@ -0,0 +1,21 @@ +double meanAngle(double[] angles) { + double y_part = 0.0; + double x_part = 0.0; + + for (int i = 0; i < angles.length; i++) { + x_part += Math.cos(angles[i] * Math.PI / 180.0); + y_part += Math.sin(angles[i] * Math.PI / 180.0); + } + + return Math.atan2(y_part / angles.length, x_part / angles.length) * 180 / Math.PI; +} + +void main() { + double[] angleSet1 = {350.0, 10.0}; + double[] angleSet2 = {90.0, 180.0, 270.0, 360.0}; + double[] angleSet3 = {10.0, 20.0, 30.0}; + + print("\nMean Angle for 1st set : %lf degrees", meanAngle(angleSet1)); + print("\nMean Angle for 2nd set : %lf degrees", meanAngle(angleSet2)); + print("\nMean Angle for 3rd set : %lf degrees\n", meanAngle(angleSet3)); +} diff --git a/Task/Averages-Mean-time-of-day/Julia/averages-mean-time-of-day.julia b/Task/Averages-Mean-time-of-day/Julia/averages-mean-time-of-day.julia index a7064accf8..ec25c0828e 100644 --- a/Task/Averages-Mean-time-of-day/Julia/averages-mean-time-of-day.julia +++ b/Task/Averages-Mean-time-of-day/Julia/averages-mean-time-of-day.julia @@ -1,3 +1,5 @@ +using Statistics + function meantime(times::Array, dlm::String=":") c = π / (12 * 60 * 60) a = map(x -> parse.(Int, x), split.(times, dlm)) diff --git a/Task/Averages-Mean-time-of-day/Swift/averages-mean-time-of-day.swift b/Task/Averages-Mean-time-of-day/Swift/averages-mean-time-of-day.swift new file mode 100644 index 0000000000..1dea986770 --- /dev/null +++ b/Task/Averages-Mean-time-of-day/Swift/averages-mean-time-of-day.swift @@ -0,0 +1,57 @@ +import Foundation + +@inlinable public func d2r(_ f: T) -> T { f * .pi / 180 } +@inlinable public func r2d(_ f: T) -> T { f * 180 / .pi } + +public func meanOfAngles(_ angles: [Double]) -> Double { + let cInv = 1 / Double(angles.count) + let (y, x) = + angles.lazy + .map(d2r) + .map({ (sin($0), cos($0)) }) + .reduce(into: (0.0, 0.0), { $0.0 += $1.0; $0.1 += $1.1 }) + + return r2d(atan2(cInv * y, cInv * x)) +} + +struct DigitTime { + var hour: Int + var minute: Int + var second: Int + + init?(fromString str: String) { + let split = str.components(separatedBy: ":").compactMap(Int.init) + + guard split.count == 3 else { + return nil + } + + (hour, minute, second) = (split[0], split[1], split[2]) + } + + init(fromDegrees angle: Double) { + let totalSeconds = 24 * 60 * 60 * angle / 360 + + second = Int(totalSeconds.truncatingRemainder(dividingBy: 60)) + minute = Int((totalSeconds.truncatingRemainder(dividingBy: 3600) - Double(second)) / 60) + hour = Int(totalSeconds / 3600) + } + + func toDegrees() -> Double { + return 360 * Double(hour) / 24.0 + 360 * Double(minute) / (24 * 60.0) + 360 * Double(second) / (24 * 3600.0) + } +} + +extension DigitTime: CustomStringConvertible { + var description: String { String(format: "%02i:%02i:%02i", hour, minute, second) } +} + +let times = ["23:00:17", "23:40:20", "00:12:45", "00:17:19"].compactMap(DigitTime.init(fromString:)) + +guard times.count == 4 else { + fatalError() +} + +let meanTime = DigitTime(fromDegrees: 360 + meanOfAngles(times.map({ $0.toDegrees() }))) + +print("Given times \(times), the mean time is \(meanTime)") diff --git a/Task/Averages-Median/Elena/averages-median.elena b/Task/Averages-Median/Elena/averages-median.elena index a4d8a04bef..887b5dfbc3 100644 --- a/Task/Averages-Median/Elena/averages-median.elena +++ b/Task/Averages-Median/Elena/averages-median.elena @@ -30,8 +30,8 @@ extension op 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}; + 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,") is ",a1.Median); console.printLine("median of (",a2,") is ",a2.Median); diff --git a/Task/Averages-Median/Julia/averages-median.julia b/Task/Averages-Median/Julia/averages-median.julia index d6898cbd4f..2a6c70d94f 100644 --- a/Task/Averages-Median/Julia/averages-median.julia +++ b/Task/Averages-Median/Julia/averages-median.julia @@ -1,4 +1,4 @@ -# Version 5.2 +using Statistics function median2(n) s = sort(n) len = length(n) diff --git a/Task/Averages-Mode/Elena/averages-mode.elena b/Task/Averages-Mode/Elena/averages-mode.elena index 402f636862..a8d780b480 100644 --- a/Task/Averages-Mode/Elena/averages-mode.elena +++ b/Task/Averages-Mode/Elena/averages-mode.elena @@ -25,9 +25,9 @@ extension op public program() { - var array1 := new int[] {1, 1, 2, 4, 4}; - 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"}; + var array1 := new int[]::(1, 1, 2, 4, 4); + var array2 := new int[]::(1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17); + var array3 := new ::(1, "blue", 2, 7.5r, 5, "green", "red", 5, 2, "blue", "white"); console .printLine("mode of (",array1.asEnumerable(),") is (",array1.Mode,")") diff --git a/Task/Averages-Pythagorean-means/Haskell/averages-pythagorean-means-2.hs b/Task/Averages-Pythagorean-means/Haskell/averages-pythagorean-means-2.hs index 9f385f0325..fbc611f8ff 100644 --- a/Task/Averages-Pythagorean-means/Haskell/averages-pythagorean-means-2.hs +++ b/Task/Averages-Pythagorean-means/Haskell/averages-pythagorean-means-2.hs @@ -1,14 +1,12 @@ -import Control.Applicative (liftA2) import Data.List (genericLength) -- ARITHMETIC, GEOMETRIC AND HARMONIC MEANS --------------- - arithmetic, geometric, harmonic :: [Double] -> Double -arithmetic = liftA2 (/) sum genericLength +arithmetic = (/) . sum <*> genericLength -geometric = liftA2 (**) product ((1 /) . genericLength) +geometric = (**) . product <*> ((1 /) . genericLength) -harmonic = liftA2 (/) genericLength (foldr ((+) . (1 /)) 0) +harmonic = (/) . genericLength <*> foldr ((+) . (1 /)) 0 -- TEST --------------------------------------------------- xs :: [Double] diff --git a/Task/Averages-Root-mean-square/Swift/averages-root-mean-square.swift b/Task/Averages-Root-mean-square/Swift/averages-root-mean-square.swift new file mode 100644 index 0000000000..22380f5955 --- /dev/null +++ b/Task/Averages-Root-mean-square/Swift/averages-root-mean-square.swift @@ -0,0 +1,8 @@ +extension Collection where Element: FloatingPoint { + @inlinable + public func rms() -> Element { + return (lazy.map({ $0 * $0 }).reduce(0, +) / Element(count)).squareRoot() + } +} + +print("RMS of 1...10: \((1...10).map(Double.init).rms())") diff --git a/Task/Averages-Simple-moving-average/Crystal/averages-simple-moving-average.crystal b/Task/Averages-Simple-moving-average/Crystal/averages-simple-moving-average.crystal new file mode 100644 index 0000000000..0b8313149c --- /dev/null +++ b/Task/Averages-Simple-moving-average/Crystal/averages-simple-moving-average.crystal @@ -0,0 +1,15 @@ +def sma(n) Proc(Float64, Float64) + a = Array(Float64).new + ->(x : Float64) { + a.shift if a.size == n + a.push x + a.sum / a.size.to_f + } +end + +sma3, sma5 = sma(3), sma(5) + +# Copied from the Ruby solution. +(1.upto(5).to_a + 5.downto(1).to_a).each do |n| + printf "%d: sma3 = %.3f - sma5 = %.3f\n", n, sma3.call(n.to_f), sma5.call(n.to_f) +end diff --git a/Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average-1.julia b/Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average-1.julia index e978b52eba..df8c164afe 100644 --- a/Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average-1.julia +++ b/Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average-1.julia @@ -1,3 +1 @@ -SMA(N) = let buffer = Number[] - x -> (push!(buffer, x) ; mean(buffer[max(1,end-N+1):end])) - end +using Statistics diff --git a/Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average-2.julia b/Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average-2.julia index bbb0d9c796..691844d737 100644 --- a/Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average-2.julia +++ b/Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average-2.julia @@ -1,6 +1,22 @@ -SMA(N, buffer = Number[]) = - x -> begin - push!(buffer, x) - if length(buffer) == N+1 shift!(buffer) end - mean(buffer) - end +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.julia b/Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average.julia deleted file mode 100644 index 691844d737..0000000000 --- a/Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average.julia +++ /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/PowerShell/averages-simple-moving-average.psh b/Task/Averages-Simple-moving-average/PowerShell/averages-simple-moving-average.psh new file mode 100644 index 0000000000..c6036363e7 --- /dev/null +++ b/Task/Averages-Simple-moving-average/PowerShell/averages-simple-moving-average.psh @@ -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/REXX/averages-simple-moving-average.rexx b/Task/Averages-Simple-moving-average/REXX/averages-simple-moving-average.rexx index a4f503350c..6b6aaa2d08 100644 --- a/Task/Averages-Simple-moving-average/REXX/averages-simple-moving-average.rexx +++ b/Task/Averages-Simple-moving-average/REXX/averages-simple-moving-average.rexx @@ -9,7 +9,6 @@ if n=='' | n=="," then n= 10 /* " " " " " do k=n%2 by -1 to 1; @.j= k; j= j+1 /* " 2nd " " " decreasing " */ end /*k*/ - say ' number ' " SMA with period" p' ' " SMA with period" q say ' ──────── ' "───────────────────" '───────────────────' pad=' ' diff --git a/Task/Averages-Simple-moving-average/Swift/averages-simple-moving-average.swift b/Task/Averages-Simple-moving-average/Swift/averages-simple-moving-average.swift new file mode 100644 index 0000000000..be22e06cd0 --- /dev/null +++ b/Task/Averages-Simple-moving-average/Swift/averages-simple-moving-average.swift @@ -0,0 +1,28 @@ +struct SimpleMovingAverage { + var period: Int + var numbers = [Double]() + + mutating func addNumber(_ n: Double) -> Double { + numbers.append(n) + + if numbers.count > period { + numbers.removeFirst() + } + + guard !numbers.isEmpty else { + return 0 + } + + return numbers.reduce(0, +) / Double(numbers.count) + } +} + +for period in [3, 5] { + print("Moving average with period \(period)") + + var averager = SimpleMovingAverage(period: period) + + for n in [1.0, 2, 3, 4, 5, 5, 4, 3, 2, 1] { + print("n: \(n); average \(averager.addNumber(n))") + } +} diff --git a/Task/Balanced-brackets/Haskell/balanced-brackets-1.hs b/Task/Balanced-brackets/Haskell/balanced-brackets-1.hs index 0cfa89c906..b49306d9d7 100644 --- a/Task/Balanced-brackets/Haskell/balanced-brackets-1.hs +++ b/Task/Balanced-brackets/Haskell/balanced-brackets-1.hs @@ -8,22 +8,24 @@ import VShuffle -- after, the i'th bracket. We assume the string contains only brackets. isBalanced :: String -> Maybe Int isBalanced = bal (-1) 0 - where bal :: Int -> Int -> String -> Maybe Int - bal _ 0 [] = Nothing - bal i _ [] = Just i - bal i (-1) _ = Just i - bal i n ('[':bs) = bal (i+1) (n+1) bs - bal i n (']':bs) = bal (i+1) (n-1) bs + where + bal :: Int -> Int -> String -> Maybe Int + bal _ 0 [] = Nothing + bal i _ [] = Just i + bal i (-1) _ = Just i + bal i n ('[':bs) = bal (i + 1) (n + 1) bs + bal i n (']':bs) = bal (i + 1) (n - 1) bs -- Print a string, indicating whether it contains balanced brackets. If not, -- indicate the bracket at which the imbalance was found. check :: String -> IO () check s = maybe (good s) (bad s) (isBalanced s) - where good s = printf "Good \"%s\"\n" s - bad s n = printf "Bad \"%s\"\n%*s^\n" s (n+6) " " + where + good = printf "Good \"%s\"\n" + bad s n = printf "Bad \"%s\"\n%*s^\n" s (n + 6) " " main :: IO () main = do let bs = cycle "[]" rs <- replicateM 10 newStdGen - zipWithM_ (\n r -> check $ shuffle (take n bs) r) [0,2..] rs + zipWithM_ (\n r -> check $ shuffle (take n bs) r) [0,2 ..] rs diff --git a/Task/Balanced-brackets/Haskell/balanced-brackets-2.hs b/Task/Balanced-brackets/Haskell/balanced-brackets-2.hs index d60d6fe8e7..4f0aaa36c0 100644 --- a/Task/Balanced-brackets/Haskell/balanced-brackets-2.hs +++ b/Task/Balanced-brackets/Haskell/balanced-brackets-2.hs @@ -1,4 +1,6 @@ -module VShuffle (shuffle) where +module VShuffle + ( shuffle + ) where import Data.List (mapAccumL) import System.Random @@ -7,14 +9,22 @@ import qualified Data.Vector as V import qualified Data.Vector.Generic.Mutable as M -- Generate a list of array index pairs, each corresponding to a swap. -pairs :: (Enum a, Random a, RandomGen g) => a -> a -> g -> [(a, a)] -pairs l u r = snd $ mapAccumL step r [l..pred u] - where step r i = let (j, r') = randomR (i, u) r in (r', (i, j)) +pairs + :: (Enum a, Random a, RandomGen g) + => a -> a -> g -> [(a, a)] +pairs l u r = snd $ mapAccumL step r [l .. pred u] + where + step r i = + let (j, r') = randomR (i, u) r + in (r', (i, j)) -- Return a random permutation of the list. We use the algorithm described in -- http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm. -shuffle :: (RandomGen g) => [a] -> g -> [a] -shuffle xs r = V.toList . runST $ do - v <- V.unsafeThaw $ V.fromList xs - mapM_ (uncurry $ M.swap v) $ pairs 0 (M.length v - 1) r - V.unsafeFreeze v +shuffle + :: (RandomGen g) + => [a] -> g -> [a] +shuffle xs r = + V.toList . runST $ + do v <- V.unsafeThaw $ V.fromList xs + mapM_ (uncurry $ M.swap v) $ pairs 0 (M.length v - 1) r + V.unsafeFreeze v diff --git a/Task/Balanced-brackets/JavaScript/balanced-brackets-2.js b/Task/Balanced-brackets/JavaScript/balanced-brackets-2.js index 6c8dc2cbe5..da0da94304 100644 --- a/Task/Balanced-brackets/JavaScript/balanced-brackets-2.js +++ b/Task/Balanced-brackets/JavaScript/balanced-brackets-2.js @@ -1,60 +1,56 @@ -(() => { - 'use strict'; +console.log("Supplied examples"); +var tests = ["", "[]", "][", "[][]", "][][", "[[][]]", "[]][[]"]; +for (var test of tests) +{ + console.log("The string '" + test + "' is " + + (isStringBalanced(test) ? "" : "not ") + "OK."); +} +console.log(); +console.log("Random generated examples"); +for (var example = 1; example <= 10; example++) +{ + var test = generate(Math.floor(Math.random() * 10) + 1); + console.log("The string '" + test + "' is " + + (isStringBalanced(test) ? "" : "not ") + "OK."); +} - // Int -> String - let randomBrackets = n => range(1, n) - .map(() => Math.random() < 0.5 ? '[' : ']') - .join(''); +function isStringBalanced(str) +{ + var paired = 0; + for (var i = 0; i < str.length && paired >= 0; i++) + { + var c = str[i]; + if (c == '[') + paired++; + else if (c == ']') + paired--; + } + return (paired == 0); +} - // imbalance :: String -> Integer - let imbalance = strBrackets => { - - // iDepth: initial nesting depth (0 = closed) - // iIndex: starting character position - - // errorIndex :: [Char] -> Int -> Int -> Int - let errorIndex = (xs, iDepth, iIndex) => { - if (xs.length > 0) { - let tail = xs.slice(1), - iNext = iDepth + (xs[0] === '[' ? 1 : -1); - - if (iNext < 0) return iIndex; // unmatched closing bracket - else return tail.length ? errorIndex( - tail, iNext, iIndex + 1 - ) : iNext === 0 ? -1 : iIndex; // balanced ? problem index ? - - } else return iDepth === 0 ? -1 : iIndex; - }; - - return errorIndex(strBrackets.split(''), 0, 0); - }; - - - // GENERIC FUNCTION - - // range :: Int -> Int -> [Int] - let range = (m, n) => - Array.from({ - length: Math.floor(n - m) + 1 - }, (_, i) => m + i); - - // TESTING AND FORMATTING OUTPUT - - let lngPairs = 6, - strPad = Array(lngPairs * 2 + 4) - .join(' '); - - return range(0, lngPairs) - .map(n => { - let w = n * 2, - s = randomBrackets(w), - i = imbalance(s), - blnOK = i === -1; - - return "'" + s + "'" + strPad.slice(w + 2) + - (blnOK ? 'OK' : 'problem') + - (blnOK ? '' : '\n' + Array(i + 2) - .join(' ') + '^'); - }) - .join('\n'); -})(); +function generate(n) +{ + var opensCount = 0, closesCount = 0; + // Choose at random until n of one type generated + var generated = ""; + while (opensCount < n && closesCount < n) + { + switch (Math.floor(Math.random() * 2) + 1) + { + case 1: + opensCount++; + generated += "["; + break; + case 2: + closesCount++; + generated += "]"; + break; + default: + break; + } + } + // Now pad with the remaining other brackets + generated += + opensCount == n ? "]".repeat(n - closesCount) : "[".repeat(n - opensCount); + return generated; +} diff --git a/Task/Balanced-brackets/JavaScript/balanced-brackets-3.js b/Task/Balanced-brackets/JavaScript/balanced-brackets-3.js new file mode 100644 index 0000000000..3deb90ab82 --- /dev/null +++ b/Task/Balanced-brackets/JavaScript/balanced-brackets-3.js @@ -0,0 +1,95 @@ +(() => { + 'use strict'; + + // findUnbalancedBracket :: String -> String -> Maybe Int + const findUnbalancedBracket = strBrackets => strHaystack => { + const + openBracket = strBrackets[0], + closeBracket = strBrackets[1]; + const go = (xs, iDepth, iCharPosn) => + // iDepth: initial nesting depth (0 = closed) + // iCharPosn: starting character position + 0 < xs.length ? (() => { + const + h = xs[0], + tail = xs.slice(1), + iNext = iDepth + ( + strBrackets.includes(h) ? ( + openBracket === h ? ( + 1 + ) : -1 + ) : 0 + ); + return 0 > iNext ? ( + Just(iCharPosn) // Unmatched closing bracket. + ) : 0 < tail.length ? go( + tail, iNext, 1 + iCharPosn + ) : 0 !== iNext ? ( + Just(iCharPosn) + ) : Nothing(); + })() : 0 !== iDepth ? ( + Just(iCharPosn) + ) : Nothing(); + return go(strHaystack.split(''), 0, 0); + }; + + + // TEST ----------------------------------------------- + // main :: IO () + const main = () => { + const + intPairs = 6, + strPad = ' '.repeat(4 + (2 * intPairs)); + console.log( + enumFromTo(0)(intPairs) + .map(pairCount => { + const + stringLength = 2 * pairCount, + strSample = randomBrackets(stringLength); + return "'" + strSample + "'" + + strPad.slice(2 + stringLength) + maybe('OK')( + iUnMatched => 'problem\n' + + ' '.repeat(1 + iUnMatched) + '^' + )( + findUnbalancedBracket('[]')(strSample) + ); + }).join('\n') + ); + }; + + // Int -> String + const randomBrackets = n => + enumFromTo(1)(n) + .map(() => Math.random() < 0.5 ? ( + '[' + ) : ']').join(''); + + + // GENERIC -------------------------------------------- + + // Just :: a -> Maybe a + const Just = x => ({ + type: 'Maybe', + Nothing: false, + Just: x + }); + + // Nothing :: Maybe a + const Nothing = () => ({ + type: 'Maybe', + Nothing: true, + }); + + // enumFromTo :: Int -> Int -> [Int] + const enumFromTo = m => n => + Array.from({ + length: 1 + n - m + }, (_, i) => m + i); + + // maybe :: b -> (a -> b) -> Maybe a -> b + const maybe = v => f => m => + m.Nothing ? v : f(m.Just); + + // --- + return main(); +})(); diff --git a/Task/Balanced-brackets/Julia/balanced-brackets-1.julia b/Task/Balanced-brackets/Julia/balanced-brackets-1.julia index 80b7e622b9..28da3ea495 100644 --- a/Task/Balanced-brackets/Julia/balanced-brackets-1.julia +++ b/Task/Balanced-brackets/Julia/balanced-brackets-1.julia @@ -1,3 +1,5 @@ +using Printf + function balancedbrackets(str::AbstractString) i = 0 for c in str diff --git a/Task/Balanced-brackets/X86-Assembly/balanced-brackets.x86 b/Task/Balanced-brackets/X86-Assembly/balanced-brackets-1.x86 similarity index 100% rename from Task/Balanced-brackets/X86-Assembly/balanced-brackets.x86 rename to Task/Balanced-brackets/X86-Assembly/balanced-brackets-1.x86 diff --git a/Task/Balanced-brackets/X86-Assembly/balanced-brackets-2.x86 b/Task/Balanced-brackets/X86-Assembly/balanced-brackets-2.x86 new file mode 100644 index 0000000000..32c6ed07ad --- /dev/null +++ b/Task/Balanced-brackets/X86-Assembly/balanced-brackets-2.x86 @@ -0,0 +1,98 @@ +PROGRAM "balancedbrackets" +VERSION "0.001" + +IMPORT "xst" + +DECLARE FUNCTION Entry() +INTERNAL FUNCTION IsStringBalanced(str$) +INTERNAL FUNCTION Generate$(n%%) + +' 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() + PRINT "Supplied examples" + DIM tests$[6] + tests$[0] = "" + tests$[1] = "[]" + tests$[2] = "][" + tests$[3] = "[][]" + tests$[4] = "][][" + tests$[5] = "[[][]]" + tests$[6] = "[]][[]" + FOR example@@ = 0 TO UBOUND(tests$[]) + test$ = tests$[example@@] + PRINT "The string '"; test$; "' is "; + IFT IsStringBalanced(test$) THEN + PRINT "OK." + ELSE + PRINT "not OK." + END IF + NEXT example@@ + PRINT + PRINT "Random generated examples" + XstGetSystemTime (@msec) + SRand(INT(msec) MOD 32768) + FOR example@@ = 1 TO 10 + test$ = Generate$(INT(Rand() / 32768.0 * 10.0) + 1) + PRINT "The string '"; test$; "' is "; + IFT IsStringBalanced(test$) THEN + PRINT "OK." + ELSE + PRINT "not OK." + END IF + NEXT example@@ +END FUNCTION + +FUNCTION IsStringBalanced(s$) + paired& = 0 + i%% = 1 + DO WHILE i%% <= LEN(s$) && paired& >= 0 + c$ = MID$(s$, i%%, 1) + SELECT CASE c$ + CASE "[": + INC paired& + CASE "]": + DEC paired& + END SELECT + INC i%% + LOOP +END FUNCTION (paired& = 0) + +FUNCTION Generate$(n%%) + opensCount%% = 0 + closesCount%% = 0 + ' Choose at random until n%% of one type generated + generated$ = "" + DO WHILE opensCount%% < n%% && closesCount%% < n%% + SELECT CASE (INT(Rand() / 32768.0 * 2.0) + 1) + CASE 1: + INC opensCount%% + generated$ = generated$ + "[" + CASE 2: + INC closesCount%% + generated$ = generated$ + "]" + END SELECT + LOOP + ' Now pad with the remaining other brackets + IF opensCount%% = n%% THEN + generated$ = generated$ + CHR$(']', n%% - closesCount%%) + ELSE + generated$ = generated$ + CHR$('[', n%% - opensCount%%) + END IF +END FUNCTION generated$ + +' 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/Balanced-ternary/C/balanced-ternary.c b/Task/Balanced-ternary/C/balanced-ternary.c new file mode 100644 index 0000000000..29bf1f9b1e --- /dev/null +++ b/Task/Balanced-ternary/C/balanced-ternary.c @@ -0,0 +1,202 @@ +#include +#include + +void reverse(char *p) { + size_t len = strlen(p); + char *r = p + len - 1; + while (p < r) { + *p ^= *r; + *r ^= *p; + *p++ ^= *r--; + } +} + +void to_bt(int n, char *b) { + static char d[] = { '0', '+', '-' }; + static int v[] = { 0, 1, -1 }; + + char *ptr = b; + *ptr = 0; + + while (n) { + int r = n % 3; + if (r < 0) { + r += 3; + } + + *ptr = d[r]; + *(++ptr) = 0; + + n -= v[r]; + n /= 3; + } + + reverse(b); +} + +int from_bt(const char *a) { + int n = 0; + + while (*a != '\0') { + n *= 3; + if (*a == '+') { + n++; + } else if (*a == '-') { + n--; + } + a++; + } + + return n; +} + +char last_char(char *ptr) { + char c; + + if (ptr == NULL || *ptr == '\0') { + return '\0'; + } + + while (*ptr != '\0') { + ptr++; + } + ptr--; + + c = *ptr; + *ptr = 0; + return c; +} + +void add(const char *b1, const char *b2, char *out) { + if (*b1 != '\0' && *b2 != '\0') { + char c1[16]; + char c2[16]; + char ob1[16]; + char ob2[16]; + char d[3] = { 0, 0, 0 }; + char L1, L2; + + strcpy(c1, b1); + strcpy(c2, b2); + L1 = last_char(c1); + L2 = last_char(c2); + if (L2 < L1) { + L2 ^= L1; + L1 ^= L2; + L2 ^= L1; + } + + if (L1 == '-') { + if (L2 == '0') { + d[0] = '-'; + } + if (L2 == '-') { + d[0] = '+'; + d[1] = '-'; + } + } + if (L1 == '+') { + if (L2 == '0') { + d[0] = '+'; + } + if (L2 == '-') { + d[0] = '0'; + } + if (L2 == '+') { + d[0] = '-'; + d[1] = '+'; + } + } + if (L1 == '0') { + if (L2 == '0') { + d[0] = '0'; + } + } + + add(c1, &d[1], ob1); + add(ob1, c2, ob2); + strcpy(out, ob2); + + d[1] = 0; + strcat(out, d); + } else if (*b1 != '\0') { + strcpy(out, b1); + } else if (*b2 != '\0') { + strcpy(out, b2); + } else { + *out = '\0'; + } +} + +void unary_minus(const char *b, char *out) { + while (*b != '\0') { + if (*b == '-') { + *out++ = '+'; + b++; + } else if (*b == '+') { + *out++ = '-'; + b++; + } else { + *out++ = *b++; + } + } + *out = '\0'; +} + +void subtract(const char *b1, const char *b2, char *out) { + char buf[16]; + unary_minus(b2, buf); + add(b1, buf, out); +} + +void mult(const char *b1, const char *b2, char *out) { + char r[16] = "0"; + char t[16]; + char c1[16]; + char c2[16]; + char *ptr = c2; + + strcpy(c1, b1); + strcpy(c2, b2); + + reverse(c2); + + while (*ptr != '\0') { + if (*ptr == '+') { + add(r, c1, t); + strcpy(r, t); + } + if (*ptr == '-') { + subtract(r, c1, t); + strcpy(r, t); + } + strcat(c1, "0"); + + ptr++; + } + + ptr = r; + while (*ptr == '0') { + ptr++; + } + strcpy(out, ptr); +} + +int main() { + const char *a = "+-0++0+"; + char b[16]; + const char *c = "+-++-"; + char t[16]; + char d[16]; + + to_bt(-436, b); + subtract(b, c, t); + mult(a, t, d); + + printf(" a: %14s %10d\n", a, from_bt(a)); + printf(" b: %14s %10d\n", b, from_bt(b)); + printf(" c: %14s %10d\n", c, from_bt(c)); + printf("a*(b-c): %14s %10d\n", d, from_bt(d)); + + return 0; +} diff --git a/Task/Balanced-ternary/REXX/balanced-ternary.rexx b/Task/Balanced-ternary/REXX/balanced-ternary.rexx index f8cb8afe85..87efa81fd1 100644 --- a/Task/Balanced-ternary/REXX/balanced-ternary.rexx +++ b/Task/Balanced-ternary/REXX/balanced-ternary.rexx @@ -10,43 +10,44 @@ Co = '+-++-' ; Cbt = Co ; @@ = 'balanced ternary =' call btShow '[a*(b-c)]', $bt exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -d2bt: procedure; parse arg x 1; p=0; $.='-'; $.1='+'; $.0=0; #= +d2bt: procedure; parse arg x 1; p= 0; $.= '-'; $.1= "+"; $.0= 0; #= x=x / 1 - do until x==0; _= (x // (3** (p+1) ) ) % 3**p - if _== 2 then _= -1; else if _== -2 then _=1 - x=x - _ * (3**p); p=p+1; #=$._ || # - end /*until*/; return # + do until x==0; _= (x // (3** (p+1) ) ) % 3**p + if _== 2 then _= -1 + else if _== -2 then _= 1 + x=x - _ * (3**p); p= p+1; #= $._ || # + end /*until*/; return # /*──────────────────────────────────────────────────────────────────────────────────────*/ -bt2d: procedure; parse arg x; r=reverse(x); #=0; $.=-1; $.0=0; _='+'; $._=1 - do j=1 for length(x); _=substr(r,j,1); #= # + $._ * 3**(j-1); end; return # +bt2d: procedure; parse arg x; r= reverse(x); #= 0; $.= -1; $.0= 0; _= '+'; $._= 1 + do j=1 for length(x); _= substr(r,j,1); #= # + $._ * 3**(j-1); end; return # /*──────────────────────────────────────────────────────────────────────────────────────*/ -btAdd: procedure; parse arg x,y; rx=reverse(x); ry=reverse(y); carry=0 - @.=0 ; _='-'; @._= -1; _="+"; @._=1 - $.='-'; $.0=0; $.1= '+' +btAdd: procedure; parse arg x,y; rx= reverse(x); ry= reverse(y); carry= 0 + @.=0 ; _= '-'; @._= -1; _= "+"; @._= 1 + $.= '-'; $.0= 0; $.1= '+' #=; do j=1 for max( length(x), length(y) ) - x_=substr(rx, j, 1); xn=@.x_ - y_=substr(ry, j, 1); yn=@.y_ - s=xn + yn + carry; carry= 0 + x_= substr(rx, j, 1); xn= @.x_ + y_= substr(ry, j, 1); yn= @.y_ + s= xn + yn + carry; carry= 0 if s== 2 then do; s=-1; carry= 1; end if s== 3 then do; s= 0; carry= 1; end if s==-2 then do; s= 1; carry=-1; end - #=$.s || # + #= $.s || # end /*j*/ - if carry\==0 then #=$.carry || #; return btNorm(#) + if carry\==0 then #= $.carry || #; return btNorm(#) /*──────────────────────────────────────────────────────────────────────────────────────*/ btMul: procedure; parse arg x 1 x1 2, y 1 y1 2; if x==0 | y==0 then return 0 - S=1; x=btNorm(x); y=btNorm(y) /*handle: 0-xxx values.*/ - if x1=='-' then do; x=btNeg(x); S=-S; end /*positate the number. */ - if y1=='-' then do; y=btNeg(y); S=-S; end /* " " " */ + S= 1; x= btNorm(x); y= btNorm(y) /*handle: 0-xxx values.*/ + if x1=='-' then do; x= btNeg(x); S=-S; end /*positate the number. */ + if y1=='-' then do; y= btNeg(y); S=-S; end /* " " " */ if length(y)>length(x) then parse value x y with y x /*optimize " " */ P=0 do until y==0 /*keep adding 'til done*/ - P=btAdd(P, x) /*multiple the hard way*/ - y=btSub(y, '+') /*subtract 1 from Y.*/ + P= btAdd(P, x) /*multiple the hard way*/ + y= btSub(y, '+') /*subtract 1 from Y.*/ end /*until*/ if S==-1 then P=btNeg(P); return P /*adjust the product sign; return. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ btNeg: return translate(arg(1), '-+', "+-") /*negate bal_ternary #.*/ -btNorm: _=strip(arg(1),'L',0); if _=='' then _=0; return _ /*normalize the number.*/ -btSub: return btAdd(arg(1), btNeg(arg(2))) /*subtract two BT args.*/ -btShow: say center(arg(1),9) right(arg(2),20) @@ right(bt2d(arg(2)),9) @; return +btNorm: _= strip(arg(1), 'L', 0); if _=='' then _=0; return _ /*normalize the number.*/ +btSub: return btAdd( arg(1), btNeg( arg(2) ) ) /*subtract two BT args.*/ +btShow: say center( arg(1), 9) right( arg(2), 20) @@ right( bt2d(arg(2)), 9) @; return diff --git a/Task/Balanced-ternary/Visual-Basic-.NET/balanced-ternary.visual b/Task/Balanced-ternary/Visual-Basic-.NET/balanced-ternary.visual new file mode 100644 index 0000000000..6d7faba802 --- /dev/null +++ b/Task/Balanced-ternary/Visual-Basic-.NET/balanced-ternary.visual @@ -0,0 +1,188 @@ +Imports System.Text + +Module Module1 + Sub Main() + Dim a As New BalancedTernary("+-0++0+") + Console.WriteLine("a: {0} = {1}", a, a.ToLong) + Dim b As New BalancedTernary(-436) + Console.WriteLine("b: {0} = {1}", b, b.ToLong) + Dim c As New BalancedTernary("+-++-") + Console.WriteLine("c: {0} = {1}", c, c.ToLong) + Dim d = a * (b - c) + Console.WriteLine("a * (b - c): {0} = {1}", d, d.ToLong) + End Sub + + Class BalancedTernary + Private Enum BalancedTernaryDigit + MINUS = -1 + ZERO = 0 + PLUS = 1 + End Enum + + Private ReadOnly value() As BalancedTernaryDigit + + ' empty = 0 + Public Sub New() + ReDim value(-1) + End Sub + + ' create from string + Public Sub New(str As String) + ReDim value(str.Length - 1) + For i = 1 To str.Length + If str(i - 1) = "-" Then + value(i - 1) = BalancedTernaryDigit.MINUS + ElseIf str(i - 1) = "0" Then + value(i - 1) = BalancedTernaryDigit.ZERO + ElseIf str(i - 1) = "+" Then + value(i - 1) = BalancedTernaryDigit.PLUS + Else + Throw New ArgumentException("Unknown Digit: " + str(i - 1)) + End If + Next + Array.Reverse(value) + End Sub + + ' convert integer + Public Sub New(l As Long) + Dim value As New List(Of BalancedTernaryDigit) + Dim sign = Math.Sign(l) + l = Math.Abs(l) + + While l <> 0 + Dim remainder = CType(l Mod 3, Byte) + If remainder = 0 OrElse remainder = 1 Then + value.Add(remainder) + l /= 3 + ElseIf remainder = 2 Then + value.Add(BalancedTernaryDigit.MINUS) + l = (l + 1) / 3 + End If + End While + + Me.value = value.ToArray + If sign < 0 Then + Invert() + End If + End Sub + + ' copy constructor + Public Sub New(origin As BalancedTernary) + ReDim value(origin.value.Length - 1) + Array.Copy(origin.value, value, origin.value.Length) + End Sub + + ' only for internal use + Private Sub New(value() As BalancedTernaryDigit) + Dim endi = value.Length - 1 + While endi > 0 AndAlso value(endi) = BalancedTernaryDigit.ZERO + endi -= 1 + End While + ReDim Me.value(endi) + Array.Copy(value, Me.value, endi + 1) + End Sub + + ' invert the values + Private Sub Invert() + For i = 1 To value.Length + value(i - 1) = CType(-CType(value(i - 1), Integer), BalancedTernaryDigit) + Next + End Sub + + ' convert to string + Public Overrides Function ToString() As String + Dim result As New StringBuilder + Dim i = value.Length - 1 + While i >= 0 + If value(i) = BalancedTernaryDigit.MINUS Then + result.Append("-") + ElseIf value(i) = BalancedTernaryDigit.ZERO Then + result.Append("0") + ElseIf value(i) = BalancedTernaryDigit.PLUS Then + result.Append("+") + End If + + i -= 1 + End While + Return result.ToString + End Function + + ' convert to long + Public Function ToLong() As Long + Dim result = 0L + For i = 1 To value.Length + result += value(i - 1) * Math.Pow(3.0, i - 1) + Next + Return result + End Function + + ' unary minus + Public Shared Operator -(origin As BalancedTernary) As BalancedTernary + Dim result As New BalancedTernary(origin) + result.Invert() + Return result + End Operator + + ' addition of digits + Private Shared carry = BalancedTernaryDigit.ZERO + Private Shared Function Add(a As BalancedTernaryDigit, b As BalancedTernaryDigit) As BalancedTernaryDigit + If a <> b Then + carry = BalancedTernaryDigit.ZERO + Return a + b + Else + carry = a + Return -CType(b, Integer) + End If + End Function + + ' addition of balanced ternary numbers + Public Shared Operator +(a As BalancedTernary, b As BalancedTernary) As BalancedTernary + Dim maxLength = Math.Max(a.value.Length, b.value.Length) + Dim resultValue(maxLength) As BalancedTernaryDigit + For i = 1 To maxLength + If i - 1 < a.value.Length Then + resultValue(i - 1) = Add(resultValue(i - 1), a.value(i - 1)) + resultValue(i) = carry + Else + carry = BalancedTernaryDigit.ZERO + End If + + If i - 1 < b.value.Length Then + resultValue(i - 1) = Add(resultValue(i - 1), b.value(i - 1)) + resultValue(i) = Add(resultValue(i), carry) + End If + Next + Return New BalancedTernary(resultValue) + End Operator + + ' subtraction of balanced ternary numbers + Public Shared Operator -(a As BalancedTernary, b As BalancedTernary) As BalancedTernary + Return a + (-b) + End Operator + + ' multiplication of balanced ternary numbers + Public Shared Operator *(a As BalancedTernary, b As BalancedTernary) As BalancedTernary + Dim longValue = a.value + Dim shortValue = b.value + Dim result As New BalancedTernary + + If a.value.Length < b.value.Length Then + longValue = b.value + shortValue = a.value + End If + + For i = 1 To shortValue.Length + If shortValue(i - 1) <> BalancedTernaryDigit.ZERO Then + Dim temp(i + longValue.Length - 2) As BalancedTernaryDigit + For j = 1 To longValue.Length + temp(i + j - 2) = CType(shortValue(i - 1) * longValue(j - 1), BalancedTernaryDigit) + Next + result += New BalancedTernary(temp) + End If + Next + + Return result + End Operator + End Class + +End Module diff --git a/Task/Benfords-law/JavaScript/benfords-law.js b/Task/Benfords-law/JavaScript/benfords-law.js new file mode 100644 index 0000000000..6ce2efab05 --- /dev/null +++ b/Task/Benfords-law/JavaScript/benfords-law.js @@ -0,0 +1,3 @@ +const fibseries = n => [...Array(n)].reduce((fib, _, i) => i < 2 ? fib : fib.concat(fib[i - 1]+fib[i - 2]), [1, 1]); +const benford = array => [1, 2, 3, 4, 5, 6, 7, 8, 9].map( val => [val, array.reduce((sum, item) => sum + (`${item}`[0] === `${val}`), 0) / array.length, Math.log10(1 + 1 / val)]); +console.log(benford(fibseries(1000))) diff --git a/Task/Benfords-law/REXX/benfords-law.rexx b/Task/Benfords-law/REXX/benfords-law.rexx index 702fc60645..b5291a293e 100644 --- a/Task/Benfords-law/REXX/benfords-law.rexx +++ b/Task/Benfords-law/REXX/benfords-law.rexx @@ -1,38 +1,33 @@ -/*REXX program demonstrates some common functions (thirty decimal digits are shown). */ -numeric digits length( e() ) - length(.) /*use the width of (e) for LN & LOG. */ +/*REXX pgm demonstrates Benford's law applied to 2 common functions (30 dec. digs used).*/ +numeric digits length( e() ) - length(.) /*width of (e) for LN & LOG precision.*/ parse arg N .; if N=='' | N=="," then N= 1000 /*allow sample size to be specified. */ -LN10= ln(10) /*calculate the natural log of ten #'s.*/ +pad= " " /*W1, W2: # digs past the decimal point*/ w1= max(2 + length('observed'), length(N-2) ) /*for aligning output for a number. */ w2= max(2 + length('expected'), length(N ) ) /* " " frequency distributions.*/ -pad= " " /*W1, W2: # digs past the decimal point*/ - do j=1 for 9; #.j=pad center( format( log( 1 + 1/j ), , length(N) + 2), w2) - end /*j*/ /* [↑] gen 9 frequencey coefficients.*/ -@.= 1 - do j=3 for N-2; a= j-1; b= a-1; @.j= @.a + @.b - end /*j*/ /* [↑] generate N Fibonacci numbers.*/ +LN10= ln(10) /*calculate the ln(10) {used by LOG}*/ +call coef /*generate nine frequency coefficients.*/ +call fib /*generate N Fibonacci numbers. */ call show "Benford's law applied to" N 'Fibonacci numbers' -@.= 1 - do j=2 for N-1; a= j-1; @.j= @.a * j - end /*j*/ /* [↑] generate N factorials. */ +call fact /*generate N factorials. */ call show "Benford's law applied to" N 'factorial products' exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ +coef: do j=1 for 9; #.j=pad center(format(log(1+1/j),,length(N)+2),w2); end; return +fact: @.=1; do j=2 for N-1; a= j-1; @.j= @.a * j; end; return +fib: @.=1; do j=3 for N-2; a= j-1; b= a-1; @.j= @.a + @.b; end; return e: return 2.71828182845904523536028747135266249775724709369995957496696762772407663035 -log: return ln( arg(1) ) / LN10 -ln: procedure; arg x; e=e(); _=e; ig= (x>1.5); is= 1 -2*(ig\=1); i=0; s=x; return .ln() +log: return ln( arg(1) ) / LN10 /*──────────────────────────────────────────────────────────────────────────────────────*/ -.ln: do while ig&s>1.5 | \ig&s<.5 - do k=-1; iz= s*_**-is; if k>=0 & (ig&iz<1 | \ig&iz>.5) then leave; _= _*_; izz=iz - end /*k*/ +ln: procedure; parse arg x; e= e(); _= e; ig= (x>1.5); is= 1 - 2 * (ig\=1); i= 0; s= x + do while ig&s>1.5 | \ig&s<.5 /*nitty─gritty part of LN calculation*/ + do k=-1; iz=s*_**-is; if k>=0&(ig&iz<1|\ig&iz>.5) then leave; _=_*_; izz=iz; end s=izz; i= i + is* 2**k; end /*while*/; x= x * e** - i - 1; z= 0; _= -1; p= z - do k=1; _= -_ * x; z= z + _/k; if z=p then leave; p=z; end /*k*/; return z+i + do k=1; _= -_ * x; z= z + _/k; if z=p then leave; p= z; end /*k*/; return z+i /*──────────────────────────────────────────────────────────────────────────────────────*/ show: say; say pad ' digit ' pad center("observed",w1) pad center('expected',w2) say pad '───────' pad center("", w1, '─') pad center("",w2,'─') pad arg(1) - !.=0; do j=1 for N; _= left(@.j, 1); !._= !._ + 1 /*get the 1st digit.*/ - end /*j*/ - - do f=1 for 9 /*show the results. */ - say pad center(f,7) pad center( format( !.f/N, , length(N-2)), w1) #.f - end /*k*/ + !.=0; do j=1 for N; _= left(@.j, 1); !._= !._ + 1 /*get the 1st digit.*/ + end /*j*/ + do f=1 for 9; say pad center(f,7) pad center(format(!.f/N,,length(N-2)),w1) #.f + end /*k*/ return diff --git a/Task/Bernoulli-numbers/Haskell/bernoulli-numbers-2.hs b/Task/Bernoulli-numbers/Haskell/bernoulli-numbers-2.hs index 136c1c5b49..2bc50e4718 100644 --- a/Task/Bernoulli-numbers/Haskell/bernoulli-numbers-2.hs +++ b/Task/Bernoulli-numbers/Haskell/bernoulli-numbers-2.hs @@ -1,5 +1,4 @@ import Data.Ratio (Ratio, numerator, denominator, (%)) -import Control.Applicative (liftA2) import Data.Bool (bool) bernouillis :: Integer -> [Rational] @@ -8,7 +7,6 @@ bernouillis = fmap head . tail . scanl faulhaber [] . enumFromTo 0 faulhaber :: [Ratio Integer] -> Integer -> [Ratio Integer] faulhaber rs n = (:) =<< (-) 1 . sum $ zipWith ((*) . (n %)) [2 ..] rs - -- TEST --------------------------------------------------- main :: IO () main = do @@ -22,18 +20,17 @@ main = do id (filter ((0 /=) . snd) $ zip [0 ..] xs) - -- FORMATTING --------------------------------------------- +fTable :: String -> (a -> String) -> (b -> String) -> (a -> b) -> [a] -> String +fTable s xShow fxShow f xs = + let w = maximum (length . xShow <$> xs) + in unlines $ + s : fmap (((++) . rjust w ' ' . xShow) <*> ((" -> " ++) . fxShow . f)) xs + showRatio :: Int -> Rational -> String showRatio w r = let d = denominator r in rjust w ' ' (show (numerator r)) ++ bool [] (" / " ++ show d) (1 /= d) -rjust n c = liftA2 drop length (replicate n c ++) - -fTable :: String -> (a -> String) -> (b -> String) -> (a -> b) -> [a] -> String -fTable s xShow fxShow f xs = - let w = maximum (length . xShow <$> xs) - rjust n c = liftA2 drop length (replicate n c ++) - in unlines $ - s : fmap (((++) . rjust w ' ' . xShow) <*> ((" -> " ++) . fxShow . f)) xs +rjust :: Int -> a -> [a] -> [a] +rjust n c = drop . length <*> (replicate n c ++) diff --git a/Task/Bernoulli-numbers/Julia/bernoulli-numbers.julia b/Task/Bernoulli-numbers/Julia/bernoulli-numbers.julia index 4c5e968d2d..f5ad9015c4 100644 --- a/Task/Bernoulli-numbers/Julia/bernoulli-numbers.julia +++ b/Task/Bernoulli-numbers/Julia/bernoulli-numbers.julia @@ -1,5 +1,5 @@ function bernoulli(n) - A = Vector{Rational{BigInt}}(n + 1) + A = Vector{Rational{BigInt}}(undef, n + 1) for m = 0 : n A[m + 1] = 1 // (m + 1) for j = m : -1 : 1 @@ -11,13 +11,13 @@ end function display(n) B = map(bernoulli, 0 : n) - pad = mapreduce(x -> ndigits(num(x)) + Int(x < 0), max, B) + pad = mapreduce(x -> ndigits(numerator(x)) + Int(x < 0), max, B) argdigits = ndigits(n) for i = 0 : n - if num(B[i + 1]) & 1 == 1 + if numerator(B[i + 1]) & 1 == 1 println( "B(", lpad(i, argdigits), ") = ", - lpad(num(B[i + 1]), pad), " / ", den(B[i + 1]) + lpad(numerator(B[i + 1]), pad), " / ", denominator(B[i + 1]) ) end end diff --git a/Task/Bernoulli-numbers/Lua/bernoulli-numbers.lua b/Task/Bernoulli-numbers/Lua/bernoulli-numbers.lua new file mode 100644 index 0000000000..dea3a9c583 --- /dev/null +++ b/Task/Bernoulli-numbers/Lua/bernoulli-numbers.lua @@ -0,0 +1,45 @@ +#!/usr/bin/env luajit +local gmp = require 'gmp' ('libgmp') +local ffi = require'ffi' +local mpz, mpq = gmp.types.z, gmp.types.q +local function mpq_for(buf, op, n) + for i=0,n-1 do + op(buf[i]) + end +end +local function bernoulli(rop, n) + local a=ffi.new("mpq_t[?]", n+1) + mpq_for(a, gmp.q_init, n+1) + + for m=0,n do + gmp.q_set_ui(a[m],1, m+1) + for j=m,1,-1 do + gmp.q_sub(a[j-1], a[j], a[j-1]) + gmp.q_set_ui(rop, j, 1) + gmp.q_mul(a[j-1], a[j-1], rop) + end + end + gmp.q_set(rop,a[0]) + mpq_for(a, gmp.q_clear, n+1) +end +do --MAIN + local rop=mpq() + local n,d=mpz(),mpz() + gmp.q_init(rop) + gmp.z_inits(n, d) + local to=arg[1] and tonumber(arg[1]) or 60 + local from=arg[2] and tonumber(arg[2]) or 0 + if from~=0 then to,from=from,to end + + + for i=from,to do + bernoulli(rop, i) + if gmp.q_cmp_ui(rop, 0, 1)~=0 then + gmp.q_get_num(n, rop) + gmp.q_get_den(d, rop) + gmp.printf("B(%-2g) = %44Zd / %Zd\n", i, n, d) + end + end + gmp.z_clears(n,d) + gmp.q_clear(rop) +end diff --git a/Task/Bernoulli-numbers/R/bernoulli-numbers.r b/Task/Bernoulli-numbers/R/bernoulli-numbers.r index 210b361f64..e6c84acce2 100644 --- a/Task/Bernoulli-numbers/R/bernoulli-numbers.r +++ b/Task/Bernoulli-numbers/R/bernoulli-numbers.r @@ -1,3 +1,8 @@ -# Bernoulli numbers. 12/8/16 aev -require(pracma) -bernoulli(60) +library(pracma) + +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 = "") +} diff --git a/Task/Bernoulli-numbers/Rust/bernoulli-numbers.rust b/Task/Bernoulli-numbers/Rust/bernoulli-numbers.rust index bfbfb5739d..6aa5e333a2 100644 --- a/Task/Bernoulli-numbers/Rust/bernoulli-numbers.rust +++ b/Task/Bernoulli-numbers/Rust/bernoulli-numbers.rust @@ -71,7 +71,7 @@ fn main() { let res = context.take(up_to + 1).collect::>(); let width = res.iter().fold(0, |a, r| max(a, r.value.numer().to_string().len())); - for r in res.iter().filter(|r| r.index % 2 == 0) { + for r in res.iter().filter(|r| *r.value.numer() != ToBigInt::to_bigint(&0).unwrap()) { println!("B({:>2}) = {:>2$} / {denom}", r.index, r.value.numer(), width, denom = r.value.denom()); } diff --git a/Task/Bernoulli-numbers/Sidef/bernoulli-numbers-1.sidef b/Task/Bernoulli-numbers/Sidef/bernoulli-numbers-1.sidef index 047958aa78..4b10bc3842 100644 --- a/Task/Bernoulli-numbers/Sidef/bernoulli-numbers-1.sidef +++ b/Task/Bernoulli-numbers/Sidef/bernoulli-numbers-1.sidef @@ -1,22 +1 @@ -func bernoulli_number{} - -func bern_helper(n, k) { - binomial(n, k) * (bernoulli_number(k) / (n - k + 1)) -} - -func bern_diff(n, k, d) { - n < k ? d : bern_diff(n, k + 1, d - bern_helper(n + 1, k)) -} - -bernoulli_number = func(n) is cached { - - n.is_one && return 1/2 - n.is_odd && return 0 - - n > 0 ? bern_diff(n - 1, 0, 1) : 1 -} - -for i (0..60) { - var num = bernoulli_number(i) || next - printf("B(%2d) = %44s / %s\n", i, num.nude) -} +say bernoulli(42).as_frac #=> 1520097643918070802691/1806 diff --git a/Task/Bernoulli-numbers/Sidef/bernoulli-numbers-2.sidef b/Task/Bernoulli-numbers/Sidef/bernoulli-numbers-2.sidef index 6f9cf93bfe..6fa35fd5dd 100644 --- a/Task/Bernoulli-numbers/Sidef/bernoulli-numbers-2.sidef +++ b/Task/Bernoulli-numbers/Sidef/bernoulli-numbers-2.sidef @@ -1,13 +1,14 @@ -func bernoulli_print { - var a = [] - for m (0..60) { - a.append(1/(m+1)) - for j (flip(1..m)) { - (a[j-1] -= a[j]) *= j - } - a[0] || next - printf("B(%2d) = %44s / %s\n", m, a[0].nude) - } +func bernoulli_number(n) is cached { + + n.is_one && return 1/2 + n.is_odd && return 0 + + 1 - sum(^n, {|k| + binomial(n,k) * __FUNC__(k) / (n - k + 1) + }) +} + +for n in (0..60) { + var Bn = bernoulli_number(n) || next + printf("B(%2d) = %44s / %s\n", n, Bn.nude) } -  -bernoulli_print() diff --git a/Task/Bernoulli-numbers/Sidef/bernoulli-numbers-3.sidef b/Task/Bernoulli-numbers/Sidef/bernoulli-numbers-3.sidef new file mode 100644 index 0000000000..a9519a919c --- /dev/null +++ b/Task/Bernoulli-numbers/Sidef/bernoulli-numbers-3.sidef @@ -0,0 +1,9 @@ +func ramanujan_bernoulli_number(n) is cached { + + return 1/2 if n.is_one + return 0 if n.is_odd + + ((n%6 == 4 ? -1/2 : 1) * (n+3)/3 - sum(1 .. (n - n%6)/6, {|k| + binomial(n+3, n - 6*k) * __FUNC__(n - 6*k) + })) / binomial(n+3, n) +} diff --git a/Task/Bernoulli-numbers/Sidef/bernoulli-numbers-4.sidef b/Task/Bernoulli-numbers/Sidef/bernoulli-numbers-4.sidef new file mode 100644 index 0000000000..7dff544d02 --- /dev/null +++ b/Task/Bernoulli-numbers/Sidef/bernoulli-numbers-4.sidef @@ -0,0 +1,15 @@ +func bernoulli_number_from_zeta(n) { + + n.is_zero && return 1 + n.is_one && return 1/2 + n.is_odd && return 0 + + var log2B = (log(4*Num.tau*n)/2 + n*log(n) - n*log(Num.tau) - n)/log(2) + local Num!PREC = *(int(n + log2B) + (n <= 90 ? 18 : 0)) + + var K = 2*(n! / Num.tau**n) + var d = n.divisors.grep {|k| is_prime(k+1) }.prod {|k| k+1 } + var z = ceil((K*d).root(n-1)).primes.prod {|p| 1 - p.float**(-n) } + + (-1)**(n/2 + 1) * int(ceil(d*K / z)) / d +} diff --git a/Task/Bernoulli-numbers/Sidef/bernoulli-numbers-5.sidef b/Task/Bernoulli-numbers/Sidef/bernoulli-numbers-5.sidef new file mode 100644 index 0000000000..7f1cf30b24 --- /dev/null +++ b/Task/Bernoulli-numbers/Sidef/bernoulli-numbers-5.sidef @@ -0,0 +1,13 @@ +func bernoulli_print { + var a = [] + for m in (0..60) { + a << 1/(m+1) + for j in (1..m -> flip) { + (a[j-1] -= a[j]) *= j + } + a[0] || next + printf("B(%2d) = %44s / %s\n", m, a[0].nude) + } +} +  +bernoulli_print() diff --git a/Task/Bernoulli-numbers/Swift/bernoulli-numbers.swift b/Task/Bernoulli-numbers/Swift/bernoulli-numbers.swift new file mode 100644 index 0000000000..b42ba87adc --- /dev/null +++ b/Task/Bernoulli-numbers/Swift/bernoulli-numbers.swift @@ -0,0 +1,29 @@ +import BigInt + +public func bernoulli(n: Int) -> Frac { + guard n != 0 else { + return 1 + } + + var arr = [Frac]() + + for m in 0...n { + arr.append(Frac(numerator: 1, denominator: T(m) + 1)) + + for j in stride(from: m, through: 1, by: -1) { + arr[j-1] = (arr[j-1] - arr[j]) * Frac(numerator: T(j), denominator: 1) + } + } + + return arr[0] +} + +for n in 0...60 { + let b = bernoulli(n: n) as Frac + + guard b != 0 else { + continue + } + + print("B(\(n)) = \(b)") +} diff --git a/Task/Best-shuffle/Elena/best-shuffle.elena b/Task/Best-shuffle/Elena/best-shuffle.elena index e06155442f..8e02a0f672 100644 --- a/Task/Best-shuffle/Elena/best-shuffle.elena +++ b/Task/Best-shuffle/Elena/best-shuffle.elena @@ -37,7 +37,7 @@ extension op public program() { - new string[]{"abracadabra", "seesaw", "grrrrrr", "pop", "up", "a"}.forEach:(s) + new::("abracadabra", "seesaw", "grrrrrr", "pop", "up", "a").forEach:(s) { var shuffled_s := s.Shuffled; diff --git a/Task/Binary-digits/Ada/binary-digits.ada b/Task/Binary-digits/Ada/binary-digits.ada index d52a5f315c..1248df864f 100644 --- a/Task/Binary-digits/Ada/binary-digits.ada +++ b/Task/Binary-digits/Ada/binary-digits.ada @@ -1,4 +1,4 @@ -wwith ada.text_io;use ada.text_io; +with ada.text_io; use ada.text_io; procedure binary is bit : array (0..1) of character := ('0','1'); diff --git a/Task/Binary-digits/Elena/binary-digits.elena b/Task/Binary-digits/Elena/binary-digits.elena index 8fdf161ca2..1859caecdd 100644 --- a/Task/Binary-digits/Elena/binary-digits.elena +++ b/Task/Binary-digits/Elena/binary-digits.elena @@ -3,7 +3,7 @@ import extensions; public program() { - new int[]{5,50,9000}.forEach:(n) + new int[]::(5,50,9000).forEach:(n) { console.printLine(n.toString(2)) } diff --git a/Task/Binary-digits/LOLCODE/binary-digits.lol b/Task/Binary-digits/LOLCODE/binary-digits.lol index 7ecb69754b..4c54d7fd9a 100644 --- a/Task/Binary-digits/LOLCODE/binary-digits.lol +++ b/Task/Binary-digits/LOLCODE/binary-digits.lol @@ -1,19 +1,16 @@ HAI 1.3 - -HOW IZ I binary YR num - I HAS A digit, I HAS A bin ITZ "" - IM IN YR binarizer - digit R MOD OF num AN 2 - bin R SMOOSH digit bin MKAY - num R QUOSHUNT OF num AN 2 - NOT num, O RLY? - YA RLY, FOUND YR bin - OIC - IM OUTTA YR binarizer +HOW IZ I DECIMULBINUR YR DECIMUL + I HAS A BINUR ITZ "" + IM IN YR DUUH + BOTH SAEM DECIMUL AN SMALLR OF DECIMUL AN 0, O RLY? + YA RLY, GTFO + OIC + BINUR R SMOOSH MOD OF DECIMUL AN 2 BINUR MKAY + DECIMUL R MAEK QUOSHUNT OF DECIMUL AN 2 A NUMBR + IM OUTTA YR DUUH + FOUND YR BINUR IF U SAY SO - -IM IN YR printer UPPIN YR num - VISIBLE I IZ binary YR num MKAY -IM OUTTA YR printer - +VISIBLE I IZ DECIMULBINUR YR 5 MKAY +VISIBLE I IZ DECIMULBINUR YR 50 MKAY +VISIBLE I IZ DECIMULBINUR YR 9000 MKAY KTHXBYE diff --git a/Task/Binary-search/Ol/binary-search.ol b/Task/Binary-search/Ol/binary-search.ol new file mode 100644 index 0000000000..f94936bed2 --- /dev/null +++ b/Task/Binary-search/Ol/binary-search.ol @@ -0,0 +1,15 @@ +(define (binary-search value vector) + (let helper ((low 0) + (high (- (vector-length vector) 1))) + (unless (< high low) + (let ((middle (quotient (+ low high) 2))) + (cond + ((> (vector-ref vector middle) value) + (helper low (- middle 1))) + ((< (vector-ref vector middle) value) + (helper (+ middle 1) high)) + (else middle)))))) + +(print + (binary-search 12 [1 2 3 4 5 6 7 8 9 10 11 12 13])) +; ==> 12 diff --git a/Task/Binary-strings/Perl/binary-strings.pl b/Task/Binary-strings/Perl/binary-strings.pl new file mode 100644 index 0000000000..a0be900699 --- /dev/null +++ b/Task/Binary-strings/Perl/binary-strings.pl @@ -0,0 +1,12 @@ +$s = undef; +say 'Nothing to see here' if ! defined $s; # 'Nothing to see here' +say $s = ''; # '' +say 'Empty string' if $s eq ''; # 'Empty string' +say $s = 'be'; # 'be' +say $t = $s; # 'be' +say 'Same' if $t eq $s; # 'Same' +say $t = $t .'e' # 'bee' +say $t .= 'keeper'; # 'beekeeper' +$t =~ s/ee/ook/; say $t; # 'bookkeeper' +say $u = substr $t, 2, 2; # 'ok' +say 'Oklahoma' . ' is ' . uc $u; # 'Oklahoma is OK' diff --git a/Task/Bitmap-Bresenhams-line-algorithm/C++/bitmap-bresenhams-line-algorithm.cpp b/Task/Bitmap-Bresenhams-line-algorithm/C++/bitmap-bresenhams-line-algorithm.cpp index 6b003863c6..8c40e9e83e 100644 --- a/Task/Bitmap-Bresenhams-line-algorithm/C++/bitmap-bresenhams-line-algorithm.cpp +++ b/Task/Bitmap-Bresenhams-line-algorithm/C++/bitmap-bresenhams-line-algorithm.cpp @@ -1,4 +1,4 @@ -void Line( const float x1, const float y1, const float x2, const float y2, const Color& color ) +void Line( float x1, float y1, float x2, float y2, const Color& color ) { // Bresenham's line algorithm const bool steep = (fabs(y2 - y1) > fabs(x2 - x1)); @@ -23,7 +23,7 @@ void Line( const float x1, const float y1, const float x2, const float y2, const const int maxX = (int)x2; - for(int x=(int)x1; x 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 + } +} + +sub load-ppm ( $ppm ) { + my $fh = $ppm.IO.open( :enc('ISO-8859-1') ); + my $type = $fh.get; + my ($width, $height) = $fh.get.split: ' '; + my $depth = $fh.get; + Bitmap.new( width => $width.Int, height => $height.Int, + data => ( $fh.slurp.ords.rotor(3).map: + { Pixel.new(R => $_[0], G => $_[1], B => $_[2]) } ) + ) +} + +sub color-distance (Pixel $c1, Pixel $c2) { + sqrt( ( ($c1.R - $c2.R)² + ($c1.G - $c2.G)² + ($c1.B - $c2.B)² ) / ( 255 * sqrt(3) ) ); +} + +sub flood ($img, $x, $y, $c1) { + my $c2 = $img.pixel($x, $y); + my $max-distance = 10; + my @queue; + my %checked; + check($x, $y); + for @queue -> [$x, $y] { + $img.pixel($x, $y) = $c1.clone; + } + + sub check ($x, $y) { + my $c3 = $img.pixel($x, $y); + + if color-distance($c2, $c3) < $max-distance { + @queue.push: [$x,$y]; + @queue.elems; + %checked{"$x,$y"} = 1; + check($x - 1, $y) if $x > 0 and %checked{"{$x - 1},$y"}:!exists; + check($x + 1, $y) if $x < $img.width - 1 and %checked{"{$x + 1},$y"}:!exists; + check($x, $y - 1) if $y > 0 and %checked{"$x,{$y - 1}"}:!exists; + check($x, $y + 1) if $y < $img.height - 1 and %checked{"$x,{$y + 1}"}:!exists; + } + } +} + +my $infile = './Unfilled-Circle.ppm'; + +my Bitmap $b = load-ppm( $infile ) but PPM; + +flood($b, 5, 5, Pixel.new(:255R, :0G, :0B)); +flood($b, 5, 125, Pixel.new(:255R, :0G, :0B)); +flood($b, 125, 5, Pixel.new(:255R, :0G, :0B)); +flood($b, 125, 125, Pixel.new(:255R, :0G, :0B)); +flood($b, 50, 50, Pixel.new(:0R, :0G, :255B)); + +my $outfile = open('./Bitmap-flood-perl6.ppm', :w, :bin); + +$outfile.write: $b.P6; diff --git a/Task/Bitmap-Flood-fill/REXX/bitmap-flood-fill.rexx b/Task/Bitmap-Flood-fill/REXX/bitmap-flood-fill.rexx index 33cfd4d82f..8b9eed5f89 100644 --- a/Task/Bitmap-Flood-fill/REXX/bitmap-flood-fill.rexx +++ b/Task/Bitmap-Flood-fill/REXX/bitmap-flood-fill.rexx @@ -4,22 +4,22 @@ red = '000000000000000011111111'b /* " " red " " green= '000000001111111100000000'b /* " " green " " " */ white= '111111111111111111111111'b /* " " white " " " */ /*image is defined to the test image. */ -hx=125; hy=125 /*define limits (X,Y) for the image. */ -area=white; call fill 125, 25, red /*fill the white area in red. */ -area=black; call fill 125, 125, green /*fill the center orb in green. */ +hx= 125; hy= 125 /*define limits (X,Y) for the image. */ +area= white; call fill 125, 25, red /*fill the white area in red. */ +area= black; call fill 125, 125, green /*fill the center orb in green. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ fill: procedure expose image. hx hy area; parse arg x,y,fill_color /*obtain the args.*/ if x<1 | x>hx | y<1 | y>hy then return /*X or Y are outside of the image area*/ - pixel=image.x.y /*obtain the color of the X,Y pixel. */ - if pixel\==area then return /*the pixel has already been filled */ + pixel= image.x.y /*obtain the color of the X,Y pixel. */ + if pixel \== area then return /*the pixel has already been filled */ /*with the fill_color, or we are not */ /*within the area to be filled. */ - image.x.y=fill_color /*color desired area with fill_color. */ - pixel=@(x , y-1); if pixel==area then call fill x , y-1, fill_color /*north*/ - pixel=@(x-1, y ); if pixel==area then call fill x-1, y , fill_color /*west */ - pixel=@(x+1, y ); if pixel==area then call fill x+1, y , fill_color /*east */ - pixel=@(x , y+1); if pixel==area then call fill x , y+1, fill_color /*south*/ + image.x.y= fill_color /*color desired area with fill_color. */ + pixel= @(x , y-1); if pixel==area then call fill x , y-1, fill_color /*north*/ + pixel= @(x-1, y ); if pixel==area then call fill x-1, y , fill_color /*west */ + pixel= @(x+1, y ); if pixel==area then call fill x+1, y , fill_color /*east */ + pixel= @(x , y+1); if pixel==area then call fill x , y+1, fill_color /*south*/ return /*──────────────────────────────────────────────────────────────────────────────────────*/ @: parse arg $x,$y; return image.$x.$y /*return with color of the X,Y pixel.*/ 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 new file mode 100644 index 0000000000..62077b718a --- /dev/null +++ b/Task/Bitmap-Write-a-PPM-file/Stata/bitmap-write-a-ppm-file.stata @@ -0,0 +1,20 @@ +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) +} + +r = J(1, 6, (0::5) * 51) +g = J(6, 1, (0..5) * 51) +b = J(6, 6, 255) +writeppm("image.ppm", r, g, b) +end diff --git a/Task/Bitmap/Processing/bitmap b/Task/Bitmap/Processing/bitmap new file mode 100644 index 0000000000..2d87edf245 --- /dev/null +++ b/Task/Bitmap/Processing/bitmap @@ -0,0 +1,9 @@ +PGraphics bitmap = createGraphics(100,100); // Create the bitmap +bitmap.beginDraw(); +bitmap.background(255, 0, 0); // Fill bitmap with red rgb color +bitmap.endDraw(); +image(bitmap, 0, 0); // Place bitmap on screen. +color b = color(0, 0, 255); // Define a blue rgb color +set(50, 50, b); // Set blue colored pixel in the middle of the screen +color c = get(50, 50); // Get the color of same pixel +if(b == c) print("Color changed correctly"); // Verify diff --git a/Task/Bitmap/REXX/bitmap-1.rexx b/Task/Bitmap/REXX/bitmap-1.rexx index ff5b039b32..d9f841ebe1 100644 --- a/Task/Bitmap/REXX/bitmap-1.rexx +++ b/Task/Bitmap/REXX/bitmap-1.rexx @@ -1,10 +1,11 @@ /*REXX program demonstrates how to process/display a simple RGB raster graphics image.*/ -red = '00000000 00000000 11111111'b /*define a red value. */ -blue = '11111111 00000000 00000000'b /* " " blue " */ -blue = 'ff 00 00'x /*another way to define a blue value.*/ +red = 'ff 00 00'x /*a method to define a red value. */ +blue = '00 00 ff'x /*" " " " " blue " */ @. = /*define entire @. array to nulls. */ - x=10; y=40 /*set pixel's coördinates. */ +outFN = 'image' /*the filename of the output image PPM */ +sWidth = 500; sHeight= 500 /*the screen width and height in pixels*/ call RGBfill red /*set the entire image to red. */ + x= 10; y= 40 /*set pixel's coördinates. */ call RGBset x, y, blue /*set a pixel (at 10,40) to blue. */ color = RGBget(x, y) /*get the color of a pixel. */ hexV = c2x(color) /*get hex value of pixel's color. */ @@ -17,9 +18,9 @@ say xy ' pixel in binary: ' bin3V /*show again, but with spaces. say /*show a blank between binary and hex. */ say xy ' pixel in hex: ' hexV /*show again, but in hexadecimal. */ say xy ' pixel in hex: ' hex3V /*show again, but with spaces. */ -call PPMwrite 'image', 500, 500 /*create a PPM (output) file of image. */ /* ◄■■■■■■■■ not part of this task.*/ +call PPMwrite outFN, sWidth, sHeight /*create a PPM (output) file of image. */ /* ◄■■■■■■■■ not part of this task.*/ say /*show a blank. */ -say 'The file image.PPM was created.' /*inform user that a file was created. */ +say 'The file ' outFN".PPM was created." /*inform user that a file was created. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ RGBfill: @.=arg(1); return /*fill image with a color.*/ diff --git a/Task/Bitwise-IO/Red/bitwise-io.red b/Task/Bitwise-IO/Red/bitwise-io.red new file mode 100644 index 0000000000..6b6b9d0e28 --- /dev/null +++ b/Task/Bitwise-IO/Red/bitwise-io.red @@ -0,0 +1,58 @@ +Red [ + Title: "Bitwise IO" + Link: http://rosettacode.org/wiki/Bitwise_IO + Source: https://github.com/vazub/rosetta-red + File: "%bitwiseio.red" + Rights: "Copyright (C) 2020 Vasyl Zubko. All rights reserved." + License: "Blue Oak Model License - https://blueoakcouncil.org/license/1.0.0" + Tabs: 4 +] + +str-compress: function [ + "Compressesor" + str [string!] +][ + buf: copy "" + bit-str: enbase/base str 2 + foreach [bit1 bit2 bit3 bit4 bit5 bit6 bit7 bit8] bit-str [ + append buf rejoin [bit2 bit3 bit4 bit5 bit6 bit7 bit8] + ] + if (pad-bits: (length? buf) // 8) <> 0 [ + loop (8 - pad-bits) [append buf "0"] + ] + debase/base buf 2 +] + +str-expand: function [ + "Decompressor" + bin-hex [binary!] +][ + bit-str: enbase/base bin-hex 2 + filled: 0 + buf: copy [] + acc: copy "" + foreach bit bit-str [ + append acc bit + filled: filled + 1 + if filled = 7 [ + append buf debase/base rejoin ["0" acc] 2 + clear acc + filled: 0 + ] + ] + if (last buf) = #{00} [take/last buf] + rejoin buf +] + +; DEMO +in-string: "Red forever!" +compressed: str-compress in-string +expanded: str-expand compressed +prin [ + pad "Input (string): " 20 mold in-string newline newline + pad "Input (bits): " 20 enbase/base in-string 2 newline + pad "Compressed (bits): " 20 enbase/base compressed 2 newline newline + pad "Input (hex): " 20 to-binary in-string newline + pad "Compressed (hex): " 20 compressed newline newline + pad "Expanded (string): " 20 mold to-string expanded +] diff --git a/Task/Bitwise-operations/Harbour/bitwise-operations.harbour b/Task/Bitwise-operations/Harbour/bitwise-operations.harbour new file mode 100644 index 0000000000..c9d16a3c96 --- /dev/null +++ b/Task/Bitwise-operations/Harbour/bitwise-operations.harbour @@ -0,0 +1,42 @@ +PROCEDURE Main(...) + local n1 := 42, n2 := 2 + local aPar := hb_AParams() + local nRot + + if ! Empty( aPar ) + n1 := Val( aPar[1] ) + hb_Adel( aPar, 1, .T. ) + if ! Empty( aPar ) + n2 := Val( aPar[1] ) + endif + endif + clear screen + + ? "Bitwise operations with two integers" + ? "n1 =", hb_ntos(n1) + ? "n2 =", hb_ntos(n2) + ? "------------------------------------" + ? "AND -->", hb_BitAnd( n1, n2 ) + ? "OR -->", hb_BitOr( n1, n2 ) + ? "XOR -->", hb_BitXor( n1, n2 ) + ? "NOT -->", hb_BitNot( n1 ) + ? "LSHIFT -->", hb_bitShift( n1, n2 ) + ? "RSHIFT -->", hb_bitShift( n1, -n2 ) + ? "RarSHIFT -->", hb_bitShift( n1, -n2 ) + + /* left/right rotation is not implemented, but we can use inline C-code to do it */ + /* rotate n1 to the left by n2 bits */ + nRot := hb_Inline( n1, n2 ) { + HB_UINT x = hb_parni( 1 ), s = hb_parni( 2 ); + hb_retni( (x << s) | (x >> (-s & 31)) ); + } // (x << s) | (x >> (32 - s)); + ? "Rotate left -->", nRot + + /* rotate n1 to the right by n2 bits */ + nRot := HB_INLINE( n1, n2 ){ + HB_UINT x = hb_parni( 1 ), s = hb_parni( 2 ); + hb_retni( (x >> s) | (x << (32 - s)) ); + } + ? "Rotate right -->", nRot + + return diff --git a/Task/Bitwise-operations/Pike/bitwise-operations.pike b/Task/Bitwise-operations/Pike/bitwise-operations.pike new file mode 100644 index 0000000000..50041d6c58 --- /dev/null +++ b/Task/Bitwise-operations/Pike/bitwise-operations.pike @@ -0,0 +1,18 @@ +void bitwise(int a, int b) +{ + write("a and b: %d\n", a & b); + write("a or b: %d\n", a | b); + write("a xor b: %d\n", a ^ b); + write("not a: %d\n", ~a); + write("a << b: 0x%x\n", a << b); + write("a >> b: %d\n", a >> b); + // ints in Pike do not overflow, if a particular size of the int + // is desired then cap it with an AND operation + write("a << b & 0xffffffff (32bit cap): 0x%x\n", + a << b & 0xffffffff); +} + +void main() +{ + bitwise(255, 30); +} diff --git a/Task/Bitwise-operations/Red/bitwise-operations.red b/Task/Bitwise-operations/Red/bitwise-operations.red new file mode 100644 index 0000000000..c56e711635 --- /dev/null +++ b/Task/Bitwise-operations/Red/bitwise-operations.red @@ -0,0 +1,17 @@ +Red [Source: https://github.com/vazub/rosetta-red] + +a: 10 +b: 2 + +print [ + pad "a =" 10 a newline + pad "b =" 10 b newline + pad "a AND b:" 10 a and b newline + pad "a OR b:" 10 a or b newline + pad "a XOR b:" 10 a xor b newline + pad "NOT a:" 10 complement a newline + pad "a >>> b:" 10 a >>> b newline + pad "a >> b:" 10 a >> b newline + pad "a << b:" 10 a << b newline + ; there are no circular shift operators in Red +] diff --git a/Task/Boolean-values/Go/boolean-values.go b/Task/Boolean-values/Go/boolean-values.go new file mode 100644 index 0000000000..cabd217b49 --- /dev/null +++ b/Task/Boolean-values/Go/boolean-values.go @@ -0,0 +1,26 @@ +package main + +import ( + "fmt" + "reflect" + "strconv" +) + +func main() { + var n bool = true + fmt.Println(n) // prt true + fmt.Printf("%T\n", n) // prt bool + n = !n + fmt.Println(n) // prt false + + x := 5 + y := 8 + fmt.Println("x == y:", x == y) // prt x == y: false + fmt.Println("x < y:", x < y) // prt x < y: true + + fmt.Println("\nConvert String into Boolean Data type\n") + str1 := "japan" + fmt.Println("Before :", reflect.TypeOf(str1)) // prt Before : string + bolStr, _ := strconv.ParseBool(str1) + fmt.Println("After :", reflect.TypeOf(bolStr)) // prt After : bool +} diff --git a/Task/Box-the-compass/Factor/box-the-compass.factor b/Task/Box-the-compass/Factor/box-the-compass.factor new file mode 100644 index 0000000000..d7fd0ba2cc --- /dev/null +++ b/Task/Box-the-compass/Factor/box-the-compass.factor @@ -0,0 +1,27 @@ +USING: formatting kernel math sequences ; + +CONSTANT: 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" + "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" +} + +{ + 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 +} + +[ + dup 32 * 360 /f 0.5 + >integer 32 mod [ 1 + ] [ box nth ] bi + "%6.2f° %2d %s\n" printf +] each diff --git a/Task/Box-the-compass/Julia/box-the-compass.julia b/Task/Box-the-compass/Julia/box-the-compass.julia index cd46704eef..e1d8317807 100644 --- a/Task/Box-the-compass/Julia/box-the-compass.julia +++ b/Task/Box-the-compass/Julia/box-the-compass.julia @@ -1,23 +1,23 @@ -function degree2compasspoint(d::Float64)::String - majors = ("north", "east", "south", "ovest", "north", "east", "south", "ovest") - quart1 = ("N", "N by E", "N-NE", "NE by N", "NE", "NE by E", "E-NE", "E by N") +using Printf - d = (d % 360) + 360/64 - majorindex, minor = divrem(d, 90) - minorindex = div(minor * 4, 45) - majorindex += 1 - minorindex += 1 - p1, p2 = majors[majorindex:majorindex+1] - if p1 in ("north", "south"); q = quart1 - else q = quart1 end - return titlecase(replace(replace(q[minorindex], 'N', p1), 'E', p2)) +function degree2compasspoint(d::Float64) + majors = ("north", "east", "south", "west", "north", "east", "south", "west") + quarter1 = ("N", "N by E", "N-NE", "NE by N", "NE", "NE by E", "E-NE", "E by N") + quarter2 = map(p -> replace(p, "NE" => "EN"), quarter1) + + d = d % 360 + 360 / 64 + imajor, minor = divrem(d, 90) + iminor = div(minor * 4, 45) + imajor += 1 + iminor += 1 + p1, p2 = majors[imajor:imajor+1] + q = p1 in ("north", "south") ? quarter1 : quarter2 + titlecase(replace(replace(q[iminor], 'N' => p1), 'E' => p2)) end for i in 0:32 d = i * 11.25 - m = i % 3 - if m == 1; d += 5.62 end - if m == 2; d -= 5.62 end - n = i % 32 + 1 - @printf("%2i %-17s %10.2f°\n", n, degree2compasspoint(d), d) + i % 3 == 1 && (d += 5.62) + i % 3 == 2 && (d -= 5.62) + @printf("%2i %-17s %10.2f°\n", i % 32 + 1, degree2compasspoint(d), d) end diff --git a/Task/Box-the-compass/Nim/box-the-compass.nim b/Task/Box-the-compass/Nim/box-the-compass.nim index 2bea7f535c..71bd34acc6 100644 --- a/Task/Box-the-compass/Nim/box-the-compass.nim +++ b/Task/Box-the-compass/Nim/box-the-compass.nim @@ -1,18 +1,30 @@ -import strfmt +import math, sequtils, strformat, strutils -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 + headingNames: array[1..32, string] = [ + "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"] + maxNameLength = headingNames.mapIt(it.len).max + degreesPerHeading = 360 / 32 + +func toCompassIndex(degree: float): 1..32 = + var degree = (degree + degreesPerHeading / 2).floorMod 360 + int(degree / degreesPerHeading) + 1 + +func toCompassHeading(degree: float): string = headingNames[degree.toCompassIndex] for i in 0..32: - let j = i mod 32 - var d = float(i) * 11.25 - if i mod 3 == 1: d += 5.62 - if i mod 3 == 2: d -= 5.62 - printlnfmt "{:2} {:18} {:>6.2f}", j + 1, names[j], d + let + heading = float(i) * 11.25 + (case i mod 3 + of 1: 5.62 + of 2: -5.62 + else: 0) + index = heading.toCompassIndex + compassHeading = heading.toCompassHeading.alignLeft(maxNameLength) + echo fmt"{index:>2} {compassHeading} {heading:6.2f}" diff --git a/Task/Box-the-compass/UNIX-Shell/box-the-compass.sh b/Task/Box-the-compass/UNIX-Shell/box-the-compass.sh index d2f37885b5..4f590f4199 100644 --- a/Task/Box-the-compass/UNIX-Shell/box-the-compass.sh +++ b/Task/Box-the-compass/UNIX-Shell/box-the-compass.sh @@ -11,18 +11,16 @@ test_angles=( 0.00 16.87 16.88 33.75 50.62 50.63 67.50 236.25 253.12 253.13 270.00 286.87 286.88 303.75 320.62 320.63 337.50 354.37 354.38 ) - -# capitalize a string -function capitalize { - echo "$1" | sed 's/^./\U&/' +capitalize() { + printf '%s%s\n' "$(tr a-z A-Z <<<"${1:0:1}")" "${1:1}" } # convert compass point abbreviation to full text of label function expand_point { - local label="$1" + local label=$1 set -- N north E east S south W west b " by " while (( $# )); do - label="${label//$1/$2}" + label=${label//$1/$2} shift 2 done capitalize "$label" @@ -35,6 +33,7 @@ function amod { # convert a compass angle from degrees into a box index (1..32) function compass_point { + # use bc or dc depending on what's on the system #amod $(dc <<<"$1 5.625 + 11.25 / 1 + p") 32 amod $(bc <<<"($1 + 5.625) / 11.25 + 1") 32 } diff --git a/Task/Break-OO-privacy/00DESCRIPTION b/Task/Break-OO-privacy/00DESCRIPTION index b71d448914..1da952f4ec 100644 --- a/Task/Break-OO-privacy/00DESCRIPTION +++ b/Task/Break-OO-privacy/00DESCRIPTION @@ -8,6 +8,7 @@ {{omit from|Locomotive Basic}} {{omit from|Lotus 123 Macro Scripting}} {{omit from|Mathematica}} +{{omit from|R}} {{omit from|Rust}} {{omit from|SmileBASIC}} {{omit from|ZX Spectrum Basic}} diff --git a/Task/Brownian-tree/Ada/brownian-tree.ada b/Task/Brownian-tree/Ada/brownian-tree.ada new file mode 100644 index 0000000000..fb12999349 --- /dev/null +++ b/Task/Brownian-tree/Ada/brownian-tree.ada @@ -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/Bulls-and-cows-Player/Factor/bulls-and-cows-player.factor b/Task/Bulls-and-cows-Player/Factor/bulls-and-cows-player.factor new file mode 100644 index 0000000000..7cab0a7485 --- /dev/null +++ b/Task/Bulls-and-cows-Player/Factor/bulls-and-cows-player.factor @@ -0,0 +1,27 @@ +USING: arrays combinators.short-circuit formatting fry io kernel +math math.combinatorics math.functions math.order math.parser +math.ranges random regexp sequences sets splitting ; + +: bulls ( seq1 seq2 -- n ) [ = 1 0 ? ] 2map sum ; +: cows ( seq1 seq2 -- n ) [ intersect length ] [ bulls - ] 2bi ; +: score ( seq1 seq2 -- pair ) [ bulls ] [ cows 2array ] 2bi ; +: possibilities ( -- seq ) 9 [1,b] 4 ; +: pare ( seq guess score -- new-seq ) '[ _ score _ = ] filter ; +: >number ( seq -- n ) reverse [ 10^ * ] map-index sum ; +: >score ( str -- pair ) "," split [ string>number ] map ; +: ask ( n -- ) "My guess is %d. How many bulls, cows? " printf ; + +: valid-input? ( str -- ? ) + { [ R/ \d,\d/ matches? ] [ >score sum 0 4 between? ] } 1&& ; + +: get-score ( n -- pair ) + [ ask ] keep flush readln dup valid-input? + [ nip >score ] [ drop get-score ] if ; + +: game ( seq -- ) + dup random [ + dup >number get-score dup first 4 = + [ 3drop "Success!" print ] [ pare game ] if + ] [ drop "Scoring inconsistency." print ] if* ; + +possibilities game diff --git a/Task/Bulls-and-cows-Player/Java/bulls-and-cows-player-1.java b/Task/Bulls-and-cows-Player/Java/bulls-and-cows-player-1.java new file mode 100644 index 0000000000..4b478f99b8 --- /dev/null +++ b/Task/Bulls-and-cows-Player/Java/bulls-and-cows-player-1.java @@ -0,0 +1,80 @@ +public class BullsAndCowsPlayerGame { + + private static int count; + private static Console io = System.console(); + + private final GameNumber secret; + private List pool = new ArrayList<>(); + + public BullsAndCowsPlayerGame(GameNumber secret) { + this.secret = secret; + fillPool(); + } + + private void fillPool() { + for (int i = 123; i < 9877; i++) { + int[] arr = AutoGuessNumber.parseDigits(i, 4); + + if (GameNumber.isGuess(arr)) { + pool.add(new AutoGuessNumber(i, 4)); + } + } + } + + public void play() { + io.printf("Bulls and Cows%n"); + io.printf("==============%n"); + io.printf("Secret number is %s%n", secret); + + do { + AutoGuessNumber guess = guessNumber(); + io.printf("Guess #%d is %s from %d%n", count, guess, pool.size()); + + GuessResult result = secret.match(guess); + if (result != null) { + printScore(io, result); + + if (result.isWin()) { + io.printf("The answer is %s%n", guess); + break; + } + + clearPool(guess, result); + } else { + io.printf("No more variants%n"); + System.exit(0); + } + } while (true); + } + + private AutoGuessNumber guessNumber() { + Random random = new Random(); + if (pool.size() > 0) { + int number = random.nextInt(pool.size()); + count++; + return pool.get(number); + } + return null; + } + + private static void printScore(Console io, GuessResult result) { + io.printf("%1$d %2$d%n", result.getBulls(), result.getCows()); + } + + private void clearPool(AutoGuessNumber guess, GuessResult guessResult) { + pool.remove(guess); + + for (int i = 0; i < pool.size(); i++) { + AutoGuessNumber g = pool.get(i); + GuessResult gr = guess.match(g); + + if (!guessResult.equals(gr)) { + pool.remove(g); + } + } + } + + public static void main(String[] args) { + new BullsAndCowsPlayerGame(new GameNumber()).play(); + } +} diff --git a/Task/Bulls-and-cows-Player/Java/bulls-and-cows-player-2.java b/Task/Bulls-and-cows-Player/Java/bulls-and-cows-player-2.java new file mode 100644 index 0000000000..9485afea22 --- /dev/null +++ b/Task/Bulls-and-cows-Player/Java/bulls-and-cows-player-2.java @@ -0,0 +1,39 @@ +public abstract class AbstractGuessNumber { + + protected int[] digits; + private int length; + + public AbstractGuessNumber(int length) { + this.length = length; + this.digits = new int[this.length]; + } + + public int[] getDigits() { + return digits; + } + + public int getLength() { + return length; + } + + public GuessResult match(AbstractGuessNumber guessable) { + int bulls = 0; + int cows = 0; + + if (guessable != null) { + for (int i = 0; i < this.getLength(); i++) { + for (int j = 0; j < guessable.getLength(); j++) { + + if (digits[i] == guessable.getDigits()[j]) { + if (i == j) { + bulls++; + } else { + cows++; + } + } + } + } + } + return new GuessResult(getLength(), bulls, cows); + } +} diff --git a/Task/Bulls-and-cows-Player/Java/bulls-and-cows-player-3.java b/Task/Bulls-and-cows-Player/Java/bulls-and-cows-player-3.java new file mode 100644 index 0000000000..f3e6523c6e --- /dev/null +++ b/Task/Bulls-and-cows-Player/Java/bulls-and-cows-player-3.java @@ -0,0 +1,69 @@ +public class GameNumber extends AbstractGuessNumber { + + public GameNumber() { + super(4); + defineNumber(); + } + + public static boolean isGuess(int[] digits) { + return (digits != null && isUnique(digits) && isAllDigits(digits)); + } + + protected static boolean isAllDigits(int[] array) { + for (int i = 0; i < array.length; i++) { + char digit = (char) (array[i] + '0'); + + if (!Character.isDigit(digit)) { + return false; + } + } + return true; + } + + protected static boolean isUnique(int[] array) { + for (int j = 0; j < array.length; j++) { + int a = array[j]; + + for (int i = 0; i < j; i++) { + if (a == array[i]) { + // seen this int before + return false; + } + } + } + return true; + } + + public static int[] parseDigits(int number, int length) { + int[] arr = new int[length]; + int temp = number; + for (int i = length - 1; i >= 0; i--) { + arr[i] = temp % 10; + temp /= 10; + } + return arr; + } + + protected void defineNumber() { + int[] arr = generateRandom(); + + for (int i = 0; i < getLength(); i++) { + digits[i] = arr[i]; + } + } + + private int[] generateRandom() { + int[] arr; + do { + Random random = new Random(); + int number = random.nextInt(9877) + 123; + arr = parseDigits(number, getLength()); + } while (!isGuess(arr)); + return arr; + } + + @Override + public String toString() { + return Arrays.toString(digits); + } +} diff --git a/Task/Bulls-and-cows-Player/Java/bulls-and-cows-player-4.java b/Task/Bulls-and-cows-Player/Java/bulls-and-cows-player-4.java new file mode 100644 index 0000000000..a486170a19 --- /dev/null +++ b/Task/Bulls-and-cows-Player/Java/bulls-and-cows-player-4.java @@ -0,0 +1,30 @@ +public class AutoGuessNumber extends AbstractGuessNumber { + + public AutoGuessNumber(int number, int lenght) { + super(lenght); + defineNumber(number); + } + + public static int[] parseDigits(int number, int length) { + int[] arr = new int[length]; + int temp = number; + for (int i = length - 1; i >= 0; i--) { + arr[i] = temp % 10; + temp /= 10; + } + return arr; + } + + protected void defineNumber(int number) { + int[] arr = parseDigits(number, getLength()); + + for (int i = 0; i < getLength(); i++) { + digits[i] = arr[i]; + } + } + + @Override + public String toString() { + return Arrays.toString(digits); + } +} diff --git a/Task/Bulls-and-cows-Player/Java/bulls-and-cows-player-5.java b/Task/Bulls-and-cows-Player/Java/bulls-and-cows-player-5.java new file mode 100644 index 0000000000..12b3c16ef6 --- /dev/null +++ b/Task/Bulls-and-cows-Player/Java/bulls-and-cows-player-5.java @@ -0,0 +1,49 @@ +public class GuessResult { + + private static int guessNum = 0; + private int bulls; + private int cows; + private int length; + + public GuessResult(int length, int bulls, int cows) { + this.length = length; + this.bulls = bulls; + this.cows = cows; + guessNum++; + } + + public int getBulls() { + return bulls; + } + + public int getCows() { + return cows; + } + + public boolean isWin() { + return (bulls == length); + } + + @Override + public String toString() { + final StringBuffer sb = new StringBuffer("GuessResult {"); + sb.append("bulls=").append(bulls); + sb.append(", cows=").append(cows); + sb.append('}'); + return sb.toString(); + } + + public int getId() { + return guessNum; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + GuessResult that = (GuessResult) o; + return bulls == that.bulls && + cows == that.cows && + length == that.length; + } +} diff --git a/Task/Bulls-and-cows/BASIC/bulls-and-cows-3.basic b/Task/Bulls-and-cows/BASIC/bulls-and-cows-3.basic new file mode 100644 index 0000000000..53470b2eb0 --- /dev/null +++ b/Task/Bulls-and-cows/BASIC/bulls-and-cows-3.basic @@ -0,0 +1,38 @@ +100 D$="123456789" +110 FOR I=1 TO 4 +120 P=INT(RND(1)*LEN(D$))+1 +130 N$=N$+MID$(D$,P,1) +140 D$=MID$(D$,1,P - 1)+MID$(D$,P+1,8) +150 NEXT +160 PRINT CHR$(147);"A RANDOM NUMBER HAS BEEN CREATED." +170 PRINT "THE NUMBER HAS FOUR DIGITS FROM 1 TO 9, WITHOUT DUPLICATION." +200 FOR Q=0 TO 1 STEP 0 +210 INPUT "GUESS THE NUMBER: "; G% +219 REM CONVERT TO STRING AND TRIM LEADING SPACE +220 G$=RIGHT$(STR$(G%),4) +230 M=LEN(G$)<>4 OR G%=0 +240 IF NOT M THEN GOSUB 600 +250 IF NOT M THEN GOSUB 700 +260 IF M THEN PRINT "THE GUESS IS MALFORMED.":NEXT Q +270 B=0 +280 C=0 +300 FOR I=1 TO 4 +310 C$=MID$(N$,I,1) +320 BULL=MID$(G$,I,1)=C$ +330 COW=0 +340 IF NOT BULL THEN FOR J=1 TO 4:COW=MID$(G$,J,1)=C$:IF NOT COW THEN NEXT J +350 B=B+ABS(BULL) +360 C=C+ABS(COW) +370 NEXT I +380 PRINT "BULLS:";B:PRINT "COWS:";C +390 Q=ABS(G$=N$) +400 NEXT Q +500 PRINT "GOOD JOB!":END +600 FOR I=2 TO 4:M=MID$(G$,I,1)="0" +610 IF NOT M THEN NEXT I +620 RETURN +700 FOR I=1 TO 3 +710 FOR J=I+1 TO 4 +720 M=MID$(G$,I,1)=MID$(G$,J,1) +730 IF NOT M THEN NEXT J,I +740 RETURN diff --git a/Task/Bulls-and-cows/Elena/bulls-and-cows.elena b/Task/Bulls-and-cows/Elena/bulls-and-cows.elena index f3da84bcd7..e76c6ff76f 100644 --- a/Task/Bulls-and-cows/Elena/bulls-and-cows.elena +++ b/Task/Bulls-and-cows/Elena/bulls-and-cows.elena @@ -9,7 +9,7 @@ class GameMaster constructor() { // generate secret number - var randomNumbers := new int[]{1,2,3,4,5,6,7,8,9}.randomize(9); + var randomNumbers := new int[]::(1,2,3,4,5,6,7,8,9).randomize(9); theNumbers := randomNumbers.Subarray(0, 4); theAttempt := new Integer(1); @@ -84,7 +84,7 @@ public program() { var gameMaster := new GameMaster(); - lazy::(^gameMaster.proceed(gameMaster.ask())).doWhile(); + (lazy:gameMaster.proceed(gameMaster.ask())).doWhile(); console.readChar() } diff --git a/Task/Bulls-and-cows/REXX/bulls-and-cows-1.rexx b/Task/Bulls-and-cows/REXX/bulls-and-cows-1.rexx index 5b9d62536f..c11581ff68 100644 --- a/Task/Bulls-and-cows/REXX/bulls-and-cows-1.rexx +++ b/Task/Bulls-and-cows/REXX/bulls-and-cows-1.rexx @@ -1,30 +1,27 @@ /*REXX program scores the Bulls & Cows game with CBLFs (Carbon Based Life Forms). */ -?=; do until length(?)==4; r=random(1, 9) /*generate a unique four-digit number. */ - if pos(r, ?)\==0 then iterate /*don't allow a repeated digit/numeral.*/ - ?=? || r /*add random digit by concatenation. */ - end /*until length ···*/ /* [↑] builds a unique four-digit num.*/ -$= '──────── [Bulls & Cows] ' - do until bulls==4; say /*play until guessed or enters "QUIT".*/ - say $ 'Please enter a 4-digit guess (with no zeroes) [or Quit]:' - pull n; n=space(n, 0); if abbrev('QUIT', n, 1) then exit /*wants to quit ?*/ - q=?; L=length(n); bulls=0; cows=0 /*initialize some REXX variables. */ - - do j=1 for L; if substr(n, j, 1)\==substr(q, j, 1) then iterate /*bull?*/ - bulls=bulls +1; q=overlay(., q, j) /*bump bull count; disallow for cow.*/ - end /*j*/ /* [↑] bull count────────~─────────*/ - /*cow ?*/ - do k=1 for L; _=substr(n, k, 1); if pos(_, q)==0 then iterate - cows=cows + 1; q=translate(q, , _) /*bump cow count; allow mult digits.*/ - end /*k*/ /* [↑] cow count─────────~────────*/ - say; @= 'You got' bulls - if L\==0 & bulls\==4 then say $ @ 'bull's(bulls) "and" cows 'cow's(cows). - end /*until bulls==4*/ -say - say " ┌─────────────────────────────────────────┐" - say " │ │" - say " │ Congratulations, you've guessed it !! │" - say " │ │" - say " └─────────────────────────────────────────┘"; say +?=; do until length(?)==4; r= random(1, 9) /*generate a unique four-digit number. */ + if pos(r,?)\==0 then iterate; ?= ? || r /*don't allow a repeated digit/numeral. */ + end /*until length*/ /* [↑] builds a unique four-digit number*/ +$= '──────── [Bulls & Cows] ' /*a literal that is part of the prompt. */ + do until bulls==4; say /*play until guessed or enters "Quit".*/ + say $ 'Please enter a 4-digit guess (with no zeroes) [or Quit]:' + pull n; n=space(n, 0); if abbrev('QUIT', n, 1) then exit /*user wants to quit?*/ + q=?; L= length(n); bulls= 0; cows= 0 /*initialize some REXX variables. */ + do j=1 for L; if substr(n, j, 1)\==substr(q, j, 1) then iterate /*is bull?*/ + bulls= bulls +1; q= overlay(., q, j) /*bump the bull count; disallow for cow.*/ + end /*j*/ /* [↑] bull count───────────────────────*/ + /*is cow? */ + do k=1 for L; _= substr(n, k, 1); if pos(_, q)==0 then iterate + cows=cows + 1; q= translate(q, , _) /*bump the cow count; allow mult digits.*/ + end /*k*/ /* [↑] cow count───────────────────────*/ + say; @= 'You got' bulls + if L\==0 & bulls\==4 then say $ @ 'bull's(bulls) "and" cows 'cow's(cows). + end /*until bulls*/ + say " ┌─────────────────────────────────────────┐" + say " │ │" + say " │ Congratulations, you've guessed it !! │" + say " │ │" + say " └─────────────────────────────────────────┘" exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ s: if arg(1)==1 then return ''; return "s" /*this function handles pluralization. */ diff --git a/Task/CRC-32/Delphi/crc-32.delphi b/Task/CRC-32/Delphi/crc-32.delphi new file mode 100644 index 0000000000..d7b61cddf4 --- /dev/null +++ b/Task/CRC-32/Delphi/crc-32.delphi @@ -0,0 +1,15 @@ +program CalcCRC32; + +{$APPTYPE CONSOLE} + +uses + System.SysUtils, System.ZLib; + +var + Data: AnsiString = 'The quick brown fox jumps over the lazy dog'; + CRC: UInt32; + +begin + CRC := crc32(0, @Data[1], Length(Data)); + WriteLn(Format('CRC32 = %8.8X', [CRC])); +end. diff --git a/Task/CRC-32/F-Sharp/crc-32-1.fs b/Task/CRC-32/F-Sharp/crc-32-1.fs new file mode 100644 index 0000000000..c5385111a1 --- /dev/null +++ b/Task/CRC-32/F-Sharp/crc-32-1.fs @@ -0,0 +1,39 @@ +module Crc32 = + + open System + + // Generator polynomial (modulo 2) for the reversed CRC32 algorithm. + let private s_generator = uint32 0xEDB88320 + + // Generate lookup table + let private lutIntermediate input = + if (input &&& uint32 1) <> uint32 0 + then s_generator ^^^ (input >>> 1) + else input >>> 1 + + let private lutEntry input = + {0..7} + |> Seq.fold (fun acc x -> lutIntermediate acc) input + + let private crc32lut = + [uint32 0 .. uint32 0xFF] + |> List.map lutEntry + + let crc32byte (register : uint32) (byte : byte) = + crc32lut.[Convert.ToInt32((register &&& uint32 0xFF) ^^^ Convert.ToUInt32(byte))] ^^^ (register >>> 8) + + // CRC32 of a byte array + let crc32 (input : byte[]) = + let result = Array.fold crc32byte (uint32 0xFFFFFFFF) input + ~~~result + + // CRC32 from ASCII string + let crc32OfAscii (inputAscii : string) = + let bytes = System.Text.Encoding.ASCII.GetBytes(inputAscii) + crc32 bytes + + // Test + let testString = "The quick brown fox jumps over the lazy dog" + printfn "ASCII Input: %s" testString + let result = crc32OfAscii testString + printfn "CRC32: 0x%x" result diff --git a/Task/CRC-32/F-Sharp/crc-32-2.fs b/Task/CRC-32/F-Sharp/crc-32-2.fs new file mode 100644 index 0000000000..01080b652b --- /dev/null +++ b/Task/CRC-32/F-Sharp/crc-32-2.fs @@ -0,0 +1,2 @@ +ASCII Input: The quick brown fox jumps over the lazy dog +CRC32: 0x414fa339 diff --git a/Task/CRC-32/Haxe/crc-32.haxe b/Task/CRC-32/Haxe/crc-32.haxe new file mode 100644 index 0000000000..d1259bb95e --- /dev/null +++ b/Task/CRC-32/Haxe/crc-32.haxe @@ -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/Pike/crc-32.pike b/Task/CRC-32/Pike/crc-32.pike new file mode 100644 index 0000000000..0c18480057 --- /dev/null +++ b/Task/CRC-32/Pike/crc-32.pike @@ -0,0 +1,2 @@ +string foo = "The quick brown fox jumps over the lazy dog"; +write("0x%x\n", Gz.crc32(foo)); diff --git a/Task/CRC-32/REXX/crc-32.rexx b/Task/CRC-32/REXX/crc-32.rexx index dd4a7168a5..3819ed3320 100644 --- a/Task/CRC-32/REXX/crc-32.rexx +++ b/Task/CRC-32/REXX/crc-32.rexx @@ -4,31 +4,28 @@ call show 'The quick brown fox jumps over the lazy dog' /*the 1st call show 'Generate CRC32 Checksum For Byte Array Example' /* " 2nd " */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -CRC_32: procedure; parse arg !,$; c='edb88320'x /*2nd arg used for repeated invocations*/ - f='ffFFffFF'x /* [↓] build an 8─bit indexed table,*/ - do i=0 for 256; z=d2c(i) /* one byte at a time.*/ - r=right(z, 4, '0'x) /*insure the "R" is thirty-two bits.*/ +CRC_32: procedure; parse arg !,$; c= 'edb88320'x /*2nd arg used for repeated invocations*/ + f= 'ffFFffFF'x /* [↓] build an 8─bit indexed table,*/ + do i=0 for 256; z= d2c(i) /* one byte at a time.*/ + r= right(z, 4, '0'x) /*insure the "R" is thirty─two bits.*/ /* [↓] handle each rightmost byte bit.*/ - do j=0 for 8; rb=x2b(c2x(r)) /*handle each bit of rightmost 8 bits. */ - r=x2c(b2x(0 || left(rb, 31))) /*shift it right (an unsigned) 1 bit.*/ - if right(rb,1) then r=bitxor(r,c) /*this is a bin bit for XOR grunt─work.*/ - end /*j*/ - !.z=r /*assign to an eight─bit index table. */ - end /*i*/ - - $=bitxor(word($ '0000000'x, 1), f) /*utilize the user's CRC or a default. */ - do k=1 for length(!) /*start number crunching the input data*/ - ?=bitxor(right($,1), substr(!,k,1)) - $=bitxor('0'x || left($, 3), !.?) - end /*k*/ + do j=0 for 8; rb= x2b(c2x(r)) /*handle each bit of rightmost 8 bits. */ + r= x2c( b2x(0 || left(rb, 31) ) ) /*shift it right (an unsigned) 1 bit.*/ + if right(rb,1) then r= bitxor(r, c) /*this is a bin bit for XOR grunt─work.*/ + end /*j*/ + !.z= r /*assign to an eight─bit index table. */ + end /*i*/ + $=bitxor( word($ '0000000'x, 1), f) /*utilize the user's CRC or a default. */ + do k=1 for length(! ) /*start number crunching the input data*/ + ?= bitxor(right($,1), substr(!,k,1) ) + $= bitxor('0'x || left($, 3), !.?) + end /*k*/ return $ /*return with cyclic redundancy check. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ show: procedure; parse arg Xstring; numeric digits 12; say; say - checksum=CRC_32(Xstring) /*invoke CRC_32 to create a CRC.*/ - checksum=bitxor(checksum, 'ffFFffFF'x) /*final convolution for checksum.*/ + checksum= bitxor(CRC_32(Xstring), 'ffFFffFF'x) /*invoke CRC_32 to create a CRC. */ say center(' input string [length of' length(Xstring) "bytes] ", 79, '═') - say Xstring /*show the string on its own line*/ - say /*↓↓↓↓↓↓↓↓↓↓↓↓ is fifteen blanks*/ - say "hex CRC-32 checksum =" c2x(checksum) left('', 15), - "dec CRC-32 checksum =" c2d(checksum) /*show the CRC-32 in hex and dec.*/ + say Xstring; say /*show the string on its own line*/ + say "hex CRC─32 checksum =" c2x(checksum) left('', 15), + "dec CRC─32 checksum =" c2d(checksum) /*show the CRC─32 in hex and dec.*/ return diff --git a/Task/CRC-32/Vala/crc-32-1.vala b/Task/CRC-32/Vala/crc-32-1.vala new file mode 100644 index 0000000000..db8a2cbadc --- /dev/null +++ b/Task/CRC-32/Vala/crc-32-1.vala @@ -0,0 +1,6 @@ +using ZLib.Utility; + +void main() { + var str = (uint8[])"The quick brown fox jumps over the lazy dog".to_utf8(); + stdout.printf("%lx\n", crc32(0, str)); +} diff --git a/Task/CRC-32/Vala/crc-32-2.vala b/Task/CRC-32/Vala/crc-32-2.vala new file mode 100644 index 0000000000..c7a8a33e95 --- /dev/null +++ b/Task/CRC-32/Vala/crc-32-2.vala @@ -0,0 +1,37 @@ +public class Crc32 +{ + private const uint32 s_generator = 0xedb88320u; + + public Crc32() + { + m_table = new uint32[256]; + uint32 rem; + for (uint32 i = 0; i < 256; i++) { + rem = i; + for (uint32 j = 0; j < 8; j++) { + if ((rem & 1) != 0) { + rem >>= 1; + rem ^= s_generator; + } else + rem >>= 1; + } + m_table[i] = rem; + } + } + + public uint32 get(string str) { + uint32 crc = 0; + crc = ~crc; + for (int i = 0; i < str.length; i++) { + crc = (crc >> 8) ^ m_table[(crc & 0xff) ^ str[i]]; + } + return ~crc; + } + + private uint32[] m_table; +} + +void main() { + var crc32 = new Crc32(); + stdout.printf("%x\n", crc32.get("The quick brown fox jumps over the lazy dog")); +} diff --git a/Task/CSV-data-manipulation/C-sharp/csv-data-manipulation.cs b/Task/CSV-data-manipulation/C-sharp/csv-data-manipulation.cs index 387f5274f8..13b823c241 100644 --- a/Task/CSV-data-manipulation/C-sharp/csv-data-manipulation.cs +++ b/Task/CSV-data-manipulation/C-sharp/csv-data-manipulation.cs @@ -1,108 +1,21 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; using System.IO; +using System.Linq; -namespace CSV +namespace CSV_data_manipulation { - class CSV + class Program { - private Dictionary, string> _data; - private int _rows; - private int _cols; - - public int Rows { get { return _rows; } } - public int Cols { get { return _cols; } } - - public CSV() + static void Main() { - Clear(); - } - - public void Clear() - { - _rows = 0; - _cols = 0; - _data = new Dictionary, string>(); - } - - public void Open(StreamReader stream, char delim = ',') - { - string line; - int col = 0; - int row = 0; - - Clear(); - - while ((line = stream.ReadLine()) != null) + var input = File.ReadAllLines("test_in.csv"); + var output = input.Select((line, i) => { - if (line.Length > 0) - { - string[] values = line.Split(delim); - col = 0; - foreach (var value in values) - { - this[col,row] = value; - col++; - } - row++; - } - } - stream.Close(); - } - - public void Save(StreamWriter stream, char delim = ',') - { - for (int row = 0; row < _rows; row++) - { - for (int col = 0; col < _cols; col++) - { - stream.Write(this[col, row]); - if (col < _cols - 1) - { - stream.Write(delim); - } - } - stream.WriteLine(); - } - stream.Flush(); - stream.Close(); - } - - public string this[int col, int row] - { - get - { - try - { - return _data[new Tuple(col, row)]; - } - catch - { - return ""; - } - } - - set - { - _data[new Tuple(col, row)] = value.ToString().Trim(); - _rows = Math.Max(_rows, row + 1); - _cols = Math.Max(_cols, col + 1); - } - } - - static void Main(string[] args) - { - CSV csv = new CSV(); - - csv.Open(new StreamReader(@"test_in.csv")); - csv[0, 0] = "Column0"; - csv[1, 1] = "100"; - csv[2, 2] = "200"; - csv[3, 3] = "300"; - csv[4, 4] = "400"; - csv.Save(new StreamWriter(@"test_out.csv")); + if (i == 0) + return line + ",SUM"; + var sum = line.Split(',').Select(int.Parse).Sum(); + return line + "," + sum; + }).ToArray(); + File.WriteAllLines("test_out.csv", output); } } } diff --git a/Task/CSV-data-manipulation/Julia/csv-data-manipulation.julia b/Task/CSV-data-manipulation/Julia/csv-data-manipulation.julia index f79aca6fee..3ce8b0ec7d 100644 --- a/Task/CSV-data-manipulation/Julia/csv-data-manipulation.julia +++ b/Task/CSV-data-manipulation/Julia/csv-data-manipulation.julia @@ -1,14 +1,8 @@ +using DataFrames, CSV + ifn = "csv_data_manipulation_in.dat" ofn = "csv_data_manipulation_out.dat" -ifile = open(ifn, "r") -(a, h) = readcsv(ifile, Int, header=true) -close(ifile) - -a = hcat(a, sum(a, 2)) -h = hcat(h, "SUM") -a = vcat(h, a) - -ofile = open(ofn, "w") -writecsv(ofile, a) -close(ofile) +df = CSV.read(ifn) +df.SUM = sum.(eachrow(df)) +CSV.write(ofn, df) diff --git a/Task/CSV-data-manipulation/MATLAB/csv-data-manipulation.m b/Task/CSV-data-manipulation/MATLAB/csv-data-manipulation-1.m similarity index 100% rename from Task/CSV-data-manipulation/MATLAB/csv-data-manipulation.m rename to Task/CSV-data-manipulation/MATLAB/csv-data-manipulation-1.m diff --git a/Task/CSV-data-manipulation/MATLAB/csv-data-manipulation-2.m b/Task/CSV-data-manipulation/MATLAB/csv-data-manipulation-2.m new file mode 100644 index 0000000000..f186f2df17 --- /dev/null +++ b/Task/CSV-data-manipulation/MATLAB/csv-data-manipulation-2.m @@ -0,0 +1,4 @@ +filename='data.csv'; +data = readtable(filename); +data.SUM = sum([data{:,:}],2); +writetable(data,filename); diff --git a/Task/CSV-data-manipulation/R/csv-data-manipulation-2.r b/Task/CSV-data-manipulation/R/csv-data-manipulation-2.r index b13e967755..7fc9e71b87 100644 --- a/Task/CSV-data-manipulation/R/csv-data-manipulation-2.r +++ b/Task/CSV-data-manipulation/R/csv-data-manipulation-2.r @@ -1 +1,9 @@ - write.csv(df,row.names = FALSE,file = "foo.csv") +df <- read.csv(textConnection( +"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")) + +df$sum <- rowSums(df) +write.csv(df,row.names = FALSE) diff --git a/Task/CSV-data-manipulation/R/csv-data-manipulation-3.r b/Task/CSV-data-manipulation/R/csv-data-manipulation-3.r new file mode 100644 index 0000000000..b13e967755 --- /dev/null +++ b/Task/CSV-data-manipulation/R/csv-data-manipulation-3.r @@ -0,0 +1 @@ + write.csv(df,row.names = FALSE,file = "foo.csv") diff --git a/Task/CSV-data-manipulation/Ruby/csv-data-manipulation.rb b/Task/CSV-data-manipulation/Ruby/csv-data-manipulation.rb index 882985d075..34b8e53c86 100644 --- a/Task/CSV-data-manipulation/Ruby/csv-data-manipulation.rb +++ b/Task/CSV-data-manipulation/Ruby/csv-data-manipulation.rb @@ -4,7 +4,7 @@ ar = CSV.table("test.csv").to_a #table method assumes headers and converts numbe # manipulate: ar.first << "SUM" -ar[1..-1].each{|row| row << row.inject(:+)} +ar[1..-1].each{|row| row << row.sum} # write: CSV.open("out.csv", 'w') do |csv| diff --git a/Task/CSV-to-HTML-translation/Julia/csv-to-html-translation-1.julia b/Task/CSV-to-HTML-translation/Julia/csv-to-html-translation-1.julia index 1aed96274e..758957af9d 100644 --- a/Task/CSV-to-HTML-translation/Julia/csv-to-html-translation-1.julia +++ b/Task/CSV-to-HTML-translation/Julia/csv-to-html-translation-1.julia @@ -1,6 +1,10 @@ -function csv2html(fname::ASCIIString; header::Bool=false) - csv = readcsv(fname) - @assert(length(csv) > 0) +using DataFrames, CSV + +using CSV, DataFrames + +function csv2html(fname; header::Bool=false) + csv = CSV.read(fname) + @assert(size(csv, 2) > 0) str = """ diff --git a/Task/CSV-to-HTML-translation/Julia/csv-to-html-translation-2.julia b/Task/CSV-to-HTML-translation/Julia/csv-to-html-translation-2.julia index 930691c88b..8cc9261b68 100644 --- a/Task/CSV-to-HTML-translation/Julia/csv-to-html-translation-2.julia +++ b/Task/CSV-to-HTML-translation/Julia/csv-to-html-translation-2.julia @@ -62,5 +62,4 @@ - diff --git a/Task/CSV-to-HTML-translation/R/csv-to-html-translation-1.r b/Task/CSV-to-HTML-translation/R/csv-to-html-translation-1.r new file mode 100644 index 0000000000..2ef8f6b620 --- /dev/null +++ b/Task/CSV-to-HTML-translation/R/csv-to-html-translation-1.r @@ -0,0 +1,20 @@ +File <- "~/test.csv" +Opened <- readLines(con = File) +Size <- length(Opened) + +HTML <- "~/test.html" + +Table <- list() + +for(i in 1:Size) +{ + #i=1 + Split <- unlist(strsplit(Opened[i],split = ",")) + Table[i] <- paste0("",Split,"",collapse = "") + Table[i] <- paste0("",Table[i],"") +} + +Table[1] <- paste0("",Table[1]) +Table[length(Table)] <- paste0(Table[length(Table)],"
") + +writeLines(as.character(Table), HTML) diff --git a/Task/CSV-to-HTML-translation/R/csv-to-html-translation-2.r b/Task/CSV-to-HTML-translation/R/csv-to-html-translation-2.r new file mode 100644 index 0000000000..d7045bf0d5 --- /dev/null +++ b/Task/CSV-to-HTML-translation/R/csv-to-html-translation-2.r @@ -0,0 +1,6 @@ + + + + + +
CharacterSpeech
The multitudeThe messiah! Show us the messiah!
Brians motherNow you listen here! He's not the messiah; he's a very naughty boy! Now go away!
The multitudeWho are you?
Brians motherI'm his mother; that's who!
The multitudeBehold his mother! Behold his mother!
diff --git a/Task/Caesar-cipher/EDSAC-order-code/caesar-cipher.edsac b/Task/Caesar-cipher/EDSAC-order-code/caesar-cipher.edsac new file mode 100644 index 0000000000..c765c44c4a --- /dev/null +++ b/Task/Caesar-cipher/EDSAC-order-code/caesar-cipher.edsac @@ -0,0 +1,215 @@ + [Caesar cipher for Rosetta Code. + EDSAC program, Initial Orders 2.] + + [Table for converting alphabetic position 0..25 to EDSAC code. + The EDSAC code is in the high 5 bits.] + T 54 K [access table via C parameter] + P 56 F + T 56 K + AFBFCFDFEFFFGFHFIFJFKFLFMFNFOFPFQFRFSFTFUFVFWFXFYFZF + + [Table for converting 5-bit EDSAC code to alphabetic position 0..25. + Computed at run time (so the programmer doesn't need to know the EDSAC codes). + 32 entries; entry is -1 if the EDSAC code does not represent a letter.] + T 53 K [access table via B parameter] + P 82 F + + [Subroutine to read string from input and + store with char codes in high 5 bits. + String is terminated by blank row of tape, which is stored. + Input: 0F holds address of string in address field (bits 1..11). + 22 locations; workspace: 4D] + T 114 K + GKA3FT19@AFA20@T10@I5FA4DR16FT4DA4FUFE14@A21@G18@T5FA10@A2FE4@T5FEFUFK2048F + + [Subroutine to print string with character codes in high 5 bits. + String is terminated by blank row of tape, which is not printed. + Input: 0F holds address of string in address field (bits 1..11). + 18 locations; orkspace: 4F] + T 136 K + GKA3FT16@AFA2@T5@AFU4FE10@A17@G15@O4FT4FA5@A2FG4@TFEFK2048F + + [Define start of user message] + T 47 K [access message via M parameter] + P 350 F [address of message] + + T 154 K + G K + [Constants] + [0] P M [address of user message] + [1] A B + [2] A C + [3] T B + [4] P 25 F + [5] P 26 F + [6] P 31 F + [7] K 2048 F [(1) letter shift (2) used in test for + blank row of tape at end of message] + [8] @ F [carriage return] + [9] & F [line feed] + [10] K 4096 F [null char] + + [Constant messages. Each includes new line at the end.] + [11] TF EF SF TF IF NF GF @F &F K4096F + [21] P 11 @ + [22] EF NF TF EF RF !F MF EF SF SF AF GF EF @F &F K4096F + [38] P 22 @ + [39] MF UF SF TF !F SF TF AF RF TF !F WF IF TF HF !F BF !F TF OF !F ZF @F &F K4096F + [64] P 39 @ + + [Subroutine to convert EDSAC code to alphabetic position. + Input: 4F holds EDSAC code in high 5 bits + Output: 4F holds alphabetic position (0..25, or -1 if not a letter). + Workspace: 5F] + [65] A 3 F [make jump for return] + T 75 @ [plant in code] + A 4 F [load EDSAC code] + R 512 F [shift code into address field] + T 5 F [temp store] + C 5 F [acc := address bits only] + A 1 @ [make order to load alphabetic position] + T 73 @ [plant in code] + [73] A B [load alphabetic position] + T 4 F [store in 4F] + [75] E F [return] + + [Subroutine to encipher or decipher a message by Caesar shift. + Input: Message is accessed by the M parameter, and + terminated by a blank row of tape. + Output: 0F = error flag: 0 if OK, < 0 if error (bad message prefix) + Workspace 4F.] + [76] A 3 F [make jump for return] + T 119 @ [plant in code] + A 80 @ [load order to access first char] + T 95 @ [plant in code] + [80] A M [load first char of message] + T 4 F [pass to subroutine] + [82] A 82 @ [get alphabetic position] + G 65 @ + A 4 F [load alphabetic position] + U F [to 0F for use as shift] + S 2 F [check it's not 0 or -1] + G 118 @ [error exit if it is] + T 1 F [clear acc] + S F [load negative of shift] + G 108 @ [jump to store first char + and convert rest of message] + [Here after skipping non-letter] + [91] T 4 F [clear acc] + [Here after converting letter] + [92] A 95 @ [load order to read character] + A 2 F [inc address to next character] + T 95 @ [store back] + [95] A M [load char from message (in top 5 bits)] + E 100 @ [if >= 0 then not blank row] + A 7 @ [if < 0, test for blank row] + G 117 @ [jump out if so] + S 7 @ [restore after test] + [100] T 4 F [character to 4F for subroutine] + [101] A 101 @ [for return from subroutine] + G 65 @ [sets 4F := alphabetic position] + A 4 F [to acc] + G 91 @ [if < 0 then not a letter; don't change it] + A F [apply Caesar shift] + [Subtract 26 if required, so result is in range 0..25] + S 5 @ [subtract 26] + E 109 @ [skip next if result >= 0] + [108] A 5 @ [add 26] + [109] A 2 @ [make order to read EDSAC letter at that position] + T 114 @ [plant in code] + A 95 @ [load A order from above] + A 14 C [add 'O F' to make T order] + T 115 @ [plant in code] + [114] A C [load enciphered letter] + [115] T M [overwrite original letter] + E 92 @ [loop back] + [117] T F [flag = 0 for OK] + [118] T F [flag to 0F: 0 if OK, < 0 if error] + [119] E F [return with acc = 0] + + [Subroutine to print encipered or deciphered message, plus new line] + [120] A 3 F [make jump order for return] + T 128 @ [plant in code] + A @ [load address of message] + T F [to 0F for print subroutine] + [124] A 124 @ + G 136 F [print message, clears acc] + O 8 @ [print new line] + O 9 @ + [128] E F [return with acc = 0] + + [Main routine] + [129] O 7 @ [set letter shift] + H 6 @ [mult reg has this value throughout; + selects bits 1..5 of 17-bit value] + [Build inverse table from direct table + First initialize all 32 locations to -1] + A 6 @ [work backwards] + [132] A 3 @ [make T order for inverse table] + T 135 @ [plant in code] + S 2 F [make -1 in address field] + [135] T B [store in inverse table] + A 135 @ [get T order] + S 2 F [dec address] + S 3 @ [compare with start of table] + E 132 @ [loop till done] + [Now fill in entries by reversing direct table] + T F [clear acc] + A 4 @ [work backwards] + [142] U 5 F [index in 5F] + A 2 @ [make A order for direct table] + T 145 @ [plant in code] + [145] A C [load entry from direct table, code in top 5 bits] + R 512 F [shift 11 right, 5-bit code to address field] + T 4 F [temp store] + C 4 F [pick out 5-bit code] + A 3 @ [make T order for inverse table] + T 152 @ [plant in code] + A 5 F [load index] + [152] T B [store in inverse table] + A 5 F [load index again] + S 2 F [update index] + E 142 @ [loop back] + [Here when inverse table is complete] + [156] T F [clear acc] + [157] A 21 @ [load address of "testing" message] + T F [to 0F for print subroutine] + [159] A 159 @ + G 136 F [print "testing message"] + E 168 @ [jump to read from end of this file] + [Loop back here to get message from user] + [162] A 38 @ [load address of prompt] + T F [to 0F for print subroutine] + [164] A 164 @ + G 136 F [print prompt] + O 10 @ [print null to flush teleprinter buffer] + Z F [stop] + [First time here, read message from end of this file. + Later times, read message from file chosen by the user.] + [168] A @ [load address of message] + T F [to 0F for input] + [170] A 170 @ + G 114 F [read message] + [172] A 172 @ + G 120 @ [print message] + [174] A 174 @ + G 76 @ [call Caesar shift subroutine] + A F [load error flag] + E 184 @ [jump if OK] + T F [error, clear acc] + A 64 @ [load address of error message] + T F + [181] A 181 @ + G 136 F [print error message] + E 162 @ [back to try again] + [Here if message was enciphered without error] + [184] A 184 @ + G 120 @ [print enciphered message] + [186] A 186 @ + G 76 @ [call Caesar shift subroutine] + [188] A 188 @ + G 120 @ [print deciphered message] + E 162 @ [back for another message] + E 129 Z [define entry point] + P F [acc = 0 on entry] +DGAZA!FREQUENS!LIBYCUM!DUXIT!KARTHAGO!TRIUMPHUM. diff --git a/Task/Caesar-cipher/PHP/caesar-cipher.php b/Task/Caesar-cipher/PHP/caesar-cipher-1.php similarity index 100% rename from Task/Caesar-cipher/PHP/caesar-cipher.php rename to Task/Caesar-cipher/PHP/caesar-cipher-1.php diff --git a/Task/Caesar-cipher/PHP/caesar-cipher-2.php b/Task/Caesar-cipher/PHP/caesar-cipher-2.php new file mode 100644 index 0000000000..818f01cf2b --- /dev/null +++ b/Task/Caesar-cipher/PHP/caesar-cipher-2.php @@ -0,0 +1,9 @@ +
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 index de050a2767..1592126df7 100644 --- a/Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers.elena +++ b/Task/Calendar---for-REAL-programmers/Elena/calendar---for-real-programmers.elena @@ -4,8 +4,8 @@ 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"}; +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 { @@ -39,12 +39,13 @@ class CalendarMonthPrinter { theLine.writeCopies(" ",theDate.DayOfWeek == 0 ? 7 : (theDate.DayOfWeek - 1)); - doUntil(theDate.Month != theMonth || theDate.DayOfWeek == 1) + do { theLine.writePaddingLeft(theDate.Day.Printable, $32, 3); theDate := theDate.addDays:1 } + until:(theDate.Month != theMonth || theDate.DayOfWeek == 1) }; int length := theLine.Length; diff --git a/Task/Calendar---for-REAL-programmers/REXX/calendar---for-real-programmers.rexx b/Task/Calendar---for-REAL-programmers/REXX/calendar---for-real-programmers.rexx index 176d0ebeaa..72a06db0d0 100644 --- a/Task/Calendar---for-REAL-programmers/REXX/calendar---for-real-programmers.rexx +++ b/Task/Calendar---for-REAL-programmers/REXX/calendar---for-real-programmers.rexx @@ -1,5 +1,6 @@ /*REXX PROGRAM TO SHOW ANY YEAR'S (MONTHLY) CALENDAR (WITH/WITHOUT GRID)*/ @ABC= +PARSE VALUE SCRSIZE() WITH SD SW . DO J=0 TO 255;_=D2C(J);IF DATATYPE(_,'L') THEN @ABC=@ABC||_;END @ABCU=@ABC; UPPER @ABCU DAYS_='SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY' @@ -14,7 +15,7 @@ DAYS=; MONTHS= MONTHS=MONTHS TRANSLATE(LEFT(_,1))SUBSTR(_,2) END CALFILL=' '; MC=12; _='1 3 1234567890' "FB"X -PARSE VAR _ GRID CALSPACES # CHK . CV_ DAYS.1 DAYS.2 DAYS.3 DAYSN SD SW +PARSE VAR _ GRID CALSPACES # CHK . CV_ DAYS.1 DAYS.2 DAYS.3 DAYSN _=0; PARSE VAR _ COLS 1 JD 1 LOWERCASE 1 MAXKALPUTS 1 NARROW 1, NARROWER 1 NARROWEST 1 SHORT 1 SHORTER 1 SHORTEST 1, SMALL 1 SMALLER 1 SMALLEST 1 UPPERCASE @@ -57,11 +58,13 @@ IF _\=='' | \IS#(MM) | \IS#(DD) | \IS#(YYYY) THEN CALL ERX 86 END /*SELECT*/ END /*DO WHILE OPTS\== ...*/ +IF SD==0 THEN SD= 43; SD= SD-3 +IF SW==0 THEN SW= 80; SW= SW-1 MC=INT(MC,'MONTHSCALENDER'); IF MC>0 THEN CAL=1 DAYS=' 'DAYS; MONTHS=' 'MONTHS CYYYY=RIGHT(DATE(),4); HYY=LEFT(CYYYY,2); LYY=RIGHT(CYYYY,2) DY.=31; _=30; PARSE VAR _ DY.4 1 DY.6 1 DY.9 1 DY.11; DY.2=28+LY(YYYY) -YY=RIGHT(YYYY,2); SD=P(SD 43); SW=P(SW 80); CW=10; CINDENT=1; CALWIDTH=76 +YY=RIGHT(YYYY,2); CW=10; CINDENT=1; CALWIDTH=76 IF SMALL THEN DO; NARROW=1 ; SHORT=1 ; END IF SMALLER THEN DO; NARROWER=1 ; SHORTER=1 ; END IF SMALLEST THEN DO; NARROWEST=1; SHORTEST=1; END diff --git a/Task/Calendar/Liberty-BASIC/calendar.liberty b/Task/Calendar/Liberty-BASIC/calendar.liberty new file mode 100644 index 0000000000..20b5480422 --- /dev/null +++ b/Task/Calendar/Liberty-BASIC/calendar.liberty @@ -0,0 +1,59 @@ +rem Adapted from LB examples included with software +[start] + prompt "Enter year(yyyy)?";year + if year<1900 then notice "1900 or later":goto [start] + ax=1:gx=8:ay=3:gy=10 + locate 52,1:print year + for mr = 0 to 3 + for mc = 0 to 2 + mt=mt+1 + aDate$ = str$(mt)+"/01/"+str$(year) + px = ax+mc*gx + py = ay+mr*gy + gosub [printout] + next mc + next mr + gosub [snoopy] +end + +[printout] + locate 4*px-3+int((30-len(monthname$(aDate$)))/2),py + print monthname$(aDate$) + FirstDay=date$(word$(aDate$,1,"/")+"/1/"+word$(aDate$,3,"/")) + LastDay$=date$(date$(word$(date$(FirstDay+32),1,"/")+"/1/"+word$(date$(FirstDay+32),3,"/"))-1) + dow=val(word$("3 4 5 x 6 7 x 1 2",int((FirstDay/7-int(FirstDay/7))*10)+1)) + locate px*4-3, py+1 + print " Su Mo Tu We Th Fr Sa" + for i=1 to val(mid$(LastDay$,4,2)) + y=int((i+dow-2)/7) + x=px+(i+dow-2)-y*7 + x=4*x + locate x-4,py+y+2 + print using("###",i) + next i +return + +[snoopy] + locate ax, ay+4*gy + print space$(4*gx);" ,-~~-.___." + print space$(4*gx);" / ()=(() \" + print space$(4*gx);" ( ( 0" + print space$(4*gx);" \._\, ,----'" + print space$(4*gx);" ##XXXxxxxxxx" + print space$(4*gx);" / ---'~;" + print space$(4*gx);" / /~|-" + print space$(4*gx);" _____=( ~~ |______ " + print space$(4*gx);" /_____________________\ " + print space$(4*gx);" /_______________________\" + print space$(4*gx);" /_________________________\" + print space$(4*gx);"/___________________________\" + print space$(4*gx);" |____________________|" + print space$(4*gx);" |____________________|" + print space$(4*gx);" |____________________|" + print space$(4*gx);" | |" +return + +function monthname$(aDate$) + month=val(aDate$) + monthname$=word$("January February March April May June July August September October November December",month) +end function diff --git a/Task/Calendar/Nim/calendar.nim b/Task/Calendar/Nim/calendar.nim new file mode 100644 index 0000000000..e9a4fd7c28 --- /dev/null +++ b/Task/Calendar/Nim/calendar.nim @@ -0,0 +1,38 @@ +import times +import strformat + +proc printCalendar(year, nCols: int) = + var rows = 12 div nCols + var date = initDateTime(1, mJan, year, 0, 0, 0, utc()) + if rows mod nCols != 0: + inc rows + var offs = getDayOfWeek(date.monthday, date.month, date.year).int + var mons: array[12, array[8, string]] + for m in 0..11: + mons[m][0] = &"{$date.month:^21}" + mons[m][1] = " Su Mo Tu We Th Fr Sa" + var dim = getDaysInMonth(date.month, date.year) + for d in 1..42: + var day = d > offs and d <= offs + dim + var str = if day: &" {d-offs:2}" else: " " + mons[m][2 + (d - 1) div 7] &= str + offs = (offs + dim) mod 7 + date = date + months(1) + var snoopyString, yearString: string + formatValue(snoopyString, "[Snoopy Picture]", "^" & $(nCols * 24 + 4)) + formatValue(yearString, $year, "^" & $(nCols * 24 + 4)) + echo snoopyString, "\n" , yearString, "\n" + for r in 0.. 11: + break + for i, line in mons[r * nCols + c]: + s[i] &= &" {line}" + for line in s: + if line == "": + break + echo line + echo "" + +printCalendar(1969, 3) 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 new file mode 100644 index 0000000000..c37f86a156 --- /dev/null +++ b/Task/Call-a-foreign-language-function/C/call-a-foreign-language-function-1.c @@ -0,0 +1,24 @@ +#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 new file mode 100644 index 0000000000..6897885455 --- /dev/null +++ b/Task/Call-a-foreign-language-function/C/call-a-foreign-language-function-2.c @@ -0,0 +1,16 @@ +#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/OCaml/call-a-foreign-language-function-1.ocaml b/Task/Call-a-foreign-language-function/OCaml/call-a-foreign-language-function-1.ocaml index 5748b3b31d..af497cf570 100644 --- a/Task/Call-a-foreign-language-function/OCaml/call-a-foreign-language-function-1.ocaml +++ b/Task/Call-a-foreign-language-function/OCaml/call-a-foreign-language-function-1.ocaml @@ -1,3 +1,3 @@ void myfunc_a(); float myfunc_b(int, float); -char *myfunc_c(int *); +char *myfunc_c(int *, int); diff --git a/Task/Call-a-foreign-language-function/OCaml/call-a-foreign-language-function-3.ocaml b/Task/Call-a-foreign-language-function/OCaml/call-a-foreign-language-function-3.ocaml index ff4c2099d9..64c7eb7b4e 100644 --- a/Task/Call-a-foreign-language-function/OCaml/call-a-foreign-language-function-3.ocaml +++ b/Task/Call-a-foreign-language-function/OCaml/call-a-foreign-language-function-3.ocaml @@ -9,7 +9,7 @@ caml_myfunc_a(value unit) { } CAMLprim value -caml_myfunc_b(value a; value b) { +caml_myfunc_b(value a, value b) { float c = myfunc_b(Int_val(a), Double_val(b)); return caml_copy_double(c); } @@ -24,7 +24,7 @@ caml_myfunc_c(value ml_array) { for (i=0; i < len; i++) { arr[i] = Int_val(Field(ml_array, i)); } - s = myfunc_c(arr); + s = myfunc_c(arr, len); free(arr); return caml_copy_string(s); } diff --git a/Task/Call-a-foreign-language-function/OCaml/call-a-foreign-language-function-5.ocaml b/Task/Call-a-foreign-language-function/OCaml/call-a-foreign-language-function-5.ocaml new file mode 100644 index 0000000000..c5858d4cb5 --- /dev/null +++ b/Task/Call-a-foreign-language-function/OCaml/call-a-foreign-language-function-5.ocaml @@ -0,0 +1,11 @@ +open Ctypes +open Foreign + +let myfunc_a = foreign "myfunc_a" (void @-> returning void) +let myfunc_b = foreign "myfunc_b" (int @-> float @-> returning float) +let myfunc_c = foreign "myfunc_c" (ptr void @-> int @-> returning string) + +let myfunc_c lst = + let arr = CArray.of_list int lst in + myfunc_c (to_voidp (CArray.start arr)) (CArray.length arr) +;; diff --git a/Task/Call-a-function-in-a-shared-library/Go/call-a-function-in-a-shared-library-1.go b/Task/Call-a-function-in-a-shared-library/Go/call-a-function-in-a-shared-library-1.go new file mode 100644 index 0000000000..224e741eea --- /dev/null +++ b/Task/Call-a-function-in-a-shared-library/Go/call-a-function-in-a-shared-library-1.go @@ -0,0 +1,8 @@ +#include +/* gcc -shared -fPIC -nostartfiles fakeimglib.c -o fakeimglib.so */ +int openimage(const char *s) +{ + static int handle = 100; + fprintf(stderr, "opening %s\n", s); + return handle++; +} diff --git a/Task/Call-a-function-in-a-shared-library/Go/call-a-function-in-a-shared-library-2.go b/Task/Call-a-function-in-a-shared-library/Go/call-a-function-in-a-shared-library-2.go new file mode 100644 index 0000000000..f0fe79aaab --- /dev/null +++ b/Task/Call-a-function-in-a-shared-library/Go/call-a-function-in-a-shared-library-2.go @@ -0,0 +1,52 @@ +package main + +/* +#cgo LDFLAGS: -ldl + +#include +#include + +typedef int (*someFunc) (const char *s); + +int bridge_someFunc(someFunc f, const char *s) { + return f(s); +} +*/ +import "C" +import ( + "fmt" + "os" + "unsafe" +) + +var handle = -1 + +func myOpenImage(s string) int { + fmt.Fprintf(os.Stderr, "internal openImage opens %s...\n", s) + handle++ + return handle +} + +func main() { + libpath := C.CString("./fakeimglib.so") + defer C.free(unsafe.Pointer(libpath)) + imglib := C.dlopen(libpath, C.RTLD_LAZY) + var imghandle int + if imglib != nil { + openimage := C.CString("openimage") + defer C.free(unsafe.Pointer(openimage)) + fp := C.dlsym(imglib, openimage) + if fp != nil { + fi := C.CString("fake.img") + defer C.free(unsafe.Pointer(fi)) + imghandle = int(C.bridge_someFunc(C.someFunc(fp), fi)) + + } else { + imghandle = myOpenImage("fake.img") + } + C.dlclose(imglib) + } else { + imghandle = myOpenImage("fake.img") + } + fmt.Printf("opened with handle %d\n", imghandle) +} diff --git a/Task/Call-a-function-in-a-shared-library/Perl/call-a-function-in-a-shared-library-1.pl b/Task/Call-a-function-in-a-shared-library/Perl/call-a-function-in-a-shared-library-1.pl new file mode 100644 index 0000000000..60a29b611f --- /dev/null +++ b/Task/Call-a-function-in-a-shared-library/Perl/call-a-function-in-a-shared-library-1.pl @@ -0,0 +1,10 @@ +use Inline + C => "DATA", + ENABLE => "AUTOWRAP", + LIBS => "-lm"; + +print 4*atan(1) . "\n"; + +__DATA__ +__C__ +double atan(double x); diff --git a/Task/Call-a-function-in-a-shared-library/Perl/call-a-function-in-a-shared-library-2.pl b/Task/Call-a-function-in-a-shared-library/Perl/call-a-function-in-a-shared-library-2.pl new file mode 100644 index 0000000000..5e326c1520 --- /dev/null +++ b/Task/Call-a-function-in-a-shared-library/Perl/call-a-function-in-a-shared-library-2.pl @@ -0,0 +1,7 @@ +use FFI::Platypus; +my $ffi = FFI::Platypus->new; +$ffi->lib(undef); +$ffi->attach(puts => ['string'] => 'int'); +$ffi->attach(atan => ['double'] => 'double'); + +puts(4*atan(1)); 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 5bd89cb701..ce3efa2f68 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 c0 := { console.writeLine("No argument provided") }; var c2 := (int a, int b){ console.printLine("Arguments ",a," and ",b," provided") }; diff --git a/Task/Call-a-function/Go/call-a-function-10.go b/Task/Call-a-function/Go/call-a-function-10.go new file mode 100644 index 0000000000..64c134f5dd --- /dev/null +++ b/Task/Call-a-function/Go/call-a-function-10.go @@ -0,0 +1,2 @@ + list = append(list, a, d, e, i) + i = len(list) diff --git a/Task/Call-a-function/Go/call-a-function-11.go b/Task/Call-a-function/Go/call-a-function-11.go new file mode 100644 index 0000000000..13235f3657 --- /dev/null +++ b/Task/Call-a-function/Go/call-a-function-11.go @@ -0,0 +1,21 @@ +package main + +import "fmt" + +// int parameter, so arguments will be passed to it by value. +func zeroval(ival int) { + ival = 0 +} +// has an *int parameter, meaning that it takes an int pointer. +func zeroptr(iptr *int) { + *iptr = 0 +} +func main() { + i := 1 + fmt.Println("initial:", i) // prt initial: 1 + zeroval(i) + fmt.Println("zeroval:", i) // prt zeroval: 1 + zeroptr(&i) + fmt.Println("zeroptr:", i) // prt zeroptr: 0 + fmt.Println("pointer:", &i) // prt pointer: 0xc0000140b8 +} diff --git a/Task/Call-a-function/Go/call-a-function-12.go b/Task/Call-a-function/Go/call-a-function-12.go new file mode 100644 index 0000000000..475f98af38 --- /dev/null +++ b/Task/Call-a-function/Go/call-a-function-12.go @@ -0,0 +1,27 @@ +package main + +import "fmt" + +func mkAdd(a int) func(int) int { + return func(b int) int { + return a + b + } +} +func sum(x, y int) int { + return x + y +} + +func partialSum(x int) func(int) int { + return func(y int) int { + return sum(x, y) + } +} +func main() { + // Is partial application possible and how + add2 := mkAdd(2) + add3 := mkAdd(3) + fmt.Println(add2(5), add3(6)) // prt 7 9 + // Currying functions in go + partial := partialSum(13) + fmt.Println(partial(5)) //prt 18 +} diff --git a/Task/Call-a-function/Go/call-a-function-5.go b/Task/Call-a-function/Go/call-a-function-5.go index 05a1bb6830..768aff8b9f 100644 --- a/Task/Call-a-function/Go/call-a-function-5.go +++ b/Task/Call-a-function/Go/call-a-function-5.go @@ -1 +1,14 @@ - if 2*g(1, 3.0)+4 > 0 {} +package main + +import "fmt" + +type Params struct { + a, b, c int +} +func doIt(p Params) int { + return p.a + p.b + p.c +} + +func main() { + fmt.Println(doIt(Params{a: 1, c: 9})) // prt 10 +} diff --git a/Task/Call-a-function/Go/call-a-function-6.go b/Task/Call-a-function/Go/call-a-function-6.go index 5f61e283c2..34803a26d0 100644 --- a/Task/Call-a-function/Go/call-a-function-6.go +++ b/Task/Call-a-function/Go/call-a-function-6.go @@ -1,9 +1,15 @@ - fn := func(r rune) rune { - if unicode.IsSpace(r) { - return -1 - } - return r - } - strings.Map(fn, "Spaces removed") - strings.Map(unicode.ToLower, "Test") - strings.Map(func(r rune) rune { return r + 1 }, "shift") +package main + +import "fmt" + +func bar(a, b, c int) { + fmt.Printf("%d, %d, %d", a, b, c) +} + +func main() { + args := make(map[string]int) + args["a"] = 3 + args["b"] = 2 + args["c"] = 1 + bar(args["a"], args["b"], args["c"]) // prt 3, 2, 1 +} diff --git a/Task/Call-a-function/Go/call-a-function-7.go b/Task/Call-a-function/Go/call-a-function-7.go index eade45e08c..05a1bb6830 100644 --- a/Task/Call-a-function/Go/call-a-function-7.go +++ b/Task/Call-a-function/Go/call-a-function-7.go @@ -1,4 +1 @@ - a, b := f() // multivalue return - _, c := f() // only some of a multivalue return - d := g(a, c) // single return value - e, i := g(d, b), g(d, 2) // multiple assignment + if 2*g(1, 3.0)+4 > 0 {} diff --git a/Task/Call-a-function/Go/call-a-function-8.go b/Task/Call-a-function/Go/call-a-function-8.go index 64c134f5dd..5f61e283c2 100644 --- a/Task/Call-a-function/Go/call-a-function-8.go +++ b/Task/Call-a-function/Go/call-a-function-8.go @@ -1,2 +1,9 @@ - list = append(list, a, d, e, i) - i = len(list) + fn := func(r rune) rune { + if unicode.IsSpace(r) { + return -1 + } + return r + } + strings.Map(fn, "Spaces removed") + strings.Map(unicode.ToLower, "Test") + strings.Map(func(r rune) rune { return r + 1 }, "shift") diff --git a/Task/Call-a-function/Go/call-a-function-9.go b/Task/Call-a-function/Go/call-a-function-9.go new file mode 100644 index 0000000000..eade45e08c --- /dev/null +++ b/Task/Call-a-function/Go/call-a-function-9.go @@ -0,0 +1,4 @@ + a, b := f() // multivalue return + _, c := f() // only some of a multivalue return + d := g(a, c) // single return value + e, i := g(d, b), g(d, 2) // multiple assignment diff --git a/Task/Call-a-function/Ol/call-a-function.ol b/Task/Call-a-function/Ol/call-a-function.ol index f615555fc5..b88f7ea74b 100644 --- a/Task/Call-a-function/Ol/call-a-function.ol +++ b/Task/Call-a-function/Ol/call-a-function.ol @@ -64,13 +64,13 @@ ; ==> a: 3 ; ==> b: 13 ; or nicer (and shorter) form available from ol version 2.1 -(named-args-function '{(a . 3)}) +(named-args-function '{a 3}) ; ==> a: 3 ; ==> b: 13 -(named-args-function '{(b . 7)}) +(named-args-function '{b 7}) ; ==> a: 8 ; ==> b: 7 -(named-args-function '{(a . 3) (b . 7)}) +(named-args-function '{a 3 b 7}) ; ==> a: 3 ; ==> b: 7 diff --git a/Task/Call-a-function/Perl-6/call-a-function-11.pl6 b/Task/Call-a-function/Perl-6/call-a-function-11.pl6 new file mode 100644 index 0000000000..33b89c18c6 --- /dev/null +++ b/Task/Call-a-function/Perl-6/call-a-function-11.pl6 @@ -0,0 +1,91 @@ +{ +state $n; + +multi f () { print ' f' ~ ++$n } +multi f ($a) { die if 1 != $a; print ' f' ~ ++$n } +multi f ($a,$b) { die if 3 != $a+$b; print ' f' ~ ++$n } +multi f (@a) { die if @a != [2,3,4]; print ' f' ~ ++$n } +multi f ($a,$b,$c) { die if 2 != $a || 4 != $c; print ' f' ~ ++$n } +sub g ($a,*@b) { die if @b != [2,3,4] || 1 != $a; print ' g' ~ ++$n } + +my \i = -> { print ' i' ~ ++$n } +my \l = -> $a { die if 1 != $a; print ' l' ~ ++$n } +my \m = -> $a,$b { die if 1 != $a || 2 != $b; print ' m' ~ ++$n } +my \n = -> @a { die if @a != [2,3,4]; print ' n' ~ ++$n } + +Int.^add_method( 'j', method () + { die if 1 != self; print ' j' ~ ++$n } ); +Int.^add_method( 'k', method ($a) + { die if 1 != self || 2 != $a; print ' k' ~ ++$n } ); +Int.^add_method( 'h', method (@a) + { die if @a != [2,3,4] || 1 != self; print ' h' ~ ++$n } ); + +my $ref = &f; # soft ref +my $f := &f; # hard ref +my $g := &g; # hard ref +my $f-sym = '&f'; # symbolic ref +my $g-sym = '&g'; # symbolic ref +my $j-sym = 'j'; # symbolic ref +my $k-sym = 'k'; # symbolic ref +my $h-sym = 'h'; # symbolic ref + +# Calling a function with no arguments: + +f; # 1 as list operator +f(); # 2 as function +i.(); # 3 as function, explicit postfix form # defined via pointy-block +$ref(); # 4 as object invocation +$ref.(); # 5 as object invocation, explicit postfix +&f(); # 6 as object invocation +&f.(); # 7 as object invocation, explicit postfix +::($f-sym)(); # 8 as symbolic ref + +# Calling a function with exactly one argument: + +f 1; # 9 as list operator +f(1); # 10 as named function +l.(1); # 11 as named function, explicit postfix # defined via pointy-block +$f(1); # 12 as object invocation (must be hard ref) +$ref.(1); # 13 as object invocation, explicit postfix +1.$f; # 14 as pseudo-method meaning $f(1) (hard ref only) +1.$f(); # 15 as pseudo-method meaning $f(1) (hard ref only) +1.&f; # 16 as pseudo-method meaning &f(1) (is hard f) +1.&f(); # 17 as pseudo-method meaning &f(1) (is hard f) +1.j; # 18 as method via dispatcher # requires custom method, via 'Int.^add_method' +1.j(); # 19 as method via dispatcher +1."$j-sym"(); # 20 as method via dispatcher, symbolic + +# Calling a function with exactly two arguments: + +f 1,2; # 21 as list operator +f(1,2); # 22 as named function +m.(1,2); # 23 as named function, explicit postfix # defined via pointy-block +$ref(1,2); # 24 as object invocation (must be hard ref) +$ref.(1,2); # 25 as object invocation, explicit postfix +1.$f: 2; # 26 as pseudo-method meaning $f(1,2) (hard ref only) +1.$f(2); # 27 as pseudo-method meaning $f(1,2) (hard ref only) +1.&f: 2; # 28 as pseudo-method meaning &f(1,2) (is hard f) +1.&f(2); # 29 as pseudo-method meaning &f(1,2) (is hard f) +1.k: 2; # 30 as method via dispatcher # requires custom method, via 'Int.^add_method' +1.k(2); # 31 as method via dispatcher +1."$k-sym"(2); # 32 as method via dispatcher, symbolic + +# Calling a function with a variable number of arguments (varargs): + +my @args = 2,3,4; + +f @args; # 33 as list operator +f(@args); # 34 as named function +n.(@args); # 35 as named function, explicit postfix # defined via pointy-block +$ref(@args); # 36 as object invocation (must be hard ref) +$ref.(@args); # 37 as object invocation, explicit postfix +1.$g: @args; # 38 as pseudo-method meaning $f(1,@args) (hard ref) +1.$g(@args); # 39 as pseudo-method meaning $f(1,@args) (hard ref) +1.&g: @args; # 40 as pseudo-method meaning &f(1,@args) +1.&g(@args); # 41 as pseudo-method meaning &f(1,@args) +1.h: @args; # 42 as method via dispatcher # requires custom method, via 'Int.^add_method' +1.h(@args); # 43 as method via dispatcher +1."$h-sym"(@args); # 44 as method via dispatcher, symbolic +f(|@args); # 45 equivalent to f(1,2,3) + +} diff --git a/Task/Call-an-object-method/C/call-an-object-method.c b/Task/Call-an-object-method/C/call-an-object-method.c new file mode 100644 index 0000000000..122c236c54 --- /dev/null +++ b/Task/Call-an-object-method/C/call-an-object-method.c @@ -0,0 +1,27 @@ +#include +#include + +typedef struct{ + int x; + int (*funcPtr)(int); +}functionPair; + +int factorial(int num){ + if(num==0||num==1) + return 1; + else + return num*factorial(num-1); +} + +int main(int argc,char** argv) +{ + functionPair response; + + if(argc!=2) + return printf("Usage : %s ",argv[0]); + else{ + response = (functionPair){.x = atoi(argv[1]),.funcPtr=&factorial}; + printf("\nFactorial of %d is %d\n",response.x,response.funcPtr(response.x)); + } + return 0; +} diff --git a/Task/Carmichael-3-strong-pseudoprimes/AWK/carmichael-3-strong-pseudoprimes.awk b/Task/Carmichael-3-strong-pseudoprimes/AWK/carmichael-3-strong-pseudoprimes.awk new file mode 100644 index 0000000000..2139926760 --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/AWK/carmichael-3-strong-pseudoprimes.awk @@ -0,0 +1,42 @@ +# syntax: GAWK -f CARMICHAEL_3_STRONG_PSEUDOPRIMES.AWK +# converted from C +BEGIN { + printf("%5s%8s%8s%13s\n","P1","P2","P3","PRODUCT") + for (p1=2; p1<62; p1++) { + if (!is_prime(p1)) { continue } + for (h3=1; h3 1) + } + else if (!(n%2) || !(n%3)) { + return(0) + } + else { + for (i=5; i*i<=n; i+=6) { + if (!(n%i) || !(n%(i+2))) { + return(0) + } + } + return(1) + } +} +function mod(n,m) { +# the % operator actually calculates the remainder of a / b so we need a small adjustment so it works as expected for negative values + return(((n%m)+m)%m) +} diff --git a/Task/Carmichael-3-strong-pseudoprimes/Factor/carmichael-3-strong-pseudoprimes.factor b/Task/Carmichael-3-strong-pseudoprimes/Factor/carmichael-3-strong-pseudoprimes.factor new file mode 100644 index 0000000000..fe7bfed231 --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/Factor/carmichael-3-strong-pseudoprimes.factor @@ -0,0 +1,23 @@ +USING: formatting kernel locals math math.primes math.ranges +sequences ; +IN: rosetta-code.carmichael + +:: carmichael ( p1 -- ) + 1 p1 (a,b) [| h3 | + h3 p1 + [1,b) [| d | + h3 p1 + p1 1 - * d mod zero? + p1 neg p1 * h3 rem d h3 mod = and + [ + p1 1 - h3 p1 + * d /i 1 + :> p2 + p1 p2 * h3 /i 1 + :> p3 + p2 p3 [ prime? ] both? + p2 p3 * p1 1 - mod 1 = and + [ p1 p2 p3 "%d %d %d\n" printf ] when + ] when + ] each + ] each +; + +: carmichael-demo ( -- ) 61 primes-upto [ carmichael ] each ; + +MAIN: carmichael-demo diff --git a/Task/Carmichael-3-strong-pseudoprimes/Nim/carmichael-3-strong-pseudoprimes.nim b/Task/Carmichael-3-strong-pseudoprimes/Nim/carmichael-3-strong-pseudoprimes.nim new file mode 100644 index 0000000000..d16a4c2b4b --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/Nim/carmichael-3-strong-pseudoprimes.nim @@ -0,0 +1,34 @@ +import strformat + +func myMod(n, m: int64): int64 = + ((n mod m) + m) mod m + +func isPrime(n: int64): bool = + if n == 2 or n == 3: + return true + elif n < 2 or n mod 2 == 0 or n mod 3 == 0: + return false + var `div` = 5i64 + var `inc` = 2i64 + while `div` * `div` <= n: + if n mod `div` == 0: + return false + `div` += `inc` + `inc` = 6 - `inc` + return true + +for p in 2i64..63: + if not isPrime(p): + continue + for h3 in 2i64..p: + var g = h3 + p + for d in 1..g: + if g * (p - 1) mod d != 0 or myMod(-p * p, h3) != d mod h3: + continue + var q = 1 + (p - 1) * g div d + if not isPrime(q): + continue + var r = 1 + (p * q div h3) + if not isPrime(r) or (q * r) mod (p - 1) != 1: + continue + echo &"{p:5} × {q:5} × {r:5} = {p * q * r:10}" diff --git a/Task/Carmichael-3-strong-pseudoprimes/Prolog/carmichael-3-strong-pseudoprimes.pro b/Task/Carmichael-3-strong-pseudoprimes/Prolog/carmichael-3-strong-pseudoprimes.pro new file mode 100644 index 0000000000..1b247d6801 --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/Prolog/carmichael-3-strong-pseudoprimes.pro @@ -0,0 +1,31 @@ +show(Limit) :- + forall( + carmichael(Limit, P1, P2, P3, C), + format("~w * ~w * ~w ~t~20| = ~w~n", [P1, P2, P3, C])). + +carmichael(Upto, P1, P2, P3, X) :- + between(2, Upto, P1), + prime(P1), + Limit is P1 - 1, between(2, Limit, H3), + MaxD is H3 + P1 - 1, between(1, MaxD, D), + (H3 + P1)*(P1 - 1) mod D =:= 0, + -P1*P1 mod H3 =:= D mod H3, + P2 is 1 + (P1 - 1)*(H3 + P1) div D, + prime(P2), + P3 is 1 + P1*P2 div H3, + prime(P3), + X is P1*P2*P3. + +wheel235(L) :- + W = [4, 2, 4, 2, 4, 6, 2, 6 | W], + L = [1, 2, 2 | W]. + +prime(N) :- + N >= 2, + wheel235(W), + prime(N, 2, W). + +prime(N, D, _) :- D*D > N, !. +prime(N, D, [A|As]) :- + N mod D =\= 0, + D2 is D + A, prime(N, D2, As). diff --git a/Task/Carmichael-3-strong-pseudoprimes/Swift/carmichael-3-strong-pseudoprimes.swift b/Task/Carmichael-3-strong-pseudoprimes/Swift/carmichael-3-strong-pseudoprimes.swift new file mode 100644 index 0000000000..c133ce1a77 --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/Swift/carmichael-3-strong-pseudoprimes.swift @@ -0,0 +1,70 @@ +import Foundation + +extension BinaryInteger { + @inlinable + public var isPrime: Bool { + if self == 0 || self == 1 { + return false + } else if self == 2 { + return true + } + + let max = Self(ceil((Double(self).squareRoot()))) + + for i in stride(from: 2, through: max, by: 1) { + if self % i == 0 { + return false + } + } + + return true + } +} + +@inlinable +public func carmichael(p1: T) -> [(T, T, T)] { + func mod(_ n: T, _ m: T) -> T { (n % m + m) % m } + + var res = [(T, T, T)]() + + guard p1.isPrime else { + return res + } + + for h3 in stride(from: 2, to: p1, by: 1) { + for d in stride(from: 1, to: h3 + p1, by: 1) { + if (h3 + p1) * (p1 - 1) % d != 0 || mod(-p1 * p1, h3) != d % h3 { + continue + } + + let p2 = 1 + (p1 - 1) * (h3 + p1) / d + + guard p2.isPrime else { + continue + } + + let p3 = 1 + p1 * p2 / h3 + + guard p3.isPrime && (p2 * p3) % (p1 - 1) == 1 else { + continue + } + + res.append((p1, p2, p3)) + } + } + + return res +} + + +let res = + (1..<62) + .lazy + .filter({ $0.isPrime }) + .map(carmichael) + .filter({ !$0.isEmpty }) + .flatMap({ $0 }) + +for c in res { + print(c) +} diff --git a/Task/Carmichael-3-strong-pseudoprimes/Vala/carmichael-3-strong-pseudoprimes.vala b/Task/Carmichael-3-strong-pseudoprimes/Vala/carmichael-3-strong-pseudoprimes.vala new file mode 100644 index 0000000000..159d6b1891 --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/Vala/carmichael-3-strong-pseudoprimes.vala @@ -0,0 +1,33 @@ +long mod(long n, long m) { + return ((n % m) + m) % m; +} + +bool is_prime(long n) { + if (n == 2 || n == 3) + return true; + else if (n < 2 || n % 2 == 0 || n % 3 == 0) + return false; + for (long div = 5, inc = 2; div * div <= n; + div += inc, inc = 6 - inc) + if (n % div == 0) + return false; + return true; +} + +void main() { + for (long p = 2; p <= 63; p++) { + if (!is_prime(p)) continue; + for (long h3 = 2; h3 <= p; h3++) { + var g = h3 + p; + for (long d = 1; d <= g; d++) { + if ((g * (p - 1)) % d != 0 || mod(-p * p, h3) != d % h3) + continue; + var q = 1 + (p - 1) * g / d; + if (!is_prime(q)) continue; + var r = 1 + (p * q / h3); + if (!is_prime(r) || (q * r) % (p - 1) != 1) continue; + stdout.printf("%5ld × %5ld × %5ld = %10ld\n", p, q, r, p * q * r); + } + } + } +} diff --git a/Task/Casting-out-nines/C/casting-out-nines.c b/Task/Casting-out-nines/C/casting-out-nines.c new file mode 100644 index 0000000000..eba840490e --- /dev/null +++ b/Task/Casting-out-nines/C/casting-out-nines.c @@ -0,0 +1,21 @@ +#include +#include + +int main() { + const int N = 2; + int base = 10; + int c1 = 0; + int c2 = 0; + int k; + + for (k = 1; k < pow(base, N); k++) { + c1++; + if (k % (base - 1) == (k * k) % (base - 1)) { + c2++; + printf("%d ", k); + } + } + + printf("\nTring %d numbers instead of %d numbers saves %f%%\n", c2, c1, 100.0 - 100.0 * c2 / c1); + return 0; +} diff --git a/Task/Casting-out-nines/Rust/casting-out-nines.rust b/Task/Casting-out-nines/Rust/casting-out-nines.rust new file mode 100644 index 0000000000..c74690a360 --- /dev/null +++ b/Task/Casting-out-nines/Rust/casting-out-nines.rust @@ -0,0 +1,21 @@ +fn compare_co9_efficiency(base: u64, upto: u64) { + let naive_candidates: Vec = (1u64..upto).collect(); + let co9_candidates: Vec = naive_candidates.iter().cloned() + .filter(|&x| x % (base - 1) == (x * x) % (base - 1)) + .collect(); + for candidate in &co9_candidates { + print!("{} ", candidate); + } + println!(); + println!( + "Trying {} numbers instead of {} saves {:.2}%", + co9_candidates.len(), + naive_candidates.len(), + 100.0 - 100.0 * (co9_candidates.len() as f64 / naive_candidates.len() as f64) + ); +} + +fn main() { + compare_co9_efficiency(10, 100); + compare_co9_efficiency(16, 256); +} diff --git a/Task/Catalan-numbers-Pascals-triangle/Vala/catalan-numbers-pascals-triangle.vala b/Task/Catalan-numbers-Pascals-triangle/Vala/catalan-numbers-pascals-triangle.vala new file mode 100644 index 0000000000..2a2c774674 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Vala/catalan-numbers-pascals-triangle.vala @@ -0,0 +1,11 @@ +void main() { + const int N = 15; + uint64[] t = {0, 1}; + for (int i = 1; i <= N; i++) { + for (int j = i; j > 1; j--) t[j] = t[j] + t[j - 1]; + t[i + 1] = t[i]; + for (int j = i + 1; j > 1; j--) t[j] = t[j] + t[j - 1]; + print(@"$(t[i + 1] - t[i]) "); + } + print("\n"); +} diff --git a/Task/Catalan-numbers/EDSAC-order-code/catalan-numbers.edsac b/Task/Catalan-numbers/EDSAC-order-code/catalan-numbers.edsac new file mode 100644 index 0000000000..2c170a456d --- /dev/null +++ b/Task/Catalan-numbers/EDSAC-order-code/catalan-numbers.edsac @@ -0,0 +1,99 @@ + [Calculation of Catalan numbers. + EDSAC program, Initial Orders 2.] + + [Define where to store the list of Catalan numbers.] + T 54 K [store address in location 54, so that values + are accessed by code letter C (for Catalan)] + P 200 F [<------ address here] + + [Modification of library subroutine P7. + Prints signed integer up to 10 digits, right-justified. + 54 storage locations; working position 4D. + 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@ + + [Main routine] + T 120 K [load at 120] + G K [set @ (theta) to load address] + [Variables] + [0] P F [index of Catalan number] + [Constants] + [1] P 7 D [maximum index required] + [2] P D [single-word 1] + [3] P 2 F [to change addresses by 2] + [4] H #C [these 3 are used to manufacture EDSAC orders] + [5] T #C + [6] V #C + [7] K 4096 F [(1) add to change T order into H order + (2) teleprinter null] + [8] # F [figures shift] + [9] ! F [space] + [10] @ F [carriage return] + [11] & F [line feed] + + [Enter with acc = 0] + [12] O 8 @ [set teleprinter to figures] + T 4 D [clear 5F and sandwich bit] + A 2 @ [load single-word 1] + T 4 F [store as double word at 4D; clear acc] + [Here with index in acc, Catalan number in 4D] + [16] U @ [store index] + L 1 F [times 4 by shifting] + A 5 @ [make T order to store Catalan number] + U 27 @ [plant in code] + A 7 @ [make H order with same address] + U 45 @ [plant in code] + S 47 @ [make A order with same address] + T 34 @ [plant in code] + A 6 @ [load V order for start of list] + T 46 @ [plant in code] + A 4 D [Catalan number from temp store] + [27] T #C [store in list (manufactured order)] + T D [clear 1F and sandwich bit] + A @ [load single-word index] + T F [store as double word at 0D] + [31] A 31 @ [for return from print subroutine] + G 56 F [print index] + O 9 @ [followed by space] + [34] A #C [load Catalan number (manufactured order)] + T D [to 0D for printing] + [36] A 36 @ [for return from print subroutine] + G 56 F [print Catalan number] + O 10 @ [followed by new line] + O 11 @ + T 4 D [clear partial sum] + A @ [load index] + S 1 @ [reached the maximum?] + E 64 @ [if so, jump to exit] + [Inner loop to compute sum of products C{i}*C(n-1}] + [44] T F [clear acc] + [45] H #C [C{n-i} to mult reg (manufactured order)] + [46] V #C [acc := C{i}*C{n-i} (manufactiured order)] + [Multiply product by 2^34 (see preamble). The 'L F' order is + also exploited above to convert an H order into an A order.] + [47] L F [shift acc left by 13 (the maximum available)] + L F [shift 13 more] + L 64 F [shift 8 more, total 34] + A 4 D [add partial sum] + T 4 D [update partial sum] + A 46 @ [inc i in V order] + A 3 @ + T 46 @ + A 45 @ [dec (n - i) in H order] + S 3 @ + U 45 @ + S 4 @ [is (n - i) now negative?] + E 44 @ [if not, loop back] + [Here with latest Catalan number in temp store 4D] + T F [clear acc] + A @ [load index] + A 2 @ [add 1] + E 16 @ [back to start of outer loop] + [64] O 7 @ [exit; print null to flush teleprinter buffer] + Z F [stop] + E 12 Z [define entry point] + P F [acc = 0 on entry] diff --git a/Task/Catalan-numbers/Scala/catalan-numbers.scala b/Task/Catalan-numbers/Scala/catalan-numbers.scala index 009f8eeb59..aea90c7a22 100644 --- a/Task/Catalan-numbers/Scala/catalan-numbers.scala +++ b/Task/Catalan-numbers/Scala/catalan-numbers.scala @@ -1,10 +1,11 @@ -object Catalan { - def factorial(n: BigInt) = BigInt(1).to(n).foldLeft(BigInt(1))(_ * _) - def catalan(n: BigInt) = factorial(2 * n) / (factorial(n + 1) * factorial(n)) - - def main(args: Array[String]) { +object CatalanNumbers { + def main(args: Array[String]): Unit = { for (n <- 0 to 15) { println("catalan(" + n + ") = " + catalan(n)) } } + + def catalan(n: BigInt): BigInt = factorial(2 * n) / (factorial(n + 1) * factorial(n)) + + def factorial(n: BigInt): BigInt = BigInt(1).to(n).foldLeft(BigInt(1))(_ * _) } diff --git a/Task/Catalan-numbers/Vala/catalan-numbers.vala b/Task/Catalan-numbers/Vala/catalan-numbers.vala new file mode 100644 index 0000000000..b8f72eb6cd --- /dev/null +++ b/Task/Catalan-numbers/Vala/catalan-numbers.vala @@ -0,0 +1,77 @@ +namespace CatalanNumbers { + public class CatalanNumberGenerator { + private static double factorial(double n) { + if (n == 0) + return 1; + return n * factorial(n - 1); + } + + public double first_method(double n) { + const double top_multiplier = 2; + return factorial(top_multiplier * n) / (factorial(n + 1) * factorial(n)); + } + + public double second_method(double n) { + if (n == 0) { + return 1; + } + double sum = 0; + double i = 0; + for (; i <= (n - 1); i++) { + sum += second_method(i) * second_method((n - 1) - i); + } + return sum; + } + + public double third_method(double n) { + if (n == 0) { + return 1; + } + return ((2 * (2 * n - 1)) / (n + 1)) * third_method(n - 1); + } + } + + void main() { + CatalanNumberGenerator generator = new CatalanNumberGenerator(); + DateTime initial_time; + DateTime final_time; + TimeSpan ts; + + stdout.printf("Direct Method\n"); + stdout.printf(" n%9s\n", "C_n"); + stdout.printf("............\n"); + initial_time = new DateTime.now(); + for (double i = 0; i <= 15; i++) { + stdout.printf("%2s %8s\n", i.to_string(), Math.ceil(generator.first_method(i)).to_string()); + } + final_time = new DateTime.now(); + ts = final_time.difference(initial_time); + stdout.printf("............\n"); + stdout.printf("Time Elapsed: %s μs\n", ts.to_string()); + + stdout.printf("\nRecursive Method 1\n"); + stdout.printf(" n%9s\n", "C_n"); + stdout.printf("............\n"); + initial_time = new DateTime.now(); + for (double i = 0; i <= 15; i++) { + stdout.printf("%2s %8s\n", i.to_string(), Math.ceil(generator.second_method(i)).to_string()); + } + final_time = new DateTime.now(); + ts = final_time.difference(initial_time); + stdout.printf("............\n"); + stdout.printf("Time Elapsed: %s μs\n", ts.to_string()); + + stdout.printf("\nRecursive Method 2\n"); + stdout.printf(" n%9s\n", "C_n"); + stdout.printf("............\n"); + initial_time = new DateTime.now(); + for (double i = 0; i <= 15; i++) { + stdout.printf("%2s %8s\n", i.to_string(), Math.ceil(generator.third_method(i)).to_string()); + } + final_time = new DateTime.now(); + ts = final_time.difference(initial_time); + stdout.printf("............\n"); + stdout.printf("Time Elapsed: %s μs\n", ts.to_string()); + + } +} diff --git a/Task/Catmull-Clark-subdivision-surface/Go/catmull-clark-subdivision-surface.go b/Task/Catmull-Clark-subdivision-surface/Go/catmull-clark-subdivision-surface.go new file mode 100644 index 0000000000..fe5751f97a --- /dev/null +++ b/Task/Catmull-Clark-subdivision-surface/Go/catmull-clark-subdivision-surface.go @@ -0,0 +1,286 @@ +package main + +import ( + "fmt" + "sort" +) + +type ( + Point [3]float64 + Face []int + + Edge struct { + pn1 int // point number 1 + pn2 int // point number 2 + fn1 int // face number 1 + fn2 int // face number 2 + cp Point // center point + } + + PointEx struct { + p Point + n int + } +) + +func sumPoint(p1, p2 Point) Point { + sp := Point{} + for i := 0; i < 3; i++ { + sp[i] = p1[i] + p2[i] + } + return sp +} + +func mulPoint(p Point, m float64) Point { + mp := Point{} + for i := 0; i < 3; i++ { + mp[i] = p[i] * m + } + return mp +} + +func divPoint(p Point, d float64) Point { + return mulPoint(p, 1.0/d) +} + +func centerPoint(p1, p2 Point) Point { + return divPoint(sumPoint(p1, p2), 2) +} + +func getFacePoints(inputPoints []Point, inputFaces []Face) []Point { + facePoints := make([]Point, len(inputFaces)) + for i, currFace := range inputFaces { + facePoint := Point{} + for _, cpi := range currFace { + currPoint := inputPoints[cpi] + facePoint = sumPoint(facePoint, currPoint) + } + facePoint = divPoint(facePoint, float64(len(currFace))) + facePoints[i] = facePoint + } + return facePoints +} + +func getEdgesFaces(inputPoints []Point, inputFaces []Face) []Edge { + var edges [][3]int + for faceNum, face := range inputFaces { + numPoints := len(face) + for pointIndex := 0; pointIndex < numPoints; pointIndex++ { + pointNum1 := face[pointIndex] + var pointNum2 int + if pointIndex < numPoints-1 { + pointNum2 = face[pointIndex+1] + } else { + pointNum2 = face[0] + } + if pointNum1 > pointNum2 { + pointNum1, pointNum2 = pointNum2, pointNum1 + } + edges = append(edges, [3]int{pointNum1, pointNum2, faceNum}) + } + } + sort.Slice(edges, func(i, j int) bool { + if edges[i][0] == edges[j][0] { + if edges[i][1] == edges[j][1] { + return edges[i][2] < edges[j][2] + } + return edges[i][1] < edges[j][1] + } + return edges[i][0] < edges[j][0] + }) + numEdges := len(edges) + eIndex := 0 + var mergedEdges [][4]int + for eIndex < numEdges { + e1 := edges[eIndex] + if eIndex < numEdges-1 { + e2 := edges[eIndex+1] + if e1[0] == e2[0] && e1[1] == e2[1] { + mergedEdges = append(mergedEdges, [4]int{e1[0], e1[1], e1[2], e2[2]}) + eIndex += 2 + } else { + mergedEdges = append(mergedEdges, [4]int{e1[0], e1[1], e1[2], -1}) + eIndex++ + } + } else { + mergedEdges = append(mergedEdges, [4]int{e1[0], e1[1], e1[2], -1}) + eIndex++ + } + } + var edgesCenters []Edge + for _, me := range mergedEdges { + p1 := inputPoints[me[0]] + p2 := inputPoints[me[1]] + cp := centerPoint(p1, p2) + edgesCenters = append(edgesCenters, Edge{me[0], me[1], me[2], me[3], cp}) + } + return edgesCenters +} + +func getEdgePoints(inputPoints []Point, edgesFaces []Edge, facePoints []Point) []Point { + edgePoints := make([]Point, len(edgesFaces)) + for i, edge := range edgesFaces { + cp := edge.cp + fp1 := facePoints[edge.fn1] + var fp2 Point + if edge.fn2 == -1 { + fp2 = fp1 + } else { + fp2 = facePoints[edge.fn2] + } + cfp := centerPoint(fp1, fp2) + edgePoints[i] = centerPoint(cp, cfp) + } + return edgePoints +} + +func getAvgFacePoints(inputPoints []Point, inputFaces []Face, facePoints []Point) []Point { + numPoints := len(inputPoints) + tempPoints := make([]PointEx, numPoints) + for faceNum := range inputFaces { + fp := facePoints[faceNum] + for _, pointNum := range inputFaces[faceNum] { + tp := tempPoints[pointNum].p + tempPoints[pointNum].p = sumPoint(tp, fp) + tempPoints[pointNum].n++ + } + } + avgFacePoints := make([]Point, numPoints) + for i, tp := range tempPoints { + avgFacePoints[i] = divPoint(tp.p, float64(tp.n)) + } + return avgFacePoints +} + +func getAvgMidEdges(inputPoints []Point, edgesFaces []Edge) []Point { + numPoints := len(inputPoints) + tempPoints := make([]PointEx, numPoints) + for _, edge := range edgesFaces { + cp := edge.cp + for _, pointNum := range []int{edge.pn1, edge.pn2} { + tp := tempPoints[pointNum].p + tempPoints[pointNum].p = sumPoint(tp, cp) + tempPoints[pointNum].n++ + } + } + avgMidEdges := make([]Point, len(tempPoints)) + for i, tp := range tempPoints { + avgMidEdges[i] = divPoint(tp.p, float64(tp.n)) + } + return avgMidEdges +} + +func getPointsFaces(inputPoints []Point, inputFaces []Face) []int { + numPoints := len(inputPoints) + pointsFaces := make([]int, numPoints) + for faceNum := range inputFaces { + for _, pointNum := range inputFaces[faceNum] { + pointsFaces[pointNum]++ + } + } + return pointsFaces +} + +func getNewPoints(inputPoints []Point, pointsFaces []int, avgFacePoints, avgMidEdges []Point) []Point { + newPoints := make([]Point, len(inputPoints)) + for pointNum := range inputPoints { + n := float64(pointsFaces[pointNum]) + m1, m2, m3 := (n-3)/n, 1.0/n, 2.0/n + oldCoords := inputPoints[pointNum] + p1 := mulPoint(oldCoords, m1) + afp := avgFacePoints[pointNum] + p2 := mulPoint(afp, m2) + ame := avgMidEdges[pointNum] + p3 := mulPoint(ame, m3) + p4 := sumPoint(p1, p2) + newPoints[pointNum] = sumPoint(p4, p3) + } + return newPoints +} + +func switchNums(pointNums [2]int) [2]int { + if pointNums[0] < pointNums[1] { + return pointNums + } + return [2]int{pointNums[1], pointNums[0]} +} + +func cmcSubdiv(inputPoints []Point, inputFaces []Face) ([]Point, []Face) { + facePoints := getFacePoints(inputPoints, inputFaces) + edgesFaces := getEdgesFaces(inputPoints, inputFaces) + edgePoints := getEdgePoints(inputPoints, edgesFaces, facePoints) + avgFacePoints := getAvgFacePoints(inputPoints, inputFaces, facePoints) + avgMidEdges := getAvgMidEdges(inputPoints, edgesFaces) + pointsFaces := getPointsFaces(inputPoints, inputFaces) + newPoints := getNewPoints(inputPoints, pointsFaces, avgFacePoints, avgMidEdges) + var facePointNums []int + nextPointNum := len(newPoints) + for _, facePoint := range facePoints { + newPoints = append(newPoints, facePoint) + facePointNums = append(facePointNums, nextPointNum) + nextPointNum++ + } + edgePointNums := make(map[[2]int]int) + for edgeNum := range edgesFaces { + pointNum1 := edgesFaces[edgeNum].pn1 + pointNum2 := edgesFaces[edgeNum].pn2 + edgePoint := edgePoints[edgeNum] + newPoints = append(newPoints, edgePoint) + edgePointNums[[2]int{pointNum1, pointNum2}] = nextPointNum + nextPointNum++ + } + var newFaces []Face + for oldFaceNum, oldFace := range inputFaces { + if len(oldFace) == 4 { + a, b, c, d := oldFace[0], oldFace[1], oldFace[2], oldFace[3] + facePointAbcd := facePointNums[oldFaceNum] + edgePointAb := edgePointNums[switchNums([2]int{a, b})] + edgePointDa := edgePointNums[switchNums([2]int{d, a})] + edgePointBc := edgePointNums[switchNums([2]int{b, c})] + edgePointCd := edgePointNums[switchNums([2]int{c, d})] + newFaces = append(newFaces, Face{a, edgePointAb, facePointAbcd, edgePointDa}) + newFaces = append(newFaces, Face{b, edgePointBc, facePointAbcd, edgePointAb}) + newFaces = append(newFaces, Face{c, edgePointCd, facePointAbcd, edgePointBc}) + newFaces = append(newFaces, Face{d, edgePointDa, facePointAbcd, edgePointCd}) + } + } + return newPoints, newFaces +} + +func main() { + inputPoints := []Point{ + {-1.0, 1.0, 1.0}, + {-1.0, -1.0, 1.0}, + {1.0, -1.0, 1.0}, + {1.0, 1.0, 1.0}, + {1.0, -1.0, -1.0}, + {1.0, 1.0, -1.0}, + {-1.0, -1.0, -1.0}, + {-1.0, 1.0, -1.0}, + } + + inputFaces := []Face{ + {0, 1, 2, 3}, + {3, 2, 4, 5}, + {5, 4, 6, 7}, + {7, 0, 3, 5}, + {7, 6, 1, 0}, + {6, 1, 2, 4}, + } + + outputPoints := make([]Point, len(inputPoints)) + outputFaces := make([]Face, len(inputFaces)) + copy(outputPoints, inputPoints) + copy(outputFaces, inputFaces) + iterations := 1 + for i := 0; i < iterations; i++ { + outputPoints, outputFaces = cmcSubdiv(outputPoints, outputFaces) + } + for _, p := range outputPoints { + fmt.Printf("% .4f\n", p) + } + fmt.Println() + for _, f := range outputFaces { + fmt.Printf("%2d\n", f) + } +} diff --git a/Task/Catmull-Clark-subdivision-surface/Julia/catmull-clark-subdivision-surface.julia b/Task/Catmull-Clark-subdivision-surface/Julia/catmull-clark-subdivision-surface.julia new file mode 100644 index 0000000000..18b0cc6c56 --- /dev/null +++ b/Task/Catmull-Clark-subdivision-surface/Julia/catmull-clark-subdivision-surface.julia @@ -0,0 +1,145 @@ +using Makie, Statistics + +# Point3f0 is a 3-tuple of 32-bit floats for 3-dimensional space, and all Points are 3D. +Point = Point3f0 + +# a Face is defined by the points that are its vertices, in order. +Face = Vector{Point} + +# an Edge is a line segment where the points are sorted +struct Edge + p1::Point + p2::Point + Edge(a, b) = new(min(a, b), max(a, b)) +end + +edgemidpoint(edge) = (edge.p1 + edge.p2) / 2.0 +facesforpoint(p, faces) = [f for f in faces if p in f] +facesforedge(e, faces) = [f for f in faces if (e.p1 in f) && (e.p2 in f)] +nexttohole(edge, faces) = length(facesforedge(edge, faces)) < 2 + +function newedgepoint(edge, faces) + f = facesforedge(edge, faces) + p1, p2, len = edge.p1, edge.p2, length(f) + if len == 2 + return (p1 + p2 + mean(f[1]) + mean(f[2])) / 4.0 + elseif len == 1 + return (p1 + p2 + mean(f[1])) / 3.0 + end + return (p1 + p2) / 2.0 +end + +function edgesforface(face) + ret, indices = Vector{Edge}(), collect(1:length(face)) + for i in 1:length(face)-1 + push!(ret, Edge(face[indices[1]], face[indices[2]])) + indices .= circshift(indices, 1) + end + ret +end + +function edgesforpoint(p, faces) + f = filter(x -> p in x, faces) + return filter(e -> p == e.p1 || p == e.p2, mapreduce(edgesforface, vcat, f)) +end + +function adjacentpoints(point, face) + a = indexin([point], face) + if a[1] != nothing + adjacent = (a[1] == 1) ? [face[end], face[2]] : + a[1] == length(face) ? [face[end-1], face[1]] : + [face[a[1] - 1], face[a[1] + 1]] + return sort(adjacent) + else + throw("point $point not in face $face") + end +end + +adjacentedges(point, face) = [Edge(point, x) for x in adjacentpoints(point, face)] +facewrapped(face) = begin f = deepcopy(face); push!(f, f[1]); f end +drawface(face, colr) = lines(facewrapped(face); color=colr) +drawface!(face, colr) = lines!(facewrapped(face); color=colr) +drawfaces!(faces, colr) = for f in faces drawface!(f, colr) end +const colors = [:red, :green, :blue, :gold] + +function drawfaces(faces, colr) + scene = drawface(faces[1], colr) + if length(faces) > 1 + for f in faces[2:end] + drawface!(f, colr) + end + end + scene +end + +function catmullclarkstep(faces) + d, E, dprime = Set(reduce(vcat, faces)), Dict{Vector, Point}(), Dict{Point, Point}() + for face in faces, (i, p) in enumerate(face) + edge = (p == face[end]) ? Edge(p, face[1]) : Edge(p, face[i + 1]) + E[[edge, face]] = newedgepoint(edge, faces) + end + for p in d + F = mean([mean(face) for face in facesforpoint(p, faces)]) + pe = edgesforpoint(p, faces) + R = mean(map(edgemidpoint, pe)) + n = length(pe) + dprime[p] = (F + 2 * R + p * (n - 3)) / n + end + newfaces = Vector{Face}() + for face in faces + v = mean(face) + for point in face + fp1, fp2 = map(x -> E[[x, face]], adjacentedges(point, face)) + push!(newfaces, [fp1, dprime[point], fp2, v]) + end + end + return newfaces +end + +""" + catmullclark(faces, iters, scene) + +Perform a multistep Catmull-Clark subdivision of a surface. See Wikipedia or page 53 +of http://graphics.stanford.edu/courses/cs468-10-fall/LectureSlides/10_Subdivision.pdf +Plots the iterations, with colors for each iteration as set in the colors array. +Uses a Makie Scene of scene to plot the iters iterations. +""" +function catmullclark(faces, iters, scene) + nextfaces = deepcopy(faces) + for i in 1:iters + nextfaces = catmullclarkstep(nextfaces) + drawfaces!(nextfaces, colors[i]) + display(scene) + sleep(1) + end +end + +const inputpoints = [ + [-1.0, -1.0, -1.0], + [-1.0, -1.0, 1.0], + [-1.0, 1.0, -1.0], + [-1.0, 1.0, 1.0], + [1.0, -1.0, -1.0], + [1.0, -1.0, 1.0], + [1.0, 1.0, -1.0], + [1.0, 1.0, 1.0] +] + +const inputfaces = [ + [0, 4, 5, 1], + [4, 6, 7, 5], + [6, 2, 3, 7], + [2, 0, 1, 3], + [1, 5, 7, 3], + [0, 2, 6, 4] +] + +const faces = [map(x -> Point3f0(inputpoints[x]), p .+ 1) for p in inputfaces] + +scene = drawfaces(faces, :black) +display(scene) +sleep(1) + +catmullclark(faces, 4, scene) + +println("Press Enter to continue", readline()) diff --git a/Task/Catmull-Clark-subdivision-surface/Python/catmull-clark-subdivision-surface.py b/Task/Catmull-Clark-subdivision-surface/Python/catmull-clark-subdivision-surface.py index 8d02441206..61b6288c40 100644 --- a/Task/Catmull-Clark-subdivision-surface/Python/catmull-clark-subdivision-surface.py +++ b/Task/Catmull-Clark-subdivision-surface/Python/catmull-clark-subdivision-surface.py @@ -311,9 +311,9 @@ def get_points_faces(input_points, input_faces): def get_new_points(input_points, points_faces, avg_face_points, avg_mid_edges): """ - m1 = (n - 3) / n - m2 = 1 / n - m3 = 2 / n + m1 = (n - 3.0) / n + m2 = 1.0 / n + m3 = 2.0 / n new_coords = (m1 * old_coords) + (m2 * avg_face_points) + (m3 * avg_mid_edges) @@ -324,9 +324,9 @@ def get_new_points(input_points, points_faces, avg_face_points, avg_mid_edges): for pointnum in range(len(input_points)): n = points_faces[pointnum] - m1 = (n - 3) / n - m2 = 1 / n - m3 = 2 / n + m1 = (n - 3.0) / n + m2 = 1.0 / n + m3 = 2.0 / n old_coords = input_points[pointnum] p1 = mul_point(old_coords, m1) afp = avg_face_points[pointnum] diff --git a/Task/Character-codes/Go/character-codes-2.go b/Task/Character-codes/Go/character-codes-2.go index bfba538651..83e2ddc5a9 100644 --- a/Task/Character-codes/Go/character-codes-2.go +++ b/Task/Character-codes/Go/character-codes-2.go @@ -1,21 +1,12 @@ package main -import "fmt" +import ( + "fmt" +) func main() { - // yes, there is more concise syntax, but this makes - // the data types very clear. - var b byte = 'a' - var r rune = 'π' - var s string = "aπ" - - fmt.Println(b, r, s) - fmt.Println("string cast to []rune:", []rune(s)) - // A range loop over a string gives runes, not bytes - fmt.Print(" string range loop: ") - for _, c := range s { - fmt.Print(c, " ") // c is type rune - } - // We can also print the bytes of a string without an explicit loop - fmt.Printf("\n string bytes: % #x\n", s) + // Given a character value in your language, print its code + fmt.Printf("%d\n", 'A') // prt 65 + // Given a code, print out the corresponding character. + fmt.Printf("%c\n", 65) // prt A } diff --git a/Task/Character-codes/Go/character-codes-3.go b/Task/Character-codes/Go/character-codes-3.go index 6da1b155d2..bfba538651 100644 --- a/Task/Character-codes/Go/character-codes-3.go +++ b/Task/Character-codes/Go/character-codes-3.go @@ -1,3 +1,21 @@ -b := byte(97) -r := rune(960) -fmt.Printf("%c %c\n%c %c\n", 97, 960, b, r) +package main + +import "fmt" + +func main() { + // yes, there is more concise syntax, but this makes + // the data types very clear. + var b byte = 'a' + var r rune = 'π' + var s string = "aπ" + + fmt.Println(b, r, s) + fmt.Println("string cast to []rune:", []rune(s)) + // A range loop over a string gives runes, not bytes + fmt.Print(" string range loop: ") + for _, c := range s { + fmt.Print(c, " ") // c is type rune + } + // We can also print the bytes of a string without an explicit loop + fmt.Printf("\n string bytes: % #x\n", s) +} diff --git a/Task/Character-codes/Go/character-codes-4.go b/Task/Character-codes/Go/character-codes-4.go index 538a423d08..6da1b155d2 100644 --- a/Task/Character-codes/Go/character-codes-4.go +++ b/Task/Character-codes/Go/character-codes-4.go @@ -1,3 +1,3 @@ -fmt.Println(string(97)) // prints "a" -fmt.Println(string(960)) // prints "π" -fmt.Println(string([]rune{97, 960})) // prints "aπ" +b := byte(97) +r := rune(960) +fmt.Printf("%c %c\n%c %c\n", 97, 960, b, r) diff --git a/Task/Character-codes/Go/character-codes-5.go b/Task/Character-codes/Go/character-codes-5.go new file mode 100644 index 0000000000..538a423d08 --- /dev/null +++ b/Task/Character-codes/Go/character-codes-5.go @@ -0,0 +1,3 @@ +fmt.Println(string(97)) // prints "a" +fmt.Println(string(960)) // prints "π" +fmt.Println(string([]rune{97, 960})) // prints "aπ" diff --git a/Task/Character-codes/Perl-6/character-codes.pl6 b/Task/Character-codes/Perl-6/character-codes.pl6 index 9bae28b790..4b0ee2f7a5 100644 --- a/Task/Character-codes/Perl-6/character-codes.pl6 +++ b/Task/Character-codes/Perl-6/character-codes.pl6 @@ -1,2 +1,27 @@ -say ord('𪚥').fmt('0x%04x'); -say chr(0x2a6a5); +for 'AΑА𪚥🇺🇸👨‍👩‍👧‍👦'.comb { + .put for + [ 'Character', + 'Character name', + 'Unicode property', + 'Ordinal(s)', + 'Hex ordinal(s)', + 'UTF-8', + 'UTF-16LE', + 'UTF-16BE', + 'Round trip by name', + 'Round trip by ordinal' + ]».fmt('%21s:') + Z + [ $_, + .uninames.join(', '), + .uniprops, + .ords, + .ords.fmt('0x%X'), + .encode('utf8' )».fmt('%02X'), + .encode('utf16le')».fmt('%02X').join.comb(4), + .encode('utf16be')».fmt('%02X').join.comb(4), + .uninames».uniparse.join, + .ords.chrs + ]; + say ''; +} diff --git a/Task/Character-codes/Perl/character-codes-1.pl b/Task/Character-codes/Perl/character-codes-1.pl new file mode 100644 index 0000000000..788d0c0f4b --- /dev/null +++ b/Task/Character-codes/Perl/character-codes-1.pl @@ -0,0 +1,19 @@ +use strict; +use warnings; +use utf8; +binmode(STDOUT, ':utf8'); +use Encode; +use Unicode::UCD 'charinfo'; +use List::AllUtils qw(zip natatime); + +for my $c (split //, 'AΑА薵') { + my $o = ord $c; + my $utf8 = join '', map { sprintf "%x ", ord } split //, Encode::encode("utf8", $c); + my $iterator = natatime 2, zip + @{['Character', 'Character name', 'Ordinal(s)', 'Hex ordinal(s)', 'UTF-8', 'Round trip']}, + @{[ $c, charinfo($o)->{'name'}, $o, sprintf("0x%x",$o), $utf8, chr $o, ]}; + while ( my ($label, $value) = $iterator->() ) { + printf "%14s: %s\n", $label, $value + } + print "\n"; +} diff --git a/Task/Character-codes/Perl/character-codes-2.pl b/Task/Character-codes/Perl/character-codes-2.pl new file mode 100644 index 0000000000..1a4fd8f0d2 --- /dev/null +++ b/Task/Character-codes/Perl/character-codes-2.pl @@ -0,0 +1,19 @@ +use strict; +use warnings; +use feature 'say'; +use utf8; +binmode(STDOUT, ':utf8'); +use Unicode::Normalize 'NFC'; +use Unicode::UCD qw(charinfo charprop); + +while ('Δ̂🇺🇸👨‍👩‍👧‍👦' =~ /(\X)/g) { + my @ordinals = map { ord } split //, my $c = $1; + printf "%14s: %s\n"x7 . "\n", + 'Character', NFC $c, + 'Character name', join(', ', map { charinfo($_)->{'name'} } @ordinals), + 'Unicode property', join(', ', map { charprop($_, "Gc") } @ordinals), + 'Ordinal(s)', join(' ', @ordinals), + 'Hex ordinal(s)', join(' ', map { sprintf("0x%x", $_) } @ordinals), + 'UTF-8', join('', map { sprintf "%x ", ord } (utf8::encode($c), split //, $c)), + 'Round trip', join('', map { chr } @ordinals); +} diff --git a/Task/Character-codes/Perl/character-codes.pl b/Task/Character-codes/Perl/character-codes.pl deleted file mode 100644 index b719ed390e..0000000000 --- a/Task/Character-codes/Perl/character-codes.pl +++ /dev/null @@ -1,2 +0,0 @@ -print ord('a'), "\n"; # prints "97" -print chr(97), "\n"; # prints "a" diff --git a/Task/Character-codes/Ruby/character-codes.rb b/Task/Character-codes/Ruby/character-codes.rb new file mode 100644 index 0000000000..1a7d5c6087 --- /dev/null +++ b/Task/Character-codes/Ruby/character-codes.rb @@ -0,0 +1,4 @@ +> "a".ord +=> 97 +> 97.chr +=> "a" diff --git a/Task/Chat-server/Perl/chat-server.pl b/Task/Chat-server/Perl/chat-server-1.pl similarity index 100% rename from Task/Chat-server/Perl/chat-server.pl rename to Task/Chat-server/Perl/chat-server-1.pl diff --git a/Task/Chat-server/Perl/chat-server-2.pl b/Task/Chat-server/Perl/chat-server-2.pl new file mode 100644 index 0000000000..f038244c60 --- /dev/null +++ b/Task/Chat-server/Perl/chat-server-2.pl @@ -0,0 +1,80 @@ +#!/usr/bin/perl + +use strict; # http://www.rosettacode.org/wiki/Chat_server +use warnings; +use IO::Socket; +use IO::Select; # with write queueing + +my $port = shift // 6666; +my (%nicks, @users, %data); + +my $listen = IO::Socket::INET->new(LocalPort => $port, Listen => 9, + Reuse => 1) or die "$@ opening socket on port $port"; +my $rsel = IO::Select->new($listen); +my $wsel = IO::Select->new(); +print "ready on $port...\n"; + +sub to + { + my $text = pop; + for ( @_ ) + { + length $data{$_}{out} or $wsel->add( $_ ); + length( $data{$_}{out} .= $text ) > 1e4 and left( $_ ); + } + return $text; + } + +sub left + { + my $h = shift; + @users = grep $h != $_, @users; + if( defined( my $nick = delete $nicks{$h} ) ) + { + print to @users, "$nick has left\n"; + } + delete $data{$h}; + $rsel->remove($h); + } + +while( 1 ) + { + my ($reads, $writes) = IO::Select->select($rsel, $wsel, undef, 5); + for my $h ( @{ $writes // [] } ) + { + my $len = syswrite $h, $data{$h}{out}; + $len and substr $data{$h}{out}, 0, $len, ''; + length $data{$h}{out} or $wsel->remove( $h ); + } + for my $h ( @{ $reads // [] } ) + { + if( $h == $listen ) # new connection + { + $rsel->add( my $client = $h->accept ); + $data{$client} = { h => $client, out => "enter nick: ", in => '' }; + $wsel->add( $client ); + } + elsif( not sysread $h, $data{$h}{in}, 4096, length $data{$h}{in} ) # closed + { + left $h; + } + elsif( exists $nicks{$h} ) # user is signed in + { + my @others = grep $h != $_, @users; + to @others, "$nicks{$h}> $&" while $data{$h}{in} =~ s/.*\n//; + } + elsif( $data{$h}{in} =~ s/^(\w+)\r?\n.*//s and + not grep lc $1 eq lc, values %nicks ) + { # user has joined + my $all = join ' ', sort values %nicks; + $nicks{$h} = $1; + push @users, $h; + print to @users, "$nicks{$h} has joined $all\n"; + } + else # bad nick + { + to $h, "nick invalid or in use, enter nick: "; + $data{$h}{in} = ''; + } + } + } diff --git a/Task/Check-Machin-like-formulas/00DESCRIPTION b/Task/Check-Machin-like-formulas/00DESCRIPTION index 101b74e6a7..32d135225b 100644 --- a/Task/Check-Machin-like-formulas/00DESCRIPTION +++ b/Task/Check-Machin-like-formulas/00DESCRIPTION @@ -21,7 +21,7 @@ Verify the following Machin-like formulas are correct by calculating the value o : {\pi\over4} = 44 \arctan{1\over57} + 7 \arctan{1\over239} - 12 \arctan{1\over682} + 24 \arctan{1\over12943} : {\pi\over4} = 88 \arctan{1\over172} + 51 \arctan{1\over239} + 32 \arctan{1\over682} + 44 \arctan{1\over5357} + 68 \arctan{1\over12943} -and confirm that the following formula is incorrect by showing   '''tan'''   (''right hand side)''   is ''not''   '''1''': +and confirm that the following formula is ''incorrect'' by showing   '''tan'''   (''right hand side)''   is ''not''   '''1''': : {\pi\over4} = 88 \arctan{1\over172} + 51 \arctan{1\over239} + 32 \arctan{1\over682} + 44 \arctan{1\over5357} + 68 \arctan{1\over12944} diff --git a/Task/Check-Machin-like-formulas/Java/check-machin-like-formulas.java b/Task/Check-Machin-like-formulas/Java/check-machin-like-formulas.java new file mode 100644 index 0000000000..e11872c36b --- /dev/null +++ b/Task/Check-Machin-like-formulas/Java/check-machin-like-formulas.java @@ -0,0 +1,146 @@ +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class CheckMachinFormula { + + private static String FILE_NAME = "MachinFormula.txt"; + + public static void main(String[] args) { + try { + runPrivate(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + private static void runPrivate() throws IOException { + try (BufferedReader reader = new BufferedReader(new FileReader(new File(FILE_NAME)));) { + String inLine = null; + while ( (inLine = reader.readLine()) != null ) { + String[] split = inLine.split("="); + System.out.println(tanLeft(split[0].trim()) + " = " + split[1].trim().replaceAll("\\s+", " ") + " = " + tanRight(split[1].trim())); + } + } + } + + private static String tanLeft(String formula) { + if ( formula.compareTo("pi/4") == 0 ) { + return "1"; + } + throw new RuntimeException("ERROR 104: Unknown left side: " + formula); + } + + private static final Pattern ARCTAN_PATTERN = Pattern.compile("(-{0,1}\\d+)\\*arctan\\((\\d+)/(\\d+)\\)"); + + private static Fraction tanRight(String formula) { + Matcher matcher = ARCTAN_PATTERN.matcher(formula); + List terms = new ArrayList<>(); + while ( matcher.find() ) { + terms.add(new Term(Integer.parseInt(matcher.group(1)), new Fraction(matcher.group(2), matcher.group(3)))); + } + return evaluateArctan(terms); + } + + private static Fraction evaluateArctan(List terms) { + if ( terms.size() == 1 ) { + Term term = terms.get(0); + return evaluateArctan(term.coefficient, term.fraction); + } + int size = terms.size(); + List left = terms.subList(0, (size+1) / 2); + List right = terms.subList((size+1) / 2, size); + return arctanFormula(evaluateArctan(left), evaluateArctan(right)); + } + + private static Fraction evaluateArctan(int coefficient, Fraction fraction) { + //System.out.println("C = " + coefficient + ", F = " + fraction); + if ( coefficient == 1 ) { + return fraction; + } + else if ( coefficient < 0 ) { + return evaluateArctan(-coefficient, fraction).negate(); + } + if ( coefficient % 2 == 0 ) { + Fraction f = evaluateArctan(coefficient/2, fraction); + return arctanFormula(f, f); + } + Fraction a = evaluateArctan(coefficient/2, fraction); + Fraction b = evaluateArctan(coefficient - (coefficient/2), fraction); + return arctanFormula(a, b); + } + + private static Fraction arctanFormula(Fraction f1, Fraction f2) { + return f1.add(f2).divide(Fraction.ONE.subtract(f1.multiply(f2))); + } + + private static class Fraction { + + public static final Fraction ONE = new Fraction("1", "1"); + + private BigInteger numerator; + private BigInteger denominator; + + public Fraction(String num, String den) { + numerator = new BigInteger(num); + denominator = new BigInteger(den); + } + + public Fraction(BigInteger num, BigInteger den) { + numerator = num; + denominator = den; + } + + public Fraction negate() { + return new Fraction(numerator.negate(), denominator); + } + + public Fraction add(Fraction f) { + BigInteger gcd = denominator.gcd(f.denominator); + BigInteger first = numerator.multiply(f.denominator.divide(gcd)); + BigInteger second = f.numerator.multiply(denominator.divide(gcd)); + return new Fraction(first.add(second), denominator.multiply(f.denominator).divide(gcd)); + } + + public Fraction subtract(Fraction f) { + return add(f.negate()); + } + + public Fraction multiply(Fraction f) { + BigInteger num = numerator.multiply(f.numerator); + BigInteger den = denominator.multiply(f.denominator); + BigInteger gcd = num.gcd(den); + return new Fraction(num.divide(gcd), den.divide(gcd)); + } + + public Fraction divide(Fraction f) { + return multiply(new Fraction(f.denominator, f.numerator)); + } + + @Override + public String toString() { + if ( denominator.compareTo(BigInteger.ONE) == 0 ) { + return numerator.toString(); + } + return numerator + " / " + denominator; + } + } + + private static class Term { + + private int coefficient; + private Fraction fraction; + + public Term(int c, Fraction f) { + coefficient = c; + fraction = f; + } + } + +} diff --git a/Task/Check-Machin-like-formulas/REXX/check-machin-like-formulas.rexx b/Task/Check-Machin-like-formulas/REXX/check-machin-like-formulas.rexx index b72fb4cbae..deeb418e50 100644 --- a/Task/Check-Machin-like-formulas/REXX/check-machin-like-formulas.rexx +++ b/Task/Check-Machin-like-formulas/REXX/check-machin-like-formulas.rexx @@ -1,5 +1,6 @@ /*REXX program evaluates some Machin─like formulas and verifies their veracity. */ -@.=; pi= pi(); numeric digits( length(pi) ) - length(.); numeric fuzz 3 +@.=; pi= pi(); numeric digits( length(pi) ) - length(.); numeric fuzz 3 +say center(' computing with ' digits() " decimal digits ", 110, '═') @.1 = 'pi/4 = atan(1/2) + atan(1/3)' @.2 = 'pi/4 = 2*atan(1/3) + atan(1/7)' @.3 = 'pi/4 = 4*atan(1/5) - atan(1/239)' @@ -15,13 +16,13 @@ @.13= 'pi/4 = 22*atan(1/28) + 2*atan(1/443) - 5*atan(1/1393) - 10*atan(1/11018)' @.14= 'pi/4 = 22*atan(1/38) + 17*atan(7/601) + 10*atan(7/8149)' @.15= 'pi/4 = 44*atan(1/57) + 7*atan(1/239) - 12*atan(1/682) + 24*atan(1/12943)' -@.16= 'pi/4 = 88*atan(1/172) + 51*atan(1/239) + 32*atan(1/682) + 44*atan(1/5357) + 68*atan(1/12943)' -@.17= 'pi/4 = 88*atan(1/172) + 51*atan(1/239) + 32*atan(1/682) + 44*atan(1/5357) + 68*atan(1/12944)' +@.16= 'pi/4 = 88*atan(1/172) + 51*atan(1/239) + 32*atan(1/682) + 44*atan(1/5357) + 68 *atan(1/12943)' +@.17= 'pi/4 = 88*atan(1/172) + 51*atan(1/239) + 32*atan(1/682) + 44*atan(1/5357) + 68 *atan(1/12944)' @.18= 'pi/4 = 88*atan(1/172) + 51*atan(1/239) + 32*atan(1/682) + 44*atan(1/5357) + 67.9999999994*atan(1/12943)' do j=1 while @.j\=='' /*evaluate each "Machin─like" formulas.*/ - interpret 'answer=' "(" @.j ')' /*where REXX does the heavy lifting. */ - say right( word( 'bad OK', answer+1), 3)": " @.j + interpret 'answer=' @.j /*where REXX does the heavy lifting. */ + say right( word( 'bad OK', answer + 1), 3)": " @.j end /*j*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ @@ -35,5 +36,5 @@ Asin: procedure; parse arg x 1 z 1 o 1 p; a=abs(x); aa=a*a /*──────────────────────────────────────────────────────────────────────────────────────*/ sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); m.=9; h=d+6; numeric form 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 + 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 diff --git a/Task/Check-that-file-exists/Frink/check-that-file-exists.frink b/Task/Check-that-file-exists/Frink/check-that-file-exists.frink new file mode 100644 index 0000000000..d3507695bc --- /dev/null +++ b/Task/Check-that-file-exists/Frink/check-that-file-exists.frink @@ -0,0 +1,34 @@ +checkFile[filename] := +{ + file = newJava["java.io.File", [filename]] + if file.exists[] and file.isFile[] + println["$filename is a file"] + else + println["$filename is not a file"] +} + +checkDir[filename] := +{ + file = newJava["java.io.File", [filename]] + if file.exists[] and file.isDirectory[] + println["$filename is a directory"] + else + println["$filename is not a directory"] +} + +checkFile["input.txt"] +checkFile["/input.txt"] +checkDir["docs"] +checkDir["/docs"] + +// This tests the "unusual" filename with various Unicode +// normalizations that would look identical to a human +// For example, the á character could be written as either +// the Unicode sequences +// \u00e1 ('LATIN SMALL LETTER A WITH ACUTE') +// or +// \u0061\u0301 ('LATIN SMALL LETTER A' 'COMBINING ACUTE ACCENT') +unusual = "`Abdu'l-Bahá.txt" +checkFile[unusual] +checkFile[normalizeUnicode[unusual, "NFC"]] +checkFile[normalizeUnicode[unusual, "NFD"]] diff --git a/Task/Check-that-file-exists/R/check-that-file-exists.r b/Task/Check-that-file-exists/R/check-that-file-exists-1.r similarity index 100% rename from Task/Check-that-file-exists/R/check-that-file-exists.r rename to Task/Check-that-file-exists/R/check-that-file-exists-1.r diff --git a/Task/Check-that-file-exists/R/check-that-file-exists-2.r b/Task/Check-that-file-exists/R/check-that-file-exists-2.r new file mode 100644 index 0000000000..063e2ec37a --- /dev/null +++ b/Task/Check-that-file-exists/R/check-that-file-exists-2.r @@ -0,0 +1 @@ +file.exists("`Abdu'l-Bahá.txt") diff --git a/Task/Check-that-file-exists/Stata/check-that-file-exists-4.stata b/Task/Check-that-file-exists/Stata/check-that-file-exists-4.stata new file mode 100644 index 0000000000..ad84a0a2f7 --- /dev/null +++ b/Task/Check-that-file-exists/Stata/check-that-file-exists-4.stata @@ -0,0 +1 @@ +confirm file "\`Abdu'l-Bahá.txt" diff --git a/Task/Chinese-remainder-theorem/Julia/chinese-remainder-theorem.julia b/Task/Chinese-remainder-theorem/Julia/chinese-remainder-theorem.julia index f798e3f2ca..c524cfacd2 100644 --- a/Task/Chinese-remainder-theorem/Julia/chinese-remainder-theorem.julia +++ b/Task/Chinese-remainder-theorem/Julia/chinese-remainder-theorem.julia @@ -1,26 +1,6 @@ -function chineseremainder(n::Array{Int}, a::Array{Int}) - sum = 0 - prd = prod(n) - for (ni, ai) in zip(n, a) - p = prd ÷ ni - sum += ai * mulinv(p, ni) * p - end - return sum % prd -end - -function mulinv(a::Int, b::Int) - @assert(a % b != 0, "$a is multiple of $b") - @assert(b % a != 0, "$b is multiple of $a") - b0 = b - x0, x1 = 0, 1 - if b == 1 return 1 end - while a > 1 - q = a ÷ b - a, b = b, a % b - x0, x1 = x1 - q * x0, x0 - end - if x1 < 0 x1 += b0 end - return x1 +function chineseremainder(n::Array, a::Array) + Π = prod(n) + mod(sum(ai * invmod(Π ÷ ni, ni) * Π ÷ ni for (ni, ai) in zip(n, a)), Π) end @show chineseremainder([3, 5, 7], [2, 3, 2]) diff --git a/Task/Chinese-remainder-theorem/Lobster/chinese-remainder-theorem.lobster b/Task/Chinese-remainder-theorem/Lobster/chinese-remainder-theorem.lobster new file mode 100644 index 0000000000..b9099437ae --- /dev/null +++ b/Task/Chinese-remainder-theorem/Lobster/chinese-remainder-theorem.lobster @@ -0,0 +1,41 @@ +import std + +def extended_gcd(a, b): + var s = 0 + var old_s = 1 + var t = 1 + var old_t = 0 + var r = b + var old_r = a + + while r != 0: + let quotient = old_r / r + old_r, r = r, old_r - quotient * r + old_s, s = s, old_s - quotient * s + old_t, t = t, old_t - quotient * t + + return old_r, old_s, old_t, t, s + +def for2(xs, ys, fun): return for xs.length: fun(xs[_], ys[_]) + +def crt(xs, ys): + let p = reduce(xs): _a * _b + var r = 0 + for2(xs,ys) x, y: + let q = p / x + let z,s,_t,_qt,_qs = q.extended_gcd(x) + if z != 1: + return "ng " + x + " not coprime", 0 + if s < 0: r += y * (s + x) * q + else: r += y * s * q + return "ok", r % p + + +def print_crt(xs, ys): + let msg, res = crt(xs, ys) + print(msg + " " + res) + +print_crt([3,5,7],[2,3,2]) +print_crt([11,12,13],[10,4,12]) +print_crt([11,22,19],[10,4,9]) +print_crt([100,23],[19,0]) diff --git a/Task/Chinese-remainder-theorem/Prolog/chinese-remainder-theorem.pro b/Task/Chinese-remainder-theorem/Prolog/chinese-remainder-theorem.pro new file mode 100644 index 0000000000..30271be4bd --- /dev/null +++ b/Task/Chinese-remainder-theorem/Prolog/chinese-remainder-theorem.pro @@ -0,0 +1,24 @@ +product(A, B, C) :- C is A*B. + +pair(X, Y, X-Y). + +egcd(_, 0, 1, 0) :- !. +egcd(A, B, X, Y) :- + divmod(A, B, Q, R), + egcd(B, R, S, X), + Y is S - Q*X. + +modinv(A, B, X) :- + egcd(A, B, X, Y), + A*X + B*Y =:= 1. + +crt_fold(A, M, P, R0, R1) :- % system of equations of (x = a) (mod m); p = M/m + modinv(P, M, Inv), + R1 is R0 + A*Inv*P. + +crt(Pairs, N) :- + maplist(pair, As, Ms, Pairs), + foldl(product, Ms, 1, M), + maplist(divmod(M), Ms, Ps, _), % p(n) <- M/m(n) + foldl(crt_fold, As, Ms, Ps, 0, N0), + N is N0 mod M. diff --git a/Task/Chinese-remainder-theorem/Rust/chinese-remainder-theorem.rust b/Task/Chinese-remainder-theorem/Rust/chinese-remainder-theorem.rust index f7eb11dc2f..1ca00bc6a0 100644 --- a/Task/Chinese-remainder-theorem/Rust/chinese-remainder-theorem.rust +++ b/Task/Chinese-remainder-theorem/Rust/chinese-remainder-theorem.rust @@ -1,43 +1,41 @@ -fn mul_inv(mut a: i32,mut b: i32)-> i32 - { let b0=b;let mut t;let mut q; - let mut x0=0;let mut x1=1; - if b==1 - {return 1; - } - while a>1 - { q=a/b; - t=b; - b=a%b; - a=t; - t=x0; - x0=x1-q*x0; - x1=t; - } - if x1<0 - {x1+=b0; - } - x1 - } +fn egcd(a: i64, b: i64) -> (i64, i64, i64) { + if a == 0 { + (b, 0, 1) + } else { + let (g, x, y) = egcd(b % a, a); + (g, y - (b / a) * x, x) + } +} -fn chinese_remainder(n: &mut[i32],a: &mut[i32],len: usize)->i32 - { - let mut p=0;let mut prod=1;let mut sum=0; - for i in 0..len - { prod*=n[i]; - } - for i in 0..len - { p=prod/n[i]; - sum += a[i]*mul_inv(p, n[i])*p; - } - sum%prod - } +fn mod_inv(x: i64, n: i64) -> Option { + let (g, x, _) = egcd(x, n); + if g == 1 { + Some((x % n + n) % n) + } else { + None + } +} +fn chinese_remainder(residues: &[i64], modulii: &[i64]) -> Option { + let prod = modulii.iter().product::(); + + let mut sum = 0; + + for (&residue, &modulus) in residues.iter().zip(modulii) { + let p = prod / modulus; + sum += residue * mod_inv(p, modulus)? * p + } + + Some(sum % prod) +} fn main() { + let modulii = [3,5,7]; + let residues = [2,3,2]; - let mut n = [3,5,7]; - let mut a = [2,3,2]; - let s = a.len(); - println!("{}",chinese_remainder(&mut n,&mut a,s)); + match chinese_remainder(&residues, &modulii) { + Some(sol) => println!("{}", sol), + None => println!("modulii not pairwise coprime") + } } diff --git a/Task/Cholesky-decomposition/JavaScript/cholesky-decomposition.js b/Task/Cholesky-decomposition/JavaScript/cholesky-decomposition.js new file mode 100644 index 0000000000..9103065f91 --- /dev/null +++ b/Task/Cholesky-decomposition/JavaScript/cholesky-decomposition.js @@ -0,0 +1,13 @@ +const cholesky = function (array) { + const zeros = [...Array(array.length)].map( _ => Array(array.length).fill(0)); + const L = zeros.map((row, r, xL) => row.map((v, c) => { + const sum = row.reduce((s, _, i) => i < c ? s + xL[r][i] * xL[c][i] : s, 0); + return xL[r][c] = c < r + 1 ? r === c ? Math.sqrt(array[r][r] - sum) : (array[r][c] - sum) / xL[c][c] : v; + })); + return L; +} + +let arr3 = [[25, 15, -5], [15, 18, 0], [-5, 0, 11]]; +console.log(cholesky(arr3)); +let arr4 = [[18, 22, 54, 42], [22, 70, 86, 62], [54, 86, 174, 134], [42, 62, 134, 106]]; +console.log(cholesky(arr4)); diff --git a/Task/Cholesky-decomposition/Lobster/cholesky-decomposition.lobster b/Task/Cholesky-decomposition/Lobster/cholesky-decomposition.lobster new file mode 100644 index 0000000000..8ce0a694e3 --- /dev/null +++ b/Task/Cholesky-decomposition/Lobster/cholesky-decomposition.lobster @@ -0,0 +1,79 @@ +import std + +// choleskyLower returns the cholesky decomposition of a symmetric real +// matrix. The matrix must be positive definite but this is not checked +def choleskyLower(order, a) -> [float]: + let l = map(a.length): 0.0 + var row, col = 1, 1 + var dr = 0 // index of diagonal element at end of row + var dc = 0 // index of diagonal element at top of column + for(a) e, i: + if i < dr: + let d = (e - l[i]) / l[dc] + l[i] = d + var ci, cx = col, dc + var j = i + 1 + while j <= dr: + cx += ci + ci += 1 + l[j] += d * l[cx] + j += 1 + col += 1 + dc += col + else: + l[i] = sqrt(e - l[i]) + row += 1 + dr += row + col = 1 + dc = 0 + return l + +// symmetric.print prints a square matrix from the packed representation, +// printing the upper triange as a transpose of the lower +def print_symmetric(order, s): + //const eleFmt = "%10.5f " + var str = "" + var row, diag = 1, 0 + for(s) e, i: + str += e + " " // format? + if i == diag: + var j, col = diag+row, row + while col < order: + str += s[j] + " " // format? + col++ + j += col + print(str); str = "" + row += 1 + diag += row + +// lower.print prints a square matrix from the packed representation, +// printing the upper triangle as all zeros. +def print_lower(order, l): + //const eleFmt = "%10.5f " + var str = "" + var row, diag = 1, 0 + for(l) e, i: + str += e + " " // format? + if i == diag: + var j = row + while j < order: + str += 0.0 + " " // format? + j += 1 + print(str); str = "" + row += 1 + diag += row + +def demo(order, a): + print("A:") + print_symmetric(order, a) + print("L:") + print_lower(order, choleskyLower(order, a)) + +demo(3, [25.0, + 15.0, 18.0, + -5.0, 0.0, 11.0]) + +demo(4, [18.0, + 22.0, 70.0, + 54.0, 86.0, 174.0, + 42.0, 62.0, 134.0, 106.0]) diff --git a/Task/Circles-of-given-radius-through-two-points/AWK/circles-of-given-radius-through-two-points.awk b/Task/Circles-of-given-radius-through-two-points/AWK/circles-of-given-radius-through-two-points.awk new file mode 100644 index 0000000000..5293fd68e7 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/AWK/circles-of-given-radius-through-two-points.awk @@ -0,0 +1,29 @@ +# syntax: GAWK -f CIRCLES_OF_GIVEN_RADIUS_THROUGH_TWO_POINTS.AWK +# converted from PL/I +BEGIN { + split("0.1234,0,0.1234,0.1234,0.1234",m1x,",") + split("0.9876,2,0.9876,0.9876,0.9876",m1y,",") + split("0.8765,0,0.1234,0.8765,0.1234",m2x,",") + split("0.2345,0,0.9876,0.2345,0.9876",m2y,",") + leng = split("2,1,2,0.5,0",r,",") + print(" x1 y1 x2 y2 r cir1x cir1y cir2x cir2y") + print("------- ------- ------- ------- ---- ------- ------- ------- -------") + for (i=1; i<=leng; i++) { + printf("%7.4f %7.4f %7.4f %7.4f %4.2f %s\n",m1x[i],m1y[i],m2x[i],m2y[i],r[i],main(m1x[i],m1y[i],m2x[i],m2y[i],r[i])) + } + exit(0) +} +function main(m1x,m1y,m2x,m2y,r, bx,by,pb,x,x1,y,y1) { + if (r == 0) { return("radius of zero gives no circles") } + x = (m2x - m1x) / 2 + y = (m2y - m1y) / 2 + bx = m1x + x + by = m1y + y + pb = sqrt(x^2 + y^2) + if (pb == 0) { return("coincident points give infinite circles") } + if (pb > r) { return("points are too far apart for the given radius") } + cb = sqrt(r^2 - pb^2) + x1 = y * cb / pb + y1 = x * cb / pb + return(sprintf("%7.4f %7.4f %7.4f %7.4f",bx-x1,by+y1,bx+x1,by-y1)) +} diff --git a/Task/Circles-of-given-radius-through-two-points/REXX/circles-of-given-radius-through-two-points.rexx b/Task/Circles-of-given-radius-through-two-points/REXX/circles-of-given-radius-through-two-points.rexx index 6108e284f3..35597338db 100644 --- a/Task/Circles-of-given-radius-through-two-points/REXX/circles-of-given-radius-through-two-points.rexx +++ b/Task/Circles-of-given-radius-through-two-points/REXX/circles-of-given-radius-through-two-points.rexx @@ -1,4 +1,4 @@ -/*REXX program finds two circles with a specific radius given two (X,Y) points. */ +/*REXX pgm finds two circles with a specific radius given two (X1,Y1) & (X2,Y2) points*/ @.=; @.1= 0.1234 0.9876 0.8765 0.2345 2 @.2= 0 2 0 0 1 @.3= 0.1234 0.9876 0.1234 0.9876 2 @@ -7,7 +7,7 @@ say ' x1 y1 x2 y2 radius circle1x circle1y circle2x circle2y' say ' ════════ ════════ ════════ ════════ ══════ ════════ ════════ ════════ ════════' do j=1 while @.j\==''; parse var @.j p1 p2 p3 p4 r /*points, radii*/ - say f(p1) f(p2) f(p3) f(p4) center(r/1,9) "───► " 2circ(@.j) + say f(p1) f(p2) f(p3) f(p4) center(r/1, 9) "───► " 2circ(@.j) end /*j*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ @@ -19,11 +19,11 @@ exit /*stick a fork in it, we're al cb=sqrt(r**2 - pb**2); x1=y * cb / pb; y1=x * cb / pb return f(bx-x1) f(by+y1) f(bx+x1) f(by-y1) /*──────────────────────────────────────────────────────────────────────────────────────*/ -f: f=right( format( arg(1), , 4), 9); _=f /*format # with 4 dec digits*/ - if pos(.,f)>0 & pos('E',f)=0 then f=strip(f,'T',0) /*strip trailing 0s if .& ¬E*/ - return left(strip(f,'T',.), length(_)) /*strip trailing dec point. */ +f: arg f; f= right( format(f, , 4), 9); _= f /*format # with 4 dec digits*/ + if pos(.,f)>0 & pos('E',f)=0 then f= strip(f,'T',0) /*strip trailing 0s if .& ¬E*/ + return left( strip(f, 'T', .), length(_) ) /*strip trailing dec point. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ sqrt: procedure; arg x; if x=0 then return 0; d=digits(); numeric digits; h=d+6; m.=9 numeric form; 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 + 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 diff --git a/Task/Classes/Phix/classes.phix b/Task/Classes/Phix/classes.phix new file mode 100644 index 0000000000..a2c12b770f --- /dev/null +++ b/Task/Classes/Phix/classes.phix @@ -0,0 +1,10 @@ +class number + public integer n = 3 + procedure show() + printf(1,"show: n is %d\n",{n}) + end procedure +end class +number v = new({4}) +?v.n +v.n = 5 +v.show() diff --git a/Task/Closures-Value-capture/Elena/closures-value-capture.elena b/Task/Closures-Value-capture/Elena/closures-value-capture.elena index 94d1b7a2e9..f4c976d396 100644 --- a/Task/Closures-Value-capture/Elena/closures-value-capture.elena +++ b/Task/Closures-Value-capture/Elena/closures-value-capture.elena @@ -3,7 +3,7 @@ import extensions; public program() { - var functions := Array.allocate(10).populate:(int i => (^ i * i) ); + var functions := Array.allocate(10).populate:(int i => {^ i * i} ); functions.forEach:(func) { console.printLine(func()) } } diff --git a/Task/Collections/Elena/collections-1.elena b/Task/Collections/Elena/collections-1.elena index e21de05eb6..526d4a193b 100644 --- a/Task/Collections/Elena/collections-1.elena +++ b/Task/Collections/Elena/collections-1.elena @@ -3,4 +3,4 @@ var stringArr := Array.allocate(5); stringArr[0] := "string"; // initialized array -var intArray := new int[](1, 2, 3, 4, 5). +var intArray := new int[]::(1, 2, 3, 4, 5); diff --git a/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-1.basic b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-1.basic new file mode 100644 index 0000000000..484a9c0728 --- /dev/null +++ b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-1.basic @@ -0,0 +1,3 @@ +X = PDL (0) * 5 / 32 +Y = PDL (1) * 3 / 16 + COLOR= SCRN( X,Y) diff --git a/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-10.basic b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-10.basic new file mode 100644 index 0000000000..e7714239eb --- /dev/null +++ b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-10.basic @@ -0,0 +1 @@ +Color = Point(x, y) diff --git a/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-11.basic b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-11.basic new file mode 100644 index 0000000000..c1dcf33b53 --- /dev/null +++ b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-11.basic @@ -0,0 +1,3 @@ +hDC = GetDC_(0) +Color = GetPixel_(hDC, x, y) +ReleaseDC_(0, hDC) diff --git a/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-12.basic b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-12.basic new file mode 100644 index 0000000000..c07db2d584 --- /dev/null +++ b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-12.basic @@ -0,0 +1,23 @@ +poz.point +If OpenWindow(0,0,0,100,45,"Get pixel color at cursor position",#PB_Window_MinimizeGadget) + TextGadget(0,0,0,50,12,"Red: ") + TextGadget(1,0,15,50,12,"Green: ") + TextGadget(2,0,30,50,12,"Blue: ") + TextGadget(3,50,0,50,12,"") + TextGadget(4,50,15,50,12,"") + TextGadget(5,50,30,50,12,"") + hDC = GetDC_(0) + Repeat + oldx=poz\x + oldy=poz\y +GetCursorPos_(@poz) +Color = GetPixel_(hDC, poz\x, poz\y) +If poz\x<>oldx Or poz\y<>oldy + SetGadgetText(3,Str(Red(color))) + SetGadgetText(4,Str(Green(color))) + SetGadgetText(5,Str(Blue(color))) +EndIf +event=WaitWindowEvent(200) +Until event=#PB_Event_CloseWindow +ReleaseDC_(0, hDC) +EndIf diff --git a/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-13.basic b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-13.basic new file mode 100644 index 0000000000..4ebc7a78dd --- /dev/null +++ b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-13.basic @@ -0,0 +1,4 @@ +DEF GETPX X,Y OUT R,G,B + PCOL=GSPOIT(X,Y) + RGBREAD PCOL OUT R,G,B +END diff --git a/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-14.basic b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-14.basic new file mode 100644 index 0000000000..a020c6e0c7 --- /dev/null +++ b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-14.basic @@ -0,0 +1 @@ +pxlTest(y, x) © returns boolean diff --git a/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-15.basic b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-15.basic new file mode 100644 index 0000000000..a7696c86fa --- /dev/null +++ b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-15.basic @@ -0,0 +1,10 @@ + Private Function GetPixelColor(ByVal Location As Point) As Color + + Dim b As New Bitmap(1, 1) + Dim g As Graphics = Graphics.FromImage(b) + + g.CopyFromScreen(Location, Point.Empty, New Size(1, 1)) + + Return b.GetPixel(0, 0) + + End Function diff --git a/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-16.basic b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-16.basic new file mode 100644 index 0000000000..2db984c946 --- /dev/null +++ b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-16.basic @@ -0,0 +1,23 @@ +Option Explicit + +Private Type POINTAPI + x As Long + y As Long +End Type + +Private Declare Function GetPixel Lib "gdi32" (ByVal hdc As Long, ByVal x As Long, ByVal y As Long) As Long +Private Declare Function GetCursorPos Lib "USER32" (lpPoint As POINTAPI) As Long +Private Declare Function GetWindowDC Lib "USER32" (ByVal hWnd As Long) As Long + +Sub Color_of_a_screen_pixel() +Dim myColor As Long + myColor = Get_Color_Under_Cursor +End Sub + +Function Get_Color_Under_Cursor() As Long +Dim Pos As POINTAPI, lngDc As Long + + lngDc = GetWindowDC(0) + GetCursorPos Pos + Get_Color_Under_Cursor = GetPixel(lngDc, Pos.x, Pos.y) +End Function diff --git a/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-17.basic b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-17.basic new file mode 100644 index 0000000000..957526bc8d --- /dev/null +++ b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-17.basic @@ -0,0 +1,14 @@ +open window 100, 100 +backcolor 255, 0, 0 +clear window +color 0, 255, 0 +fill rectangle 50, 50, 75, 75 + +x = 60 : y = 60 + +s$ = right$(getbit$(x, y, x, y), 6) +blue = dec(right$(s$, 2)) +green = dec(mid$(s$, 3, 2)) +red = dec(left$(s$, 2)) + +print red, " ", green, " ", blue diff --git a/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-2.basic b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-2.basic new file mode 100644 index 0000000000..535fca91da --- /dev/null +++ b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-2.basic @@ -0,0 +1,41 @@ + 100 REM GET HCOLOR + 110 REM PARAMETERS: X Y + 120 REM RETURNS: C + 130 REM + 140 P = 0:X = X + 1 + 150 ON (X < 280) GOSUB 300 + 160 PR = P:P = 0:X = X - 2 + 170 ON (X > = 0) GOSUB 300 + 180 PL = P:X = X + 1: GOSUB 300 + 190 ODD = X - INT (X / 2) * 2 + 200 C = H * 4 + 210 IF NOT ((PL = PR) AND (PL < > P)) THEN C = C + P * 3: RETURN + 220 IF ODD THEN P = NOT P + 230 C = C + P + 1 + 240 RETURN + 250 REM + 260 REM GET PIXEL + 270 REM PARAMETERS: X Y + 280 REM RETURNS: H P + 290 REM + 300 H = INT (X / 7) + 310 V = INT (Y / 8) + 320 VO = PEEK (37) + 330 HO = PEEK (36) + 340 VTAB V + 1: HTAB 1 + 350 A = PEEK (41) * 256 + 360 A = A + PEEK (40) + H + 370 VTAB VO + 1: HTAB HO + 1 + 380 A = A + 8192 - 1024 + 390 P = PEEK (230) / 32 + 400 IF P = 2 THEN A = A + 8192 + 410 A = A + (Y - V * 8) * 1024 + 420 B = X - H * 7 + 430 V = PEEK (A) + 440 H = INT (V / 128) + 450 V = INT (V / (2 ^ B)) + 460 P = V - INT (V / 2) * 2 + 470 RETURN + +X = 267 : Y = 166 : GOSUB 100 +HCOLOR= C diff --git a/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-3.basic b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-3.basic new file mode 100644 index 0000000000..b66f8534df --- /dev/null +++ b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-3.basic @@ -0,0 +1,2 @@ + palette_index% = POINT(x%, y%) + RGB24b_colour% = TINT(x%, y%) diff --git a/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-4.basic b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-4.basic new file mode 100644 index 0000000000..6ce823ea4e --- /dev/null +++ b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-4.basic @@ -0,0 +1,26 @@ +5 rem commodore 64 example +10 base=2*4096:x=100:y=50:poke53280,0 +20 gosub 1000:print chr$(147); +30 bg=11:fg=1:rem set foreground and background colors +40 for i=1024 to 1503:poke i,fg*16+bg:next +50 for i=base to base+7990:poke i,0:next +60 gosub 1200 +70 poke byte, peek(byte) or 2^bit +80 print"{home}{crsr-down 14}"; +90 px=((peek(byte) and 2^bit)>0) +100 co=peek(cb)and(15+(-225*px)):if px then co=co/16 +110 print"pixel color at";x;"{crsr-left},";y;"{crsr-left}:";co;"{crsr-left} " +120 getk$:ifk$=""then 120 +130 gosub 1100:end +1000 rem turn on graphics +1010 poke53272,peek(53272) or 8 +1020 poke53265,peek(53265) or 32 +1030 return +1100 rem turn off graphics +1110 poke53265,peek(53265) and 223 +1120 poke53272,peek(53272) and 247 +1130 return +1200 rem convert x-y into mem location +1210 ro=int(y/8):ch=int(x/8):li=y and 7 +1220 bit=7-(x and 7):byte=base+ro*320+char*8+li:cb=1024+ro+ch +1230 return diff --git a/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-5.basic b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-5.basic new file mode 100644 index 0000000000..ce02d45b95 --- /dev/null +++ b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-5.basic @@ -0,0 +1,6 @@ +10 color 0,1:color 1,3: rem set border to black and pixel color to red +15 graphic 2,1: rem enter split graphics/text mode and clear screen +20 draw 1,100,50 : rem plot pixel at 100,50 +30 print "pixel color at";rdot(0);",";rdot(1);"is";rclr(rdot(2)) +40 get k$:if k$="" then 40 +50 graphic 0,1 : rem return to text mode diff --git a/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-6.basic b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-6.basic new file mode 100644 index 0000000000..fa7b86e4d2 --- /dev/null +++ b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-6.basic @@ -0,0 +1,13 @@ +FB 1.05.0 Win64 + +' Set an appropriate screen mode - 320 x 240 x 8bpp indexed color +ScreenRes 320, 240, 8 + +' Draw a line using color 12 (light red) +Line (20,20)-(100,100), 12 + +' Print the color of a point on the line +Print Point(20,20) '' prints 12 + +' Sleep before the program closes +Sleep diff --git a/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel.basic b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-7.basic similarity index 100% rename from Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel.basic rename to Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-7.basic diff --git a/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-8.basic b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-8.basic new file mode 100644 index 0000000000..3f0dfba47a --- /dev/null +++ b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-8.basic @@ -0,0 +1,25 @@ +'This example requires the Windows API +Struct point, x As long, y As long + +hDC = GetDC(0) +result = GetCursorPos() +Print GetPixel(hDC, point.x.struct, point.y.struct) +Call ReleaseDC 0, hDC +End + + + Sub ReleaseDC hWnd, hDC + CallDLL #user32,"ReleaseDC", hWnd As uLong, hDC As uLong, ret As Long + End Sub + + Function GetDC(hWnd) + CallDLL #user32, "GetDC", hWnd As uLong, GetDC As uLong + End Function + + Function GetCursorPos() + CallDLL #user32, "GetCursorPos", point As struct, GetCursorPos As uLong + End Function + + Function GetPixel(hDC, x, y) + CallDLL #gdi32, "GetPixel", hDC As uLong, x As long, y As long, GetPixel As long + End Function diff --git a/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-9.basic b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-9.basic new file mode 100644 index 0000000000..f5bb546012 --- /dev/null +++ b/Task/Color-of-a-screen-pixel/BASIC/color-of-a-screen-pixel-9.basic @@ -0,0 +1,3 @@ +10 x=320:y=200 +20 color=TEST(x,y) +30 PRINT "Pen color at"; x; y; "is"; color diff --git a/Task/Color-of-a-screen-pixel/Perl-6/color-of-a-screen-pixel-1.pl6 b/Task/Color-of-a-screen-pixel/Perl-6/color-of-a-screen-pixel-1.pl6 new file mode 100644 index 0000000000..b0c007b0f2 --- /dev/null +++ b/Task/Color-of-a-screen-pixel/Perl-6/color-of-a-screen-pixel-1.pl6 @@ -0,0 +1,18 @@ +use GD::Raw; + +my $file = '/tmp/one-pixel-screen-capture.png'; + +qqx/screencapture -R 123,456,1,1 $file/; + +my $fh = fopen($file, "rb") or die; +my $image = gdImageCreateFromPng($fh); +my $pixel = gdImageGetPixel($image, 0, 0); +my ($red,$green,$blue) = + gdImageRed( $image, $pixel), + gdImageGreen($image, $pixel), + gdImageBlue( $image, $pixel); + +say "RGB: $red, $green, $blue"; + +fclose($fh); +unlink $file; diff --git a/Task/Color-of-a-screen-pixel/Perl-6/color-of-a-screen-pixel-2.pl6 b/Task/Color-of-a-screen-pixel/Perl-6/color-of-a-screen-pixel-2.pl6 new file mode 100644 index 0000000000..c14e424c54 --- /dev/null +++ b/Task/Color-of-a-screen-pixel/Perl-6/color-of-a-screen-pixel-2.pl6 @@ -0,0 +1,55 @@ +#!/usr/bin/env perl6 + +signal(SIGINT).tap: { sleep .1; cleanup(); print "\n" xx 50, "\e[H\e[J"; exit(0) } + +multi MAIN () { + use X11::libxdo; + my $xdo = Xdo.new; + my ($lx, $ly) = 0, 0; + loop { + sleep .1; + my ($x, $y, $) = $xdo.get-mouse-location; + next if $lx == $x and $ly == $y; + ($lx, $ly) = $x, $y; + display $x, $y, |get-pixel($x, $y); + } +} + +my %*SUB-MAIN-OPTS = :named-anywhere; + +multi MAIN ( + Int $x, #= Integer x coordinate to pick + Int $y, #= Integer y coordinate to pick + $q = False #= Boolean "quiet" mode, set truthy for decimal values, set to h for hex values + ) { + my ($red, $green, $blue) = get-pixel($x, $y); + + if $q { + $q.lc eq 'h' ?? + ( printf "%02X:%02X:%02X\n", $red, $green, $blue ) !! + ( printf "%03d:%03d:%03d\n", $red, $green, $blue ); + } else { + display($x, $y, $red, $green, $blue); + cleanup(); + } + exit(0); +} + +sub get-pixel ($x, $y) { + my $xcolor = + qqx/import -window root -crop 1x1+{$x-1 max 0}+{$y-2 max 0} -depth 8 txt:-/ + .comb(/ ** 6/); + + |$xcolor.comb(2)».parse-base(16); +} + +sub display ($x, $y, $r, $g, $b) { + print "\e[?25l\e[48;2;0;0;0m\e[38;2;255;255;255m\e[H\e[J"; + printf " x: %4d y: $y\n", $x; + printf " RGB: %03d:%03d:%03d \n HEX: %02X:%02X:%02X\n", + $r, $g, $b, $r, $g, $b; + print "\e[38;2;{$r};{$g};{$b}m ", + ('█' x 18 xx 6).join("\n "), "\n\n"; +} + +sub cleanup { print "\e[0m\e[?25h" } diff --git a/Task/Color-of-a-screen-pixel/Perl/color-of-a-screen-pixel.pl b/Task/Color-of-a-screen-pixel/Perl/color-of-a-screen-pixel.pl new file mode 100644 index 0000000000..b8532893ba --- /dev/null +++ b/Task/Color-of-a-screen-pixel/Perl/color-of-a-screen-pixel.pl @@ -0,0 +1,14 @@ +use strict; +use warnings; +use GD; + +my $file = '/tmp/one-pixel-screen-capture.png'; + +system "screencapture -R 123,456,1,1 $file"; + +my $image = GD::Image->newFromPng($file); +my $index = $image->getPixel(0,0); +my($red,$green,$blue) = $image->rgb($index); +print "RGB: $red, $green, $blue\n"; + +unlink $file; diff --git a/Task/Color-quantization/Perl/color-quantization.pl b/Task/Color-quantization/Perl/color-quantization.pl new file mode 100644 index 0000000000..382e849e7e --- /dev/null +++ b/Task/Color-quantization/Perl/color-quantization.pl @@ -0,0 +1,9 @@ +use strict; +use warnings; + +use Imager; + +my $img = Imager->new; +$img->read(file => 'frog.png'); +my $img16 = $img->to_paletted({ max_colors => 16}); +$img16->write(file => "frog-16.png") diff --git a/Task/Colour-bars-Display/AWK/colour-bars-display.awk b/Task/Colour-bars-Display/AWK/colour-bars-display.awk new file mode 100644 index 0000000000..fa26b61943 --- /dev/null +++ b/Task/Colour-bars-Display/AWK/colour-bars-display.awk @@ -0,0 +1,13 @@ +BEGIN { + nrcolors = 8 + + for (height=0; height<20; height++) { + for (width=0; width SDL.Enable_Screen) then + return; + end if; + + SDL.Video.Windows.Makers.Create (Win => Window, + Title => "", + Position => SDL.Natural_Coordinates'(0, 0), + Size => SDL.Positive_Sizes'(0, 0), + Flags => SDL.Video.Windows.Full_Screen_Desktop); + SDL.Video.Renderers.Makers.Create (Renderer, Window.Get_Surface); + + Bar_Width := Window.Get_Size.Width / 8; + for A in Colours'Range loop + Renderer.Set_Draw_Colour (Colour => Colours (A)); + Renderer.Fill (Rectangle => (X => SDL.C.int (A) * Bar_Width, Y => 0, + Width => Bar_Width, + Height => Window.Get_Size.Height)); + end loop; + Window.Update_Surface; + + Wait_Loop : loop + while SDL.Events.Events.Poll (Event) loop + exit Wait_Loop when Event.Common.Event_Type = SDL.Events.Keyboards.Key_Down; + end loop; + delay 0.050; + end loop Wait_Loop; + Window.Finalize; + SDL.Finalise; +end Colour_Bars_Display; diff --git a/Task/Colour-pinstripe-Display/00DESCRIPTION b/Task/Colour-pinstripe-Display/00DESCRIPTION index c7345869f6..a039e8c00d 100644 --- a/Task/Colour-pinstripe-Display/00DESCRIPTION +++ b/Task/Colour-pinstripe-Display/00DESCRIPTION @@ -2,4 +2,6 @@ The task is to create 1 pixel wide coloured vertical pinstripes with a sufficien After filling the top quarter of the display, we switch to a wider 2 pixel wide vertical pinstripe pattern. Halfway down the display we switch to 3 pixel wide vertical pinstripe and then finally to a 4 pixels wide vertical pinstripe for the last quarter of the display. -c.f. [[Pinstripe/Display]] +cf. +* [[Pinstripe/Display|display black and white ]] +* [[Colour pinstripe/Printer|print colour]] diff --git a/Task/Colour-pinstripe-Display/Ada/colour-pinstripe-display.ada b/Task/Colour-pinstripe-Display/Ada/colour-pinstripe-display.ada new file mode 100644 index 0000000000..03628e0ab5 --- /dev/null +++ b/Task/Colour-pinstripe-Display/Ada/colour-pinstripe-display.ada @@ -0,0 +1,74 @@ +with SDL.Video.Windows.Makers; +with SDL.Video.Renderers.Makers; +with SDL.Video.Palettes; +with SDL.Events.Events; + +procedure Colour_Pinstripe_Display is + + Width : constant := 1_200; + Height : constant := 800; + + Window : SDL.Video.Windows.Window; + Renderer : SDL.Video.Renderers.Renderer; + Event : SDL.Events.Events.Events; + + procedure Draw_Pinstripe (Line_Width : in Integer; + Line_Height : in Integer; + Screen_Width : in Integer; + Y : in Integer) + is + type Colour_Range is (Black, Red, Green, Blue, Magenta, Cyan, Yellow, White); + Colours : constant array (Colour_Range) of SDL.Video.Palettes.Colour + := (Black => (0, 0, 0, 255), Red => (255, 0, 0, 255), + Green => (0, 255, 0, 255), Blue => (0, 0, 255, 255), + Magenta => (255, 0, 255, 255), Cyan => (0, 255, 255, 255), + Yellow => (255, 255, 0, 255), White => (255, 255, 255, 255)); + Col : Colour_Range := Colour_Range'First; + Count : constant Integer := Screen_Width / Line_Width; + begin + for A in 0 .. Count loop + Renderer.Set_Draw_Colour (Colour => Colours (Col)); + Renderer.Fill (Rectangle => (X => SDL.C.int (A * Line_Width), Y => SDL.C.int (Y), + Width => SDL.C.int (Line_Width), + Height => SDL.C.int (Line_Height))); + Col := (if Col = Colour_Range'Last + then Colour_Range'First + else Colour_Range'Succ (Col)); + end loop; + end Draw_Pinstripe; + + 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; + delay 0.100; + 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 => "Pinstripe", + 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); + + Draw_Pinstripe (1, Height / 4, Width, 0); + Draw_Pinstripe (2, Height / 4, Width, 200); + Draw_Pinstripe (3, Height / 4, Width, 400); + Draw_Pinstripe (4, Height / 4, Width, 600); + Window.Update_Surface; + + Wait; + Window.Finalize; + SDL.Finalise; +end Colour_Pinstripe_Display; diff --git a/Task/Colour-pinstripe-Printer/Perl-6/colour-pinstripe-printer.pl6 b/Task/Colour-pinstripe-Printer/Perl-6/colour-pinstripe-printer.pl6 new file mode 100644 index 0000000000..b1309354b3 --- /dev/null +++ b/Task/Colour-pinstripe-Printer/Perl-6/colour-pinstripe-printer.pl6 @@ -0,0 +1,57 @@ +unit sub MAIN ($dpi = 300, $size = 'letter'); + +my $filename = './Color-pinstripe-printer-perl6.png'; + +my %paper = ( + 'letter' => { :width(8.5), :height(11.0) } + 'A4' => { :width(8.2677), :height(11.6929)} +); + +my ($w, $h) = %paper{$size} »*» $dpi; + +# ROYGBIVK +my @color = (1,0,0),(1,.598,0),(1,1,0),(0,1,0),(0,0,1),(.294,0,.51),(.58,0,.827),(0,0,0); + +my $gap = floor $w % ($dpi * +@color) / 2; + +my $rows = (1, * * 2 … * > $dpi).elems; + +my $height = $dpi; + +use Cairo; + +my @colors = @color.map: { Cairo::Pattern::Solid.new.create(|$_) }; + +given Cairo::Image.create(Cairo::FORMAT_ARGB32, $w, $h) -> $image { + given Cairo::Context.new($image) { + my Cairo::Pattern::Solid $bg .= create(1,1,1); + .rectangle(0, 0, $w, $h); + .pattern($bg); + .fill; + $bg.destroy; + + my $y = $gap; + for ^$rows -> $row { + my $x = $gap; + my $width = $dpi / (2 ** $row); + for @colors -> $this { + my $v = 0; + while $v++ < (2 ** ($row - 1)) { + given Cairo::Context.new($image) -> $block { + $block.rectangle($x, $y, $width, $height); + $block.pattern($this); + $block.fill; + $block.destroy; + } + $x += $width; + $x += $width if $row; + } + } + $y += $height; + } + } + $image.write_png($filename); +} + +# Uncomment next line if you actually want to print it +#run('lp', $filename) diff --git a/Task/Combinations-and-permutations/Factor/combinations-and-permutations.factor b/Task/Combinations-and-permutations/Factor/combinations-and-permutations.factor new file mode 100644 index 0000000000..25be429cc4 --- /dev/null +++ b/Task/Combinations-and-permutations/Factor/combinations-and-permutations.factor @@ -0,0 +1,4 @@ +USING: math.combinatorics prettyprint ; + +1000 10 nCk . ! 263409560461970212832400 +1000 10 nPk . ! 955860613004397508326213120000 diff --git a/Task/Combinations-and-permutations/Java/combinations-and-permutations.java b/Task/Combinations-and-permutations/Java/combinations-and-permutations.java new file mode 100644 index 0000000000..1b63976c0b --- /dev/null +++ b/Task/Combinations-and-permutations/Java/combinations-and-permutations.java @@ -0,0 +1,71 @@ +import java.math.BigInteger; + +public class CombinationsAndPermutations { + + public static void main(String[] args) { + System.out.println(Double.MAX_VALUE); + System.out.println("A sample of permutations from 1 to 12 with exact Integer arithmetic:"); + for ( int n = 1 ; n <= 12 ; n++ ) { + int k = n / 2; + System.out.printf("%d P %d = %s%n", n, k, permutation(n, k)); + } + + System.out.println(); + System.out.println("A sample of combinations from 10 to 60 with exact Integer arithmetic:"); + for ( int n = 10 ; n <= 60 ; n += 5 ) { + int k = n / 2; + System.out.printf("%d C %d = %s%n", n, k, combination(n, k)); + } + + System.out.println(); + System.out.println("A sample of permutations from 5 to 15000 displayed in floating point arithmetic:"); + System.out.printf("%d P %d = %s%n", 5, 2, display(permutation(5, 2), 50)); + for ( int n = 1000 ; n <= 15000 ; n += 1000 ) { + int k = n / 2; + System.out.printf("%d P %d = %s%n", n, k, display(permutation(n, k), 50)); + } + + System.out.println(); + System.out.println("A sample of combinations from 100 to 1000 displayed in floating point arithmetic:"); + for ( int n = 100 ; n <= 1000 ; n += 100 ) { + int k = n / 2; + System.out.printf("%d C %d = %s%n", n, k, display(combination(n, k), 50)); + } + + } + + private static String display(BigInteger val, int precision) { + String s = val.toString(); + precision = Math.min(precision, s.length()); + StringBuilder sb = new StringBuilder(); + sb.append(s.substring(0, 1)); + sb.append("."); + sb.append(s.substring(1, precision)); + sb.append(" * 10^"); + sb.append(s.length()-1); + return sb.toString(); + } + + public static BigInteger combination(int n, int k) { + // Select value with smallest intermediate results + // combination(n, k) = combination(n, n-k) + if ( n-k < k ) { + k = n-k; + } + BigInteger result = permutation(n, k); + while ( k > 0 ) { + result = result.divide(BigInteger.valueOf(k)); + k--; + } + return result; + } + + public static BigInteger permutation(int n, int k) { + BigInteger result = BigInteger.ONE; + for ( int i = n ; i >= n-k+1 ; i-- ) { + result = result.multiply(BigInteger.valueOf(i)); + } + return result; + } + +} diff --git a/Task/Combinations-with-repetitions/Lobster/combinations-with-repetitions.lobster b/Task/Combinations-with-repetitions/Lobster/combinations-with-repetitions.lobster new file mode 100644 index 0000000000..2e49d64494 --- /dev/null +++ b/Task/Combinations-with-repetitions/Lobster/combinations-with-repetitions.lobster @@ -0,0 +1,25 @@ +import std + +// set S of length n, choose k + +def choose(s, k, f): + let got = map(k): s[0] + let n = s.length + + def choosi(n_chosen, at): + var count = 0 + if n_chosen == k: + f(got) + return 1 + var i = at + while i < n: + got[n_chosen] = s[i] + count += choosi(n_chosen + 1, i) + i += 1 + return count + return choosi(0, 0) + +let count = choose(["iced", "jam", "plain"], 2): print(_) +print count +let extra = choose(map(10):_, 3): _ +print extra diff --git a/Task/Combinations-with-repetitions/PureBasic/combinations-with-repetitions.purebasic b/Task/Combinations-with-repetitions/PureBasic/combinations-with-repetitions.purebasic index 6df06870fb..066c2bce27 100644 --- a/Task/Combinations-with-repetitions/PureBasic/combinations-with-repetitions.purebasic +++ b/Task/Combinations-with-repetitions/PureBasic/combinations-with-repetitions.purebasic @@ -49,7 +49,7 @@ If OpenConsole() Dim dougnut.s(n - 1) For i = 0 To n - 1: Read.s dougnut(i): Next - PrintN("Combinations of " + Str(k) + " dougnuts taken " + Str(n) + " at a time with repetitions.") + PrintN("Combinations of " + Str(n) + " dougnut types taken " + Str(k) + " at a time with repetitions.") combinationCount = 0 Repeat PrintN(display(combIndex(), dougnut())) diff --git a/Task/Combinations/J/combinations-4.j b/Task/Combinations/J/combinations-4.j index b3a630bb1f..f1a6921fc7 100644 --- a/Task/Combinations/J/combinations-4.j +++ b/Task/Combinations/J/combinations-4.j @@ -1,3 +1,10 @@ -combr=: dyad define M. - if. (x>:y)+.0=x do. i.(x<:y),x else. (0,.x combr&.<: y),1+x combr y-1 end. +comb2=: dyad define + d =. 1 + y - x + k =. >: |. i. d + z =. < \. |. i. d + for. i.x-1 do. + z=. , each /\. k ,. each z + k =. 1 + k + end. + ;{.z ) diff --git a/Task/Combinations/J/combinations-5.j b/Task/Combinations/J/combinations-5.j index 13e4c36a64..b3a630bb1f 100644 --- a/Task/Combinations/J/combinations-5.j +++ b/Task/Combinations/J/combinations-5.j @@ -1 +1,3 @@ -combb=: (#~ ((-:/:~)>/:~-:\:~)"1)@(# #: [: i. ^~) +combr=: dyad define M. + if. (x>:y)+.0=x do. i.(x<:y),x else. (0,.x combr&.<: y),1+x combr y-1 end. +) diff --git a/Task/Combinations/J/combinations-6.j b/Task/Combinations/J/combinations-6.j new file mode 100644 index 0000000000..980099ca22 --- /dev/null +++ b/Task/Combinations/J/combinations-6.j @@ -0,0 +1,7 @@ + combr=: 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-7.j b/Task/Combinations/J/combinations-7.j new file mode 100644 index 0000000000..13e4c36a64 --- /dev/null +++ b/Task/Combinations/J/combinations-7.j @@ -0,0 +1 @@ +combb=: (#~ ((-:/:~)>/:~-:\:~)"1)@(# #: [: i. ^~) diff --git a/Task/Combinations/Lobster/combinations-1.lobster b/Task/Combinations/Lobster/combinations-1.lobster new file mode 100644 index 0000000000..0546d0012b --- /dev/null +++ b/Task/Combinations/Lobster/combinations-1.lobster @@ -0,0 +1,21 @@ +import std + +// combi is an itertor that solves the Combinations problem for iota arrays as stated + +def combi(m, n, f): + let c = map(n): _ + + while true: + f(c) + var i = n-1 + c[i] = c[i] + 1 + if c[i] > m - 1: + while c[i] >= m - n + i: + i -= 1 + if i < 0: return + c[i] = c[i] + 1 + while i < n-1: + c[i+1] = c[i] + 1 + i += 1 + +combi(5, 3): print(_) diff --git a/Task/Combinations/Lobster/combinations-2.lobster b/Task/Combinations/Lobster/combinations-2.lobster new file mode 100644 index 0000000000..63f651aac2 --- /dev/null +++ b/Task/Combinations/Lobster/combinations-2.lobster @@ -0,0 +1,22 @@ +import std + +// comba solves the general problem for any values in an input array + +def comba(arr: [T], k) -> [[T]]: + let ret = [] + for(arr.length) i: + if k == 1: + ret.push([arr[i]]) + else: + let sub = comba(arr.slice(i+1, -1), k-1) + for(sub) next: + next.insert(0, arr[i]) + ret.push(next) + return ret + +print comba([0,1,2,3,4], 3) +print comba(["Crosby", "Stills", "Nash", "Young"], 3) +// Of course once could use combi to index the input array instead +var s = "" +combi(4, 3): s += (map(_) i: ["Crosby", "Stills", "Nash", "Young"][i]) + " " +print s diff --git a/Task/Combinations/Mathematica/combinations.math b/Task/Combinations/Mathematica/combinations-1.math similarity index 100% rename from Task/Combinations/Mathematica/combinations.math rename to Task/Combinations/Mathematica/combinations-1.math diff --git a/Task/Combinations/Mathematica/combinations-2.math b/Task/Combinations/Mathematica/combinations-2.math new file mode 100644 index 0000000000..decacf44c3 --- /dev/null +++ b/Task/Combinations/Mathematica/combinations-2.math @@ -0,0 +1 @@ +Subsets[Range[5], {2}] diff --git a/Task/Combinations/Python/combinations-5.py b/Task/Combinations/Python/combinations-5.py new file mode 100644 index 0000000000..42bf135d4e --- /dev/null +++ b/Task/Combinations/Python/combinations-5.py @@ -0,0 +1,4 @@ +def comb(m, s): + if m == 1: return [[x] for x in s] + if m == len(s): return [s] + return [s[:1] + a for a in comb(m-1, s[1:])] + comb(m, s[1:]) diff --git a/Task/Combinations/REXX/combinations.rexx b/Task/Combinations/REXX/combinations.rexx index bb1a5e8d8b..b8f9f49a37 100644 --- a/Task/Combinations/REXX/combinations.rexx +++ b/Task/Combinations/REXX/combinations.rexx @@ -1,21 +1,28 @@ /*REXX program displays combination sets for X things taken Y at a time. */ parse arg x y $ . /*get optional arguments from the C.L. */ if x=='' | x=="," then x=5 /*No X specified? Then use default.*/ -if y=='' | y=="," then y=3 /* " Y " " " " */ -if $=='' | $=="," then $= '123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' +if y=='' | y=="," then y=3; oy= y; y= abs(y) /* " Y " " " " */ +if $=='' | $=="," then $='123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', + "~!@#$%^&*()_+`{}|[]\:;<>?,./█┌┐└┘±≥≤≈∙" /*some extended chars*/ /* [↑] No $ specified? Use default.*/ +if y>x then do; say y " can't be greater than " x; exit 1; end say "────────────" x ' things taken ' y " at a time:" say "────────────" combN(x,y) ' combinations.' exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -combN: procedure expose $; parse arg x,y; xp=x+1; xm=xp-y; !.=0 - do i=1 for y; !.i=i; end /*i*/ - do j=1; L=; do d=1 for y; L=L word(substr($,!.d,1) !.d, 1); end /*d*/ - say L; !.y=!.y+1 +combN: procedure expose $ oy; parse arg x,y; xp= x+1; xm= xp-y; !.= 0 + if x=0 | y=0 then return 'no' + do i=1 for y; !.i= i + end /*i*/ + do j=1; L= + do d=1 for y; L= L substr($, !.d, 1) + end /*d*/ + if oy>0 then say L; !.y= !.y+1 /*don't show if OY<0 */ if !.y==xp then if .combN(y-1) then leave end /*j*/ return j -.combN: procedure expose !. y xm; parse arg d; if d==0 then return 1; p=!.d - do u=d to y; !.u=p+1; if !.u==xm+u then return .combN(u-1); p=!.u - end /*u*/ - return 0 +/*──────────────────────────────────────────────────────────────────────────────────────*/ +.combN: procedure expose !. y xm; parse arg d; if d==0 then return 1; p= !.d + do u=d to y; !.u= p+1; if !.u==xm+u then return .combN(u-1); p= !.u + end /*u*/ /* ↑ */ + return 0 /*recursive call──►──────┘ */ diff --git a/Task/Command-line-arguments/Julia/command-line-arguments.julia b/Task/Command-line-arguments/Julia/command-line-arguments.julia index c9bde08773..4c3234cdbf 100644 --- a/Task/Command-line-arguments/Julia/command-line-arguments.julia +++ b/Task/Command-line-arguments/Julia/command-line-arguments.julia @@ -1,4 +1,6 @@ -prog = basename(Base.source_path()) +using Printf + +prog = Base.basename(Base.source_path()) println(prog, "'s command-line arguments are:") for s in ARGS diff --git a/Task/Comments/Batch-File/comments-2.bat b/Task/Comments/Batch-File/comments-2.bat index 86f1456b74..bb4b295b98 100644 --- a/Task/Comments/Batch-File/comments-2.bat +++ b/Task/Comments/Batch-File/comments-2.bat @@ -1,2 +1,2 @@ -:: Another option, though unsupported and known +:: Another option, though undocumented and known :: to fail in some cases. Best avoided. diff --git a/Task/Comments/Batch-File/comments-3.bat b/Task/Comments/Batch-File/comments-3.bat new file mode 100644 index 0000000000..19a15755f5 --- /dev/null +++ b/Task/Comments/Batch-File/comments-3.bat @@ -0,0 +1 @@ +% this works as long as you have no variable named exactly like this sentence. % diff --git a/Task/Comments/Dart/comments.dart b/Task/Comments/Dart/comments.dart new file mode 100644 index 0000000000..f214c4a044 --- /dev/null +++ b/Task/Comments/Dart/comments.dart @@ -0,0 +1,12 @@ +// This is a single line comment, which lasts until the end of the line. The Dart linter prefers this one. + +/* This is also a valid single line comment. Unlike the first one, this one terminates after one of these -> */ + +/* + You can use the syntax above to make multi line comments as well. + Like this! +*/ + +/// These are doc comments. You can use dartdoc to generate doc pages for your classes with these. +/// +/// Formatting [variable] and [function] names like so allows dartdoc to link to the documentation for those entities. diff --git a/Task/Comments/LOLCODE/comments-1.lol b/Task/Comments/LOLCODE/comments-1.lol new file mode 100644 index 0000000000..8169fae1df --- /dev/null +++ b/Task/Comments/LOLCODE/comments-1.lol @@ -0,0 +1,3 @@ +OBTW This is a +multi line comment +TLDR diff --git a/Task/Comments/LOLCODE/comments-2.lol b/Task/Comments/LOLCODE/comments-2.lol new file mode 100644 index 0000000000..2de0cb8fba --- /dev/null +++ b/Task/Comments/LOLCODE/comments-2.lol @@ -0,0 +1 @@ +BTW This is a single line comment. diff --git a/Task/Comments/Perl-6/comments-1.pl6 b/Task/Comments/Perl-6/comments-1.pl6 new file mode 100644 index 0000000000..c0599c384c --- /dev/null +++ b/Task/Comments/Perl-6/comments-1.pl6 @@ -0,0 +1,2 @@ +# the answer to everything +my $x = 42; diff --git a/Task/Comments/Perl-6/comments-2.pl6 b/Task/Comments/Perl-6/comments-2.pl6 new file mode 100644 index 0000000000..a4897610b6 --- /dev/null +++ b/Task/Comments/Perl-6/comments-2.pl6 @@ -0,0 +1,6 @@ +#`( + Comments beginning with a backtick and one or more opening bracketing characters are embedded comments. + They can span more than one line… +) + +my $y = #`{ …or only part of a line. } 3; diff --git a/Task/Comments/Perl-6/comments-3.pl6 b/Task/Comments/Perl-6/comments-3.pl6 new file mode 100644 index 0000000000..148f6f1797 --- /dev/null +++ b/Task/Comments/Perl-6/comments-3.pl6 @@ -0,0 +1,3 @@ +for #`(each element in) my @array { + say #`(or print element) $_ #`(with a newline); +} diff --git a/Task/Comments/Perl-6/comments-4.pl6 b/Task/Comments/Perl-6/comments-4.pl6 new file mode 100644 index 0000000000..db53793a7a --- /dev/null +++ b/Task/Comments/Perl-6/comments-4.pl6 @@ -0,0 +1,3 @@ +#`{{ + This close curly brace } won't terminate the comment early. +}} diff --git a/Task/Comments/Perl-6/comments-5.pl6 b/Task/Comments/Perl-6/comments-5.pl6 new file mode 100644 index 0000000000..1e35cc85c0 --- /dev/null +++ b/Task/Comments/Perl-6/comments-5.pl6 @@ -0,0 +1,6 @@ +=begin comment + +Pod is the successor to Perl 5's POD. This is the simplest way to use it for multi-line comments. +For more about Pod, see Pod: https://docs.perl6.org/language/pod + +=end comment diff --git a/Task/Comments/Perl-6/comments-6.pl6 b/Task/Comments/Perl-6/comments-6.pl6 new file mode 100644 index 0000000000..70d416dc93 --- /dev/null +++ b/Task/Comments/Perl-6/comments-6.pl6 @@ -0,0 +1,9 @@ +#| Compute the distance between two points in the plane. +sub distance( + Rat \x1, #= First point's abscissa, + Rat \y1, #= First point's ordinate, + Rat \x2, #= Second point's abscissa, + Rat \y2, #= Second point's ordinate, +){ + return sqrt((x2 - x1)**2 + (y2 - y1)**2) +} diff --git a/Task/Comments/Perl-6/comments.pl6 b/Task/Comments/Perl-6/comments.pl6 deleted file mode 100644 index b97906a183..0000000000 --- a/Task/Comments/Perl-6/comments.pl6 +++ /dev/null @@ -1,28 +0,0 @@ -my $x = 2; # Single-line comment. - -#`( - Comments beginning with a backtick and one or more - opening bracketing characters are embedded comments. - They can span more than one line… -) - -my $y = #`{ …or only part of a line. } 3; - -#`{{ - Using more than one bracketing character lets you include - an unmatched close bracket, like this: } -}} - -#`⁅ Synopsis 2: "Bracketing characters are defined as any - Unicode characters with either bidirectional mirrorings or - Ps/Pe/Pi/Pf properties." ⁆ - -=begin comment - -Pod is the successor to Perl 5's POD. This is the simplest way -to use it for multi-line comments. For more about Pod, see -Synopsis 26: - -http://perlcabal.org/syn/S26.html - -=end comment diff --git a/Task/Compile-time-calculation/Prolog/compile-time-calculation.pro b/Task/Compile-time-calculation/Prolog/compile-time-calculation.pro new file mode 100644 index 0000000000..bdb0d7de0f --- /dev/null +++ b/Task/Compile-time-calculation/Prolog/compile-time-calculation.pro @@ -0,0 +1,9 @@ +% Taken from RosettaCode Factorial page for Prolog +fact(X, 1) :- X<2. +fact(X, F) :- Y is X-1, fact(Y,Z), F is Z*X. + +goal_expansion((X = factorial_of(N)), (X = F)) :- fact(N,F). + +test :- + F = factorial_of(10), + format('!10 = ~p~n', F). diff --git a/Task/Compound-data-type/Pike/compound-data-type.pike b/Task/Compound-data-type/Pike/compound-data-type.pike new file mode 100644 index 0000000000..f1dfb78476 --- /dev/null +++ b/Task/Compound-data-type/Pike/compound-data-type.pike @@ -0,0 +1,14 @@ +class Point { + int x, y; + void create(int _x, int _y) + { + x = _x; + y = _y; + } +} + +void main() +{ + object point = Point(10, 20); + write("%d %d\n", point->x, point->y); +} diff --git a/Task/Compound-data-type/Vala/compound-data-type.vala b/Task/Compound-data-type/Vala/compound-data-type.vala new file mode 100644 index 0000000000..cb7ce3d377 --- /dev/null +++ b/Task/Compound-data-type/Vala/compound-data-type.vala @@ -0,0 +1,4 @@ +struct Point { + int x; + int y; +} diff --git a/Task/Conditional-structures/Ol/conditional-structures-5.ol b/Task/Conditional-structures/Ol/conditional-structures-5.ol index 678ab80175..9a230fc0de 100644 --- a/Task/Conditional-structures/Ol/conditional-structures-5.ol +++ b/Task/Conditional-structures/Ol/conditional-structures-5.ol @@ -1,8 +1,8 @@ -(cond - ((= (* 2 2) 4) - (print "cond: equal")) - ((= (* 2 2) 6) - (print "cond: not equal")) +(case (vector 'selector 1 2 3) + (['case1 x y] + (print "case: case1 " x ", " y)) + (['selector x y z] + (print "case: selector " x ", " y ", " z)) (else - (print "cond: i don't know"))) -; ==> cond: equal + (print "case: i don't know"))) +; ==> tuple-case: selector 1, 2, 3 diff --git a/Task/Conditional-structures/Ol/conditional-structures-6.ol b/Task/Conditional-structures/Ol/conditional-structures-6.ol index 82528035f6..678ab80175 100644 --- a/Task/Conditional-structures/Ol/conditional-structures-6.ol +++ b/Task/Conditional-structures/Ol/conditional-structures-6.ol @@ -1,8 +1,8 @@ -(tuple-case (tuple 'selector 1 2 3) - ((case1 x y) - (print "tuple-case: case1 " x ", " y)) - ((selector x y z) - (print "tuple-case: selector " x ", " y ", " z)) +(cond + ((= (* 2 2) 4) + (print "cond: equal")) + ((= (* 2 2) 6) + (print "cond: not equal")) (else - (print "tuple-case: i don't know"))) -; ==> tuple-case: selector 1, 2, 3 + (print "cond: i don't know"))) +; ==> cond: equal diff --git a/Task/Conjugate-transpose/Julia/conjugate-transpose-3.julia b/Task/Conjugate-transpose/Julia/conjugate-transpose-3.julia index 715e19c524..09a4642740 100644 --- a/Task/Conjugate-transpose/Julia/conjugate-transpose-3.julia +++ b/Task/Conjugate-transpose/Julia/conjugate-transpose-3.julia @@ -1,2 +1,3 @@ +eye(A) = A^0 isnormal(A) = size(A,1) == size(A,2) && A'*A == A*A' isunitary(A) = size(A,1) == size(A,2) && A'*A == eye(A) diff --git a/Task/Conjugate-transpose/Stata/conjugate-transpose.stata b/Task/Conjugate-transpose/Stata/conjugate-transpose.stata new file mode 100644 index 0000000000..7682ada9a4 --- /dev/null +++ b/Task/Conjugate-transpose/Stata/conjugate-transpose.stata @@ -0,0 +1,31 @@ +: a=1,2i\3i,4 + +: a + 1 2 + +-----------+ + 1 | 1 2i | + 2 | 3i 4 | + +-----------+ + +: a' + 1 2 + +-------------+ + 1 | 1 -3i | + 2 | -2i 4 | + +-------------+ + +: transposeonly(a) + 1 2 + +-----------+ + 1 | 1 3i | + 2 | 2i 4 | + +-----------+ + +: a*a'==a'*a + 0 + +: a'==a + 0 + +: a'*a==I(rows(a)) + 0 diff --git a/Task/Constrained-random-points-on-a-circle/Factor/constrained-random-points-on-a-circle.factor b/Task/Constrained-random-points-on-a-circle/Factor/constrained-random-points-on-a-circle.factor new file mode 100644 index 0000000000..f571c8e9cc --- /dev/null +++ b/Task/Constrained-random-points-on-a-circle/Factor/constrained-random-points-on-a-circle.factor @@ -0,0 +1,7 @@ +USING: io kernel math.matrices math.order math.ranges +math.statistics math.vectors random sequences strings ; + +CHAR: X -15 15 [a,b] dup cartesian-product concat +[ sum-of-squares 100 225 between? ] filter 100 sample +[ 15 v+n ] map 31 31 32 [ matrix-set-nths ] keep +[ >string print ] each diff --git a/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-1.rexx b/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-1.rexx index f1f58e290e..72fc618ad9 100644 --- a/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-1.rexx +++ b/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-1.rexx @@ -1,26 +1,21 @@ /*REXX program generates 100 random points in an annulus: 10 ≤ √(x²≤y²) ≤ 15 */ -parse arg points low high . /*obtain optional args from the C.L. */ -if points=='' then points=100 -if low=='' then low=10; low2= low**2 /*define a shortcut for squaring LOW. */ -if high=='' then high=15; high2=high**2 /* " " " " " HIGH.*/ +parse arg pts LO HI . /*obtain optional args from the C.L. */ +if pts=='' then pts= 100 /*Not specified? Then use the default.*/ +if LO=='' then LO= 10; LO2= LO**2 /*define a shortcut for squaring LO. */ +if HI=='' then HI= 15; HI2= HI**2 /* " " " " " HI. */ $= - do x=-high; x2=x*x /*generate all possible annulus points.*/ - if x<0 & x2>high2 then iterate - if x>0 & x2>high2 then leave - do y=-high; s=x2+y*y - if (y<0 & s>high2) | s0 & s>high2 then leave - $=$ x','y /*add a point─set to the $ list. */ - end /*y*/ - end /*x*/ - -plotChar='Θ'; minY=high2; maxY=-minY; ap=words($); @.= - - do j=1 for points /*define the x,y points [character O].*/ - parse value word($,random(1,ap)) with x ',' y /*pick a random point in the annulus.*/ - @.y=overlay(plotChar, @.y, x+high+1) /*define: the data point. */ - minY=min(minY,y); maxY=max(maxY,y) /*perform the plot point restricting. */ - end /*j*/ - /* [↓] only show displayable section. */ - do y=minY to maxY; say @.y; end /*display the annulus to the terminal. */ + do x=-HI; xx= x*x /*generate all possible annulus points.*/ + if x<0 & xx>HI2 then iterate + if x>0 & xx>HI2 then leave + do y=-HI; s= xx + y*y + if (y<0 & s>HI2) | s0 & s>HI2 then leave + $= $ x','y /*add a point─set to the $ list. */ + end /*y*/ + end /*x*/ + plotChr= 'Θ'; minY= HI2; maxY= -minY; #= words($); @.= + do pts; parse value word($, random(1,#)) with x ',' y /*random point in annulus*/ + @.y= overlay(plotChr, @.y, x*2 + HI*2 + 1); minY= min(minY, y); maxY= max(maxY, y) + end /*pts*/ /* [↑] plot a point; find min & max Y.*/ /*stick a fork in it, we're all done. */ + do y=minY to maxY; say @.y; end /*display the annulus to the terminal. */ diff --git a/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-2.rexx b/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-2.rexx index e4ccb95ac8..5ea3c710fd 100644 --- a/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-2.rexx +++ b/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-2.rexx @@ -1,26 +1,40 @@ -/*REXX program generates 100 random points in an annulus: 10 ≤ √(x²≤y²) ≤ 15 */ -parse arg points low high . /*obtain optional args from the C.L. */ -if points=='' then points=100 -if low=='' then low=10; low2= low**2 /*define a shortcut for squaring LOW. */ -if high=='' then high=15; high2=high**2 /* " " " " " HIGH.*/ -$= - do x=-high; x2=x*x /*generate all possible annulus points.*/ - if x<0 & x2>high2 then iterate - if x>0 & x2>high2 then leave - do y=-high; s=x2+y*y - if (y<0 & s>high2) | s0 & s>high2 then leave - $=$ x','y /*add a point─set to the $ list. */ - end /*y*/ - end /*x*/ - -plotChar='Θ'; minY=high2; maxY=-minY; ap=words($); @.= - - do j=1 for points /*define the x,y points [character O].*/ - parse value word($,random(1,ap)) with x ',' y /*pick a random point in the annulus.*/ - @.y=overlay(plotChar, @.y, 2*x+2*high+1) /*define: the data point. */ - minY=min(minY,y); maxY=max(maxY,y) /*perform the plot point restricting. */ - end /*j*/ - /* [↓] only show displayable section. */ - do y=minY to maxY; say @.y; end /*display the annulus to the terminal. */ - /*stick a fork in it, we're all done. */ +/* REXX --------------------------------------------------------------- +* show 100 random points of an annulus with radius 10 to 15 +* 18.06.2014 Walter Pachl 'derived/simplified' from REXX version 1 +*--------------------------------------------------------------------*/ + Parse Arg points low high scale . /* allow parms from command line.*/ + If points=='' Then points=100 /* number of points */ + If low=='' Then low=10 /* inner radius */ + If high=='' Then high=15 /* outer radius */ + If scale=='' Then scale=2 /* horizontal scaling */ + low2=low**2 + high2=high**2 + /* first compute all possible points */ + point.=0 + Do x=-high To high + x2=x*x + Do y=-high To high + y2=y*y + s=x2+y2 + If s>=low2 &s<=high2 Then Do + z=point.0+1 + point.z=x y + point.0=z + End + End + End + plotchar='O' + line.='' + np=point.0 /* available points */ + Do j=1 To points /* pick the needed points */ + r=random(1,np) + Parse Var point.r x y /* coordinates */ + line.y=overlay(plotchar,line.y,scale*(x+high)+1) /* put into line*/ + point.r=point.np /* replace taken point by last*/ + np=np-1 /* reduce available points */ + If np=0 Then Leave /* all possible points taken */ + End +/* now draw the picture */ + Do y=-high To high + Say line.y + End diff --git a/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-3.rexx b/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-3.rexx index 5ea3c710fd..d129063063 100644 --- a/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-3.rexx +++ b/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-3.rexx @@ -1,40 +1,78 @@ /* REXX --------------------------------------------------------------- -* show 100 random points of an annulus with radius 10 to 15 -* 18.06.2014 Walter Pachl 'derived/simplified' from REXX version 1 +* 19.06.2014 Walter Pachl alternate algorithm +* the idea: yl is a list of y coordinates which may have unused points +* one of the y's is picked at random +* Then we look for unused x coordinates in this line +* we pick one at random or drop the y from yl if none is found +* When yl becomes empty, all points are used and we stop *--------------------------------------------------------------------*/ - Parse Arg points low high scale . /* allow parms from command line.*/ - If points=='' Then points=100 /* number of points */ - If low=='' Then low=10 /* inner radius */ - If high=='' Then high=15 /* outer radius */ - If scale=='' Then scale=2 /* horizontal scaling */ - low2=low**2 - high2=high**2 - /* first compute all possible points */ - point.=0 - Do x=-high To high +Parse Arg n r rr scale +If r='' Then r=10 +If rr='' Then rr=15 +If n='' Then n=100 +If scale='' Then scale=2 +r2=r*r +rr2=rr*rr +ymin=0 +ymax=rr*2 +ol='' +pp.=0 +used.=0 +yl='' /* list of available y values */ +Do y=-rr To rr + yl=yl y + End +Do Until pp.0=n /*look for the required points*/ + If yl='' Then Do /* no more points available */ + Say 'all points filled' + Leave + End + yi=random(1,words(yl)) /* pick a y */ + y=word(yl,yi) + y2=y*y + p.=0 + Do x=0 To rr /* Loop through possible x's */ x2=x*x - Do y=-high To high - y2=y*y - s=x2+y2 - If s>=low2 &s<=high2 Then Do - z=point.0+1 - point.z=x y - point.0=z - End + xy2=x2+y2 + If xy2>=r2&xy2<=rr2 Then Do /* within the annulus */ + Call take x y + Call take (-x) y End End - plotchar='O' - line.='' - np=point.0 /* available points */ - Do j=1 To points /* pick the needed points */ - r=random(1,np) - Parse Var point.r x y /* coordinates */ - line.y=overlay(plotchar,line.y,scale*(x+high)+1) /* put into line*/ - point.r=point.np /* replace taken point by last*/ - np=np-1 /* reduce available points */ - If np=0 Then Leave /* all possible points taken */ + If p.0>0 Then Do /* some x's found (or just 1) */ + xi=random(1,p.0) /* pick an x */ + z=pp.0+1 + pp.z=p.xi + pp.0=z + Parse Var pp.z xa ya + used.xa.ya=1 /* remember it's taken */ End -/* now draw the picture */ - Do y=-high To high - Say line.y + Else Do /* no x for this y */ + yi=wordpos(y,yl) /* remove y from yl */ + Select + When yi=1 Then yl=subword(yl,yi+1) + When yi=words(yl) Then yl=subword(yl,1,yi-1) + Otherwise yl=subword(yl,1,yi-1) subword(yl,yi+1) + End End + End +line.='' /* empty the raster */ +Do i=1 To pp.0 /* place the points */ + Parse Var pp.i x y + line.y=overlay('+',line.y,scale*(rr+x)+1) + End +Do y=-rr To rr /* show the result */ + Say line.y + End +say pp.0 'points filled' +Exit +Return + +take: Procedure Expose p. used. /* add x to p. if its not used*/ + Parse Arg x y + If used.x.y=0 Then Do + z=p.0+1 + p.z=x y + p.0=z + End + Return 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 new file mode 100644 index 0000000000..859cc85936 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/EDSAC-order-code/continued-fraction-arithmetic-construct-from-rational-number.edsac @@ -0,0 +1,240 @@ + [Continued fractions from rationals. + EDSAC program, Initial Orders 2.] + + [Memory usage: + 56..109 Print subroutine, modified from the EDSAC library + 110..146 Division subroutine for long positive integers + 148..196 Continued fraction subroutine, as specified by Rosetta Code + 200..260 Main routine + 262.. List of rationals, variable number of items] + + [Define where to store the list of rationals.] + T 45 K [store address in location 45; + values are then accessed by code letter H (*)] + P 262 F [<------ address here] + [(*) Arbitrary choice. We could equally well use 46 and N, 47 and M, etc.] + + [Library subroutine R2. Reads positive integers during input of orders, + and is then overwritten (so doesn't take up any memory). + Negative numbers can be input by adding 2^35. + Each integer is followed by 'F', except the last is followed by '#TZ'.] + GKT20FVDL8FA40DUDTFI40FA40FS39FG@S2FG23FA5@T5@E4@E13Z + T #H [Tell R2 the storage location defined above] + + [Rationals to be read by R2. First item is count, then num/den pairs.] + 8F 1F2F 3F1F 33F8F 13F11F 22F7F 34359738217F77F + 141421356F100000000F 314285714F100000000#TZ + + [---------------------------------------------------------------------- + Modification of library subroutine P7. + Prints signed integer up to 10 digits, left-justified. + 54 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@ + + [---------------------------------------------------------------------- + Division subroutine for long positive 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. + Working locations 0D, 8D.] + T 110 K + G K + A 3 F [plant link] + T 35 @ + A 6 D [load divisor] + U 8 D [save at 8D (6D is required for quotient)] + [4] T D [initialize shifted divisor] + A 4 D [load dividend] + R D [shift 1 right] + S D [shifted divisor > dividend/2 yet?] + G 13 @ [yes, start subtraction] + T 36 @ [no, clear acc] + A D [shift divisor 1 more] + L D + E 4 @ [loop back (always, since acc >= 0)] + [13] T 36 @ [clear acc] + T 6 D [initialize quotient to 0] + [15] A 4 D [load remainder (initially = dividend)] + S D [trial subtraction] + G 23 @ [skip if can't subtract] + T 4 D [update remainder] + A 6 D [load quotient] + Y F [add 1 by rounding twice (*)] + Y F + T 6 D + [23] T 36 @ [clear acc] + A 8 D [load original divisor] + S D [is shifted divisor back to original?] + E 35 @ [yes, exit (with accumulator = 0, + in accordance with EDSAC convention)] + T 36 @ [no, clear acc] + A D [shift divisor 1 right] + R D + T D + A 6 D [shift quotient 1 left] + L D + T 6 D + E 15 @ [loop back (always, since acc = 0)] + [35] E F [return; order set up at runtime] + [36] P F [junk word, to clear accumulator] + + [(*) This saves the bother of defining a double-word constant 1 + and making sure that it's at an even address.] + + [---------------------------------------------------------------------- + Subroutine for lazy evaluation of continued fraction. + Must be loaded at an even address. + Locations relative to start of subroutine: + 0: Entry point + 1: Flag, < 0 if c.f. is finished, >= 0 if there's another term + 2, 3: Next term of c.f., provided the flag (location 1) is >= 0 + 4, 5: Caller places numerator here before first call + 6, 7: Caller places denominator here before first call; must be > 0 + + After setting up the numerator and denominator of the rational number, + the caller should repeatedly call location 0, reading the result + from location 1 and double location 2. + Locations 4..7 are maintained by the subroutine and should not be changed + by the caller until a new continued fraction is required.] + + T 46 K [place address of subroutine in location 46] + P 148 F + E 25 K [load the code below to that address (WWG page 18)] + T N + G K + [0] G 8 @ [entry point] + [1] P F [flag returned here] + [2] P F P F [term returned here, if flag >= 0; + also used as temporary store] + [4] P F P F [caller puts numerator here] + [6] P F P F [caller puts denominator here] + [8] A 3 F [plant link] + T 28 @ + S 6#@ [load negative of denominator] + E 44 @ [if denom <= 0, no more terms] + T F [clear acc] + A 4#@ [load numerator] + T 2#@ [save before overwriting] + A 6#@ [load denominator] + U 4#@ [make it numerator for next call] + T 6 D [also to 6D for division] + A 2#@ [load numerator] + G 29 @ [special action if negative] + T 4 D [to 4D for division] + [21] A 21 @ [for return from next] + G 110 F [call the above division subroutine] + A 4 D [load remainder] + T 6#@ [make it denominator for next call] + A 6 D [load quotient] + [26] T 2#@ [return it as next term] + [27] T 1 @ [flag >= 0 means term is valid] + [28] E F [exit with acc = 0] + + [Here if rational = -n/d where n, d > 0. Principle is: + if n + d - 1 = qd + r then -n = -qd + (d - 1 - r)] + [29] T 4 D [save numerator in 4D] + S 6 D [acc := -den] + Y F [add 1 by rounding twice] + Y F + T 2#@ [save (1 - den) for later] + S 4 D [load abs(num)] + S 2#@ [add (den - 1)] + T 4 D [to 4D for division] + [37] A 37 @ [for return from next] + G 110 F [call the above division subroutine] + S 2#@ [load (den - 1)] + S 4 D [subtract remainder] + T 6#@ [result is new denominator] + S 6 D [load negated quotient] + G 26 @ [join common code] + + [Here if there are no more terms of the c.f.] + [44] T F [clear acc] + A 8 @ [this is negative since 'A' = -4] + G 27 @ [exit with negative flag] + + [---------------------------------------------------------------------- + Main routine] + T 200 K + G K + [Variables] + [0] P F [negative counter of continued fractions] + [1] P F [character before term, first '=' then ','] + [Constants] + [2] P D [single-word 1] + [3] A 2#H [order to load first numerator] + [4] P 2 F [to inc addresses by 2] + [5] # F [teleprinter figures shift] + [6] X F [slash (in figures mode)] + [7] V F [equals sign (in figures mode)] + [8] N F [comma (in figures mode)] + [9] ! F [space] + [10] @ F [carriage return] + [11] & F [line feed] + [12] K4096 F [teleprinter null] + + [Enter with acc = 0] + [13] O 5 @ [set teleprinter to figures] + S H [negative of number of c.f.s] + T @ [initialize counter] + A 3 @ [initial load order] + [17] U 22 @ [plant order to load numerator] + A 4 @ [inc address by 2] + T 28 @ [plant order to load denominator] + A 7 @ [set to print '=' before first term] + T 1 @ + + [Demonstrate the subroutine above. + Since its address was placed in location 46, + we can use code letter N to refer to it.] + [22] A #H [load numerator (order set up at runtime)] + U 4#N [pass to subroutine] + T D [also to 0D for printing] + [25] A 25 @ [for return from print subroutine] + G 56 F [print numerator] + O 6 @ [followed by slash] + [28] A #H [load denominator (order set up at runtime)] + U 6#N [pass to subroutine] + T D [also to 0D for printing] + [31] A 31 @ [for return from print subroutine] + G 56 F [print denominator] + O 9 @ [followed by space] + [34] A 34 @ [for return from subroutine] + G N [call subroutine for next term] + A 1 N [load flag] + G 48 @ [if < 0, c.f. is finished, jump out] + O 1 @ [print equals or comma] + O 9 @ [print space] + T F [clear acc] + A 2#N [load term] + T D [to 0D for printing] + [43] A 43 @ [for return from print subroutine] + G 56 F [print term; clears acc] + A 8 @ [set to print ',' before subsequent terms] + T 1 @ + E 34 @ [loop back for next term] + + [On to next continued fraction] + [48] O 10 @ [print new line] + O 11 @ + T F [clear acc] + A @ [load negative count of c.f.s] + A 2 @ [add 1] + E 59 @ [exit if count = 0] + T @ [store back] + A 22 @ [order to load numerator] + A 4 @ [inc address by 4 for next c.f.] + A 4 @ + G 17 @ [loop back (always, since 'A' < 0)] + + [59] O 12 @ [print null to flush teleprinter buffer] + Z F [stop] + + E 13 Z [define entry point] + P F [acc = 0 on entry] diff --git a/Task/Continued-fraction/Lua/continued-fraction.lua b/Task/Continued-fraction/Lua/continued-fraction.lua new file mode 100644 index 0000000000..f2c009d39d --- /dev/null +++ b/Task/Continued-fraction/Lua/continued-fraction.lua @@ -0,0 +1,66 @@ +function calc(fa, fb, expansions) + local a = 0.0 + local b = 0.0 + local r = 0.0 + local i = expansions + while i > 0 do + a = fa(i) + b = fb(i) + r = b / (a + r) + i = i - 1 + end + a = fa(0) + return a + r +end + +function sqrt2a(n) + if n ~= 0 then + return 2.0 + else + return 1.0 + end +end + +function sqrt2b(n) + return 1.0 +end + +function napiera(n) + if n ~= 0 then + return n + else + return 2.0 + end +end + +function napierb(n) + if n > 1.0 then + return n - 1.0 + else + return 1.0 + end +end + +function pia(n) + if n ~= 0 then + return 6.0 + else + return 3.0 + end +end + +function pib(n) + local c = 2.0 * n - 1.0 + return c * c +end + +function main() + local sqrt2 = calc(sqrt2a, sqrt2b, 1000) + local napier = calc(napiera, napierb, 1000) + local pi = calc(pia, pib, 1000) + print(sqrt2) + print(napier) + print(pi) +end + +main() diff --git a/Task/Continued-fraction/Nim/continued-fraction.nim b/Task/Continued-fraction/Nim/continued-fraction.nim new file mode 100644 index 0000000000..d4601c55b8 --- /dev/null +++ b/Task/Continued-fraction/Nim/continued-fraction.nim @@ -0,0 +1,27 @@ +proc calc(f: proc(n: int): tuple[a, b: float], n: int): float = + var a, b, temp = 0.0 + for i in countdown(n, 1): + (a, b) = f(i) + temp = b / (a + temp) + (a, b) = f(0) + a + temp + +proc sqrt2(n: int): tuple[a, b: float] = + if n > 0: + (2.0, 1.0) + else: + (1.0, 1.0) + +proc napier(n: int): tuple[a, b: float] = + let a = if n > 0: float(n) else: 2.0 + let b = if n > 1: float(n - 1) else: 1.0 + (a, b) + +proc pi(n: int): tuple[a, b: float] = + let a = if n > 0: 6.0 else: 3.0 + let b = (2 * float(n) - 1) * (2 * float(n) - 1) + (a, b) + +echo $calc(sqrt2, 20) +echo $calc(napier, 15) +echo $calc(pi, 10000) diff --git a/Task/Continued-fraction/Swift/continued-fraction.swift b/Task/Continued-fraction/Swift/continued-fraction.swift new file mode 100644 index 0000000000..c68c2eba0a --- /dev/null +++ b/Task/Continued-fraction/Swift/continued-fraction.swift @@ -0,0 +1,106 @@ +extension BinaryInteger { + @inlinable + public func power(_ n: Self) -> Self { + return stride(from: 0, to: n, by: 1).lazy.map({_ in self }).reduce(1, *) + } +} + +public struct CycledSequence { + private var seq: WrappedSequence + private var iter: WrappedSequence.Iterator + + init(seq: WrappedSequence) { + self.seq = seq + self.iter = seq.makeIterator() + } +} + +extension CycledSequence: Sequence, IteratorProtocol { + public mutating func next() -> WrappedSequence.Element? { + if let ele = iter.next() { + return ele + } else { + iter = seq.makeIterator() + + return iter.next() + } + } +} + +extension Sequence { + public func cycled() -> CycledSequence { + return CycledSequence(seq: self) + } +} + +public struct ChainedSequence { + private var sequences: [AnySequence] + private var iter: AnyIterator + private var curSeq = 0 + + init(chain: ChainedSequence) { + self.sequences = chain.sequences + self.iter = chain.iter + self.curSeq = chain.curSeq + } + + init(_ seq: Seq) where Seq.Element == Element { + sequences = [AnySequence(seq)] + iter = sequences[curSeq].makeIterator() + } + + func chained(with seq: Seq) -> ChainedSequence where Seq.Element == Element { + var res = ChainedSequence(chain: self) + + res.sequences.append(AnySequence(seq)) + + return res + } +} + +extension ChainedSequence: Sequence, IteratorProtocol { + public mutating func next() -> Element? { + if let el = iter.next() { + return el + } + + curSeq += 1 + + guard curSeq != sequences.endIndex else { + return nil + } + + iter = sequences[curSeq].makeIterator() + + return iter.next() + } +} + +extension Sequence { + public func chained(with other: Seq) -> ChainedSequence where Seq.Element == Element { + return ChainedSequence(self).chained(with: other) + } +} + +func continuedFraction( + _ seq1: T, + _ seq2: V, + iterations: Int = 1000 +) -> Double where T.Element: BinaryInteger, T.Element == V.Element { + return zip(seq1, seq2).prefix(iterations).reversed().reduce(0.0, { Double($1.0) + (Double($1.1) / $0) }) +} + +let sqrtA = [1].chained(with: [2].cycled()) +let sqrtB = [1].cycled() + +print("√2 ≈ \(continuedFraction(sqrtA, sqrtB))") + +let napierA = [2].chained(with: 1...) +let napierB = [1].chained(with: 1...) + +print("e ≈ \(continuedFraction(napierA, napierB))") + +let piA = [3].chained(with: [6].cycled()) +let piB = (1...).lazy.map({ (2 * $0 - 1).power(2) }) + +print("π ≈ \(continuedFraction(piA, piB))") diff --git a/Task/Convert-decimal-number-to-rational/Factor/convert-decimal-number-to-rational.factor b/Task/Convert-decimal-number-to-rational/Factor/convert-decimal-number-to-rational.factor index 7b4f44c35e..9382af5ebf 100644 --- a/Task/Convert-decimal-number-to-rational/Factor/convert-decimal-number-to-rational.factor +++ b/Task/Convert-decimal-number-to-rational/Factor/convert-decimal-number-to-rational.factor @@ -1,2 +1,3 @@ -USE: math.floating-point -{ 0.9054054 0.518518 0.75 } [ double>ratio ] map [ . ] each +USING: kernel math.floating-point prettyprint ; + +0.9054054 0.518518 0.75 [ double>ratio . ] tri@ diff --git a/Task/Convert-decimal-number-to-rational/Nim/convert-decimal-number-to-rational-1.nim b/Task/Convert-decimal-number-to-rational/Nim/convert-decimal-number-to-rational-1.nim new file mode 100644 index 0000000000..f1e20a4ca8 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Nim/convert-decimal-number-to-rational-1.nim @@ -0,0 +1,56 @@ +import math +import fenv + +type + Rational = object + numerator: int + denominator: int + +proc `$`(self: Rational): string = + if self.denominator == 1: + $self.numerator + else: + $self.numerator & "//" & $self.denominator + +func rationalize(x: float, tol: float = epsilon(float)): Rational = + var xx = x + let flagNeg = xx < 0.0 + if flagNeg: + xx = -xx + if xx < minimumPositiveValue(float): + return Rational(numerator: 0, denominator: 1) + if abs(xx - round(xx)) < tol: + return Rational(numerator: int(round(xx)), denominator: 1) + var a = 0 + var b = 1 + var c = int(ceil(xx)) + var d = 1 + var aux1 = high(int) div 2 + while c < aux1 and d < aux1: + var aux2 = (float(a) + float(c)) / (float(b) + float(d)) + if abs(xx - aux2) < tol: + break + if xx > aux2: + inc a, c + inc b, d + else: + inc c, a + inc d, b + var gcd = gcd(a + c, b + d) + if flagNeg: + Rational(numerator: -(a + c) div gcd, denominator: (b + d) div gcd) + else: + Rational(numerator: (a + c) div gcd, denominator: (b + d) div gcd) + +echo rationalize(0.9054054054) +echo rationalize(0.9054054054, 0.0001) +echo rationalize(0.5185185185) +echo rationalize(0.5185185185, 0.0001) +echo rationalize(0.75) +echo rationalize(0.1428571428, 0.001) +echo rationalize(35.000) +echo rationalize(35.001) +echo rationalize(0.9) +echo rationalize(0.99) +echo rationalize(0.909) +echo rationalize(0.909, 0.001) diff --git a/Task/Convert-decimal-number-to-rational/Nim/convert-decimal-number-to-rational-2.nim b/Task/Convert-decimal-number-to-rational/Nim/convert-decimal-number-to-rational-2.nim new file mode 100644 index 0000000000..79b479ae38 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Nim/convert-decimal-number-to-rational-2.nim @@ -0,0 +1,11 @@ +import rationals + +echo toRational(0.9054054054) +echo toRational(0.5185185185) +echo toRational(0.75) +echo toRational(0.1428571428) +echo toRational(35.000) +echo toRational(35.001) +echo toRational(0.9) +echo toRational(0.99) +echo toRational(0.909) diff --git a/Task/Convert-decimal-number-to-rational/Sidef/convert-decimal-number-to-rational-1.sidef b/Task/Convert-decimal-number-to-rational/Sidef/convert-decimal-number-to-rational-1.sidef index f4d8ea991b..bbf7a45c05 100644 --- a/Task/Convert-decimal-number-to-rational/Sidef/convert-decimal-number-to-rational-1.sidef +++ b/Task/Convert-decimal-number-to-rational/Sidef/convert-decimal-number-to-rational-1.sidef @@ -1,3 +1,3 @@ -'0.9054054 0.518518 0.75'.split.each { |d| - say d.num.as_rat; -} +say 0.75.as_frac #=> 3/4 +say 0.518518.as_frac #=> 259259/500000 +say 0.9054054.as_frac #=> 4527027/5000000 diff --git a/Task/Convert-decimal-number-to-rational/Sidef/convert-decimal-number-to-rational-2.sidef b/Task/Convert-decimal-number-to-rational/Sidef/convert-decimal-number-to-rational-2.sidef index aaf5071ab9..f76ca7732e 100644 --- a/Task/Convert-decimal-number-to-rational/Sidef/convert-decimal-number-to-rational-2.sidef +++ b/Task/Convert-decimal-number-to-rational/Sidef/convert-decimal-number-to-rational-2.sidef @@ -1,3 +1,3 @@ -say 0.9054054.as_rat; -say 0.518518.as_rat; -say 0.75.as_rat; +'0.9054054 0.518518 0.75'.split.each { |str| + say Num(str).as_frac +} diff --git a/Task/Convert-decimal-number-to-rational/Sidef/convert-decimal-number-to-rational-3.sidef b/Task/Convert-decimal-number-to-rational/Sidef/convert-decimal-number-to-rational-3.sidef new file mode 100644 index 0000000000..962ea33b93 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Sidef/convert-decimal-number-to-rational-3.sidef @@ -0,0 +1,2 @@ +say 0.518518.rat_approx.as_frac #=> 14/27 +say 0.9054054.rat_approx.as_frac #=> 67/74 diff --git a/Task/Convert-decimal-number-to-rational/Vala/convert-decimal-number-to-rational.vala b/Task/Convert-decimal-number-to-rational/Vala/convert-decimal-number-to-rational.vala new file mode 100644 index 0000000000..f3abd9829f --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Vala/convert-decimal-number-to-rational.vala @@ -0,0 +1,56 @@ +struct Fraction { + public long d; + public long n; +} + +Fraction rat_approx(double f, long md) { + long a; + long[] h = {0, 1, 0}; + long[] k = {1, 0, 0}; + long x, d, n = 1; + bool neg = false; + if (md <= 1) return {1, (long)f}; + if (f < 0) { + neg = true; + f = -f; + } + while (f != Math.floor(f)) { + n <<= 1; + f *= 2; + } + d = (long)f; + for (int i = 0; i < 64; i++) { + a = (n != 0) ? d / n : 0; + if (i != 0 && a == 0) break; + x = d; d = n; n = x %n; + x = a; + if (k[1] * a + k[0] >= md) { + x = (md - k[0]) / k[1]; + if (x * 2 >= a || k[1] >= md) + i = 65; + else + break; + } + h[2] = x * h[1] + h[0]; h[0] = h[1]; h[1] = h[2]; + k[2] = x * k[1] + k[0]; k[0] = k[1]; k[1] = k[2]; + } + return {k[1], neg ? -h[1] : h[1]}; +} + +void main() { + double f; + + print("f = %16.14f\n", f = 1.0/7); + for (int i = 1; i < 20000000; i *= 16) { + print("denom <= %11d: ", i); + var r = rat_approx(f, i); + print("%11ld/%ld\n", r.n, r.d); + } + + print("f = %16.14f\n", f = Math.atan2(1,1) * 4); + for (int i = 1; i < 20000000; i *= 16) { + print("denom <= %11d: ", i); + var r = rat_approx(f, i); + print("%11ld/%ld\n", r.n, r.d); + } +} diff --git a/Task/Conways-Game-of-Life/Frink/conways-game-of-life.frink b/Task/Conways-Game-of-Life/Frink/conways-game-of-life.frink new file mode 100644 index 0000000000..344fb47316 --- /dev/null +++ b/Task/Conways-Game-of-Life/Frink/conways-game-of-life.frink @@ -0,0 +1,105 @@ +start = now[] +// Generate a random 10x10 grid with "1" being on and "0" being off +instructions = ["1000100110","0001100010","1000111101","1001111110","0000110011","1111000001","0100001110","1011101001","1001011000","1101110111"] + +// Create dictionary of starting positions. +rowCounter = 0 +display = new dict +for instructionStr = instructions +{ + rowCounter = rowCounter + 1 + columnCounter = 0 + instructionArr = charList[instructionStr] + for instruction = instructionArr + { + columnCounter = columnCounter + 1 + arr = [rowCounter,columnCounter] + if instruction == "1" + display@arr = 1 + else + display@arr = 0 + } +} + +// Create toggle dictionary to track changes. It starts off with everything off. +toggle = new dict +multifor[x,y] = [new range[1,10],new range[1,10]] +{ + arr = [x,y] + toggle@arr = 0 +} + +// Animate the game of life +a = new Animation[3/s] +win = undef + +// Loop through 10 changes to the grid. The starting points will tick down to two stable unchanging shapes in 10 steps. +for i = 1 to 12 // 12 steps so animation will pause on final state. +{ + // Graphics item for this frame of the animation. + g = new graphics + g.backgroundColor[1,1,1] + // Add in a transparent shape to prevent the image from jiggle to automatic scaling. + g.color[0,0,0,0] // Transparent black + g.fillRectSides[-1, -1, 12, 12] // Set minimum size + g.clipRectSides[-1, -1, 12, 12] // Set maximum size + g.color[0,0,0] // Color back to default black + multifor[x1,y1] = [new range[1,10],new range[1,10]] + { + tval = [x1,y1] + // This is programmed with a hard edge. Points beyond the border aren't considered. + xmax = min[x1+1,10] + xmin = max[x1-1,1] + ymax = min[y1+1,10] + ymin = max[y1-1,1] + // Range will be 8 surrounding cells or cells up to border. + pointx = new range[xmin,xmax] + pointy = new range[ymin,ymax] + pointsum = 0 + status = 0 + // Process each surrounded point + multifor[x2,y2] = [pointx,pointy] + { + // Assign the array to a variable so it can be used as a dictionary reference. + point = [x2,y2] + if x2 == x1 && y2 == y1 + { + status = display@point + } else // Calculate the total of surrounding points + { + pointsum = pointsum + display@point + } + } + // Animate if the point is on. + if status == 1 + { + g.color[0,0,0] + g.fillEllipseCenter[x1,y1,1,1] + } + toggle@tval = status // This will be overwritten if needed by neighbor check conditions below. + // Check if off point has 3 on point neighbors + if status == 0 && pointsum == 3 + { + toggle@tval = 1 + } + // Check if on point has between 2 and 3 on point neighbors + if status == 1 && (pointsum < 2 || pointsum > 3) + { + toggle@tval = 0 + } + } + // Add the current frame to the animation + a.add[g] + // Replace the current display with the toggle values. + for toggleKeys = keys[toggle] + { + val = toggle@toggleKeys + display@toggleKeys = val + } +} + +// Write the animation file +a.write["FrinkAnimationGoL.gif",400,400] + +end = now[] +println["Program run time: " + ((end - start)*1.0 -> "seconds")] diff --git a/Task/Conways-Game-of-Life/JavaScript/conways-game-of-life-4.js b/Task/Conways-Game-of-Life/JavaScript/conways-game-of-life-4.js new file mode 100644 index 0000000000..4aee873db2 --- /dev/null +++ b/Task/Conways-Game-of-Life/JavaScript/conways-game-of-life-4.js @@ -0,0 +1,70 @@ +const alive = 1; +const dead = 0; + +const conwaysGameOfLife = (game) => { + const newGame = [] + for (let y = 0; y < game.length; y += 1) { + const newRow = [] + for (let x = 0; x < game[y].length; x += 1) { + const cell = game[y][x]; + const prevX = x > 0 ? x - 1 : x; + const nextX = x < game[y].length - 1 ? x + 2 : x + 1; + const counter = + (game[y - 1] ? game[y - 1].slice(prevX, nextX).reduce((acc, v) => acc + v) : 0) + + (game[y][x - 1] || 0) + (game[y][x + 1] || 0) + + (game[y + 1] ? game[y + 1].slice(prevX, nextX).reduce((acc, v) => acc + v) : 0) + cell === alive + ? counter > 1 && counter <= 3 + ? newRow.push(alive) + : newRow.push(dead) + : counter === 3 + ? newRow.push(alive) + : newRow.push(dead) + } + newGame.push(newRow) + } + return newGame +} + +const generateGame = (height, width) => { + return Array.from({ length: height }, (v, k) => ( + Array.from({ length: width}, (v, k) => { + return (Math.random() * 100 | 0) < 50 ? dead : alive + }) + )) +} + +const output = (game) =>{ + process.stdout.write('\033c'); + let screen = ''; + for (let i = 0; i < game.length; i += 1) { + screen += game[i].join('') + screen += '\n' + } + console.log(screen) +} + +const setup = ((game) => { + return () => { + setInterval(() => { + output(game) + const newGame = conwaysGameOfLife(game) + game = newGame + }, 1000) + } +}) + +// for random game +// const game = generateGame(10, 10) + +// glider test +const game = [ + [0,0,0,0,0,0,0,0,0,0], + [0,0,1,0,0,0,0,0,0,0], + [0,0,0,1,0,0,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] +]; +const run = setup(game); +run() diff --git a/Task/Conways-Game-of-Life/Julia/conways-game-of-life.julia b/Task/Conways-Game-of-Life/Julia/conways-game-of-life-1.julia similarity index 100% rename from Task/Conways-Game-of-Life/Julia/conways-game-of-life.julia rename to Task/Conways-Game-of-Life/Julia/conways-game-of-life-1.julia diff --git a/Task/Conways-Game-of-Life/Julia/conways-game-of-life-2.julia b/Task/Conways-Game-of-Life/Julia/conways-game-of-life-2.julia new file mode 100644 index 0000000000..31288ed08a --- /dev/null +++ b/Task/Conways-Game-of-Life/Julia/conways-game-of-life-2.julia @@ -0,0 +1,43 @@ +using ArrayFire +using Images +using LinearAlgebra + +const blinker = [0 0 0; 1 1 1; 0 0 0] +const glider = [0 0 1; 1 0 1; 0 1 1] +const lwss = [0 1 1 1 1; 1 0 0 0 1; 0 0 0 0 1; 1 0 0 1 0] +const glidergun = [ + 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 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 1 0 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 1 1 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0; + 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0; + 0 1 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; + 0 1 1 0 0 0 0 0 0 0 0 1 0 0 0 1 0 1 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0; + 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 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 1 0 0 0 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 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] + +function lifegame(fname, initializer, mapsize=30, imgsteps=50, upscaleratio=20) + kernel = convert(Array{Float32}, [1 1 1; 1 0 1; 1 1 1]) |> AFArray + initialstate = zeros(Bool, mapsize, mapsize) + mid = div(mapsize, 2) + (xlen, ylen), (halfx, halfy) = size(initializer), div.(size(initializer), 2) + x1, x2 = mid - halfx, isodd(xlen) ? mid + halfx : mid + halfx - 1 + y1, y2 = mid - halfy, isodd(ylen) ? mid + halfy : mid + halfy - 1 + initialstate[x1:x2, y1:y2] .= initializer + state = initialstate .+ Float32(.0) |> AFArray + img = zeros(Float32, mapsize * upscaleratio, mapsize * upscaleratio, imgsteps) + for i in 1:imgsteps + nb = convolve2(state, kernel, UInt32(0), UInt32(0)) + a = (nb == 2) + b = (nb == 3) + state = ((state .* a .+ b) > 0) + Float32(0) + frame = imresize(state, ratio=upscaleratio) + img[:, :, i] .= frame + end + save(fname, img) +end + +lifegame("blinker.gif", blinker) +lifegame("glider.gif", glider) +lifegame("lwss.gif", lwss) +lifegame("glidergun.gif", glidergun, 90, 200) diff --git a/Task/Conways-Game-of-Life/Perl/conways-game-of-life-3.pl b/Task/Conways-Game-of-Life/Perl/conways-game-of-life-3.pl new file mode 100644 index 0000000000..3bededf07c --- /dev/null +++ b/Task/Conways-Game-of-Life/Perl/conways-game-of-life-3.pl @@ -0,0 +1,17 @@ +#!/usr/bin/perl + +print $_ = <<'' =~ tr/./ /r; # test case, dots only for layout +..... +..... +.###. +..... +..... + +my $gap = /..\n/ ? qr/.{$-[0]}/s : die "too small"; +my $neighborhood = qr/(?<=(...) $gap (.)) . (?=(.) $gap (...))/x; + +for my $generation ( 2 .. 4 ) + { + s/$neighborhood/ substr " $&# ", "$1$2$3$4" =~ tr|#||, 1 /ge; + print; + } diff --git a/Task/Conways-Game-of-Life/Retro/conways-game-of-life.retro b/Task/Conways-Game-of-Life/Retro/conways-game-of-life.retro index deb5c2aec8..fc06164f32 100644 --- a/Task/Conways-Game-of-Life/Retro/conways-game-of-life.retro +++ b/Task/Conways-Game-of-Life/Retro/conways-game-of-life.retro @@ -1,78 +1,70 @@ -create world - 20 20 * allot +:w/l [ $. eq? [ #0 ] [ #1 ] choose , ] s:for-each ; -create next - 20 20 * allot +'World d:create + '.................... w/l + '.................... w/l + '.................... w/l + '..ooo............... w/l + '....o............... w/l + '...o................ w/l + '.................... w/l + '.................... w/l + '.................... w/l + '.................... w/l + '.................... w/l + '....ooo............. w/l + '.................... w/l + '.................... w/l + '.................... w/l + '........ooo......... w/l + '.......ooo.......... w/l + '.................... w/l + '.................... w/l + '.................... w/l -create initial -( 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ) -( 0 ) 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , -( 1 ) 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 , 0 , 1 , 1 , 0 , -( 2 ) 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 , 0 , 1 , 1 , 0 , -( 3 ) 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , -( 4 ) 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , -( 5 ) 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , -( 6 ) 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , -( 7 ) 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , -( 8 ) 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , -( 9 ) 0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 , 1 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , -( 10 ) 0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , -( 11 ) 0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , -( 12 ) 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , -( 13 ) 0 , 0 , 1 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , -( 14 ) 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 0 , 0 , 0 , 0 , -( 15 ) 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 0 , 0 , 0 , 0 , -( 16 ) 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 0 , 0 , -( 17 ) 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , 0 , 0 , -( 18 ) 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , -( 19 ) 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , +'Next d:create + #20 #20 * allot -( Assumes anything outside the bounds is "dead" ) {{ - variable surrounding - : get ( rc- ) - 2over [ 0 19 within ] bi@ and - [ world + [ 20 * ] dip + @ ] [ 2drop 0 ] if ; - : neighbor? ( rc- ) get +surrounding ; - : NW ( rc-rc ) 2over [ 1- ] bi@ neighbor? ; - : NN ( rc-rc ) 2over [ 1- ] dip neighbor? ; - : NE ( rc-rc ) 2over [ 1- ] dip 1+ neighbor? ; - : WW ( rc-rc ) 2over 1- neighbor? ; - : EE ( rc-rc ) 2over 1+ neighbor? ; - : SW ( rc-rc ) 2over [ 1+ ] dip 1- neighbor? ; - : SS ( rc-rc ) 2over [ 1+ ] dip neighbor? ; - : SE ( rc-rc ) 2over [ 1+ ] bi@ neighbor? ; - : count ( rc-rcn ) - 0 !surrounding - NW NN NE - WW EE - SW SS SE @surrounding ; - : alive ( rc-n ) - count - [ 0 1 within ] [ drop 0 ] when - [ 4 8 within ] [ drop 0 ] when - [ 2 3 within ] [ drop 1 ] when ; - : dead ( rc-n ) - count - [ 3 = ] [ drop 1 ] when - [ 0 2 within ] [ drop 0 ] when - [ 4 8 within ] [ drop 0 ] when ; - : newState ( rc-n ) - 2over get 1 = [ alive ] [ dead ] if ; - : set ( nrc- ) next + [ 20 * ] dip + ! ; - : cols ( r- ) - 20 [ over swap newState 2rot set ] iter drop ; - : output ( n- ) [ 'o ] [ '. ] if putc space ; + 'Surrounding var + :get (rc-v) + dup-pair [ #0 #19 n:between? +] bi@ and + [ &World + [ #20 * ] dip + fetch ] [ drop-pair #0 ] choose ; + :neighbor? (rc-) get &Surrounding v:inc-by ; + :NW (rc-rc) dup-pair [ n:dec ] bi@ neighbor? ; + :NN (rc-rc) dup-pair [ n:dec ] dip neighbor? ; + :NE (rc-rc) dup-pair [ n:dec ] dip n:inc neighbor? ; + :WW (rc-rc) dup-pair n:dec neighbor? ; + :EE (rc-rc) dup-pair n:inc neighbor? ; + :SW (rc-rc) dup-pair [ n:inc ] dip n:dec neighbor? ; + :SS (rc-rc) dup-pair [ n:inc ] dip neighbor? ; + :SE (rc-rc) dup-pair [ n:inc ] bi@ neighbor? ; + :count (rc-rcn) + #0 !Surrounding NW NN NE + WW EE + SW SS SE @Surrounding ; + :alive (rc-n) + count #2 #3 n:between? [ #1 ] if; #0 ; + :dead (rc-n) + count #3 eq? [ #1 ] if; #0 ; + :new-state (rc-n) + dup-pair get #1 eq? &alive &dead choose ; + :set (nrc-) &Next + [ #20 * ] dip + store ; + :cols (r-) + #20 [ I over swap new-state rot rot set ] times drop ; + :output (n-) n:-zero? [ $o ] [ $. ] choose c:put sp ; ---reveal--- - : display ( - ) - cr world 20 [ 20 [ @+ output ] times cr ] times drop ; - : start ( - ) - initial world 20 20 * copy display ; - : gen ( - ) - 20 [ cols ] iter next world 20 20 * copy ; - : delay ( - ) time 1+ [ time over <= ] while drop ; - : run ( n- ) - [ delay clear gen display ] times ; + :display (-) + nl &World #20 [ #20 [ fetch-next output ] times nl ] times drop ; + :gen (-) + #20 [ I cols ] times &Next &World #20 #20 * copy ; }} -start 20 run +{{ + :divide #20 [ $- c:put ] times sp 'Gen:_ s:put dup n:put nl ; +---reveal--- + :gens (n-) #0 swap [ display divide n:inc gen ] times drop ; +}} + +#12 gens diff --git a/Task/Conways-Game-of-Life/Swift/conways-game-of-life.swift b/Task/Conways-Game-of-Life/Swift/conways-game-of-life.swift new file mode 100644 index 0000000000..443f4cc9b0 --- /dev/null +++ b/Task/Conways-Game-of-Life/Swift/conways-game-of-life.swift @@ -0,0 +1,95 @@ +struct Cell: Hashable { + var x: Int + var y: Int +} + +struct Colony { + private var height: Int + private var width: Int + private var cells: Set + + init(cells: Set, height: Int, width: Int) { + self.cells = cells + self.height = height + self.width = width + } + + private func neighborCounts() -> [Cell: Int] { + var counts = [Cell: Int]() + + for cell in cells.flatMap(Colony.neighbors(for:)) { + counts[cell, default: 0] += 1 + } + + return counts + } + + private static func neighbors(for cell: Cell) -> [Cell] { + return [ + Cell(x: cell.x - 1, y: cell.y - 1), + Cell(x: cell.x, y: cell.y - 1), + Cell(x: cell.x + 1, y: cell.y - 1), + Cell(x: cell.x - 1, y: cell.y), + Cell(x: cell.x + 1, y: cell.y), + Cell(x: cell.x - 1, y: cell.y + 1), + Cell(x: cell.x, y: cell.y + 1), + Cell(x: cell.x + 1, y: cell.y + 1), + ] + } + + func printColony() { + for y in 0..string ] map " x " join print ] each +USING: io kernel math.primes.factors math.ranges prettyprint +sequences ; + +: .factors ( n -- ) + dup pprint ": " write factors + [ " × " write ] [ pprint ] interleave nl ; + +"1: 1" print 2 20 [a,b] [ .factors ] each diff --git a/Task/Count-in-factors/Julia/count-in-factors.julia b/Task/Count-in-factors/Julia/count-in-factors.julia index e5c2e4ebcd..0e80053ccb 100644 --- a/Task/Count-in-factors/Julia/count-in-factors.julia +++ b/Task/Count-in-factors/Julia/count-in-factors.julia @@ -1,4 +1,4 @@ -using Primes +using Primes, Printf function strfactor(n::Integer) n > -2 || return "-1 × " * strfactor(-n) isprime(n) || n < 2 && return dec(n) diff --git a/Task/Count-in-factors/Scala/count-in-factors.scala b/Task/Count-in-factors/Scala/count-in-factors.scala index 3c2bb02dc8..2c2528bc49 100644 --- a/Task/Count-in-factors/Scala/count-in-factors.scala +++ b/Task/Count-in-factors/Scala/count-in-factors.scala @@ -1,21 +1,27 @@ -def primeFactors( n:Int ) = { +object CountInFactors extends App { - def primeStream(s: Stream[Int]): Stream[Int] = { - s.head #:: primeStream(s.tail filter { _ % s.head != 0 }) + def primeFactors(n: Int): List[Int] = { + + def primeStream(s: LazyList[Int]): LazyList[Int] = { + s.head #:: primeStream(s.tail filter { + _ % s.head != 0 + }) + } + + val primes = primeStream(LazyList.from(2)) + + def factors(n: Int): List[Int] = primes.takeWhile(_ <= n).find(n % _ == 0) match { + case None => Nil + case Some(p) => p :: factors(n / p) + } + + if (n == 1) List(1) else factors(n) } - val primes = primeStream(Stream.from(2)) - - def factors( n:Int ) : List[Int] = primes.takeWhile( _ <= n ).find( n % _ == 0 ) match { - case None => Nil - case Some(p) => p :: factors( n/p ) + // A little test... + { + val nums = (1 to 12).toList :+ 2144 :+ 6358 + nums.foreach(n => println("%6d : %s".format(n, primeFactors(n).mkString(" * ")))) } - if( n == 1 ) List(1) else factors(n) -} - -// A little test... -{ - val nums = (1 to 12).toList :+ 2144 :+ 6358 - nums.foreach( n => println( "%6d : %s".format( n, primeFactors(n).mkString(" * ") ) ) ) } diff --git a/Task/Count-in-factors/Swift/count-in-factors.swift b/Task/Count-in-factors/Swift/count-in-factors.swift new file mode 100644 index 0000000000..e50cb63738 --- /dev/null +++ b/Task/Count-in-factors/Swift/count-in-factors.swift @@ -0,0 +1,29 @@ +extension BinaryInteger { + @inlinable + public func primeDecomposition() -> [Self] { + guard self > 1 else { return [] } + + func step(_ x: Self) -> Self { + return 1 + (x << 2) - ((x >> 1) << 1) + } + + let maxQ = Self(Double(self).squareRoot()) + var d: Self = 1 + var q: Self = self & 1 == 0 ? 2 : 3 + + while q <= maxQ && self % q != 0 { + q = step(d) + d += 1 + } + + return q <= maxQ ? [q] + (self / q).primeDecomposition() : [self] + } +} + +for i in 1...20 { + if i == 1 { + print("1 = 1") + } else { + print("\(i) = \(i.primeDecomposition().map(String.init).joined(separator: " x "))") + } +} diff --git a/Task/Count-in-octal/Perl/count-in-octal-3.pl b/Task/Count-in-octal/Perl/count-in-octal-3.pl new file mode 100644 index 0000000000..1a99a607d8 --- /dev/null +++ b/Task/Count-in-octal/Perl/count-in-octal-3.pl @@ -0,0 +1,4 @@ +#!/usr/bin/perl + +$_ = 0; +s/([^7])?(7*)$/ $1 + 1 . $2 =~ tr!7!0!r /e while print "$_\n"; diff --git a/Task/Count-in-octal/Pike/count-in-octal.pike b/Task/Count-in-octal/Pike/count-in-octal.pike new file mode 100644 index 0000000000..b770952b77 --- /dev/null +++ b/Task/Count-in-octal/Pike/count-in-octal.pike @@ -0,0 +1,3 @@ +int i=1; +while(true) + write("0%o\n", i++); diff --git a/Task/Count-in-octal/Prolog/count-in-octal.pro b/Task/Count-in-octal/Prolog/count-in-octal.pro new file mode 100644 index 0000000000..ce70cc26ee --- /dev/null +++ b/Task/Count-in-octal/Prolog/count-in-octal.pro @@ -0,0 +1,14 @@ +o(O) :- member(O, [0,1,2,3,4,5,6,7]). + +octal([O]) :- o(O). +octal([A|B]) :- + octal(O), + o(T), + append(O, [T], [A|B]), + dif(A, 0). + +octalize :- + forall( + octal(X), + (maplist(write, X), nl) + ). diff --git a/Task/Count-occurrences-of-a-substring/Pike/count-occurrences-of-a-substring.pike b/Task/Count-occurrences-of-a-substring/Pike/count-occurrences-of-a-substring.pike new file mode 100644 index 0000000000..edbc5c4a36 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Pike/count-occurrences-of-a-substring.pike @@ -0,0 +1,3 @@ +write("%d %d\n", + String.count("the three truths", "th"), + String.count("ababababab", "abab")); diff --git a/Task/Count-the-coins/COBOL/count-the-coins.cobol b/Task/Count-the-coins/COBOL/count-the-coins.cobol new file mode 100644 index 0000000000..3a083ed90f --- /dev/null +++ b/Task/Count-the-coins/COBOL/count-the-coins.cobol @@ -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/Commodore-BASIC/count-the-coins-1.commodore b/Task/Count-the-coins/Commodore-BASIC/count-the-coins-1.commodore new file mode 100644 index 0000000000..6c57408097 --- /dev/null +++ b/Task/Count-the-coins/Commodore-BASIC/count-the-coins-1.commodore @@ -0,0 +1,27 @@ +5 m=100:rem money = $1.00 or 100 pennies. +10 print chr$(147);chr$(14);"This program will calculate the number" +11 print "of combinations of 'change' that can be" +12 print "given for a $1 bill." +13 print:print "The coin values are:" +14 print "0.01 = Penny":print "0.05 = Nickle" +15 print "0.10 = Dime":print "0.25 = Quarter" +16 print +20 print "Would you like to see each combination?" +25 get k$:yn=(k$="y"):if k$="" then 25 +100 p=m:ti$="000000" +130 q=int(m/25) +140 count=0:ps=1 +147 if yn then print "Count P N D Q" +150 for qc=0 to q:d=int((m-qc*25)/10) +160 for dc=0 to d:n=int((m-dc*10)/5) +170 for nc=0 to n:p=m-nc*5 +180 for pc=0 to p step 5 +190 s=pc+nc*5+dc*10+qc*25 +200 if s=m then count=count+1:if yn then gosub 1000 +210 next:next:next:next +245 en$=ti$ +250 print:print count;"different combinations found in" +260 print tab(len(str$(count))+1); +265 print left$(en$,2);":";mid$(en$,3,2);":";right$(en$,2);"." +270 end +1000 print count;tab(6);pc;tab(11);nc;tab(16);dc;tab(21);qc:return diff --git a/Task/Count-the-coins/Commodore-BASIC/count-the-coins-2.commodore b/Task/Count-the-coins/Commodore-BASIC/count-the-coins-2.commodore new file mode 100644 index 0000000000..95317286d3 --- /dev/null +++ b/Task/Count-the-coins/Commodore-BASIC/count-the-coins-2.commodore @@ -0,0 +1,2 @@ +145 if not yn then poke 53265,peek(53265) and 239 +245 en$=ti$:if not yn then poke 53265,peek(53265) or 16 diff --git a/Task/Count-the-coins/Commodore-BASIC/count-the-coins-3.commodore b/Task/Count-the-coins/Commodore-BASIC/count-the-coins-3.commodore new file mode 100644 index 0000000000..20a37dbadd --- /dev/null +++ b/Task/Count-the-coins/Commodore-BASIC/count-the-coins-3.commodore @@ -0,0 +1,2 @@ +145 if not yn then fast +245 en$=ti$:if not yn then slow diff --git a/Task/Count-the-coins/Prolog/count-the-coins.pro b/Task/Count-the-coins/Prolog/count-the-coins.pro new file mode 100644 index 0000000000..3a7803abf0 --- /dev/null +++ b/Task/Count-the-coins/Prolog/count-the-coins.pro @@ -0,0 +1,10 @@ +:- use_module(library(clpfd)). + +% Basic, Q = Quarter, D = Dime, N = Nickel, P = Penny +coins(Q, D, N, P, T) :- + [Q,D,N,P] ins 0..T, + T #= (Q * 25) + (D * 10) + (N * 5) + P. + +coins_for(T) :- + coins(Q,D,N,P,T), + maplist(indomain, [Q,D,N,P]). diff --git a/Task/Create-a-file-on-magnetic-tape/00DESCRIPTION b/Task/Create-a-file-on-magnetic-tape/00DESCRIPTION index 725a16cd4f..f3b4f41ef0 100644 --- a/Task/Create-a-file-on-magnetic-tape/00DESCRIPTION +++ b/Task/Create-a-file-on-magnetic-tape/00DESCRIPTION @@ -1,6 +1,7 @@ {{omit from|Axe}} {{omit from|AWK|not OO}} {{omit from|BASIC|not OO}} +{{omit from|C sharp}} {{omit from|Fortran|not OO}} {{omit from|GUISS}} {{omit from|Locomotive Basic}} @@ -12,6 +13,7 @@ {{omit from|PARI/GP}} {{omit from|Retro}} {{omit from|TI-89 BASIC}} +{{omit from|Visual Basic .NET}} {{omit from|zkl}} The task is to create a new file called "TAPE.FILE" of any size on Magnetic Tape. diff --git a/Task/Create-a-file/BASIC/create-a-file-3.basic b/Task/Create-a-file/BASIC/create-a-file-3.basic new file mode 100644 index 0000000000..aacb228e4b --- /dev/null +++ b/Task/Create-a-file/BASIC/create-a-file-3.basic @@ -0,0 +1,6 @@ +10 rem create a file +20 open 10,8,10,"0:output.txt,seq,write" +30 print#10,chr$(0) +40 close 10 +50 rem check device status for error +60 open 15,8,15:input#15,a,b$,c,d:print a;b$;c;d:close 15 diff --git a/Task/Create-a-file/Retro/create-a-file.retro b/Task/Create-a-file/Retro/create-a-file.retro index e47cc4ac51..06f8816626 100644 --- a/Task/Create-a-file/Retro/create-a-file.retro +++ b/Task/Create-a-file/Retro/create-a-file.retro @@ -1,3 +1,2 @@ -with files' -"output.txt" :w open close drop -"/output.txt" :w open close drop +'output.txt file:W file:open file:close +'/output.txt file:W file:open file:close diff --git a/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-1.basic b/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-1.basic new file mode 100644 index 0000000000..cec3313822 --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-1.basic @@ -0,0 +1,7 @@ +10 INPUT "ENTER TWO INTEGERS:"; X%, Y% +20 DIM A%(X% - 1, Y% - 1) +30 X% = RND(1) * X% +40 Y% = RND(1) * Y% +50 A%(X%, Y%) = -32767 +60 PRINT A%(X%, Y%) +70 CLEAR diff --git a/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-10.basic b/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-10.basic new file mode 100644 index 0000000000..efd5e989db --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-10.basic @@ -0,0 +1,14 @@ + 10 PRINT "1ST DIMENSION: "; + 20 INPUT D1 + 30 PRINT D1 + 40 PRINT "2ND DIMENSION: "; + 50 INPUT D2 + 60 PRINT D2 + 70 DIM A(D1,D1) + 80 PRINT "ARRAY CREATED" + 90 LET X=1+INT (D1*RND) +100 LET Y=1+INT (D2*RND) +110 LET A(X,Y)=37 +120 PRINT "ITEM ";X;", ";Y;" = ";A(X,Y) +130 CLEAR +140 PRINT "ARRAY DESTROYED" diff --git a/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-11.basic b/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-11.basic new file mode 100644 index 0000000000..b075dec864 --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-11.basic @@ -0,0 +1,6 @@ +10 INPUT "Size? ";rows;"*";columns +20 DIM a(rows,columns): REM defines a numeric array +30 LET a=INT (RND*rows)+1: LET c=INT (RND*columns+1): REM the array is labelled a, but the letter a is still available for variable assignment +40 LET a(a,c)=1 +50 PRINT a(a,c) +60 DIM a(1): REM arrays cannot be removed without CLEARing the entire variable space, but redimensioning them to 1 will save most of the space they used diff --git a/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-12.basic b/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-12.basic new file mode 100644 index 0000000000..37fe624868 --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-12.basic @@ -0,0 +1,6 @@ +Input "ROWS? ",R +Input "COLS? ",C +{R,C}→dim([A]) +42→[A](1,1) +Disp [A](1,1) +DelVar [A] diff --git a/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-13.basic b/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-13.basic new file mode 100644 index 0000000000..d2dd954886 --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-13.basic @@ -0,0 +1,14 @@ +Module Program + Sub Main() + Console.WriteLine("Enter two space-delimited integers:") + Dim input = Console.ReadLine().Split() + Dim rows = Integer.Parse(input(0)) + Dim cols = Integer.Parse(input(1)) + + ' VB uses max-index for array creation. + Dim arr(rows - 1, cols - 1) As Integer + + arr(0, 0) = 2 + Console.WriteLine(arr(0, 0)) + End Sub +End Module diff --git a/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-2.basic b/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-2.basic new file mode 100644 index 0000000000..d8dccb776f --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-2.basic @@ -0,0 +1,5 @@ + INPUT "Enter array dimensions separated by a comma: " a%, b% + + DIM array(a%, b%) + array(1, 1) = PI + PRINT array(1, 1) diff --git a/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-3.basic b/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-3.basic new file mode 100644 index 0000000000..543a0e7db9 --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-3.basic @@ -0,0 +1,11 @@ +10 print chr$(147);chr$(14); +15 print "Size of array:" +20 print "Columns (1-20)";:input x% +25 if x%<1 or x%>20 then print "Try again.":goto 20 +30 print "Rows (1-20)";:input y% +35 if y%<1 or y%>20 then print "Try again.":goto 30 +40 x%=x%-1:y%=y%-1:dim a$(x%,y%) +50 nx=int(rnd(1)*x%):ny=int(rnd(1)*y%) +60 a$(nx,ny)="X" +70 print "Element";nx;",";ny;"= '";a$(nx,ny);"'" +80 clr:rem clear variables from ram diff --git a/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-4.basic b/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-4.basic new file mode 100644 index 0000000000..4b0a3d394e --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-4.basic @@ -0,0 +1,11 @@ +' FB 1.05.0 Win64 + +Dim As Integer i, j +Input "Enter two positive integers, separated by a comma"; i, j +Dim a(1 To i, 1 To j) As Integer +a(i, j) = i * j +Print "a("; Str(i); ","; Str(j); ") ="; a(i, j) +Erase a +Print +Print "Press any key to quit" +Sleep diff --git a/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-5.basic b/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-5.basic new file mode 100644 index 0000000000..90d8f357d3 --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-5.basic @@ -0,0 +1,4 @@ +100 INPUT PROMPT "Enter array dimensions separated by a coma: ":A,B +110 NUMERIC ARRAY(1 TO A,1 TO B) +120 LET ARRAY(1,1)=PI +130 PRINT ARRAY(1,1) diff --git a/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-6.basic b/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-6.basic new file mode 100644 index 0000000000..c7df5e9a3c --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-6.basic @@ -0,0 +1,9 @@ +input "Enter first array dimension "; a +input "Enter second array dimension "; b + +dim array( a, b) + +array( 1, 1) = 123.456 +print array( 1, 1) + +end diff --git a/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-7.basic b/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-7.basic new file mode 100644 index 0000000000..e030dd4fee --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-7.basic @@ -0,0 +1,17 @@ +If OpenConsole() + Define x, y + + Print("Input X-Size: ") + x = Val(Input()) + + Print("Input Y-Size: ") + y = Val(Input()) + + Dim a(x,y) ; Should really check if x & y are larger then 1, but that would be less fun.... + + a(1,1)=Random(1000) + PrintN("a(1,1)= " + Str(a(1,1)) ) + + PrintN("Press ENTER to exit"):Input() + End ; Close down and let PureBasic delete the Console and all variables. +EndIf diff --git a/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime.basic b/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-8.basic similarity index 100% rename from Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime.basic rename to Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-8.basic diff --git a/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-9.basic b/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-9.basic new file mode 100644 index 0000000000..3ac16df2af --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/BASIC/create-a-two-dimensional-array-at-runtime-9.basic @@ -0,0 +1,9 @@ +print "Enter array 1 greater than 0"; : input a1 +print "Enter array 2 greater than 0"; : input a2 + +dim chrArray$(max(a1,1),max(a2,1)) +dim numArray(max(a1,1),max(a2,1)) + +chrArray$(1,1) = "Hello" +numArray(1,1) = 987.2 +print chrArray$(1,1);" ";numArray(1,1) diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Python/create-a-two-dimensional-array-at-runtime-1.py b/Task/Create-a-two-dimensional-array-at-runtime/Python/create-a-two-dimensional-array-at-runtime-1.py index b971a418ea..f4342131c5 100644 --- a/Task/Create-a-two-dimensional-array-at-runtime/Python/create-a-two-dimensional-array-at-runtime-1.py +++ b/Task/Create-a-two-dimensional-array-at-runtime/Python/create-a-two-dimensional-array-at-runtime-1.py @@ -1,5 +1,5 @@ width = int(raw_input("Width of myarray: ")) height = int(raw_input("Height of Array: ")) -myarray = [[0] * width for i in xrange(height)] +myarray = [[0] * width for i in range(height)] myarray[0][0] = 3.5 -print myarray[0][0] +print (myarray[0][0]) diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Python/create-a-two-dimensional-array-at-runtime-2.py b/Task/Create-a-two-dimensional-array-at-runtime/Python/create-a-two-dimensional-array-at-runtime-2.py index e50caaac0d..a96d394f5f 100644 --- a/Task/Create-a-two-dimensional-array-at-runtime/Python/create-a-two-dimensional-array-at-runtime-2.py +++ b/Task/Create-a-two-dimensional-array-at-runtime/Python/create-a-two-dimensional-array-at-runtime-2.py @@ -1,4 +1,4 @@ myarray = {(w,h): 0 for w in range(width) for h in range(height)} # or, in pre 2.7 versions of Python: myarray = dict(((w,h), 0) for w in range(width) for h in range(height)) myarray[(0,0)] = 3.5 -print myarray[(0,0)] +print (myarray[(0,0)]) diff --git a/Task/Create-an-object-at-a-given-address/00DESCRIPTION b/Task/Create-an-object-at-a-given-address/00DESCRIPTION index 9b7ea49290..2967588c73 100644 --- a/Task/Create-an-object-at-a-given-address/00DESCRIPTION +++ b/Task/Create-an-object-at-a-given-address/00DESCRIPTION @@ -1,5 +1,4 @@ {{basic data operation}} -{{omit from|Modula-2}} In systems programing it is sometimes required to place language objects at specific memory locations, like I/O registers, hardware interrupt vectors etc. diff --git a/Task/Currying/Ol/currying.ol b/Task/Currying/Ol/currying.ol new file mode 100644 index 0000000000..04fe498646 --- /dev/null +++ b/Task/Currying/Ol/currying.ol @@ -0,0 +1,7 @@ +(define (addN n) + (lambda (x) (+ x n))) + +(let ((add10 (addN 10)) + (add20 (addN 20))) + (print "(add10 4) ==> " (add10 4)) + (print "(add20 4) ==> " (add20 4))) diff --git a/Task/Currying/PHP/currying.php b/Task/Currying/PHP/currying.php new file mode 100644 index 0000000000..fb8d129e55 --- /dev/null +++ b/Task/Currying/PHP/currying.php @@ -0,0 +1,95 @@ +getMethod($callable[1]); + return $method->getNumberOfRequiredParameters(); + } + $refl = new \ReflectionFunction($callable); + return $refl->getNumberOfRequiredParameters(); +} + +function _make_function($callable) +{ + if (is_array($callable)) + return function() use($callable) { + return call_user_func_array($callable, func_get_args()); + }; + return $callable; +} + +function _execute($callable, $args, $left) +{ + if (! $left) { + $args = array_reverse($args); + } + $placeholders = _placeholder_positions($args); + if (0 < count($placeholders)) { + $n = _number_of_required_params($callable); + if ($n <= _last($placeholders[count($placeholders) - 1])) { + throw new \Exception('Argument Placeholder found on unexpected position!'); + } + foreach ($placeholders as $i) { + $args[$i] = $args[$n]; + array_splice($args, $n, 1); + } + } + return call_user_func_array($callable, $args); +} + +function _placeholder_positions($args) +{ + return array_keys(array_filter($args, '_is_placeholder')); +} + +function _is_fullfilled($callable, $args) +{ + $args = array_filter($args, function($arg) { + return ! _is_placeholder($arg); + }); + return count($args) >= _number_of_required_params($callable); +} + +function _is_placeholder($arg) +{ + return $arg instanceof Placeholder; +} + +function _rest(array $args) +{ + return array_slice($args, 1); +} + +function product($a, $b) +{ + return $a * $b; +} + +echo json_encode(array_map(curry('product', 7), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])); diff --git a/Task/DNS-query/Ada/dns-query.ada b/Task/DNS-query/Ada/dns-query-1.ada similarity index 100% rename from Task/DNS-query/Ada/dns-query.ada rename to Task/DNS-query/Ada/dns-query-1.ada diff --git a/Task/DNS-query/Ada/dns-query-2.ada b/Task/DNS-query/Ada/dns-query-2.ada new file mode 100644 index 0000000000..cac296431f --- /dev/null +++ b/Task/DNS-query/Ada/dns-query-2.ada @@ -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/Date-format/Common-Lisp/date-format.lisp b/Task/Date-format/Common-Lisp/date-format-1.lisp similarity index 100% rename from Task/Date-format/Common-Lisp/date-format.lisp rename to Task/Date-format/Common-Lisp/date-format-1.lisp diff --git a/Task/Date-format/Common-Lisp/date-format-2.lisp b/Task/Date-format/Common-Lisp/date-format-2.lisp new file mode 100644 index 0000000000..36ae2985f8 --- /dev/null +++ b/Task/Date-format/Common-Lisp/date-format-2.lisp @@ -0,0 +1,4 @@ +(local-time:format-timestring nil (local-time:now) :format '(:year "-" (:month 2) "-" (:day 2))) +;; => "2019-11-13" +(local-time:format-timestring nil (local-time:now) :format '(:long-weekday ", " :long-month #\space (:day 2) ", " :year)) +;; => "Wednesday, November 13, 2019" diff --git a/Task/Date-format/Pike/date-format.pike b/Task/Date-format/Pike/date-format.pike index 55f805b3ce..d1c088b19e 100644 --- a/Task/Date-format/Pike/date-format.pike +++ b/Task/Date-format/Pike/date-format.pike @@ -1,11 +1,8 @@ -> write("%d-%02d-%02d\n", day->year_no(), day->month_no(), day->month_day()); -2011-11-05 - -> write("%s, %s %s, %s\n", day->week_day_name(), day->month_name(), day->month_day_name(), day->year_name()); -Saturday, November 5, 2011 - -> write(day->format_ymd()+"\n"); -2011-11-05 - -> write(day->format_ext_ymd()+"\n"); -Saturday, 5 November 2011 +object cal = Calendar.ISO.Day(); +write( cal->format_ymd() +"\n" ); +string special = sprintf("%s, %s %d, %d", + cal->week_day_name(), + cal->month_name(), + cal->month_day(), + cal->year_no()); +write( special +"\n" ); diff --git a/Task/Date-manipulation/Julia/date-manipulation.julia b/Task/Date-manipulation/Julia/date-manipulation-1.julia similarity index 95% rename from Task/Date-manipulation/Julia/date-manipulation.julia rename to Task/Date-manipulation/Julia/date-manipulation-1.julia index aa8bfd93ab..dd617b273c 100644 --- a/Task/Date-manipulation/Julia/date-manipulation.julia +++ b/Task/Date-manipulation/Julia/date-manipulation-1.julia @@ -1,4 +1,4 @@ -using Base.Dates +using Dates function main() dtstr = "March 7 2009 7:30pm" # Base.Dates doesn't handle "EST" diff --git a/Task/Date-manipulation/Julia/date-manipulation-2.julia b/Task/Date-manipulation/Julia/date-manipulation-2.julia new file mode 100644 index 0000000000..40c8f27ea5 --- /dev/null +++ b/Task/Date-manipulation/Julia/date-manipulation-2.julia @@ -0,0 +1,14 @@ +using Dates, TimeZones + +function testdateparse() + tzabbrev = Dict("EST" => "+0500", "CST" => "+0600", "MST" => "+0700", "PST" => "+0800") + dtstr = "March 7 2009 7:30pm EST" + for (k, v) in tzabbrev + dtstr = replace(dtstr, k => v) + end + dtformat = dateformat"U dd yyyy HH:MMp zzzzz" + dtime = TimeZones.parse(ZonedDateTime, dtstr, dtformat) + println(Dates.format(dtime, dtformat)) +end + +testdateparse() diff --git a/Task/Day-of-the-week/Julia/day-of-the-week.julia b/Task/Day-of-the-week/Julia/day-of-the-week.julia index d6b6ab012c..5f846de91d 100644 --- a/Task/Day-of-the-week/Julia/day-of-the-week.julia +++ b/Task/Day-of-the-week/Julia/day-of-the-week.julia @@ -1,4 +1,4 @@ -using Base.Dates +using Dates lo, hi = 2008, 2121 xmas = collect(Date(lo, 12, 25):Year(1):Date(hi, 12, 25)) diff --git a/Task/Day-of-the-week/Phix/day-of-the-week.phix b/Task/Day-of-the-week/Phix/day-of-the-week.phix index db9dbcd636..cba7a80f5b 100644 --- a/Task/Day-of-the-week/Phix/day-of-the-week.phix +++ b/Task/Day-of-the-week/Phix/day-of-the-week.phix @@ -1,6 +1,7 @@ +-- demo\rosetta\Day_of_the_week.exw sequence res = {} for y=2008 to 2121 do - if day_of_week(y,12,25)=1 then + if day_of_week(y,12,25,true)="Sunday" then res = append(res,y) end if end for diff --git a/Task/Day-of-the-week/SAS/day-of-the-week.sas b/Task/Day-of-the-week/SAS/day-of-the-week.sas index 3cca1e2d62..e0fafab1a6 100644 --- a/Task/Day-of-the-week/SAS/day-of-the-week.sas +++ b/Task/Day-of-the-week/SAS/day-of-the-week.sas @@ -1,7 +1,7 @@ data _null_; do y=2008 to 2121; -a=mdy(12,25,y); -if weekday(a)=1 then put y; + a=mdy(12,25,y); + if weekday(a)=1 then put y; end; run; diff --git a/Task/Day-of-the-week/Standard-ML/day-of-the-week.ml b/Task/Day-of-the-week/Standard-ML/day-of-the-week.ml new file mode 100644 index 0000000000..26418f68e0 --- /dev/null +++ b/Task/Day-of-the-week/Standard-ML/day-of-the-week.ml @@ -0,0 +1,19 @@ +(* Call: yearsOfSundayXmas(2008, 2121) *) +fun yearsOfSundayXmas(fromYear, toYear) = + if fromYear>toYear then + () + else + let + val d = Date.date {year=fromYear, month=Date.Dec, day=25, + hour=0, minute=0, second=0, + offset=SOME Time.zeroTime} + val wd = Date.weekDay d + in + if wd=Date.Sun then + ( + print(Int.toString fromYear ^ "\n"); + yearsOfSundayXmas(fromYear+1, toYear) + ) + else + yearsOfSundayXmas(fromYear+1, toYear) + end; diff --git a/Task/Deal-cards-for-FreeCell/Scala/deal-cards-for-freecell.scala b/Task/Deal-cards-for-FreeCell/Scala/deal-cards-for-freecell.scala new file mode 100644 index 0000000000..22c86f1b45 --- /dev/null +++ b/Task/Deal-cards-for-FreeCell/Scala/deal-cards-for-freecell.scala @@ -0,0 +1,33 @@ +object Shuffler extends App { + + private val suits = Array("C", "D", "H", "S") + private val values = Array("A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K") + private val deck = values.flatMap(v => suits.map(s => s"$v$s")) + + private var seed: Int = _ + + private def random() = { + seed = (214013 * seed + 2531011) & Integer.MAX_VALUE + seed >> 16 + } + + private def getShuffledDeck = { + val d = deck.map(c => c) + for(i <- deck.length - 1 until 0 by -1) { + val r = random() % (i + 1) + val card = d(r) + d(r) = d(i) + d(i) = card + } + d.reverse + } + + def deal(seed: Int): Unit = { + this.seed = seed + getShuffledDeck.grouped(8).foreach(e => println(e.mkString(" "))) + } + + deal(1) + println + deal(617) +} diff --git a/Task/Death-Star/Ada/death-star.ada b/Task/Death-Star/Ada/death-star.ada new file mode 100644 index 0000000000..f18567ff9d --- /dev/null +++ b/Task/Death-Star/Ada/death-star.ada @@ -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/Julia/death-star.julia b/Task/Death-Star/Julia/death-star.julia index 31cefd7622..5b20d5656f 100644 --- a/Task/Death-Star/Julia/death-star.julia +++ b/Task/Death-Star/Julia/death-star.julia @@ -1,7 +1,7 @@ # run in REPL using Makie -function deathstarjpg() +function deathstar() n = 60 θ = [0; (0.5: n - 0.5) / n; 1] φ = [(0: 2n - 2) * 2 / (2n - 1); 2] @@ -14,4 +14,4 @@ function deathstarjpg() surface!(scene, x, y, z, color = rand(RGBAf0, 124, 124), show_axis=false) end -deathstarjpg() +deathstar() diff --git a/Task/Deconvolution-1D/Nim/deconvolution-1d.nim b/Task/Deconvolution-1D/Nim/deconvolution-1d.nim new file mode 100644 index 0000000000..a726c9eea2 --- /dev/null +++ b/Task/Deconvolution-1D/Nim/deconvolution-1d.nim @@ -0,0 +1,20 @@ +proc deconv(g, f: openArray[float]): seq[float] = + var h: seq[float] = newSeq[float](len(g) - len(f) + 1) + for n in 0..= len(f): + lower = n - len(f) + 1 + for i in lower..array [ clone ] deep-map T{ foo } like + +! print them both +"Before modification:" print [ [ . ] bi@ ] 2keep nl + +! modify the deep copy +[ -1 suffix! ] change-bar + +! print them both again +"After modification:" print [ . ] bi@ diff --git a/Task/Deepcopy/Factor/deepcopy-2.factor b/Task/Deepcopy/Factor/deepcopy-2.factor new file mode 100644 index 0000000000..db5abf56d4 --- /dev/null +++ b/Task/Deepcopy/Factor/deepcopy-2.factor @@ -0,0 +1,16 @@ +! Create a foo object composed of mutable objects +V{ 1 2 3 } V{ 4 5 6 } [ clone ] bi@ foo boa + +! create a copy of the reference to the object +dup + +! create a deep copy from this copy +object>bytes bytes>object + +! print them both +"Before modification:" print [ [ . ] bi@ ] 2keep nl + +! modify the deep copy +[ -99 suffix! ] change-bar + +"After modification:" print [ . ] bi@ diff --git a/Task/Define-a-primitive-data-type/C-sharp/define-a-primitive-data-type.cs b/Task/Define-a-primitive-data-type/C-sharp/define-a-primitive-data-type.cs new file mode 100644 index 0000000000..6d8d00c07d --- /dev/null +++ b/Task/Define-a-primitive-data-type/C-sharp/define-a-primitive-data-type.cs @@ -0,0 +1,115 @@ +using System; +using System.Globalization; + +struct LimitedInt : IComparable, IComparable, IConvertible, IEquatable, IFormattable +{ + const int MIN_VALUE = 1; + const int MAX_VALUE = 10; + + public static readonly LimitedInt MinValue = new LimitedInt(MIN_VALUE); + public static readonly LimitedInt MaxValue = new LimitedInt(MAX_VALUE); + + static bool IsValidValue(int value) => value >= MIN_VALUE && value <= MAX_VALUE; + + readonly int _value; + public int Value => this._value == 0 ? MIN_VALUE : this._value; // Treat the default, 0, as being the minimum value. + + public LimitedInt(int value) + { + if (!IsValidValue(value)) + throw new ArgumentOutOfRangeException(nameof(value), value, $"Value must be between {MIN_VALUE} and {MAX_VALUE}."); + this._value = value; + } + + #region IComparable + public int CompareTo(object obj) + { + if (obj is LimitedInt l) return this.Value.CompareTo(l); + throw new ArgumentException("Object must be of type " + nameof(LimitedInt), nameof(obj)); + } + #endregion + + #region IComparable + public int CompareTo(LimitedInt other) => this.Value.CompareTo(other.Value); + #endregion + + #region IConvertible + public TypeCode GetTypeCode() => this.Value.GetTypeCode(); + bool IConvertible.ToBoolean(IFormatProvider provider) => ((IConvertible)this.Value).ToBoolean(provider); + byte IConvertible.ToByte(IFormatProvider provider) => ((IConvertible)this.Value).ToByte(provider); + char IConvertible.ToChar(IFormatProvider provider) => ((IConvertible)this.Value).ToChar(provider); + DateTime IConvertible.ToDateTime(IFormatProvider provider) => ((IConvertible)this.Value).ToDateTime(provider); + decimal IConvertible.ToDecimal(IFormatProvider provider) => ((IConvertible)this.Value).ToDecimal(provider); + double IConvertible.ToDouble(IFormatProvider provider) => ((IConvertible)this.Value).ToDouble(provider); + short IConvertible.ToInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToInt16(provider); + int IConvertible.ToInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToInt32(provider); + long IConvertible.ToInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToInt64(provider); + sbyte IConvertible.ToSByte(IFormatProvider provider) => ((IConvertible)this.Value).ToSByte(provider); + float IConvertible.ToSingle(IFormatProvider provider) => ((IConvertible)this.Value).ToSingle(provider); + string IConvertible.ToString(IFormatProvider provider) => this.Value.ToString(provider); + object IConvertible.ToType(Type conversionType, IFormatProvider provider) => ((IConvertible)this.Value).ToType(conversionType, provider); + ushort IConvertible.ToUInt16(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt16(provider); + uint IConvertible.ToUInt32(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt32(provider); + ulong IConvertible.ToUInt64(IFormatProvider provider) => ((IConvertible)this.Value).ToUInt64(provider); + #endregion + + #region IEquatable + public bool Equals(LimitedInt other) => this == other; + #endregion + + #region IFormattable + public string ToString(string format, IFormatProvider formatProvider) => this.Value.ToString(format, formatProvider); + #endregion + + #region operators + public static bool operator ==(LimitedInt left, LimitedInt right) => left.Value == right.Value; + public static bool operator !=(LimitedInt left, LimitedInt right) => left.Value != right.Value; + public static bool operator <(LimitedInt left, LimitedInt right) => left.Value < right.Value; + public static bool operator >(LimitedInt left, LimitedInt right) => left.Value > right.Value; + public static bool operator <=(LimitedInt left, LimitedInt right) => left.Value <= right.Value; + public static bool operator >=(LimitedInt left, LimitedInt right) => left.Value >= right.Value; + + public static LimitedInt operator ++(LimitedInt left) => (LimitedInt)(left.Value + 1); + public static LimitedInt operator --(LimitedInt left) => (LimitedInt)(left.Value - 1); + + public static LimitedInt operator +(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value + right.Value); + public static LimitedInt operator -(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value - right.Value); + public static LimitedInt operator *(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value * right.Value); + public static LimitedInt operator /(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value / right.Value); + public static LimitedInt operator %(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value % right.Value); + + public static LimitedInt operator &(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value & right.Value); + public static LimitedInt operator |(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value | right.Value); + public static LimitedInt operator ^(LimitedInt left, LimitedInt right) => (LimitedInt)(left.Value ^ right.Value); + public static LimitedInt operator ~(LimitedInt left) => (LimitedInt)~left.Value; + + public static LimitedInt operator >>(LimitedInt left, int right) => (LimitedInt)(left.Value >> right); + public static LimitedInt operator <<(LimitedInt left, int right) => (LimitedInt)(left.Value << right); + + public static implicit operator int(LimitedInt value) => value.Value; + public static explicit operator LimitedInt(int value) + { + if (!IsValidValue(value)) throw new OverflowException(); + return new LimitedInt(value); + } + #endregion + + public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format = default, IFormatProvider provider = null) + => this.Value.TryFormat(destination, out charsWritten, format, provider); + + public override int GetHashCode() => this.Value.GetHashCode(); + public override bool Equals(object obj) => obj is LimitedInt l && this.Equals(l); + public override string ToString() => this.Value.ToString(); + + #region static methods + public static bool TryParse(ReadOnlySpan s, out int result) => int.TryParse(s, out result); + public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider, out int result) => int.TryParse(s, style, provider, out result); + public static int Parse(string s, IFormatProvider provider) => int.Parse(s, provider); + public static int Parse(string s, NumberStyles style, IFormatProvider provider) => int.Parse(s, style, provider); + public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, ref int result) => int.TryParse(s, style, provider, out result); + public static int Parse(string s) => int.Parse(s); + public static int Parse(string s, NumberStyles style) => int.Parse(s, style); + public static int Parse(ReadOnlySpan s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) => int.Parse(s, style, provider); + public static bool TryParse(string s, ref int result) => int.TryParse(s, out result); + #endregion +} diff --git a/Task/Define-a-primitive-data-type/Visual-Basic-.NET/define-a-primitive-data-type.visual b/Task/Define-a-primitive-data-type/Visual-Basic-.NET/define-a-primitive-data-type.visual index 9dff93b842..6ef8eec13e 100644 --- a/Task/Define-a-primitive-data-type/Visual-Basic-.NET/define-a-primitive-data-type.visual +++ b/Task/Define-a-primitive-data-type/Visual-Basic-.NET/define-a-primitive-data-type.visual @@ -1,138 +1,269 @@ Structure LimitedInt - Implements IComparable(Of LimitedInt) - Implements IEquatable(Of LimitedInt) + Implements IComparable, IComparable(Of LimitedInt), IConvertible, IEquatable(Of LimitedInt), IFormattable - Private m_Value As Integer 'treat the default, 0 as being really 1 + Private Const MIN_VALUE = 1 + Private Const MAX_VALUE = 10 - Public ReadOnly Property Value() As Integer - Get - Return If(m_Value = 0, 1, m_Value) - End Get - End Property + Shared ReadOnly MinValue As New LimitedInt(MIN_VALUE) + Shared ReadOnly MaxValue As New LimitedInt(MAX_VALUE) - Public Sub New(ByVal value As Integer) - If value < 1 Or value > 10 Then Throw New ArgumentOutOfRangeException("value") - m_Value = value - End Sub + Private Shared Function IsValidValue(value As Integer) As Boolean + Return value >= MIN_VALUE AndAlso value <= MAX_VALUE + End Function - Public Function CompareTo(ByVal other As LimitedInt) As Integer Implements System.IComparable(Of LimitedInt).CompareTo - Return Me.Value - other.Value - End Function + Private ReadOnly _value As Integer + ReadOnly Property Value As Integer + Get + ' Treat the default, 0, as being the minimum value. + Return If(Me._value = 0, MIN_VALUE, Me._value) + End Get + End Property - Public Overloads Function Equals(ByVal other As LimitedInt) As Boolean Implements System.IEquatable(Of LimitedInt).Equals - Return Me.Value = other.Value - End Function + Sub New(value As Integer) + If Not IsValidValue(value) Then Throw New ArgumentOutOfRangeException(NameOf(value), value, $"Value must be between {MIN_VALUE} and {MAX_VALUE}.") + Me._value = value + End Sub - Public Overrides Function GetHashCode() As Integer - Return Value.GetHashCode - End Function +#Region "IComparable" + Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo + If TypeOf obj IsNot LimitedInt Then Throw New ArgumentException("Object must be of type " + NameOf(LimitedInt), NameOf(obj)) + Return Me.CompareTo(DirectCast(obj, LimitedInt)) + End Function +#End Region - Public Overrides Function Equals(ByVal obj As Object) As Boolean - If TypeOf obj Is LimitedInt Then Return CType(obj, LimitedInt) = Me - End Function +#Region "IComparable(Of LimitedInt)" + Function CompareTo(other As LimitedInt) As Integer Implements IComparable(Of LimitedInt).CompareTo + Return Me.Value.CompareTo(other.Value) + End Function +#End Region - Public Shared Operator =(ByVal left As LimitedInt, ByVal right As LimitedInt) As Boolean - Return left.Equals(right) - End Operator +#Region "IConvertible" + Function GetTypeCode() As TypeCode Implements IConvertible.GetTypeCode + Return Me.Value.GetTypeCode() + End Function - Public Shared Operator <>(ByVal left As LimitedInt, ByVal right As LimitedInt) As Boolean - Return Not (left = right) - End Operator + Private Function ToBoolean(provider As IFormatProvider) As Boolean Implements IConvertible.ToBoolean + Return DirectCast(Me.Value, IConvertible).ToBoolean(provider) + End Function - Public Shared Operator +(ByVal left As LimitedInt, ByVal right As LimitedInt) As LimitedInt - Dim temp As Integer = left.Value + right.Value - Select Case temp - Case 1 To 10 : Return New LimitedInt(temp) - Case Else : Throw New OverflowException - End Select - End Operator + Private Function ToByte(provider As IFormatProvider) As Byte Implements IConvertible.ToByte + Return DirectCast(Me.Value, IConvertible).ToByte(provider) + End Function - Public Shared Operator -(ByVal left As LimitedInt, ByVal right As LimitedInt) As LimitedInt - Dim temp As Integer = left.Value - right.Value - Select Case temp - Case 1 To 10 : Return New LimitedInt(temp) - Case Else : Throw New OverflowException - End Select - End Operator + Private Function ToChar(provider As IFormatProvider) As Char Implements IConvertible.ToChar + Return DirectCast(Me.Value, IConvertible).ToChar(provider) + End Function - Public Shared Operator *(ByVal left As LimitedInt, ByVal right As LimitedInt) As LimitedInt - Dim temp As Integer = left.Value * right.Value - Select Case temp - Case 1 To 10 : Return New LimitedInt(temp) - Case Else : Throw New OverflowException - End Select - End Operator + Private Function ToDateTime(provider As IFormatProvider) As Date Implements IConvertible.ToDateTime + Return DirectCast(Me.Value, IConvertible).ToDateTime(provider) + End Function - Public Shared Operator /(ByVal left As LimitedInt, ByVal right As LimitedInt) As Double - Return left.Value / right.Value - End Operator + Private Function ToDecimal(provider As IFormatProvider) As Decimal Implements IConvertible.ToDecimal + Return DirectCast(Me.Value, IConvertible).ToDecimal(provider) + End Function - Public Shared Operator \(ByVal left As LimitedInt, ByVal right As LimitedInt) As LimitedInt - Dim temp As Integer = left.Value \ right.Value - Select Case temp - Case 1 To 10 : Return New LimitedInt(temp) - Case Else : Throw New OverflowException - End Select - End Operator + Private Function ToDouble(provider As IFormatProvider) As Double Implements IConvertible.ToDouble + Return DirectCast(Me.Value, IConvertible).ToDouble(provider) + End Function - Public Shared Operator Mod(ByVal left As LimitedInt, ByVal right As LimitedInt) As LimitedInt - Dim temp As Integer = left.Value Mod right.Value - Select Case temp - Case 1 To 10 : Return New LimitedInt(temp) - Case Else : Throw New OverflowException - End Select - End Operator + Private Function ToInt16(provider As IFormatProvider) As Short Implements IConvertible.ToInt16 + Return DirectCast(Me.Value, IConvertible).ToInt16(provider) + End Function - Public Shared Operator And(ByVal left As LimitedInt, ByVal right As LimitedInt) As LimitedInt - Dim temp As Integer = left.Value And right.Value - Select Case temp - Case 1 To 10 : Return New LimitedInt(temp) - Case Else : Throw New OverflowException - End Select - End Operator + Private Function ToInt32(provider As IFormatProvider) As Integer Implements IConvertible.ToInt32 + Return DirectCast(Me.Value, IConvertible).ToInt32(provider) + End Function - Public Shared Operator Or(ByVal left As LimitedInt, ByVal right As LimitedInt) As LimitedInt - Dim temp As Integer = left.Value Or right.Value - Select Case temp - Case 1 To 10 : Return New LimitedInt(temp) - Case Else : Throw New OverflowException - End Select - End Operator + Private Function ToInt64(provider As IFormatProvider) As Long Implements IConvertible.ToInt64 + Return DirectCast(Me.Value, IConvertible).ToInt64(provider) + End Function - Public Shared Operator Xor(ByVal left As LimitedInt, ByVal right As LimitedInt) As LimitedInt - Dim temp As Integer = left.Value Xor right.Value - Select Case temp - Case 1 To 10 : Return New LimitedInt(temp) - Case Else : Throw New OverflowException - End Select - End Operator + Private Function ToSByte(provider As IFormatProvider) As SByte Implements IConvertible.ToSByte + Return DirectCast(Me.Value, IConvertible).ToSByte(provider) + End Function - Public Shared Operator ^(ByVal left As LimitedInt, ByVal right As LimitedInt) As Double - Return left.Value ^ right.Value - End Operator + Private Function ToSingle(provider As IFormatProvider) As Single Implements IConvertible.ToSingle + Return DirectCast(Me.Value, IConvertible).ToSingle(provider) + End Function - Public Shared Operator <(ByVal left As LimitedInt, ByVal right As LimitedInt) As Boolean - Return left.Value < right.Value - End Operator + Private Overloads Function ToString(provider As IFormatProvider) As String Implements IConvertible.ToString + Return Me.Value.ToString(provider) + End Function - Public Shared Operator >(ByVal left As LimitedInt, ByVal right As LimitedInt) As Boolean - Return left.Value > right.Value - End Operator + Private Function ToType(conversionType As Type, provider As IFormatProvider) As Object Implements IConvertible.ToType + Return DirectCast(Me.Value, IConvertible).ToType(conversionType, provider) + End Function - Public Shared Operator <=(ByVal left As LimitedInt, ByVal right As LimitedInt) As Boolean - Return left.Value <= right.Value - End Operator + Private Function ToUInt16(provider As IFormatProvider) As UShort Implements IConvertible.ToUInt16 + Return DirectCast(Me.Value, IConvertible).ToUInt16(provider) + End Function - Public Shared Operator >=(ByVal left As LimitedInt, ByVal right As LimitedInt) As Boolean - Return left.Value >= right.Value - End Operator + Private Function ToUInt32(provider As IFormatProvider) As UInteger Implements IConvertible.ToUInt32 + Return DirectCast(Me.Value, IConvertible).ToUInt32(provider) + End Function - Public Shared Widening Operator CType(ByVal left As LimitedInt) As Integer - Return left.Value - End Operator + Private Function ToUInt64(provider As IFormatProvider) As ULong Implements IConvertible.ToUInt64 + Return DirectCast(Me.Value, IConvertible).ToUInt64(provider) + End Function +#End Region - Public Shared Narrowing Operator CType(ByVal left As Integer) As LimitedInt - Return New LimitedInt(left) - End Operator +#Region "IEquatable(Of LimitedInt)" + Overloads Function Equals(other As LimitedInt) As Boolean Implements IEquatable(Of LimitedInt).Equals + Return Me = other + End Function +#End Region +#Region "IFormattable" + Private Overloads Function ToString(format As String, formatProvider As IFormatProvider) As String Implements IFormattable.ToString + Return Me.Value.ToString(format, formatProvider) + End Function +#End Region + +#Region "Operators" + Shared Operator =(left As LimitedInt, right As LimitedInt) As Boolean + Return left.Value = right.Value + End Operator + + Shared Operator <>(left As LimitedInt, right As LimitedInt) As Boolean + Return left.Value <> right.Value + End Operator + + Shared Operator <(left As LimitedInt, right As LimitedInt) As Boolean + Return left.Value < right.Value + End Operator + + Shared Operator >(left As LimitedInt, right As LimitedInt) As Boolean + Return left.Value > right.Value + End Operator + + Shared Operator <=(left As LimitedInt, right As LimitedInt) As Boolean + Return left.Value <= right.Value + End Operator + + Shared Operator >=(left As LimitedInt, right As LimitedInt) As Boolean + Return left.Value >= right.Value + End Operator + + Shared Operator +(left As LimitedInt) As LimitedInt + Return CType(+left.Value, LimitedInt) + End Operator + + Shared Operator -(left As LimitedInt) As LimitedInt + Return CType(-left.Value, LimitedInt) + End Operator + + Shared Operator +(left As LimitedInt, right As LimitedInt) As LimitedInt + Return CType(left.Value + right.Value, LimitedInt) + End Operator + + Shared Operator -(left As LimitedInt, right As LimitedInt) As LimitedInt + Return CType(left.Value - right.Value, LimitedInt) + End Operator + + Shared Operator *(left As LimitedInt, right As LimitedInt) As LimitedInt + Return CType(left.Value * right.Value, LimitedInt) + End Operator + + Shared Operator /(left As LimitedInt, right As LimitedInt) As Double + Return left.Value / right.Value + End Operator + + Shared Operator \(left As LimitedInt, right As LimitedInt) As LimitedInt + Return CType(left.Value \ right.Value, LimitedInt) + End Operator + + Shared Operator ^(left As LimitedInt, right As LimitedInt) As Double + Return left.Value ^ right.Value + End Operator + + Shared Operator Mod(left As LimitedInt, right As LimitedInt) As LimitedInt + Return CType(left.Value Mod right.Value, LimitedInt) + End Operator + + Shared Operator And(left As LimitedInt, right As LimitedInt) As LimitedInt + Return CType(left.Value And right.Value, LimitedInt) + End Operator + + Shared Operator Or(left As LimitedInt, right As LimitedInt) As LimitedInt + Return CType(left.Value Or right.Value, LimitedInt) + End Operator + + Shared Operator Xor(left As LimitedInt, right As LimitedInt) As LimitedInt + Return CType(left.Value Xor right.Value, LimitedInt) + End Operator + + Shared Operator Not(left As LimitedInt) As LimitedInt + Return CType(Not left.Value, LimitedInt) + End Operator + + Shared Operator >>(left As LimitedInt, right As Integer) As LimitedInt + Return CType(left.Value >> right, LimitedInt) + End Operator + + Shared Operator <<(left As LimitedInt, right As Integer) As LimitedInt + Return CType(left.Value << right, LimitedInt) + End Operator + + Shared Widening Operator CType(value As LimitedInt) As Integer + Return value.Value + End Operator + + Shared Narrowing Operator CType(value As Integer) As LimitedInt + If Not IsValidValue(value) Then Throw New OverflowException() + Return New LimitedInt(value) + End Operator +#End Region + + 'Function TryFormat(destination As Span(Of Char), ByRef charsWritten As Integer, Optional format As ReadOnlySpan(Of Char) = Nothing, Optional provider As IFormatProvider = Nothing) As Boolean + ' Return Me.Value.TryFormat(destination, charsWritten, format, provider) + 'End Function + + Overrides Function GetHashCode() As Integer + Return Me.Value.GetHashCode + End Function + + Overrides Function Equals(obj As Object) As Boolean + Return TypeOf obj Is LimitedInt AndAlso Me.Equals(DirectCast(obj, LimitedInt)) + End Function + + Overrides Function ToString() As String + Return Me.Value.ToString() + End Function + +#Region "Shared Methods" + 'Shared Function TryParse(s As ReadOnlySpan(Of Char), ByRef result As Integer) As Boolean + ' Return Integer.TryParse(s, result) + 'End Function + + 'Shared Function TryParse(s As ReadOnlySpan(Of Char), style As Globalization.NumberStyles, provider As IFormatProvider, ByRef result As Integer) As Boolean + ' Return Integer.TryParse(s, style, provider, result) + 'End Function + + Shared Function Parse(s As String, provider As IFormatProvider) As Integer + Return Integer.Parse(s, provider) + End Function + + Shared Function Parse(s As String, style As Globalization.NumberStyles, provider As IFormatProvider) As Integer + Return Integer.Parse(s, style, provider) + End Function + + Shared Function TryParse(s As String, style As Globalization.NumberStyles, provider As IFormatProvider, ByRef result As Integer) As Boolean + Return Integer.TryParse(s, style, provider, result) + End Function + + Shared Function Parse(s As String) As Integer + Return Integer.Parse(s) + End Function + Shared Function Parse(s As String, style As Globalization.NumberStyles) As Integer + Return Integer.Parse(s, style) + End Function + + 'Shared Function Parse(s As ReadOnlySpan(Of Char), Optional style As Globalization.NumberStyles = Globalization.NumberStyles.Integer, Optional provider As IFormatProvider = Nothing) As Integer + ' Return Integer.Parse(s, style, provider) + 'End Function + + Shared Function TryParse(s As String, ByRef result As Integer) As Boolean + Return Integer.TryParse(s, result) + End Function +#End Region End Structure diff --git a/Task/Define-a-primitive-data-type/Visual-FoxPro/define-a-primitive-data-type.visual b/Task/Define-a-primitive-data-type/Visual-FoxPro/define-a-primitive-data-type.visual index b2d8ace9a5..ac5ce9a1cd 100644 --- a/Task/Define-a-primitive-data-type/Visual-FoxPro/define-a-primitive-data-type.visual +++ b/Task/Define-a-primitive-data-type/Visual-FoxPro/define-a-primitive-data-type.visual @@ -28,4 +28,4 @@ ELSE DODEFAULT() ENDIF THIS.lHasError = .T. -ENDDEFINE +ENDDEFINE diff --git a/Task/Delegates/Elena/delegates-1.elena b/Task/Delegates/Elena/delegates-1.elena index b21fbd44e3..7fa9d92756 100644 --- a/Task/Delegates/Elena/delegates-1.elena +++ b/Task/Delegates/Elena/delegates-1.elena @@ -37,7 +37,7 @@ public program() { var delegator := new Delegator(); - new object[]{nil, new Object(), new Operable()}.forEach:(o) + new::(nil, new Object(), new Operable()).forEach:(o) { delegator.Delegate := o; diff --git a/Task/Delegates/Elena/delegates-2.elena b/Task/Delegates/Elena/delegates-2.elena index 8e6ade314d..70cbf0197b 100644 --- a/Task/Delegates/Elena/delegates-2.elena +++ b/Task/Delegates/Elena/delegates-2.elena @@ -38,7 +38,7 @@ public program() { var delegator := new Delegator(); - new object[]{nil, new Object(), new Operable()}.forEach:(o) + new::(nil, new Object(), new Operable()).forEach:(o) { delegator.Delegate := o; diff --git a/Task/Delete-a-file/Fortran/delete-a-file.f b/Task/Delete-a-file/Fortran/delete-a-file-1.f similarity index 100% rename from Task/Delete-a-file/Fortran/delete-a-file.f rename to Task/Delete-a-file/Fortran/delete-a-file-1.f diff --git a/Task/Delete-a-file/Fortran/delete-a-file-2.f b/Task/Delete-a-file/Fortran/delete-a-file-2.f new file mode 100644 index 0000000000..c88efe365f --- /dev/null +++ b/Task/Delete-a-file/Fortran/delete-a-file-2.f @@ -0,0 +1,8 @@ +program DeleteFileExample + use kernel32 + implicit none + print *, DeleteFile("input.txt") + print *, DeleteFile("\input.txt") + print *, RemoveDirectory("docs") + print *, RemoveDirectory("\docs") +end program diff --git a/Task/Delete-a-file/Java/delete-a-file.java b/Task/Delete-a-file/Java/delete-a-file.java index 7e4a2f2631..3eee7fe54b 100644 --- a/Task/Delete-a-file/Java/delete-a-file.java +++ b/Task/Delete-a-file/Java/delete-a-file.java @@ -1,18 +1,21 @@ import java.io.File; + public class FileDeleteTest { - public static boolean deleteFile(String filename) { - boolean exists = new File(filename).delete(); - return exists; - } - public static void test(String type, String filename) { - System.out.println("The following " + type + " called " + filename + - (deleteFile(filename) ? " was deleted." : " could not be deleted.") - ); - } - public static void main(String args[]) { + public static boolean deleteFile(String filename) { + boolean exists = new File(filename).delete(); + return exists; + } + + public static void test(String type, String filename) { + System.out.println("The following " + type + " called " + filename + + (deleteFile(filename) ? " was deleted." : " could not be deleted.") + ); + } + + public static void main(String args[]) { test("file", "input.txt"); test("file", File.seperator + "input.txt"); test("directory", "docs"); test("directory", File.seperator + "docs" + File.seperator); - } + } } diff --git a/Task/Delete-a-file/Retro/delete-a-file.retro b/Task/Delete-a-file/Retro/delete-a-file.retro index 7e0f24dccc..0c311c3800 100644 --- a/Task/Delete-a-file/Retro/delete-a-file.retro +++ b/Task/Delete-a-file/Retro/delete-a-file.retro @@ -1,3 +1,2 @@ -with files' -"input.txt" delete -"/input.txt" delete +'input.txt file:delete +'/input.txt file:delete diff --git a/Task/Detect-division-by-zero/Lua/detect-division-by-zero.lua b/Task/Detect-division-by-zero/Lua/detect-division-by-zero.lua index ac4efabda8..ada1bf1423 100644 --- a/Task/Detect-division-by-zero/Lua/detect-division-by-zero.lua +++ b/Task/Detect-division-by-zero/Lua/detect-division-by-zero.lua @@ -1,5 +1,4 @@ -function div(a,b) - quot = a/b - if quot == 1/0 then error() end - return quot +local function div(a,b) + if b == 0 then error() end + return a/b end diff --git a/Task/Detect-division-by-zero/Prolog/detect-division-by-zero.pro b/Task/Detect-division-by-zero/Prolog/detect-division-by-zero.pro new file mode 100644 index 0000000000..7b41d7f03a --- /dev/null +++ b/Task/Detect-division-by-zero/Prolog/detect-division-by-zero.pro @@ -0,0 +1,2 @@ +div(A, B, C, Ex) :- + catch((C is A/B), Ex, (C = infinity)). diff --git a/Task/Detect-division-by-zero/Visual-Basic-.NET/detect-division-by-zero.visual b/Task/Detect-division-by-zero/Visual-Basic-.NET/detect-division-by-zero.visual new file mode 100644 index 0000000000..4a901f2cae --- /dev/null +++ b/Task/Detect-division-by-zero/Visual-Basic-.NET/detect-division-by-zero.visual @@ -0,0 +1,15 @@ +Module DivByZeroDetection + + Sub Main() + Console.WriteLine(safeDivision(10, 0)) + End Sub + + Private Function safeDivision(v1 As Integer, v2 As Integer) As Boolean + Try + Dim answer = v1 / v2 + Return False + Catch ex As Exception + Return True + End Try + End Function +End Module diff --git a/Task/Determine-if-a-string-is-numeric/Go/determine-if-a-string-is-numeric-1.go b/Task/Determine-if-a-string-is-numeric/Go/determine-if-a-string-is-numeric-1.go new file mode 100644 index 0000000000..9bfc0b8998 --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/Go/determine-if-a-string-is-numeric-1.go @@ -0,0 +1,19 @@ +package main + +import ( + "fmt" + "strconv" +) + +func isNumeric(s string) bool { + _, err := strconv.ParseFloat(s, 64) + return err == nil +} + +func main() { + fmt.Println("Are these strings numeric?") + strings := []string{"1", "3.14", "-100", "1e2", "NaN", "rose"} + for _, s := range strings { + fmt.Printf(" %4s -> %t\n", s, isNumeric(s)) + } +} diff --git a/Task/Determine-if-a-string-is-numeric/Go/determine-if-a-string-is-numeric-2.go b/Task/Determine-if-a-string-is-numeric/Go/determine-if-a-string-is-numeric-2.go new file mode 100644 index 0000000000..2820ce6c2a --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/Go/determine-if-a-string-is-numeric-2.go @@ -0,0 +1,28 @@ +package main + +import ( + "fmt" + "strconv" + "unicode" +) + +func isInt(s string) bool { + for _, c := range s { + if !unicode.IsDigit(c) { + return false + } + } + return true +} + +func main() { + fmt.Println("Are these strings integers?") + v := "1" + b := false + if _, err := strconv.Atoi(v); err == nil { + b = true + } + fmt.Printf(" %3s -> %t\n", v, b) + i := "one" + fmt.Printf(" %3s -> %t\n", i, isInt(i)) +} diff --git a/Task/Determine-if-a-string-is-numeric/Go/determine-if-a-string-is-numeric.go b/Task/Determine-if-a-string-is-numeric/Go/determine-if-a-string-is-numeric.go deleted file mode 100644 index 115429d82d..0000000000 --- a/Task/Determine-if-a-string-is-numeric/Go/determine-if-a-string-is-numeric.go +++ /dev/null @@ -1,6 +0,0 @@ -import "strconv" - -func IsNumeric(s string) bool { - _, err := strconv.ParseFloat(s, 64) - return err == nil -} diff --git a/Task/Determine-if-a-string-is-numeric/Julia/determine-if-a-string-is-numeric.julia b/Task/Determine-if-a-string-is-numeric/Julia/determine-if-a-string-is-numeric.julia index d34c2d7e69..fc1166c509 100644 --- a/Task/Determine-if-a-string-is-numeric/Julia/determine-if-a-string-is-numeric.julia +++ b/Task/Determine-if-a-string-is-numeric/Julia/determine-if-a-string-is-numeric.julia @@ -1,4 +1,6 @@ -isnumeric(s::AbstractString) = parse(s) isa Number +using Printf + +isnumeric(s::AbstractString) = tryparse(Float64, s) isa Number tests = ["1", "-121", "one", "pi", "1 + 1", "NaN", "1234567890123456789", "1234567890123456789123456789", "1234567890123456789123456789.0", "1.3", "1.4e10", "Inf", "1//2", "1.0 + 1.0im"] diff --git a/Task/Determine-if-a-string-is-numeric/Perl-6/determine-if-a-string-is-numeric.pl6 b/Task/Determine-if-a-string-is-numeric/Perl-6/determine-if-a-string-is-numeric.pl6 index 8dc44c19f8..611617622d 100644 --- a/Task/Determine-if-a-string-is-numeric/Perl-6/determine-if-a-string-is-numeric.pl6 +++ b/Task/Determine-if-a-string-is-numeric/Perl-6/determine-if-a-string-is-numeric.pl6 @@ -10,5 +10,5 @@ say " Coerce Don't coerce"; say ' String whitespace whitespace'; printf "%10s %8s %11s\n", "<$_>", .&is-number-w-ws, .&is-number-wo-ws for -(|<1 1.2 1.2.3 -6 1/2 12e B17 1.3e+12 1.3e12 -2.6e-3 zero -0x 0xA10 0b1001 0o16 0o18 2+5i>, '1 1 1', '', ' ').map: *.Str; +(|<1 1.2 1.2.3 -6 1/2 12e B17 1.3e+12 1.3e12 -2.6e-3 zero 0x 0xA10 0b1001 0o16 +0o18 2+5i True False Inf NaN 0x10.50 0b102 0o_5_3 ௫௯>, ' 12 ', '1 1 1', '', ' ' ).map: *.Str; diff --git a/Task/Determine-if-a-string-is-numeric/Phix/determine-if-a-string-is-numeric.phix b/Task/Determine-if-a-string-is-numeric/Phix/determine-if-a-string-is-numeric.phix new file mode 100644 index 0000000000..600a3af017 --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/Phix/determine-if-a-string-is-numeric.phix @@ -0,0 +1,14 @@ +function isNumber(string s) + return scanf(s,"%f")!={} +end function + +function testset(sequence s) + for i=1 to length(s) do + s[i] = isNumber(s[i]) + end for + return s +end function +?testset({"#a","#A","0xA","0(16)A","#FF","255","0",".14",".05","-5.2","0xf","ten","1B"}) +?testset({" 12 ",trim(" 12 ")}) +?testset({"0o16","0o18"}) +?testset({"1_000","0b10101111_11110000_11110000_00110011","-0b10101","0x10.5",""," ","1.","50e"}) diff --git a/Task/Determine-if-a-string-is-numeric/Retro/determine-if-a-string-is-numeric.retro b/Task/Determine-if-a-string-is-numeric/Retro/determine-if-a-string-is-numeric.retro index 338ce03809..300b548e3e 100644 --- a/Task/Determine-if-a-string-is-numeric/Retro/determine-if-a-string-is-numeric.retro +++ b/Task/Determine-if-a-string-is-numeric/Retro/determine-if-a-string-is-numeric.retro @@ -1 +1 @@ -"123" isNumber? +'123 a:from-string TRUE [ swap c:digit? and ] a:reduce diff --git a/Task/Determine-if-only-one-instance-is-running/D/determine-if-only-one-instance-is-running.d b/Task/Determine-if-only-one-instance-is-running/D/determine-if-only-one-instance-is-running.d new file mode 100644 index 0000000000..61777a90f2 --- /dev/null +++ b/Task/Determine-if-only-one-instance-is-running/D/determine-if-only-one-instance-is-running.d @@ -0,0 +1,20 @@ +bool is_unique_instance() +{ + import std.socket; + auto socket = new Socket(AddressFamily.UNIX, SocketType.STREAM); + auto addr = new UnixAddress("\0/tmp/myapp.uniqueness.sock"); + try + { + socket.bind(addr); + return true; + } + catch (SocketOSException e) + { + import core.stdc.errno : EADDRINUSE; + + if (e.errorCode == EADDRINUSE) + return false; + else + throw e; + } +} diff --git a/Task/Determine-if-only-one-instance-is-running/Nim/determine-if-only-one-instance-is-running.nim b/Task/Determine-if-only-one-instance-is-running/Nim/determine-if-only-one-instance-is-running-1.nim similarity index 100% rename from Task/Determine-if-only-one-instance-is-running/Nim/determine-if-only-one-instance-is-running.nim rename to Task/Determine-if-only-one-instance-is-running/Nim/determine-if-only-one-instance-is-running-1.nim diff --git a/Task/Determine-if-only-one-instance-is-running/Nim/determine-if-only-one-instance-is-running-2.nim b/Task/Determine-if-only-one-instance-is-running/Nim/determine-if-only-one-instance-is-running-2.nim new file mode 100644 index 0000000000..a13f9d03cd --- /dev/null +++ b/Task/Determine-if-only-one-instance-is-running/Nim/determine-if-only-one-instance-is-running-2.nim @@ -0,0 +1,35 @@ +import options, os +from net import newSocket, bindUnix +from nativesockets import AF_UNIX, SOCK_DGRAM, IPPROTO_IP +from posix import EADDRINUSE + +const sockAddr = "\0com.myapp.sock" # Linux will delete this when the application ends +# notice the prefixed null byte, it's the Linux abstract namespace + +proc server()= + echo "Unique instance detected" + +proc client()= + echo "Duplicate instance detected" + +when isMainModule: + var + sock = newSocket(AF_UNIX, SOCK_DGRAM, IPPROTO_IP) + isUnique: Option[bool] + + try: + sock.bindUnix(sock_addr) + is_unique = some true + except OSError: + if cint(osLastError()) == EADDRINUSE: + isUnique = some false + else: + raise getCurrentException() + + if unlikely is_unique.isNone: + echo "Error detecting uniqueness" # unreachable + else: + if isUnique.unsafeGet(): + server() + else: + client() diff --git a/Task/Digital-root/Elena/digital-root.elena b/Task/Digital-root/Elena/digital-root.elena index 283e1886ef..ba468956a4 100644 --- a/Task/Digital-root/Elena/digital-root.elena +++ b/Task/Digital-root/Elena/digital-root.elena @@ -22,7 +22,7 @@ extension op public program() { - new long[]{627615l, 39390l, 588225l, 393900588225l}.forEach:(num) + new long[]::(627615l, 39390l, 588225l, 393900588225l).forEach:(num) { var t := num.DigitalRoot; diff --git a/Task/Dinesmans-multiple-dwelling-problem/Factor/dinesmans-multiple-dwelling-problem.factor b/Task/Dinesmans-multiple-dwelling-problem/Factor/dinesmans-multiple-dwelling-problem.factor index 4d8d8ffac0..53f62daf97 100644 --- a/Task/Dinesmans-multiple-dwelling-problem/Factor/dinesmans-multiple-dwelling-problem.factor +++ b/Task/Dinesmans-multiple-dwelling-problem/Factor/dinesmans-multiple-dwelling-problem.factor @@ -22,7 +22,7 @@ IN: rosetta.dinesman 5 [1,b] all-permutations [ meets-constraints? ] filter ; : >names ( seq -- seq ) - [ 1 - qw{ baker cooper fletcher miller smith } nth ] map ; + [ qw{ baker cooper fletcher miller smith } nth swap 2array ] map-index ; : dinesman ( -- ) solutions [ >names . ] each ; diff --git a/Task/Discordian-date/Julia/discordian-date.julia b/Task/Discordian-date/Julia/discordian-date.julia index 0426508033..ed1a69f5bc 100644 --- a/Task/Discordian-date/Julia/discordian-date.julia +++ b/Task/Discordian-date/Julia/discordian-date.julia @@ -1,4 +1,4 @@ -using Base.Dates +using Dates function discordiandate(year::Integer, month::Integer, day::Integer) discordianseasons = ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"] diff --git a/Task/Documentation/Phix/documentation.phix b/Task/Documentation/Phix/documentation.phix new file mode 100644 index 0000000000..fcc24396b9 --- /dev/null +++ b/Task/Documentation/Phix/documentation.phix @@ -0,0 +1,10 @@ +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 diff --git a/Task/Documentation/Retro/documentation.retro b/Task/Documentation/Retro/documentation.retro index dc2866ae7b..9fbfad3e3a 100644 --- a/Task/Documentation/Retro/documentation.retro +++ b/Task/Documentation/Retro/documentation.retro @@ -1,15 +1,28 @@ -doc{ -======== -Function: foo -======== + # Determine The Average Word Name Length -Stack ----- -a1 a2 - b + To determine the average length of a word name two values + are needed. First, the total length of all names in the + Dictionary: -Usage ------ -Adds a1 to a2 returning b. -}doc + ~~~ + #0 [ d:name s:length + ] d:for-each + ~~~ -: foo ( aa-b ) + ; + And then the number of words in the Dictionary: + + ~~~ + #0 [ drop n:inc ] d:for-each + ~~~ + + With these, a simple division is all that's left. + + ~~~ + / + ~~~ + + Finally, display the results: + + + ~~~ + 'Average_name_length:_%n\n s:format s:put + ~~~ diff --git a/Task/Dot-product/Elena/dot-product.elena b/Task/Dot-product/Elena/dot-product.elena index c705cf4014..c3d18b60f5 100644 --- a/Task/Dot-product/Elena/dot-product.elena +++ b/Task/Dot-product/Elena/dot-product.elena @@ -9,5 +9,5 @@ extension op public program() { - console.printLine(new int[]{1, 3, -5}.dotProduct(new int[]{4, -2, -1})) + console.printLine(new int[]::(1, 3, -5).dotProduct(new int[]::(4, -2, -1))) } diff --git a/Task/Doubly-linked-list-Definition/Java/doubly-linked-list-definition.java b/Task/Doubly-linked-list-Definition/Java/doubly-linked-list-definition.java new file mode 100644 index 0000000000..45e89a1588 --- /dev/null +++ b/Task/Doubly-linked-list-Definition/Java/doubly-linked-list-definition.java @@ -0,0 +1,25 @@ +import java.util.LinkedList; + +public class DoublyLinkedList { + + public static void main(String[] args) { + LinkedList list = new LinkedList(); + list.addFirst("Add First"); + list.addLast("Add Last 1"); + list.addLast("Add Last 2"); + list.addLast("Add Last 1"); + traverseList(list); + + list.removeFirstOccurrence("Add Last 1"); + traverseList(list); + } + + private static void traverseList(LinkedList list) { + System.out.println("Traverse List:"); + for ( int i = 0 ; i < list.size() ; i++ ) { + System.out.printf("Element number %d - Element value = '%s'%n", i, list.get(i)); + } + System.out.println(); + } + +} diff --git a/Task/Doubly-linked-list-Element-definition/Factor/doubly-linked-list-element-definition.factor b/Task/Doubly-linked-list-Element-definition/Factor/doubly-linked-list-element-definition.factor new file mode 100644 index 0000000000..77dd58879c --- /dev/null +++ b/Task/Doubly-linked-list-Element-definition/Factor/doubly-linked-list-element-definition.factor @@ -0,0 +1 @@ +TUPLE: node data next prev ; diff --git a/Task/Doubly-linked-list-Element-insertion/Java/doubly-linked-list-element-insertion.java b/Task/Doubly-linked-list-Element-insertion/Java/doubly-linked-list-element-insertion.java new file mode 100644 index 0000000000..1869b8e888 --- /dev/null +++ b/Task/Doubly-linked-list-Element-insertion/Java/doubly-linked-list-element-insertion.java @@ -0,0 +1,40 @@ +import java.util.LinkedList; + +@SuppressWarnings("serial") +public class DoublyLinkedListInsertion extends LinkedList { + + public static void main(String[] args) { + DoublyLinkedListInsertion list = new DoublyLinkedListInsertion(); + list.addFirst("Add First 1"); + list.addFirst("Add First 2"); + list.addFirst("Add First 3"); + list.addFirst("Add First 4"); + list.addFirst("Add First 5"); + traverseList(list); + + list.addAfter("Add First 3", "Add New"); + traverseList(list); + } + + /* + * Add after indicated node. If not in the list, added as the last node. + */ + public void addAfter(T after, T element) { + int index = indexOf(after); + if ( index >= 0 ) { + add(index + 1, element); + } + else { + addLast(element); + } + } + + private static void traverseList(LinkedList list) { + System.out.println("Traverse List:"); + for ( int i = 0 ; i < list.size() ; i++ ) { + System.out.printf("Element number %d - Element value = '%s'%n", i, list.get(i)); + } + System.out.println(); + } + +} diff --git a/Task/Draw-a-clock/Ada/draw-a-clock.ada b/Task/Draw-a-clock/Ada/draw-a-clock.ada new file mode 100644 index 0000000000..285b1315ac --- /dev/null +++ b/Task/Draw-a-clock/Ada/draw-a-clock.ada @@ -0,0 +1,99 @@ +with Ada.Numerics.Elementary_Functions; +with Ada.Calendar.Formatting; +with Ada.Calendar.Time_Zones; + +with SDL.Video.Windows.Makers; +with SDL.Video.Renderers.Makers; +with SDL.Events.Events; + +procedure Draw_A_Clock is + use Ada.Calendar; + use Ada.Calendar.Formatting; + Window : SDL.Video.Windows.Window; + Renderer : SDL.Video.Renderers.Renderer; + Event : SDL.Events.Events.Events; + Offset : Time_Zones.Time_Offset; + + procedure Draw_Clock (Stamp : Time) + is + use SDL.C; + use Ada.Numerics.Elementary_Functions; + Radi : constant array (0 .. 59) of int := (0 | 15 | 30 | 45 => 2, + 5 | 10 | 20 | 25 | 35 | 40 | 50 | 55 => 1, + others => 0); + Diam : constant array (0 .. 59) of int := (0 | 15 | 30 | 45 => 5, + 5 | 10 | 20 | 25 | 35 | 40 | 50 | 55 => 3, + others => 1); + Width : constant int := Window.Get_Surface.Size.Width; + Height : constant int := Window.Get_Surface.Size.Height; + Radius : constant Float := Float (int'Min (Width, Height)); + R_1 : constant Float := 0.48 * Radius; + R_2 : constant Float := 0.35 * Radius; + R_3 : constant Float := 0.45 * Radius; + R_4 : constant Float := 0.47 * Radius; + Hour : constant Hour_Number := Formatting.Hour (Stamp, Offset); + Minute : constant Minute_Number := Formatting.Minute (Stamp, Offset); + Second : constant Second_Number := Formatting.Second (Stamp); + + function To_X (A : Float; R : Float) return int is + (Width / 2 + int (R * Sin (A, 60.0))); + + function To_Y (A : Float; R : Float) return int is + (Height / 2 - int (R * Cos (A, 60.0))); + + begin + SDL.Video.Renderers.Makers.Create (Renderer, Window.Get_Surface); + Renderer.Set_Draw_Colour ((0, 0, 150, 255)); + Renderer.Fill (Rectangle => (0, 0, Width, Height)); + Renderer.Set_Draw_Colour ((200, 200, 200, 255)); + for A in 0 .. 59 loop + Renderer.Fill (Rectangle => (To_X (Float (A), R_1) - Radi (A), + To_Y (Float (A), R_1) - Radi (A), Diam (A), Diam (A))); + end loop; + Renderer.Set_Draw_Colour ((200, 200, 0, 255)); + Renderer.Draw (Line => ((Width / 2, Height / 2), + (To_X (5.0 * (Float (Hour) + Float (Minute) / 60.0), R_2), + To_Y (5.0 * (Float (Hour) + Float (Minute) / 60.0), R_2)))); + Renderer.Draw (Line => ((Width / 2, Height / 2), + (To_X (Float (Minute) + Float (Second) / 60.0, R_3), + To_Y (Float (Minute) + Float (Second) / 60.0, R_3)))); + Renderer.Set_Draw_Colour ((220, 0, 0, 255)); + Renderer.Draw (Line => ((Width / 2, Height / 2), + (To_X (Float (Second), R_4), + To_Y (Float (Second), R_4)))); + Renderer.Fill (Rectangle => (Width / 2 - 3, Height / 2 - 3, 7, 7)); + end Draw_Clock; + + 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; + +begin + Offset := Time_Zones.UTC_Time_Offset; + + if not SDL.Initialise (Flags => SDL.Enable_Screen) then + return; + end if; + + SDL.Video.Windows.Makers.Create (Win => Window, + Title => "Draw a clock", + Position => SDL.Natural_Coordinates'(X => 10, Y => 10), + Size => SDL.Positive_Sizes'(300, 300), + Flags => SDL.Video.Windows.Resizable); + loop + Draw_Clock (Clock); + Window.Update_Surface; + delay 0.200; + exit when Poll_Quit; + end loop; + + Window.Finalize; + SDL.Finalise; +end Draw_A_Clock; diff --git a/Task/Draw-a-clock/Processing/draw-a-clock-1 b/Task/Draw-a-clock/Processing/draw-a-clock-1 new file mode 100644 index 0000000000..ffdcf34f31 --- /dev/null +++ b/Task/Draw-a-clock/Processing/draw-a-clock-1 @@ -0,0 +1,19 @@ +void draw() { + drawClock(); +} +void drawClock() { + background(192); + translate(width/2, height/2); + float s = second() * TWO_PI / 60.0; + float m = minute() * TWO_PI / 60.0; + float h = hour() * TWO_PI / 12.0; + rotate(s); + strokeWeight(1); + line(0, 0, 0, -width*0.5); + rotate(-s+m); + strokeWeight(2); + line(0, 0, 0, -width*0.4); + rotate(-m+h); + strokeWeight(4); + line(0, 0, 0, -width*0.2); +} diff --git a/Task/Draw-a-clock/Processing/draw-a-clock-2 b/Task/Draw-a-clock/Processing/draw-a-clock-2 new file mode 100644 index 0000000000..3805285576 --- /dev/null +++ b/Task/Draw-a-clock/Processing/draw-a-clock-2 @@ -0,0 +1,7 @@ +int lastSec = second(); +void draw() { + if (lastSec!=second()) { + drawClock(); + lastSec=second(); + } +} diff --git a/Task/Draw-a-cuboid/Processing/draw-a-cuboid b/Task/Draw-a-cuboid/Processing/draw-a-cuboid new file mode 100644 index 0000000000..d80082578b --- /dev/null +++ b/Task/Draw-a-cuboid/Processing/draw-a-cuboid @@ -0,0 +1,13 @@ +size(500, 500, P3D); +background(0); +// position +translate(width/2, height/2, -width/2); +rotateZ(radians(15)); +rotateY(radians(-30)); +rotateX(radians(-25)); +// optional fill and lighting colors +noStroke(); +fill(192, 255, 192); +pointLight(255, 255, 255, 400, -400, 400); +// draw box +box(200, 300, 400); diff --git a/Task/Draw-a-sphere/BASIC/draw-a-sphere-1.basic b/Task/Draw-a-sphere/BASIC/draw-a-sphere-1.basic index 55d69dbf7c..6961a6b748 100644 --- a/Task/Draw-a-sphere/BASIC/draw-a-sphere-1.basic +++ b/Task/Draw-a-sphere/BASIC/draw-a-sphere-1.basic @@ -1,7 +1,7 @@ clg color white rect 0,0,graphwidth, graphheight -For n = 1 to 100 -color rgb(2*n,2*n,2*n) -circle 150-2*n/3,150-n/2,150-n +for n = 1 to 100 + color rgb(2*n,2*n,2*n) + circle 150-2*n/3,150-n/2,150-n next n diff --git a/Task/Draw-a-sphere/Batch-File/draw-a-sphere.bat b/Task/Draw-a-sphere/Batch-File/draw-a-sphere.bat index 11a202dd2c..e67dbb0084 100644 --- a/Task/Draw-a-sphere/Batch-File/draw-a-sphere.bat +++ b/Task/Draw-a-sphere/Batch-File/draw-a-sphere.bat @@ -1,40 +1,105 @@ +:: Draw a Sphere Task from Rosetta Code +:: Batch File Implementation + @echo off -setlocal enabledelayedexpansion -mode con cols=80 +rem -------------- define arithmetic "functions" +rem more info: https://www.dostips.com/forum/viewtopic.php?f=3&t=6744 -set /a r=220,cent=340,r2=r/2 -set "spaces= " -set "block1=MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM" -set "block2=#########" -set "block3=XXXXXXXXX" -set "block4=ooooooooo" -set "block5=?????????" -set "block6=*********" -set "block7=~~~~~~~~~" -set "block8=---------" +rem integer sqrt arithmetic function by Aacini and penpen +rem source: https://www.dostips.com/forum/viewtopic.php?f=3&t=5819&start=30#p44016 +set "sqrt(N)=( M=(N),j=M/(11*1024)+40, j=(M/j+j)>>1, j=(M/j+j)>>1, j=(M/j+j)>>1, j=(M/j+j)>>1, j=(M/j+j)>>1, j+=(M-j*j)>>31 )" -set wy=0 -set linea= -echo Batch-File ASCII Ball -echo. -for /L %%y in (-%r%,10,%r%) do ( - set /a "w1=r*r-%%y*%%y" - call:sqrt2 w1 w1 - set /a "w1=14*w1/10,wy=(cent-w1),cnt=0,sp=wy/10,centre=cent/10-sp" - call set "linea=%%spaces:~0,!sp!%%%%block1:~0,!centre!%% - set /a wy=0,sum=0 - for %%i in (30 80 120 150 170 185 195 200) do ( - set /a "cnt+=1,wy2=(%%i+r2)*w1/r,ww=(wy2+5)/10-sum,wy=wy2,sum+=ww" - call set miblock=%%block!cnt!%% - call set "Linea=%%linea%%%%miblock:~0,!ww!%%" - ) - call echo(!linea! +rem -------------- define batch file macros with parameters appended +rem more info: https://www.dostips.com/forum/viewtopic.php?f=3&t=2518 +setlocal disabledelayedexpansion % == required for macro ==% +(set \n=^^^ +%== this creates escaped line feed for macro ==% ) -echo. -exit /b -:sqrt2 [num] calculates integer square root . By AAcini -set "s=!%~1!" -set /A "x=s/(11*1024)+40,x=(s/x+x)>>1,x=(s/x+x)>>1,x=(s/x+x)>>1,x=(s/x+x)>>1,x=(s/x+x)>>1,x+=(s-x*x)>>31 -set %~2=%x% -exit /b +rem normalize macro +rem argument: v +set normalize=for %%# in (1 2) do if %%#==2 ( %\n% + for /f "tokens=1" %%a in ("!args!") do set "v=%%a" %\n% + set /a "length_sqrd=!v![0]*!v![0]+!v![1]*!v![1]+!v![2]*!v![2]" %\n% + set /a "length=%sqrt(N):N=!length_sqrd!%" %== sqrt(N) applied ==% %\n% + set /a "!v![0]*=100", "!v![1]*=100", "!v![2]*=100" %== normalized elements mult. by 100 ==% %\n% + set /a "!v![0]/=length", "!v![1]/=length", "!v![2]/=length" %\n% +) else set args= + +rem dot macro +rem arguments: s t outputvar +set dot=for %%# in (1 2) do if %%#==2 ( %\n% + for /f "tokens=1,2,3" %%a in ("!args!") do ( %\n% + set "s=%%a" %\n% + set "t=%%b" %\n% + set "outputvar=%%c" %\n% + ) %\n% + set /a "d=!s![0]*!t![0]+!s![1]*!t![1]+!s![2]*!t![2]" %\n% + if !d! lss 0 (set /a "!outputvar!=-d") else (set "!outputvar!=0") %\n% +) else set args= + +rem -------------- define pseudo-arrays +set "shades[0]=." +set "shades[1]=:" +set "shades[2]=!" +set "shades[3]=*" +set "shades[4]=o" +set "shades[5]=e" +set "shades[6]=&" +set "shades[7]=#" +set "shades[8]=%%" +set "shades[9]=@" +set "num_shades=9" %== start at 0 ==% + +set "light[0]=30" & set "light[1]=30" & set "light[2]=-50" + +rem -------------- main thing: execute drawSphere +setlocal enabledelayedexpansion +%normalize% light %== normalize macro applied ==% +rem note: due to scale up 100x of variables for calculations, +rem k=4 is the maximum value for k that does not cause overflow. +call :drawSphere 20 4 1 +exit /b 0 + +rem -------------- the function to draw the sphere +rem arguments: R k ambient +:drawSphere +rem initialize variables from arguments +set /a "R=%1", "negR=-R", "twiceR=R*2", "twiceNegR=negR*2" +set /a "sqrdR=R*R*10000" %== R^2 is mult. by 100^2 ==% +set "k=%2" +set "ambient=%3" +rem start draw line-by-line +for /l %%i in (%negR%, 1, %R%) do ( + set /a "x=100*%%i+50" %== x is mult. by 100 ==% + set "line=" + for /l %%j in (%twiceNegR%, 1, %twiceR%) do ( + set /a "y=50*%%j+50" %== y is mult. by 100 ==% + set /a "pythag = x*x + y*y" + if !pythag! lss !sqrdR! ( + set /a "vec[0]=x" + set /a "vec[1]=y" + set /a "vec[2]=sqrdR-pythag" + set /a "vec[2]=%sqrt(N):N=!vec[2]!%" %== sqrt(N) applied ==% + %normalize% vec %== normalize macro applied ==% + %dot% light vec dot_out %== dot macro applied ==% + rem since both light and vec are normalized to 100, + rem then dot_out is scaled up by 100*100 now. + set /a "dot_out/=100" %== scale-down to 100*[actual] to prevent overflow before exponentiation ==% + set "scaleup=1" %== after exponentiation, b would be scaleup*[actual] ==% + set "b=1" + for /l %%? in (1,1,%k%) do set /a "b*=dot_out","scaleup*=100" %== exponentiation ==% + set /a "b+=ambient*scaleup/10" %== add ambient/10 to b ==% + set /a "b/=scaleup/100" %== scale-down to 100*[actual] ==% + set /a "intensity=(100-b)*num_shades" + set /a "intensity/=100" %== final scale-down ==% + if !intensity! lss 0 set "intensity=0" + if !intensity! gtr %num_shades% set "intensity=%num_shades%" + for %%c in (!intensity!) do set "line=!line!!shades[%%c]!" + ) else ( + set "line=!line! " + ) + ) + echo(!line! +) +goto :EOF diff --git a/Task/Draw-a-sphere/Julia/draw-a-sphere.julia b/Task/Draw-a-sphere/Julia/draw-a-sphere-1.julia similarity index 99% rename from Task/Draw-a-sphere/Julia/draw-a-sphere.julia rename to Task/Draw-a-sphere/Julia/draw-a-sphere-1.julia index 7f12d6a75a..e992c424ec 100644 --- a/Task/Draw-a-sphere/Julia/draw-a-sphere.julia +++ b/Task/Draw-a-sphere/Julia/draw-a-sphere-1.julia @@ -1,5 +1,3 @@ -# v0.6 - function draw_sphere(r, k, ambient, light) shades = ('.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@') for i in floor(Int, -r):ceil(Int, r) diff --git a/Task/Draw-a-sphere/Julia/draw-a-sphere-2.julia b/Task/Draw-a-sphere/Julia/draw-a-sphere-2.julia new file mode 100644 index 0000000000..afc40d411b --- /dev/null +++ b/Task/Draw-a-sphere/Julia/draw-a-sphere-2.julia @@ -0,0 +1,13 @@ +# run from REPL + +using Makie + +φ = 0:π/100:2π + +θ = 0:π/200:π + +x = [cos(θ) * sin(φ) for θ in θ, φ in φ] +y = [sin(θ)*sin(φ) for θ in θ, φ in φ] +z = [cos(φ) for θ in θ, φ in φ] + +surface(x, y, z, backgroundcolor = :black, show_axis = false) diff --git a/Task/Draw-a-sphere/Processing/draw-a-sphere b/Task/Draw-a-sphere/Processing/draw-a-sphere index 98a7f5abd6..0752bd6a97 100644 --- a/Task/Draw-a-sphere/Processing/draw-a-sphere +++ b/Task/Draw-a-sphere/Processing/draw-a-sphere @@ -1,11 +1,13 @@ void setup() { - size(500,500,P3D); - background(200); + size(500, 500, P3D); } - void draw() { + background(192); + translate(width/2, height/2); + // optional color and lighting style stroke(200); - translate(250,250); + fill(255); lights(); - sphere(100); + // draw sphere + sphere(200); } diff --git a/Task/Dynamic-variable-names/00DESCRIPTION b/Task/Dynamic-variable-names/00DESCRIPTION index a9540bb89f..cb112c92da 100644 --- a/Task/Dynamic-variable-names/00DESCRIPTION +++ b/Task/Dynamic-variable-names/00DESCRIPTION @@ -1,28 +1,3 @@ -{{omit From|ACL2}} -{{omit From|Ada}} -{{omit from|AmigaE}} -{{omit from|AWK}} -{{omit from|ALGOL 68}} -{{omit from|C}} -{{omit from|C++}} -{{omit from|D}} -{{omit from|Delphi}} -{{omit from|Fortran}} -{{omit from|Free Pascal}} -{{omit from|GUISS}} -{{omit from|Java}} -{{omit from|Lily}} -{{omit from|Locomotive Basic}} -{{omit from|Metafont}} -{{omit from|NetRexx}} -{{omit from|Octave}} -{{omit from|Pascal}} -{{omit from|PureBasic}} -{{omit from|Rust}} -{{omit from|Swift}} -{{omit from|zkl}} -{{omit from|ZX Spectrum Basic}} - ;Task: Create a variable with a user-defined name. diff --git a/Task/Dynamic-variable-names/AWK/dynamic-variable-names.awk b/Task/Dynamic-variable-names/AWK/dynamic-variable-names.awk new file mode 100644 index 0000000000..e2807a1031 --- /dev/null +++ b/Task/Dynamic-variable-names/AWK/dynamic-variable-names.awk @@ -0,0 +1,36 @@ +# syntax: GAWK -f DYNAMIC_VARIABLE_NAMES.AWK +# Variables created in GAWK's internal SYMTAB (symbol table) can only be accessed via SYMTAB[name] +BEGIN { + PROCINFO["sorted_in"] = "@ind_str_asc" + show_symbol_table() + while (1) { + printf("enter variable name? ") + getline v_name + if (v_name in SYMTAB) { + printf("name already exists with a value of '%s'\n",SYMTAB[v_name]) + continue + } + if (v_name ~ /^$/) { + printf("name is null\n") + continue + } + if (v_name !~ /^[A-Za-z][A-Za-z0-9_]*$/) { + printf("name illegally constructed\n") + continue + } + break + } + printf("enter value? ") + getline v_value + SYMTAB[v_name] = v_value + printf("variable '%s' has been created and assigned the value '%s'\n\n",v_name,v_value) + show_symbol_table() + exit(0) +} +function show_symbol_table( count,i) { + for (i in SYMTAB) { + printf("%s ",i) + if (isarray(SYMTAB[i])) { count++ } + } + printf("\nsymbol table contains %d names of which %d are arrays\n\n",length(SYMTAB),count) +} diff --git a/Task/Dynamic-variable-names/Elena/dynamic-variable-names.elena b/Task/Dynamic-variable-names/Elena/dynamic-variable-names.elena index 5c773c4026..0f92747f7b 100644 --- a/Task/Dynamic-variable-names/Elena/dynamic-variable-names.elena +++ b/Task/Dynamic-variable-names/Elena/dynamic-variable-names.elena @@ -12,10 +12,10 @@ class TestClass closure() { - auto varRef := new MessageName(console.write:"Enter the variable name:".readLine()); - mixin varRef(theVariables).prop := 42; + auto prop := new MessageName(console.write:"Enter the variable name:".readLine()); + (prop.setPropertyMessage())(theVariables,42); - console.printLine(varRef.Printable,"=",mixin varRef(theVariables).get).readChar() + console.printLine(prop.Printable,"=",(prop.getPropertyMessage())(theVariables)).readChar() } } diff --git a/Task/Dynamic-variable-names/Retro/dynamic-variable-names.retro b/Task/Dynamic-variable-names/Retro/dynamic-variable-names.retro new file mode 100644 index 0000000000..e18589b037 --- /dev/null +++ b/Task/Dynamic-variable-names/Retro/dynamic-variable-names.retro @@ -0,0 +1,3 @@ +:newVariable ("-) s:get var ; + +newVariable: foo diff --git a/Task/Empty-directory/Nim/empty-directory.nim b/Task/Empty-directory/Nim/empty-directory-1.nim similarity index 100% rename from Task/Empty-directory/Nim/empty-directory.nim rename to Task/Empty-directory/Nim/empty-directory-1.nim diff --git a/Task/Empty-directory/Nim/empty-directory-2.nim b/Task/Empty-directory/Nim/empty-directory-2.nim new file mode 100644 index 0000000000..905c4df5c9 --- /dev/null +++ b/Task/Empty-directory/Nim/empty-directory-2.nim @@ -0,0 +1,7 @@ +import os, sequtils + +proc isEmptyDir(dir: string): bool = + toSeq(walkdir dir).len == 0 + +echo isEmptyDir("/tmp") # false - there is always something in "/tmp" +echo isEmptyDir("/temp") # true - "/temp" does not exist diff --git a/Task/Empty-directory/Prolog/empty-directory.pro b/Task/Empty-directory/Prolog/empty-directory.pro new file mode 100644 index 0000000000..c0410f29bd --- /dev/null +++ b/Task/Empty-directory/Prolog/empty-directory.pro @@ -0,0 +1,6 @@ +non_empty_file('.'). +non_empty_file('..'). + +empty_dir(Dir) :- + directory_files(Dir, Files), + maplist(non_empty_file, Files). diff --git a/Task/Empty-program/Futhark/empty-program.futhark b/Task/Empty-program/Futhark/empty-program.futhark index 1325e7926a..57411f3b3b 100644 --- a/Task/Empty-program/Futhark/empty-program.futhark +++ b/Task/Empty-program/Futhark/empty-program.futhark @@ -1 +1 @@ -fun main(): int = 0 +let main = 0 diff --git a/Task/Empty-program/Gambas/empty-program.gambas b/Task/Empty-program/Gambas/empty-program.gambas new file mode 100644 index 0000000000..49ab48c76d --- /dev/null +++ b/Task/Empty-program/Gambas/empty-program.gambas @@ -0,0 +1,2 @@ +Public Sub Main() +End diff --git a/Task/Empty-program/Ol/empty-program.ol b/Task/Empty-program/Ol/empty-program.ol new file mode 100644 index 0000000000..573541ac97 --- /dev/null +++ b/Task/Empty-program/Ol/empty-program.ol @@ -0,0 +1 @@ +0 diff --git a/Task/Empty-string/C-sharp/empty-string-2.cs b/Task/Empty-string/C-sharp/empty-string-2.cs index d3e501d4d6..dd9aa7165b 100644 --- a/Task/Empty-string/C-sharp/empty-string-2.cs +++ b/Task/Empty-string/C-sharp/empty-string-2.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; static class Program { - // TL; DR: + // In short: public static void Foo() { string s; @@ -16,21 +16,21 @@ static class Program // Check for empty string only (false if s is null): if (s != null && s.Length == 0) { } - // Check for null or empty (most idiomatic .NET way): + // Check for null or empty (more idiomatic in .NET): if (string.IsNullOrEmpty(s)) { } } public static void Main() { // Equality is somewhat convoluted in .NET. - // The means above are the author's recommendation for each case. + // The methods above are the author's recommendation for each case. // s is initialized to null. It is a variable of the System.String type that is a null reference and is not // the empty string. string s = null; - // Alias Console.WriteLine with a shorter name to make the demonstration code less verbose. - void P(bool x) => Console.WriteLine(x); + // Alias Console.WriteLine(bool) with a shorter name to make the demonstration code less verbose. + Action P = Console.WriteLine; // Assign the empty string literal to s. s = ""; diff --git a/Task/Empty-string/Cache-ObjectScript/empty-string.cos b/Task/Empty-string/Cache-ObjectScript/empty-string.cos new file mode 100644 index 0000000000..735e7197f5 --- /dev/null +++ b/Task/Empty-string/Cache-ObjectScript/empty-string.cos @@ -0,0 +1,15 @@ +EMPTYSTR + ; Demonstrate how to assign an empty string to a variable. + set x = "" + + ; Demonstrate how to check that a string is empty. + ; Length 0 is empty; equality/pattern check are 1=T, 0=F + write !,"Assigned x to null value. Tests: " + write !,"String length: "_$length(x)_", Equals null: "_(x = "")_", Empty pattern: "_(x?."") ; length 0 is empty + + ; Demonstrate how to check that a string is not empty. Same as above. + set x = " " ;assign to a space - not null + write !!,"Assigned x to a single blank space. Tests: " + write !,"String length: "_$length(x)_", Equals null: "_(x = "")_", Empty pattern: "_(x?."") + + quit diff --git a/Task/Empty-string/Go/empty-string.go b/Task/Empty-string/Go/empty-string-1.go similarity index 100% rename from Task/Empty-string/Go/empty-string.go rename to Task/Empty-string/Go/empty-string-1.go diff --git a/Task/Empty-string/Go/empty-string-2.go b/Task/Empty-string/Go/empty-string-2.go new file mode 100644 index 0000000000..36006c525a --- /dev/null +++ b/Task/Empty-string/Go/empty-string-2.go @@ -0,0 +1,23 @@ +package main + +import ( + "fmt" +) + +func test(s string) { + if len(s) == 0 { + fmt.Println("empty") + } else { + fmt.Println("not empty") + } +} + +func main() { + // assign an empty string to a variable. + str1 := "" + str2 := " " + // check if a string is empty. + test(str1) // prt empty + // check that a string is not empty. + test(str2) // prt not empty +} diff --git a/Task/Empty-string/Python/empty-string.py b/Task/Empty-string/Python/empty-string.py index d2701f2390..204d792f5c 100644 --- a/Task/Empty-string/Python/empty-string.py +++ b/Task/Empty-string/Python/empty-string.py @@ -1,5 +1,5 @@ s = '' -if not s: - print('String s is empty.') -if s: - print('String s is not empty.') +if len(s) == 0: + print("String is empty") +else: + print("String not empty") diff --git a/Task/Empty-string/Robotic/empty-string.robotic b/Task/Empty-string/Robotic/empty-string.robotic new file mode 100644 index 0000000000..c668fe3e05 --- /dev/null +++ b/Task/Empty-string/Robotic/empty-string.robotic @@ -0,0 +1,8 @@ +set "$string" to "" +if "$string.length" = 0 then "empty" +* "Not an empty string." +end + +: "empty" +* "Empty string" +end diff --git a/Task/Empty-string/Visual-Basic-.NET/empty-string-1.visual b/Task/Empty-string/Visual-Basic-.NET/empty-string-1.visual index fda330c8ec..d17f0dda38 100644 --- a/Task/Empty-string/Visual-Basic-.NET/empty-string-1.visual +++ b/Task/Empty-string/Visual-Basic-.NET/empty-string-1.visual @@ -9,6 +9,6 @@ s = String.Empty If s IsNot Nothing AndAlso s.Length = 0 Then End If -' Check for null or empty (most idiomatic .NET way): +' Check for null or empty (more idiomatic in .NET): If String.IsNullOrEmpty(s) Then End If diff --git a/Task/Empty-string/Visual-Basic-.NET/empty-string-2.visual b/Task/Empty-string/Visual-Basic-.NET/empty-string-2.visual index 1f6ba0da8a..9bf8adb531 100644 --- a/Task/Empty-string/Visual-Basic-.NET/empty-string-2.visual +++ b/Task/Empty-string/Visual-Basic-.NET/empty-string-2.visual @@ -1,19 +1,18 @@ Option Strict On Module Program - Sub Main() ' Equality is somewhat convoluted in .NET, and VB doesn't help by adding legacy means of comparison. - ' The means above are the author's recommendation for each case. - ' Some methods also return true if the string is Nothing/null; this is noted in the description for those that + ' The methods above are the author's recommendation for each case. + ' Some also return true if the string is Nothing/null; this is noted in the description for those that ' do. ' s is initialized to Nothing. It is a variable of the System.String type that is a null reference and is not ' the empty string. Dim s As String = Nothing - ' Alias Console.WriteLine with a shorter name to make the demonstration code less verbose. - Dim P = Sub(x As Boolean) Console.WriteLine(x) + ' Alias Console.WriteLine(Boolean) with a shorter name to make the demonstration code less verbose. + Dim P As Action(Of Boolean) = AddressOf Console.WriteLine ' Assign the empty string literal to s. s = "" @@ -111,7 +110,7 @@ Module Program Console.WriteLine() - ' Each of the means described above, except testing for a non-empty string. + ' Each of the methods described above, except testing for a non-empty string. P(s IsNot "") P(Not Object.ReferenceEquals(s, "")) P(s <> "") diff --git a/Task/Enforced-immutability/C-sharp/enforced-immutability-1.cs b/Task/Enforced-immutability/C-sharp/enforced-immutability-1.cs new file mode 100644 index 0000000000..d072b40ae4 --- /dev/null +++ b/Task/Enforced-immutability/C-sharp/enforced-immutability-1.cs @@ -0,0 +1 @@ +readonly DateTime now = DateTime.Now; diff --git a/Task/Enforced-immutability/C-sharp/enforced-immutability-2.cs b/Task/Enforced-immutability/C-sharp/enforced-immutability-2.cs new file mode 100644 index 0000000000..bb9b0c3497 --- /dev/null +++ b/Task/Enforced-immutability/C-sharp/enforced-immutability-2.cs @@ -0,0 +1 @@ +const int Max = 100; diff --git a/Task/Enforced-immutability/C-sharp/enforced-immutability-3.cs b/Task/Enforced-immutability/C-sharp/enforced-immutability-3.cs new file mode 100644 index 0000000000..1c451ed967 --- /dev/null +++ b/Task/Enforced-immutability/C-sharp/enforced-immutability-3.cs @@ -0,0 +1,3 @@ +public void Method(in int x) { + x = 5; //Compile error +} diff --git a/Task/Enforced-immutability/C-sharp/enforced-immutability-4.cs b/Task/Enforced-immutability/C-sharp/enforced-immutability-4.cs new file mode 100644 index 0000000000..7abf784e89 --- /dev/null +++ b/Task/Enforced-immutability/C-sharp/enforced-immutability-4.cs @@ -0,0 +1,4 @@ +public void Method() { + const double sqrt5 = 2.236; + ... +} diff --git a/Task/Enforced-immutability/C-sharp/enforced-immutability-5.cs b/Task/Enforced-immutability/C-sharp/enforced-immutability-5.cs new file mode 100644 index 0000000000..a2dfd487e0 --- /dev/null +++ b/Task/Enforced-immutability/C-sharp/enforced-immutability-5.cs @@ -0,0 +1 @@ +public string Key { get; } diff --git a/Task/Enforced-immutability/C-sharp/enforced-immutability-6.cs b/Task/Enforced-immutability/C-sharp/enforced-immutability-6.cs new file mode 100644 index 0000000000..fe62a5fbc9 --- /dev/null +++ b/Task/Enforced-immutability/C-sharp/enforced-immutability-6.cs @@ -0,0 +1,7 @@ +public readonly struct Point +{ + public Point(int x, int y) => (X, Y) = (x, y); + + public int X { get; } + public int Y { get; } +} diff --git a/Task/Entropy/PHP/entropy.php b/Task/Entropy/PHP/entropy.php new file mode 100644 index 0000000000..bbeffecb38 --- /dev/null +++ b/Task/Entropy/PHP/entropy.php @@ -0,0 +1,27 @@ +1.5; ii=0; is=1 - 2 * (ig\==1) - numeric digits digits()+5 /* [↓] precision of E must be≥digits()*/ - e=2.71828182845904523536028747135266249775724709369995957496696762772407663035354759 - do while ig & ox>1.5 | \ig&ox<.5; _=e; do j=-1; iz=ox * _ ** -is - if j>=0 & (ig & iz<1 | \ig&iz>.5) then leave; _=_*_; izz=iz; end /*j*/ - ox=izz; ii=ii+is*2**j; end /*while*/; 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 /*k*/ - r=z+ii; if arg()==2 then return r; return r/log2(2,.) +e: e= 2.718281828459045235360287471352662497757247093699959574966967627724076630; return e +/*──────────────────────────────────────────────────────────────────────────────────────*/ +log2: procedure; parse arg x 1 ox; ig= x>1.5; ii= 0; is= 1 - 2 * (ig\==1) + numeric digits digits()+5; call e /*the precision of E must be≥digits(). */ + do while ig & ox>1.5 | \ig&ox<.5; _= e; do j=-1; iz= ox * _ ** -is + if j>=0 & (ig & iz<1 | \ig&iz>.5) then leave; _= _ * _; izz= iz; end /*j*/ + ox=izz; ii=ii+is*2**j; end /*while*/; 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 /*k*/ + r= z + ii; if arg()==2 then return r; return r / log2(2,.) diff --git a/Task/Enumerations/Ol/enumerations-1.ol b/Task/Enumerations/Ol/enumerations-1.ol new file mode 100644 index 0000000000..a2c42c9b38 --- /dev/null +++ b/Task/Enumerations/Ol/enumerations-1.ol @@ -0,0 +1,16 @@ +(define fruits '{ + apple 0 + banana 1 + cherry 2}) +; or +(define fruits { + 'apple 0 + 'banana 1 + 'cherry 2}) + +; getting enumeration value: +(get fruits 'apple -1) ; ==> 0 +; or simply +(fruits 'apple) ; ==> 0 +; or simply with default (for non existent enumeration key) value +(fruits 'carrot -1) ; ==> -1 diff --git a/Task/Enumerations/Ol/enumerations-2.ol b/Task/Enumerations/Ol/enumerations-2.ol new file mode 100644 index 0000000000..97bab0a9ab --- /dev/null +++ b/Task/Enumerations/Ol/enumerations-2.ol @@ -0,0 +1,10 @@ +; simple function to create enumeration with autoassigning values +(define (make-enumeration . args) + (fold (lambda (ff arg i) + (put ff arg i)) + #empty + args + (iota (length args)))) + +(make-enumeration 'apple 'banana 'cherry) +; ==> '#ff((apple . 0) (banana . 1) (cherry . 2)) diff --git a/Task/Enumerations/Prolog/enumerations.pro b/Task/Enumerations/Prolog/enumerations.pro new file mode 100644 index 0000000000..2d6339a8bd --- /dev/null +++ b/Task/Enumerations/Prolog/enumerations.pro @@ -0,0 +1,7 @@ +fruit(apple,1). +fruit(banana,2). +fruit(cherry,4). + +write_fruit_name(N) :- + fruit(Name,N), + format('It is a ~p~n', Name). diff --git a/Task/Enumerations/Retro/enumerations.retro b/Task/Enumerations/Retro/enumerations.retro new file mode 100644 index 0000000000..b379db89c7 --- /dev/null +++ b/Task/Enumerations/Retro/enumerations.retro @@ -0,0 +1,3 @@ +'/examples/enum.retro include + +{ 'a=10 'b 'c 'd=998 'e 'f } a:enum diff --git a/Task/Environment-variables/Pike/environment-variables.pike b/Task/Environment-variables/Pike/environment-variables.pike new file mode 100644 index 0000000000..9e8aed43ec --- /dev/null +++ b/Task/Environment-variables/Pike/environment-variables.pike @@ -0,0 +1 @@ +write("%s\n", getenv("SHELL")); diff --git a/Task/Equilibrium-index/Elena/equilibrium-index.elena b/Task/Equilibrium-index/Elena/equilibrium-index.elena index 3fa13b73dc..b3082900a2 100644 --- a/Task/Equilibrium-index/Elena/equilibrium-index.elena +++ b/Task/Equilibrium-index/Elena/equilibrium-index.elena @@ -63,6 +63,6 @@ class EquilibriumEnumerator : Enumerator public program() { - new EquilibriumEnumerator(new int[]{ -7, 1, 5, 2, -4, 3, 0 }) + new EquilibriumEnumerator(new int[]::( -7, 1, 5, 2, -4, 3, 0 )) .forEach:printingLn } diff --git a/Task/Equilibrium-index/Haskell/equilibrium-index-1.hs b/Task/Equilibrium-index/Haskell/equilibrium-index-1.hs index 058a75aa18..52d8a0a59f 100644 --- a/Task/Equilibrium-index/Haskell/equilibrium-index-1.hs +++ b/Task/Equilibrium-index/Haskell/equilibrium-index-1.hs @@ -1,11 +1,11 @@ import System.Random (randomRIO) import Data.List (elemIndices, takeWhile) -import Control.Monad (replicateM, liftM2) +import Control.Monad (replicateM) import Control.Arrow ((&&&)) -equilibr xs = elemIndices True . map (uncurry $ (. sum) . (==) . sum) . - takeWhile (not . null . snd) $ map (flip (liftM2 (&&&) take $ drop . pred) xs) [1..] +equilibr xs = + elemIndices True . + map (\(a, b) -> sum a == sum b) . takeWhile (not . null . snd) $ + flip ((&&&) <$> take <*> (drop . pred)) xs <$> [1 ..] -langeSliert = - replicateM 2000 (randomRIO (-15,15) :: IO Int) - >>= print . equilibr +langeSliert = replicateM 2000 (randomRIO (-15, 15) :: IO Int) >>= print . equilibr diff --git a/Task/Evaluate-binomial-coefficients/Fortran/evaluate-binomial-coefficients.f b/Task/Evaluate-binomial-coefficients/Fortran/evaluate-binomial-coefficients-1.f similarity index 100% rename from Task/Evaluate-binomial-coefficients/Fortran/evaluate-binomial-coefficients.f rename to Task/Evaluate-binomial-coefficients/Fortran/evaluate-binomial-coefficients-1.f diff --git a/Task/Evaluate-binomial-coefficients/Fortran/evaluate-binomial-coefficients-2.f b/Task/Evaluate-binomial-coefficients/Fortran/evaluate-binomial-coefficients-2.f new file mode 100644 index 0000000000..11b782e148 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Fortran/evaluate-binomial-coefficients-2.f @@ -0,0 +1,43 @@ +program binomial + integer :: i, j + + do j=1,20 + write(*,fmt='(i2,a)',advance='no') j,'Cr = ' + do i=0,j + write(*,fmt='(i0,a)',advance='no') n_C_r(j,i),' ' + end do + write(*,'(a,i0)') ' 60C30 = ',n_C_r(60,30) + end do + stop + +contains + + pure function n_C_r(n, r) result(bin) + integer(16) :: bin + integer, intent(in) :: n + integer, intent(in) :: r + + integer(16) :: num + integer(16) :: den + integer :: i + integer :: k + integer, parameter :: primes(*) = [2,3,5,7,11,13,17,19] + num = 1 + den = 1 + do i=0,r-1 + num = num*(n-i) + den = den*(i+1) + if (i > 0) then + ! Divide out common prime factors + do k=1,size(primes) + if (mod(i,primes(k)) == 0) then + num = num/primes(k) + den = den/primes(k) + end if + end do + end if + end do + bin = num/den + end function n_C_r + +end program binomial diff --git a/Task/Evaluate-binomial-coefficients/Java/evaluate-binomial-coefficients-1.java b/Task/Evaluate-binomial-coefficients/Java/evaluate-binomial-coefficients-1.java index dd16e2015d..1bb18bb19f 100644 --- a/Task/Evaluate-binomial-coefficients/Java/evaluate-binomial-coefficients-1.java +++ b/Task/Evaluate-binomial-coefficients/Java/evaluate-binomial-coefficients-1.java @@ -1,18 +1,71 @@ -public class Binomial -{ - private static long binomial(int n, int k) - { - if (k>n-k) - k=n-k; +public class Binomial { - long b=1; - for (int i=1, m=n; i<=k; i++, m--) - b=b*m/i; - return b; + // precise, but may overflow and then produce completely incorrect results + private static long binomialInt(int n, int k) { + if (k > n - k) + k = n - k; + + long binom = 1; + for (int i = 1; i <= k; i++) + binom = binom * (n + 1 - i) / i; + return binom; } - public static void main(String[] args) - { - System.out.println(binomial(5, 3)); + // same as above, but with overflow check + private static Object binomialIntReliable(int n, int k) { + if (k > n - k) + k = n - k; + + long binom = 1; + for (int i = 1; i <= k; i++) { + try { + binom = Math.multiplyExact(binom, n + 1 - i) / i; + } catch (ArithmeticException e) { + return "overflow"; + } + } + return binom; + } + + // using floating point arithmetic, larger numbers can be calculated, + // but with reduced precision + private static double binomialFloat(int n, int k) { + if (k > n - k) + k = n - k; + + double binom = 1.0; + for (int i = 1; i <= k; i++) + binom = binom * (n + 1 - i) / i; + return binom; + } + + // slow, hard to read, but precise + private static BigInteger binomialBigInt(int n, int k) { + if (k > n - k) + k = n - k; + + BigInteger binom = BigInteger.ONE; + for (int i = 1; i <= k; i++) { + binom = binom.multiply(BigInteger.valueOf(n + 1 - i)); + binom = binom.divide(BigInteger.valueOf(i)); + } + return binom; + } + + private static void demo(int n, int k) { + List data = Arrays.asList( + n, + k, + binomialInt(n, k), + binomialIntReliable(n, k), + binomialFloat(n, k), + binomialBigInt(n, k)); + + System.out.println(data.stream().map(Object::toString).collect(Collectors.joining("\t"))); + } + + public static void main(String[] args) { + demo(5, 3); + demo(1000, 300); } } diff --git a/Task/Evaluate-binomial-coefficients/Java/evaluate-binomial-coefficients-2.java b/Task/Evaluate-binomial-coefficients/Java/evaluate-binomial-coefficients-2.java index 33cc125459..7cdb3118a1 100644 --- a/Task/Evaluate-binomial-coefficients/Java/evaluate-binomial-coefficients-2.java +++ b/Task/Evaluate-binomial-coefficients/Java/evaluate-binomial-coefficients-2.java @@ -1,13 +1,17 @@ -public class Binom { - public static double binomCoeff(double n, double k) { - double result = 1; - for (int i = 1; i < k + 1; i++) { - result *= (n - i + 1) / i; - } - return result; +public class Binomial +{ + private static long binom(int n, int k) + { + if (k==0) + return 1; + else if (k>n-k) + return binom(n, n-k); + else + return binom(n-1, k-1)*n/k; } - public static void main(String[] args) { - System.out.println(binomCoeff(5, 3)); + public static void main(String[] args) + { + System.out.println(binom(5, 3)); } } diff --git a/Task/Evaluate-binomial-coefficients/Julia/evaluate-binomial-coefficients-2.julia b/Task/Evaluate-binomial-coefficients/Julia/evaluate-binomial-coefficients-2.julia index f042ce7628..a774931be7 100644 --- a/Task/Evaluate-binomial-coefficients/Julia/evaluate-binomial-coefficients-2.julia +++ b/Task/Evaluate-binomial-coefficients/Julia/evaluate-binomial-coefficients-2.julia @@ -1,8 +1,8 @@ function binom(n::Integer, k::Integer) - n ≥ k || return 0 # short circuit base cases - n == 1 || k == 0 && return 1 + n ≥ k || return 0 # short circuit base cases + (n == 1 || k == 0) && return 1 - return (n * binom(n - 1, k - 1)) ÷ k + n * binom(n - 1, k - 1) ÷ k end @show binom(5, 3) diff --git a/Task/Evaluate-binomial-coefficients/Phix/evaluate-binomial-coefficients-1.phix b/Task/Evaluate-binomial-coefficients/Phix/evaluate-binomial-coefficients-1.phix index 6a4fe30249..082e5edfdf 100644 --- a/Task/Evaluate-binomial-coefficients/Phix/evaluate-binomial-coefficients-1.phix +++ b/Task/Evaluate-binomial-coefficients/Phix/evaluate-binomial-coefficients-1.phix @@ -1,5 +1,7 @@ -function binom(integer n, k) - return factorial(n)/(factorial(k)*factorial(n-k)) +global function choose(integer n, k) + atom res = 1 + for i=1 to k do + res = (res*(n-i+1))/i + end for + return res end function - -?binom(5,3) diff --git a/Task/Evaluate-binomial-coefficients/Phix/evaluate-binomial-coefficients-2.phix b/Task/Evaluate-binomial-coefficients/Phix/evaluate-binomial-coefficients-2.phix index e39d56798b..9e08909afb 100644 --- a/Task/Evaluate-binomial-coefficients/Phix/evaluate-binomial-coefficients-2.phix +++ b/Task/Evaluate-binomial-coefficients/Phix/evaluate-binomial-coefficients-2.phix @@ -1,16 +1 @@ -include builtins\mpfr.e - -function mpz_binom(integer n, k) -mpz r = mpz_init(1) - for i=1 to k do - mpz_mul_si(r,r,n-i+1) - if mpz_fdiv_q_ui(r, r, i)!=0 then ?9/0 end if --- r = ba_divide(ba_multiply(r,n-i+1),i) - end for - return mpz_get_str(r) -end function - -?mpz_binom(5,3) -?mpz_binom(100,50) -?mpz_binom(60,30) -?mpz_binom(1200,120) +?choose(5,3) diff --git a/Task/Evaluate-binomial-coefficients/Phix/evaluate-binomial-coefficients-3.phix b/Task/Evaluate-binomial-coefficients/Phix/evaluate-binomial-coefficients-3.phix new file mode 100644 index 0000000000..6f7e0d4ed9 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Phix/evaluate-binomial-coefficients-3.phix @@ -0,0 +1,5 @@ +include builtins\mpfr.e +?mpz_get_str(mpz_binom(5,3)) +?mpz_get_str(mpz_binom(100,50)) +?mpz_get_str(mpz_binom(60,30)) +?mpz_get_str(mpz_binom(1200,120)) diff --git a/Task/Evaluate-binomial-coefficients/Scheme/evaluate-binomial-coefficients.ss b/Task/Evaluate-binomial-coefficients/Scheme/evaluate-binomial-coefficients-1.ss similarity index 100% rename from Task/Evaluate-binomial-coefficients/Scheme/evaluate-binomial-coefficients.ss rename to Task/Evaluate-binomial-coefficients/Scheme/evaluate-binomial-coefficients-1.ss diff --git a/Task/Evaluate-binomial-coefficients/Scheme/evaluate-binomial-coefficients-2.ss b/Task/Evaluate-binomial-coefficients/Scheme/evaluate-binomial-coefficients-2.ss new file mode 100644 index 0000000000..f0a72ddd7c --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Scheme/evaluate-binomial-coefficients-2.ss @@ -0,0 +1,12 @@ +(define (pascal i j) + (cond ((= i 0) 1) + ((= j 0) 1) + (else (+ + (pascal (- i 1) j) + (pascal i (- j 1)))))) + +(define (choose n k) + (pascal (- n k) k))) + +(display (choose 5 3)) +(newline) diff --git a/Task/Evaluate-binomial-coefficients/Swift/evaluate-binomial-coefficients.swift b/Task/Evaluate-binomial-coefficients/Swift/evaluate-binomial-coefficients.swift new file mode 100644 index 0000000000..d3c63fe647 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Swift/evaluate-binomial-coefficients.swift @@ -0,0 +1,17 @@ +func factorial(_ n: T) -> T { + guard n != 0 else { + return 1 + } + + return stride(from: n, to: 0, by: -1).reduce(1, *) +} + +func binomial(_ x: (n: T, k: T)) -> T { + let nFac = factorial(x.n) + let kFac = factorial(x.k) + + return nFac / (factorial(x.n - x.k) * kFac) +} + +print("binomial(\(5), \(3)) = \(binomial((5, 3)))") +print("binomial(\(20), \(11)) = \(binomial((20, 11)))") diff --git a/Task/Even-or-odd/BASIC/even-or-odd-2.basic b/Task/Even-or-odd/BASIC/even-or-odd-2.basic index 6b8730486b..c0f2c155e6 100644 --- a/Task/Even-or-odd/BASIC/even-or-odd-2.basic +++ b/Task/Even-or-odd/BASIC/even-or-odd-2.basic @@ -1,7 +1,7 @@ -100 DEF ODD(X)=MOD(X,2) -110 INPUT PROMPT "Enter a number: ":X -120 IF ODD(X) THEN -130 PRINT X;"is odd." -140 ELSE -150 PRINT X;"is even." -160 END IF +10 rem determine if integer is even or odd +20 print "Enter an integer:"; +30 input i% +35 print +40 eo$="even" +50 if (i% and 1)=1 then eo$="odd" +60 print "The number ";i%;"is ";eo$;"." diff --git a/Task/Even-or-odd/BASIC/even-or-odd-3.basic b/Task/Even-or-odd/BASIC/even-or-odd-3.basic new file mode 100644 index 0000000000..6b8730486b --- /dev/null +++ b/Task/Even-or-odd/BASIC/even-or-odd-3.basic @@ -0,0 +1,7 @@ +100 DEF ODD(X)=MOD(X,2) +110 INPUT PROMPT "Enter a number: ":X +120 IF ODD(X) THEN +130 PRINT X;"is odd." +140 ELSE +150 PRINT X;"is even." +160 END IF diff --git a/Task/Even-or-odd/LOLCODE/even-or-odd.lol b/Task/Even-or-odd/LOLCODE/even-or-odd.lol new file mode 100644 index 0000000000..3d6eb3cacf --- /dev/null +++ b/Task/Even-or-odd/LOLCODE/even-or-odd.lol @@ -0,0 +1,12 @@ +HAI 1.4 +I HAS A integer +GIMMEH integer +I HAS A remainder +remainder R MOD OF integer AN 2 +BOTH SAEM remainder AN 1, O RLY? +YA RLY +VISIBLE "The integer is odd." +NO WAI +VISIBLE "The integer is even." +OIC +KTHXBYE diff --git a/Task/Even-or-odd/Ol/even-or-odd.ol b/Task/Even-or-odd/Ol/even-or-odd.ol new file mode 100644 index 0000000000..baf58ba066 --- /dev/null +++ b/Task/Even-or-odd/Ol/even-or-odd.ol @@ -0,0 +1,32 @@ +; 1. Check the least significant bit. +(define (even? i) + (if (eq? (band i 1) 0) #t #f)) +(define (odd? i) + (if (eq? (band i 1) 1) #t #f)) + +(print (if (even? 12345678987654321) "even" "odd")) ; ==> odd +(print (if (odd? 12345678987654321) "odd" "even")) ; ==> odd +(print (if (even? 1234567898765432) "even" "odd")) ; ==> even +(print (if (odd? 1234567898765432) "odd" "even")) ; ==> even + +; 2. Divide i by 2. The remainder equals 0 iff i is even. +(define (even? i) + (if (eq? (remainder i 2) 0) #t #f)) +(define (odd? i) + (if (eq? (remainder i 2) 1) #t #f)) + +(print (if (even? 12345678987654321) "even" "odd")) ; ==> odd +(print (if (odd? 12345678987654321) "odd" "even")) ; ==> odd +(print (if (even? 1234567898765432) "even" "odd")) ; ==> even +(print (if (odd? 1234567898765432) "odd" "even")) ; ==> even + +; 3. Use modular congruences. Same as 2. +(define (even? i) + (if (eq? (mod i 2) 0) #t #f)) +(define (odd? i) + (if (eq? (mod i 2) 1) #t #f)) + +(print (if (even? 12345678987654321) "even" "odd")) ; ==> odd +(print (if (odd? 12345678987654321) "odd" "even")) ; ==> odd +(print (if (even? 1234567898765432) "even" "odd")) ; ==> even +(print (if (odd? 1234567898765432) "odd" "even")) ; ==> even diff --git a/Task/Events/Nim/events.nim b/Task/Events/Nim/events-1.nim similarity index 100% rename from Task/Events/Nim/events.nim rename to Task/Events/Nim/events-1.nim diff --git a/Task/Events/Nim/events-2.nim b/Task/Events/Nim/events-2.nim new file mode 100644 index 0000000000..09dd34b233 --- /dev/null +++ b/Task/Events/Nim/events-2.nim @@ -0,0 +1,30 @@ +import locks +from os import sleep +from times import cpuTime +from strformat import fmt + +var + # condition variable which shared across threads + cond: Cond + lock: Lock + threadproc: Thread[void] + +proc waiting {.thread.} = + echo "spawned waiting proc" + let start = cpuTime() + cond.wait lock + echo fmt"thread ended after waiting: {cpuTime() - start} seconds." + +proc main = + initCond cond + initLock lock + threadproc.createThread waiting + echo "in main proc" + os.sleep 1000 + echo "send signal/event notification" + signal cond + joinThread threadproc + deinitCond cond + deinitLock lock + +main() diff --git a/Task/Evolutionary-algorithm/Elena/evolutionary-algorithm.elena b/Task/Evolutionary-algorithm/Elena/evolutionary-algorithm.elena index b3ccfcfa84..72231a0659 100644 --- a/Task/Evolutionary-algorithm/Elena/evolutionary-algorithm.elena +++ b/Task/Evolutionary-algorithm/Elena/evolutionary-algorithm.elena @@ -65,7 +65,7 @@ class EvoAlgorithm : Enumerator public program() { var attempt := new Integer(); - EvoAlgorithm.new:Target of:C.forEach:(current) + EvoAlgorithm.new:Target &of:C.forEach:(current) { console .printPaddingLeft(10,"#",attempt.append(1)) diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Crystal/exceptions-catch-an-exception-thrown-in-a-nested-call.crystal b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Crystal/exceptions-catch-an-exception-thrown-in-a-nested-call.crystal new file mode 100644 index 0000000000..f2fb861ffb --- /dev/null +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Crystal/exceptions-catch-an-exception-thrown-in-a-nested-call.crystal @@ -0,0 +1,26 @@ +class U0 < Exception +end + +class U1 < Exception +end + +def foo + 2.times do |i| + begin + bar(i) + rescue e : U0 + puts "rescued #{e}" + end + end +end + +def bar(i : Int32) + baz(i) +end + +def baz(i : Int32) + raise U0.new("this is u0") if i == 0 + raise U1.new("this is u1") if i == 1 +end + +foo diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Elena/exceptions-catch-an-exception-thrown-in-a-nested-call.elena b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Elena/exceptions-catch-an-exception-thrown-in-a-nested-call.elena index 6c685fffcd..ee315f1077 100644 --- a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Elena/exceptions-catch-an-exception-thrown-in-a-nested-call.elena +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Elena/exceptions-catch-an-exception-thrown-in-a-nested-call.elena @@ -31,7 +31,7 @@ singleton Exceptions { self.bar() } - catch(U0 e) + catch:(U0 e) { console.printLine("U0 Caught") } diff --git a/Task/Exceptions/Elena/exceptions-1.elena b/Task/Exceptions/Elena/exceptions-1.elena index faf309c954..6c2d52d46d 100644 --- a/Task/Exceptions/Elena/exceptions-1.elena +++ b/Task/Exceptions/Elena/exceptions-1.elena @@ -1,5 +1,5 @@ class MyException : Exception { constructor new() - <= new:"MyException raised"; + <= new("MyException raised"); } diff --git a/Task/Exceptions/Elena/exceptions-3.elena b/Task/Exceptions/Elena/exceptions-3.elena index bd8ff3361c..2fb968c3a6 100644 --- a/Task/Exceptions/Elena/exceptions-3.elena +++ b/Task/Exceptions/Elena/exceptions-3.elena @@ -2,7 +2,7 @@ try { o.foo() } -catch(MyException e) +catch:(MyException e) { // handle exceptions of type MyException and derived } diff --git a/Task/Exceptions/Rust/exceptions.rust b/Task/Exceptions/Rust/exceptions.rust new file mode 100644 index 0000000000..54d16cc87f --- /dev/null +++ b/Task/Exceptions/Rust/exceptions.rust @@ -0,0 +1,51 @@ +// IO error is used here just as an example of an already existing +// Error +use std::io::{Error, ErrorKind}; + +// Rust technically doesn't have exception, but different +// types of error handling. Here are two examples of results. + +fn valid_function() -> Result { + Ok(100) +} + +fn errored_function() -> Result { + Err(Error::new(ErrorKind::Other, "Something wrong happened.")) +} + +// This should happen only when an unrecoverable error happened +fn panicking_function() { + panic!("Unrecoverable state reached"); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_valid_function() { + let result = match valid_function() { + Ok(number) => number, + Err(_) => panic!("This is not going to happen"), + }; + assert_eq!(result, 100); + } + + #[test] + fn test_errored_function() { + let result = match errored_function() { + Ok(_) => panic!("This is not going to happen"), + Err(e) => { + assert_eq!(e.to_string(), "Something wrong happened."); + 0 + } + }; + assert_eq!(result, 0); + } + + #[test] + #[should_panic] + fn test_panicking_function() { + panicking_function(); + } +} diff --git a/Task/Executable-library/00DESCRIPTION b/Task/Executable-library/00DESCRIPTION index 2eab143dd7..60d78f9c2a 100644 --- a/Task/Executable-library/00DESCRIPTION +++ b/Task/Executable-library/00DESCRIPTION @@ -1,5 +1,4 @@ {{omit from|GUISS}} -{{omit from|Go}} {{omit from|MATLAB}} {{omit from|Maxima}} {{omit from|Octave}} diff --git a/Task/Executable-library/Go/executable-library-1.go b/Task/Executable-library/Go/executable-library-1.go new file mode 100644 index 0000000000..eb870a50b4 --- /dev/null +++ b/Task/Executable-library/Go/executable-library-1.go @@ -0,0 +1,37 @@ +// modulino.go +package main + +import "fmt" + +// Function borrowed from Hailstone sequence task. +// 1st arg is the number to generate the sequence for. +// 2nd arg is a slice to recycle, to reduce garbage. +func hailstone(n int, recycle []int) []int { + s := append(recycle[:0], n) + for n > 1 { + if n&1 == 0 { + n = n / 2 + } else { + n = 3*n + 1 + } + s = append(s, n) + } + return s +} + +func libMain() { + seq := hailstone(27, nil) + fmt.Println("\nHailstone sequence for the number 27:") + fmt.Println(" has", len(seq), "elements") + fmt.Println(" starts with", seq[0:4]) + fmt.Println(" ends with", seq[len(seq)-4:]) + + var longest, length int + for i := 1; i < 100000; i++ { + if le := len(hailstone(i, nil)); le > length { + longest = i + length = le + } + } + fmt.Printf("\n%d has the longest Hailstone sequence, its length being %d.\n", longest, length) +} diff --git a/Task/Executable-library/Go/executable-library-2.go b/Task/Executable-library/Go/executable-library-2.go new file mode 100644 index 0000000000..f11aadf29e --- /dev/null +++ b/Task/Executable-library/Go/executable-library-2.go @@ -0,0 +1,6 @@ +// modulino_main.go +package main + +func main() { + libMain() +} diff --git a/Task/Executable-library/Go/executable-library-3.go b/Task/Executable-library/Go/executable-library-3.go new file mode 100644 index 0000000000..cbf21b184a --- /dev/null +++ b/Task/Executable-library/Go/executable-library-3.go @@ -0,0 +1,19 @@ +// hailstone.go +package main + +import "fmt" + +func main() { + freq := make(map[int]int) + for i := 1; i < 100000; i++ { + freq[len(hailstone(i, nil))]++ + } + var mk, mv int + for k, v := range freq { + if v > mv { + mk = k + mv = v + } + } + fmt.Printf("\nThe Hailstone length returned most is %d, which occurs %d times.\n", mk, mv) +} diff --git a/Task/Executable-library/Phix/executable-library-1.phix b/Task/Executable-library/Phix/executable-library-1.phix index c14ab8f9c4..b7420fd59b 100644 --- a/Task/Executable-library/Phix/executable-library-1.phix +++ b/Task/Executable-library/Phix/executable-library-1.phix @@ -1,20 +1,3 @@ -function isMainOrInclude() --- returns 1 if called from the main file, 0 if from an include -integer res - #ilASM{ - [32] - mov eax,[ebp+20] -- prev_ebp - mov eax,[eax+8] -- rtn - mov [res],eax - [64] - mov rax,[rbp+40] -- prev_ebp - mov rax,[rax+16] -- rtn - mov [res],rax - [] - } - return res=21 -- (21=T_maintls) -end function - --global (if you want to be able to call this from test.exw) function hailstone(atom n) sequence s = {n} @@ -42,7 +25,7 @@ integer count = 1 return count end function -if isMainOrInclude() then +if include_file()==1 then sequence s = hailstone(27) integer ls = length(s) diff --git a/Task/Executable-library/Scala/executable-library.scala b/Task/Executable-library/Scala/executable-library.scala index 00b67c5efd..a053ac0e9f 100644 --- a/Task/Executable-library/Scala/executable-library.scala +++ b/Task/Executable-library/Scala/executable-library.scala @@ -1,19 +1,20 @@ object HailstoneSequence extends App { // Show it all, default number is 27. - def hailstone(n: Int): Stream[Int] = - n #:: (if (n == 1) Stream.empty else hailstone(if (n % 2 == 0) n / 2 else n * 3 + 1)) + def hailstone(n: Int): LazyList[Int] = + n #:: (if (n == 1) LazyList.empty else hailstone(if (n % 2 == 0) n / 2 else n * 3 + 1)) Hailstone.details(args.headOption.map(_.toInt).getOrElse(27)) HailTest.main(Array()) } object Hailstone extends App { // Compute a given or default number to Hailstone sequence - def details(nr: Int) = { + def details(nr: Int): Unit = { val collatz = HailstoneSequence.hailstone(nr) println(s"Use the routine to show that the hailstone sequence for the number: $nr.") println(collatz.toList) println(s"It has ${collatz.length} elements.") } + details(args.headOption.map(_.toInt).getOrElse(27)) } diff --git a/Task/Execute-Brain----/UNIX-Shell/execute-brain----.sh b/Task/Execute-Brain----/UNIX-Shell/execute-brain----.sh new file mode 100644 index 0000000000..01b446f362 --- /dev/null +++ b/Task/Execute-Brain----/UNIX-Shell/execute-brain----.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# BrainF*** interpreter in bash +if (( ! $# )); then + printf >&2 'Usage: %s program-file\n' "$0" + exit 1 +fi + +# load the program +exec 3<"$1" +program=() +while IFS= read -r line <&3; do + mapfile -t instr < <(tr -cd '[]<>.,+-' <<<"$line" | sed $'s/./&\\\n/g') + program+=("${instr[@]}") +done +exec 3<&- + +# parse loops +loops=() +matches=() +for pc in "${!program[@]}"; do + instr=${program[pc]} + if [[ $instr == '[' ]]; then + loops=("$pc" "${loops[@]}") + elif [[ $instr == ']' ]]; then + matches[$pc]=${loops[0]} + matches[${loops[0]}]=$pc + loops=(${loops[@]:1}) + fi +done + +# execute program +memory=(0) +mp=0 +pc=0 +while (( pc < ${#program[@]} )); do + instr=${program[pc]} + (( pc+=1 )) + mem=${memory[mp]} + case "$instr" in + '[') if (( ! mem )); then (( pc=${matches[pc-1]}+1 )); fi;; + ']') if (( mem )); then (( pc=${matches[pc-1]}+1 )); fi;; + +) memory[mp]=$(( (mem + 1) % 256 ));; + -) memory[mp]=$(( (mem - 1) % 256 ));; + '>') (( mp+=1 )); if (( mp >= ${#memory[@]} )); then memory+=(0); fi;; + '<') (( mp-=1 )); if (( mp < 0 )); then memory=(0 "${memory[@]}"); mp=0; fi;; + .) printf %b $(printf '\\%03o' "$mem");; + ,) read -n1 c; memory[mp]=$(LC_CTYPE=C printf '%d' "'$c");; + esac +done diff --git a/Task/Execute-a-Markov-algorithm/PHP/execute-a-markov-algorithm.php b/Task/Execute-a-Markov-algorithm/PHP/execute-a-markov-algorithm.php new file mode 100644 index 0000000000..26406e9122 --- /dev/null +++ b/Task/Execute-a-Markov-algorithm/PHP/execute-a-markov-algorithm.php @@ -0,0 +1,147 @@ +' . $spc . '(\.?)(.*)$/', $line, $matches)) { + list($dummy, $pattern, $terminating, $replacement) = $matches; + $rules[] = array( + 'pattern' => trim($pattern), + 'terminating' => ($terminating === '.'), + 'replacement' => trim($replacement), + ); + } + } + do { + $found = false; + foreach ($rules AS $rule) { + if (strpos($text, $rule['pattern']) !== FALSE) { + $text = str_replace($rule['pattern'], $rule['replacement'], $text); + if ($rule['terminating']) { + return $text; + } + $found = true; + break; + } + } + } while($found); + return $text; +} + +$conf = array( + 1 => array( + 'text' => 'I bought a B of As from T S.', + 'rule' => ' + # 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 + ', + ), + 2 => array( + 'text' => 'I bought a B of As from T S.', + 'rule' => ' + # Slightly modified from the rules on Wikipedia + A -> apple + B -> bag + S -> .shop + T -> the + the shop -> my brother + a never used -> .terminating rule + ', + ), + 3 => array( + 'text' => 'I bought a B of As W my Bgage from T S.', + 'rule' => ' + # 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 + ', + ), + 4 => array( + 'text' => '_1111*11111_', + 'rule' => ' + ### 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 + _+_ -> + ', + ), + 5 => array( + 'text' => '000000A000000', + 'rule' => ' + # 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 + ', + ), + 6 => array( + 'text' => '101', + 'rule' => ' + # Another example extracted from Wikipedia: + # http://en.wikipedia.org/wiki/Markov_Algorithm + 1 -> 0| + |0 -> 0|| + 0 -> + ', + ), +); + +foreach ($conf AS $id => $rule) { + echo 'Ruleset ', $id, ' : ', markov($rule['text'], $rule['rule']), PHP_EOL; +} diff --git a/Task/Execute-a-system-command/Visual-Basic-.NET/execute-a-system-command.visual b/Task/Execute-a-system-command/Visual-Basic-.NET/execute-a-system-command.visual new file mode 100644 index 0000000000..c08b430a15 --- /dev/null +++ b/Task/Execute-a-system-command/Visual-Basic-.NET/execute-a-system-command.visual @@ -0,0 +1,20 @@ +Module System_Command + + Sub Main() + Dim cmd As New Process + cmd.StartInfo.FileName = "cmd.exe" + cmd.StartInfo.RedirectStandardInput = True + cmd.StartInfo.RedirectStandardOutput = True + cmd.StartInfo.CreateNoWindow = True + cmd.StartInfo.UseShellExecute = False + + cmd.Start() + + cmd.StandardInput.WriteLine("dir") + cmd.StandardInput.Flush() + cmd.StandardInput.Close() + + Console.WriteLine(cmd.StandardOutput.ReadToEnd) + End Sub + +End Module diff --git a/Task/Exponentiation-operator/Kotlin/exponentiation-operator.kotlin b/Task/Exponentiation-operator/Kotlin/exponentiation-operator.kotlin index 2fc03baf58..a4b8644768 100644 --- a/Task/Exponentiation-operator/Kotlin/exponentiation-operator.kotlin +++ b/Task/Exponentiation-operator/Kotlin/exponentiation-operator.kotlin @@ -3,19 +3,19 @@ infix fun Int.ipow(exp: Int): Int = when { this == 1 -> 1 - this == -1 -> if (exp % 2 == 0) 1 else -1 + this == -1 -> if (exp and 1 == 0) 1 else -1 exp < 0 -> throw IllegalArgumentException("invalid exponent") exp == 0 -> 1 else -> { var ans = 1 var base = this var e = exp - while (e > 0) { + while (e > 1) { if (e and 1 == 1) ans *= base e = e shr 1 base *= base } - ans + ans * base } } diff --git a/Task/Extend-your-language/00DESCRIPTION b/Task/Extend-your-language/00DESCRIPTION index c830736c5e..2c979e0b5a 100644 --- a/Task/Extend-your-language/00DESCRIPTION +++ b/Task/Extend-your-language/00DESCRIPTION @@ -1,4 +1,4 @@ -{{Control Structures}}{{omit from|BBC BASIC}} +{{Control Structures}} Some programming languages allow you to [[wp:Extensible_programming|extend]] the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements. If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch: diff --git a/Task/Extensible-prime-generator/Factor/extensible-prime-generator.factor b/Task/Extensible-prime-generator/Factor/extensible-prime-generator.factor new file mode 100644 index 0000000000..d15f6e9251 --- /dev/null +++ b/Task/Extensible-prime-generator/Factor/extensible-prime-generator.factor @@ -0,0 +1,13 @@ +USING: io math.primes prettyprint sequences ; + +"First 20 primes: " write +20 nprimes . + +"Primes between 100 and 150: " write +100 150 primes-between . + +"Number of primes between 7,700 and 8,000: " write +7,700 8,000 primes-between length . + +"10,000th prime: " write +10,000 nprimes last . diff --git a/Task/Extreme-floating-point-values/Ol/extreme-floating-point-values.ol b/Task/Extreme-floating-point-values/Ol/extreme-floating-point-values.ol new file mode 100644 index 0000000000..9a59a67947 --- /dev/null +++ b/Task/Extreme-floating-point-values/Ol/extreme-floating-point-values.ol @@ -0,0 +1,6 @@ +(print "infinity: " (/ 1 (inexact 0)) +(print "minus infinity: " (/ -1 (inexact 0)) +(print "not-a-number: " (/ 0 (inexact 0)) + +; note: your must use equal? or eqv? but not eq? for comparison +(print "is this is not a number? " (equal? (/ 0 (inexact 0)) +nan.0)) diff --git a/Task/Factorial/BASIC/factorial-4.basic b/Task/Factorial/BASIC/factorial-4.basic index c7bdb340bc..04c527d9e7 100644 --- a/Task/Factorial/BASIC/factorial-4.basic +++ b/Task/Factorial/BASIC/factorial-4.basic @@ -1,7 +1,16 @@ -100 DEF FACT(N) -110 LET F=1 -120 FOR I=2 TO N -130 LET F=F*I -140 NEXT -150 LET FACT=F -160 END DEF +100 REM FACTORIAL +110 DIM F(35): F(0)=1: REM MEMOS +120 DIM S(35): SP=0: REM STACK+PTR +130 FOR I=1 TO 13 +140 : S(SP)=I: SP=SP+1: REM PUSH(I) +150 : GOSUB 200 +160 : SP=SP-1: REM POP +170 : PRINT I;"! = ";S(SP) +180 NEXT I +190 END +200 REM FACTORIAL: S(SP-1) = S(SP-1)! +210 IF F(S(SP-1)) THEN 240: REM MEMOIZED +220 S(SP)=S(SP-1)-1: SP=SP+1: GOSUB 200: REM RECURSE +230 SP=SP-1: F(S(SP-1))=S(SP-1)*S(SP): REM MEMOIZE +240 S(SP-1)=F(S(SP-1)): REM PUSH(RESULT) +250 RETURN diff --git a/Task/Factorial/BASIC/factorial-5.basic b/Task/Factorial/BASIC/factorial-5.basic index ed2c8cd76d..c7bdb340bc 100644 --- a/Task/Factorial/BASIC/factorial-5.basic +++ b/Task/Factorial/BASIC/factorial-5.basic @@ -1,6 +1,7 @@ - 10 INPUT N - 20 LET FACT=1 - 30 FOR I=2 TO N - 40 LET FACT=FACT*I - 50 NEXT I - 60 PRINT FACT +100 DEF FACT(N) +110 LET F=1 +120 FOR I=2 TO N +130 LET F=F*I +140 NEXT +150 LET FACT=F +160 END DEF diff --git a/Task/Factorial/BASIC/factorial-6.basic b/Task/Factorial/BASIC/factorial-6.basic index 211173100d..ed2c8cd76d 100644 --- a/Task/Factorial/BASIC/factorial-6.basic +++ b/Task/Factorial/BASIC/factorial-6.basic @@ -1,10 +1,6 @@ 10 INPUT N 20 LET FACT=1 - 30 GOSUB 60 - 40 PRINT FACT - 50 STOP - 60 IF N=0 THEN RETURN - 70 LET FACT=FACT*N - 80 LET N=N-1 - 90 GOSUB 60 -100 RETURN + 30 FOR I=2 TO N + 40 LET FACT=FACT*I + 50 NEXT I + 60 PRINT FACT diff --git a/Task/Factorial/BASIC/factorial-7.basic b/Task/Factorial/BASIC/factorial-7.basic new file mode 100644 index 0000000000..211173100d --- /dev/null +++ b/Task/Factorial/BASIC/factorial-7.basic @@ -0,0 +1,10 @@ + 10 INPUT N + 20 LET FACT=1 + 30 GOSUB 60 + 40 PRINT FACT + 50 STOP + 60 IF N=0 THEN RETURN + 70 LET FACT=FACT*N + 80 LET N=N-1 + 90 GOSUB 60 +100 RETURN diff --git a/Task/Factorial/Crystal/factorial-1.crystal b/Task/Factorial/Crystal/factorial-1.crystal new file mode 100644 index 0000000000..17e8dbae6c --- /dev/null +++ b/Task/Factorial/Crystal/factorial-1.crystal @@ -0,0 +1,7 @@ +def factorial(x : Int) + ans = 1 + (1..x).each do |i| + ans *= i + end + return ans +end diff --git a/Task/Factorial/Crystal/factorial-2.crystal b/Task/Factorial/Crystal/factorial-2.crystal new file mode 100644 index 0000000000..1ea1956ef8 --- /dev/null +++ b/Task/Factorial/Crystal/factorial-2.crystal @@ -0,0 +1,6 @@ +def factorial(x : Int) + if x <= 1 + return 1 + end + return x * factorial(x - 1) +end diff --git a/Task/Factorial/Emacs-Lisp/factorial-1.l b/Task/Factorial/Emacs-Lisp/factorial-1.l index d806098ba8..13de301a95 100644 --- a/Task/Factorial/Emacs-Lisp/factorial-1.l +++ b/Task/Factorial/Emacs-Lisp/factorial-1.l @@ -1,6 +1,11 @@ +;; Functional (most elegant and best suited to Lisp dialects): (defun fact (n) - "n is an integer, this function returns n!, that is n * (n - 1) -* (n - 2)....* 4 * 3 * 2 * 1" - (cond - ((= n 1) 1) - (t (* n (fact (1- 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.l b/Task/Factorial/Emacs-Lisp/factorial-2.l index 69ad879be5..aa44449526 100644 --- a/Task/Factorial/Emacs-Lisp/factorial-2.l +++ b/Task/Factorial/Emacs-Lisp/factorial-2.l @@ -1 +1,8 @@ -(defun fact (n) (apply '* (number-sequence 1 n))) +;; 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/Fortran/factorial-2.f b/Task/Factorial/Fortran/factorial-2.f index 6313a74fdd..a7ed84844a 100644 --- a/Task/Factorial/Fortran/factorial-2.f +++ b/Task/Factorial/Fortran/factorial-2.f @@ -1,6 +1,10 @@ - FUNCTION FACT(N) - INTEGER N,I,FACT - FACT=1 - DO 10 I=1,N - 10 FACT=FACT*I - END +INTEGER RECURSIVE FUNCTION RECURSIVE_FACTORIAL(X) RESULT(ANS) + INTEGER, INTENT(IN) :: X + + IF (X <= 1) THEN + ANS = 1 + ELSE + ANS = X * RECURSIVE_FACTORIAL(X-1) + END IF + +END FUNCTION RECURSIVE_FACTORIAL diff --git a/Task/Factorial/Fortran/factorial-3.f b/Task/Factorial/Fortran/factorial-3.f new file mode 100644 index 0000000000..6313a74fdd --- /dev/null +++ b/Task/Factorial/Fortran/factorial-3.f @@ -0,0 +1,6 @@ + FUNCTION FACT(N) + INTEGER N,I,FACT + FACT=1 + DO 10 I=1,N + 10 FACT=FACT*I + END diff --git a/Task/Factorial/Frink/factorial-1.frink b/Task/Factorial/Frink/factorial-1.frink index 01b86df06e..3010d48262 100644 --- a/Task/Factorial/Frink/factorial-1.frink +++ b/Task/Factorial/Frink/factorial-1.frink @@ -1 +1,6 @@ -factorial[x] := x! +// Calculate factorial with math operator +x = 5 +println[x!] + +// Calculate factorial with built-in function +println[factorial[x]] diff --git a/Task/Factorial/Frink/factorial-2.frink b/Task/Factorial/Frink/factorial-2.frink index a8fa509e5d..4bdf8d211a 100644 --- a/Task/Factorial/Frink/factorial-2.frink +++ b/Task/Factorial/Frink/factorial-2.frink @@ -1 +1,3 @@ +// Build factorial function with using a range and product function. factorial2[x] := product[1 to x] +println[factorial2[5]] diff --git a/Task/Factorial/Frink/factorial-3.frink b/Task/Factorial/Frink/factorial-3.frink new file mode 100644 index 0000000000..9414e4c5f3 --- /dev/null +++ b/Task/Factorial/Frink/factorial-3.frink @@ -0,0 +1,9 @@ +factorial3[x] := +{ + if x <= 1 + return 1 + else + return x * factorial3[x-1] // function calling itself +} + +println[factorial3[5]] diff --git a/Task/Factorial/Haxe/factorial-1.haxe b/Task/Factorial/Haxe/factorial-1.haxe new file mode 100644 index 0000000000..20d705e6a3 --- /dev/null +++ b/Task/Factorial/Haxe/factorial-1.haxe @@ -0,0 +1,6 @@ +static function factorial(n:Int):Int { + var result = 1; + while (1 1) { - sum *= n; + result *= n; n--; } - return sum; + return result; } diff --git a/Task/Factorial/Python/factorial-6.py b/Task/Factorial/Python/factorial-6.py index 5bf8836512..6566dd7509 100644 --- a/Task/Factorial/Python/factorial-6.py +++ b/Task/Factorial/Python/factorial-6.py @@ -1,5 +1,4 @@ +from numpy import prod + def factorial(n): - z=1 - if n>1: - z=n*factorial(n-1) - return z + return prod(range(1, n + 1), dtype=int) diff --git a/Task/Factorial/Python/factorial-7.py b/Task/Factorial/Python/factorial-7.py index 2e8331bac3..5bf8836512 100644 --- a/Task/Factorial/Python/factorial-7.py +++ b/Task/Factorial/Python/factorial-7.py @@ -1,27 +1,5 @@ -from cmath import * - -# Coefficients used by the GNU Scientific Library -g = 7 -p = [0.99999999999980993, 676.5203681218851, -1259.1392167224028, - 771.32342877765313, -176.61502916214059, 12.507343278686905, - -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7] - -def gamma(z): - z = complex(z) - # Reflection formula - if z.real < 0.5: - return pi / (sin(pi*z)*gamma(1-z)) - else: - z -= 1 - x = p[0] - for i in range(1, g+2): - x += p[i]/(z+i) - t = z + g + 0.5 - return sqrt(2*pi) * t**(z+0.5) * exp(-t) * x - def factorial(n): - return gamma(n+1) - -print "factorial(-0.5)**2=",factorial(-0.5)**2 -for i in range(10): - print "factorial(%d)=%s"%(i,factorial(i)) + z=1 + if n>1: + z=n*factorial(n-1) + return z diff --git a/Task/Factorial/Python/factorial-8.py b/Task/Factorial/Python/factorial-8.py new file mode 100644 index 0000000000..c837176d46 --- /dev/null +++ b/Task/Factorial/Python/factorial-8.py @@ -0,0 +1,2 @@ +def factorial(n): + return n * factorial(n - 1) if n else 1 diff --git a/Task/Factorial/Python/factorial-9.py b/Task/Factorial/Python/factorial-9.py new file mode 100644 index 0000000000..2e8331bac3 --- /dev/null +++ b/Task/Factorial/Python/factorial-9.py @@ -0,0 +1,27 @@ +from cmath import * + +# Coefficients used by the GNU Scientific Library +g = 7 +p = [0.99999999999980993, 676.5203681218851, -1259.1392167224028, + 771.32342877765313, -176.61502916214059, 12.507343278686905, + -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7] + +def gamma(z): + z = complex(z) + # Reflection formula + if z.real < 0.5: + return pi / (sin(pi*z)*gamma(1-z)) + else: + z -= 1 + x = p[0] + for i in range(1, g+2): + x += p[i]/(z+i) + t = z + g + 0.5 + return sqrt(2*pi) * t**(z+0.5) * exp(-t) * x + +def factorial(n): + return gamma(n+1) + +print "factorial(-0.5)**2=",factorial(-0.5)**2 +for i in range(10): + print "factorial(%d)=%s"%(i,factorial(i)) diff --git a/Task/Factorial/R/factorial-1.r b/Task/Factorial/R/factorial-1.r index d8baa8a6d8..266859bce5 100644 --- a/Task/Factorial/R/factorial-1.r +++ b/Task/Factorial/R/factorial-1.r @@ -1,4 +1,4 @@ fact <- function(n) { - if ( n <= 1 ) 1 - else n * fact(n-1) + if (n <= 1) 1 + else n * Recall(n - 1) } diff --git a/Task/Factorial/R/factorial-2.r b/Task/Factorial/R/factorial-2.r index fc3a2ececd..ffd155da8d 100644 --- a/Task/Factorial/R/factorial-2.r +++ b/Task/Factorial/R/factorial-2.r @@ -1,5 +1,7 @@ factIter <- function(n) { f = 1 - for (i in 2:n) f <- f * i + if (n > 1) { + for (i in 2:n) f <- f * i + } f } diff --git a/Task/Factorial/REXX/factorial-1.rexx b/Task/Factorial/REXX/factorial-1.rexx index f721bc38e7..b02528c706 100644 --- a/Task/Factorial/REXX/factorial-1.rexx +++ b/Task/Factorial/REXX/factorial-1.rexx @@ -1,4 +1,4 @@ -/*REXX program computes the factorial of a non-negative integer. */ +/*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.' @@ -6,13 +6,13 @@ 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)*/ +!= 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. */ +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 diff --git a/Task/Factorial/REXX/factorial-2.rexx b/Task/Factorial/REXX/factorial-2.rexx index cf0d79b940..0ce1aa0e4d 100644 --- a/Task/Factorial/REXX/factorial-2.rexx +++ b/Task/Factorial/REXX/factorial-2.rexx @@ -1,4 +1,4 @@ -/*REXX program computes the factorial of a non-negative integer, and it automatically */ +/*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.*/ @@ -7,16 +7,16 @@ 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 /*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 !/1 /*normalize the factorial product. */ +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 diff --git a/Task/Factorial/REXX/factorial-3.rexx b/Task/Factorial/REXX/factorial-3.rexx index 8f8ca3340a..f9f6da4455 100644 --- a/Task/Factorial/REXX/factorial-3.rexx +++ b/Task/Factorial/REXX/factorial-3.rexx @@ -1,28 +1,27 @@ -/*REXX program computes the factorial of an integer, striping trailing zeroes. */ +/*REXX program computes & shows the factorial of an integer, striping trailing zeroes. */ numeric digits 200 /*start with two hundred digits. */ -parse arg N .; if N=='' then N=0 /*obtain the optional argument from CL.*/ - -!=1 /*define the factorial product so far. */ +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. */ + 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.*/ + 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.*/ + != 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 ... */ + 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 ! */ +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. */ + 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.*/ - -!=! || copies(0, z) /*add water to rehydrate the product. */ -if z==0 then z='no' /*use gooder English for the message. */ + /*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. */ - /*stick a fork in it, we're all done. */ diff --git a/Task/Factorial/Robotic/factorial.robotic b/Task/Factorial/Robotic/factorial.robotic new file mode 100644 index 0000000000..1dabb5751a --- /dev/null +++ b/Task/Factorial/Robotic/factorial.robotic @@ -0,0 +1,15 @@ +input string "Enter a number:" +set "in" to "('ABS('input')')" +if "in" <= 1 then "one" +set "result" to 1 + +: "factorial" +set "result" to "('result' * 'in')" +dec "in" by 1 +if "in" > 1 then "factorial" +* "('result')" +end + +: "one" +* "1" +end diff --git a/Task/Factorial/Rust/factorial.rust b/Task/Factorial/Rust/factorial.rust index 02a5170c41..e1db6ea10f 100644 --- a/Task/Factorial/Rust/factorial.rust +++ b/Task/Factorial/Rust/factorial.rust @@ -6,7 +6,7 @@ fn factorial_recursive (n: u64) -> u64 { } fn factorial_iterative(n: u64) -> u64 { - (1..n+1).fold(1, |p, n| p*n) + (1..=n).product() } fn main () { diff --git a/Task/Factorial/WebAssembly/factorial.webassembly b/Task/Factorial/WebAssembly/factorial.webassembly new file mode 100644 index 0000000000..cf9a4ea978 --- /dev/null +++ b/Task/Factorial/WebAssembly/factorial.webassembly @@ -0,0 +1,16 @@ +(module + (func $fac (param f64) (result f64) + get_local 0 + f64.const 1 + f64.lt + if (result f64) + f64.const 1 + else + get_local 0 + get_local 0 + f64.const 1 + f64.sub + call $fac + f64.mul + end) + (export "fac" (func $fac))) diff --git a/Task/Factors-of-a-Mersenne-number/Prolog/factors-of-a-mersenne-number.pro b/Task/Factors-of-a-Mersenne-number/Prolog/factors-of-a-mersenne-number.pro new file mode 100644 index 0000000000..df6b348b8c --- /dev/null +++ b/Task/Factors-of-a-Mersenne-number/Prolog/factors-of-a-mersenne-number.pro @@ -0,0 +1,27 @@ +mersenne_factor(P, F) :- + prime(P), + once(( + between(1, 100_000, K), % Fail if we can't find a small factor + Q is 2*K*P + 1, + test_factor(Q, P, F))). + +test_factor(Q, P, prime) :- Q*Q > (1 << P - 1), !. +test_factor(Q, P, Q) :- + R is Q /\ 7, member(R, [1, 7]), + prime(Q), + powm(2, P, Q) =:= 1. + + +wheel235(L) :- + W = [4, 2, 4, 2, 4, 6, 2, 6 | W], + L = [1, 2, 2 | W]. + +prime(N) :- + N >= 2, + wheel235(W), + prime(N, 2, W). + +prime(N, D, _) :- D*D > N, !. +prime(N, D, [A|As]) :- + N mod D =\= 0, + D2 is D + A, prime(N, D2, As). diff --git a/Task/Factors-of-a-Mersenne-number/Scala/factors-of-a-mersenne-number.scala b/Task/Factors-of-a-Mersenne-number/Scala/factors-of-a-mersenne-number.scala index c66799d75d..4362863507 100644 --- a/Task/Factors-of-a-Mersenne-number/Scala/factors-of-a-mersenne-number.scala +++ b/Task/Factors-of-a-Mersenne-number/Scala/factors-of-a-mersenne-number.scala @@ -1,21 +1,20 @@ /** Find factors of a Mersenne number * - * The implementation finds factors for M929 and further. + * The implementation finds factors for M929 and further. * - * @example M59 = 2^059 - 1 = 576460752303423487 ( 2 msec) - * @example = 179951 × 3203431780337. + * @example M59 = 2^059 - 1 = 576460752303423487 ( 2 msec) + * @example = 179951 × 3203431780337. */ -object FactorMersenne extends App { +object FactorsOfAMersenneNumber extends App { val two: BigInt = 2 - - def sieve(nums: Stream[Int]): Stream[Int] = - Stream.cons(nums.head, sieve((nums.tail) filter (_ % nums.head != 0))) // An infinite stream of primes, lazy evaluation and memo-ized - val oddPrimes = sieve(Stream.from(3, 2)) - def primes = sieve(2 #:: oddPrimes) + val oddPrimes = sieve(LazyList.from(3, 2)) - def mersenne(p: Int) = (two pow p) - 1 + def sieve(nums: LazyList[Int]): LazyList[Int] = + LazyList.cons(nums.head, sieve((nums.tail) filter (_ % nums.head != 0))) + + def primes: LazyList[Int] = sieve(2 #:: oddPrimes) def factorMersenne(p: Int): Option[Long] = { val limit = (mersenne(p) - 1 min Int.MaxValue).toLong @@ -25,29 +24,36 @@ object FactorMersenne extends App { } // Build a stream of factors from (2*p+1) step-by (2*p) - def s(a: Long): Stream[Long] = a #:: s(a + (2 * p)) // Build stream of possible factors + def s(a: Long): LazyList[Long] = a #:: s(a + (2 * p)) // Build stream of possible factors // Limit and Filter Stream and then take the head element val e = s(2 * p + 1).takeWhile(_ < limit).filter(factorTest(p, _)) e.headOption } + def mersenne(p: Int): BigInt = (two pow p) - 1 + // Test - (primes takeWhile (_ <= 97)) ++ List(929, 937) foreach { p => - { // Needs some intermediate results for nice formatting - val nMersenne = mersenne(p); val lit = f"${nMersenne}%30d" - val preAmble = f"${s"M${p}"}%4s = 2^$p%03d - 1 = ${lit}%s" + (primes takeWhile (_ <= 97)) ++ List(929, 937) foreach { p => { // Needs some intermediate results for nice formatting + val nMersenne = mersenne(p); + val lit = f"${nMersenne}%30d" + val preAmble = f"${s"M${p}"}%4s = 2^$p%03d - 1 = ${lit}%s" - val datum = System.nanoTime - val result = factorMersenne(p) - val mSec = ((System.nanoTime - datum) / 1.e+6).round + val datum = System.nanoTime + val result = factorMersenne(p) + val mSec = ((System.nanoTime - datum) / 1.0e+6).round - def decStr = { if (lit.length > 30) f"(M has ${lit.length}%3d dec)" else "" } - def sPrime = { if (result.isEmpty) " is a Mersenne prime number." else " " * 28 } - - println(f"$preAmble${sPrime} ${f"($mSec%,1d"}%13s msec)") - if (!result.isEmpty) - println(f"${decStr}%-17s = ${result.get} × ${nMersenne / result.get}") + def decStr = { + if (lit.length > 30) f"(M has ${lit.length}%3d dec)" else "" } + + def sPrime: String = { + if (result.isEmpty) " is a Mersenne prime number." else " " * 28 + } + + println(f"$preAmble${sPrime} ${f"($mSec%,1d"}%13s msec)") + if (result.isDefined) + println(f"${decStr}%-17s = ${result.get} × ${nMersenne / result.get}") + } } } diff --git a/Task/Factors-of-an-integer/00DESCRIPTION b/Task/Factors-of-an-integer/00DESCRIPTION index ba19a2431c..a97bb7dbac 100644 --- a/Task/Factors-of-an-integer/00DESCRIPTION +++ b/Task/Factors-of-an-integer/00DESCRIPTION @@ -22,5 +22,6 @@ Note that every prime number has two factors:   '''1'''   and itself. *   [[trial factoring of a Mersenne number]] *   [[partition an integer X into N primes]] *   [[sequence of primes by Trial Division]] +*   [[sequence: smallest number greater than previous term with exactly n divisors]]

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 new file mode 100644 index 0000000000..feeab82c22 --- /dev/null +++ b/Task/Factors-of-an-integer/EDSAC-order-code/factors-of-an-integer.edsac @@ -0,0 +1,136 @@ + [Factors of an integer, for Rosetta Code website. + EDSAC program, Initial Orders 2.] + + [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 + 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 from 0D] + T 56#@ [store, since 0D is overwritten below] + A 62#@ [load 1] + T 58#@ [possible factor := 1] + S 65 @ [negative count of items per line] + T 64 @ [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 [call division subroutine; clears acc] + A 6 D [save quotient (6D may be overwritten below)] + T 60#@ + S 4 D [load negative of remainder] + G 44 @ [skip if remainder > 0] + + [Here if m is a factor of n. + Print factor m and quotient n/m 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] + + [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)] + + [Here when found all factors] + O 70 @ [print CR, LF twice] + O 71 @ + O 70 @ + O 71 @ + T F [EDSAc convention is acc = 0 on return] + [55] E F [return] + [--------] + [56] P F P F [number whose factors are to be found] + [58] P F P F [possible factor] + [60] P F P F [integer part of (number/factor)] + [62] P D P F [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] + [68] L F [right parenthesis] + [69] N F [comma] + [70] @ F [carriage return] + [71] & F [line feed] + + [Main routine for testing subroutine. + Load at even address.] + T 400 K + G K + [Test values. Not all are used below. Some have to be + stored negated; see EDSAC solution to Babbage problem] + [0] P 210 F P F [420] + [2] J 520 F P F [42,000] + [4] L 944 F V 2047 F [-420,000] + [6] & 847 D P F [99,999] + [8] # 1760 D V 2046 F [-999,999] + [10] D 768 D V 140 D [-999,999,999] + [12] # F [figure shift] + [13] K 4096 F [null character] + + [Enter with acc = 0] + [14] O 12 @ [set teleprinter to figures] + A #@ [load 420] + T D [to 0D for subroutine] + A 17 @ [for return] + G 148 F [call subrouine] + S 10#@ [load 999,999,999 as negative of -999,999,999] + T D [to subroutine, as above] + A 21 @ + G 148 F + O 13 @ [print null to flush printer buffer] + Z F [stop] + E 14 Z [define entry point] + P F [acc = 0 on entry] diff --git a/Task/Factors-of-an-integer/Pascal/factors-of-an-integer-2.pascal b/Task/Factors-of-an-integer/Pascal/factors-of-an-integer-2.pascal index a700739132..a54a521904 100644 --- a/Task/Factors-of-an-integer/Pascal/factors-of-an-integer-2.pascal +++ b/Task/Factors-of-an-integer/Pascal/factors-of-an-integer-2.pascal @@ -1,36 +1,284 @@ -program factors; -{Looking for extreme composite numbers: -http://wwwhomes.uni-bielefeld.de/achim/highly.txt} +program FacOfInteger; +{$IFDEF FPC} +// {$R+,O+} debuging purpose + {$MODE DELPHI} + {$Optimization ON,ALL} + {$CodeAlign proc=8} +{$ELSE} + {$APPTYPE CONSOLE} +{$ENDIF} +uses + sysutils; -const - MAXFACTORCNT = 1920; //number := 3491888400; +type + tPot = record + potPrim, + potMax :Uint32; + end; + + tprimeFac = record + pfPrims : array[0..13] of tPot; + pfCnt, + pfDivCnt, + pfSumOfDivs, + pfNum : Uint32; + end; + + tSmallPrimes = array[0..6541] of Word; + tItem = NativeUint; + tDivisors = array of tItem; + tpDivisor = pNativeUint; +var + SmallPrimes: tSmallPrimes; + primeDecomp: tprimeFac; + +procedure InsertSort(pDiv:tpDivisor; Left, Right : NativeInt ); +var + I, J: NativeInt; + Pivot : tItem; +begin + for i:= 1 + Left to Right do + begin + Pivot:= pDiv[i]; + j:= i - 1; + while (j >= Left) and (pDiv[j] > Pivot) do + begin + pDiv[j+1]:=pDiv[j]; + Dec(j); + end; + pDiv[j+1]:= pivot; + end; +end; + +procedure InitSmallPrimes; +var + pr,testPr,j,maxprimidx: Uint32; + isPrime : boolean; +Begin + maxprimidx := 0; + SmallPrimes[0] := 2; + pr := 3; + repeat + isprime := true; + j := 0; + repeat + testPr := SmallPrimes[j]; + IF testPr*testPr > pr then + break; + If pr mod testPr = 0 then + Begin + isprime := false; + break; + end; + inc(j); + until false; + + if isprime then + Begin + inc(maxprimidx); + SmallPrimes[maxprimidx]:= pr; + end; + inc(pr,2); + until pr > 1 shl 16 -1; +end; + +procedure PrimeFacOut(proper:Boolean=true); +var + i,k : Int32; +begin + with primeDecomp do + Begin + write(pfNum,' = '); + k := pfCnt-1; + For i := 0 to k-1 do + with pfPrims[i] do + If potMax = 1 then + write(potPrim,'*') + else + write(potPrim,'^',potMax,'*'); + with pfPrims[k] do + If potMax = 1 then + write(potPrim) + else + write(potPrim,'^',potMax); + if proper then + writeln(' got ',pfDivCnt-1,' proper divisors with sum : ',pfSumOfDivs-pfNum) + else + writeln(' got ',pfDivCnt,' divisors with sum : ',pfSumOfDivs); + end; +end; + +function DivCount(const primeDecomp:tprimeFac):NativeUInt;inline; +begin + result := primeDecomp.pfDivCnt; +end; + +function SumOfDiv(const primeDecomp:tprimeFac):NativeUInt;inline; +begin + result := primeDecomp.pfSumOfDivs; +end; + +procedure PrimeDecomposition(n:Uint32;var res:tprimeFac); +var + i,pr,fac,cnt,DivCnt,quot{to minimize divisions} : NativeUint; +Begin + res.pfNum := n; + cnt := 0; + DivCnt := 1; + i := 0; + if n <= 1 then + Begin + with res.pfPrims[0] do + Begin + potPrim := n; + potMax := 1; + end; + cnt := 1; + end + else + repeat + pr := SmallPrimes[i]; + IF pr*pr>n then + Break; + + quot := n div pr; + IF pr*quot = n then + with res do + Begin + with pfPrims[Cnt] do + Begin + potPrim := pr; + potMax := 0; + fac := pr; + repeat + n := quot; + quot := quot div pr; + inc(potMax); + fac *= pr; + until pr*quot <> n; + DivCnt *= (potMax+1); + end; + inc(Cnt); + end; + inc(i); + until false; + //a big prime left over? + IF n > 1 then + with res do + Begin + with pfPrims[Cnt] do + Begin + potPrim := n; + potMax := 1; + end; + inc(Cnt); + DivCnt *= 2; + end; + res.pfCnt:= cnt; + res.pfDivCnt := DivCnt; + res.pfSumOfDivs := 0; +end; + +procedure GetDivs(var primeDecomp:tprimeFac;var Divs:tDivisors); +var + pDivs : tpDivisor; + i,len,j,l,p,pPot,k,sum: NativeInt; +Begin + i := DivCount(primeDecomp); + IF i > Length(Divs) then + setlength(Divs,i); + pDivs := @Divs[0]; + pDivs[0] := 1; + len := 1; + l := len; + sum := 1; + For i := 0 to primeDecomp.pfCnt-1 do + with primeDecomp.pfPrims[i] do + Begin + //Multiply every divisor before with the new primefactors + //and append them to the list + k := potMax-1; + p := potPrim; + pPot :=1; + repeat + pPot *= p; + For j := 0 to len-1 do + Begin + pDivs[l]:= pPot*pDivs[j]; + sum += pDivs[l]; + inc(l); + end; + dec(k); + until k<0; + len := l; + end; + primeDecomp.pfSumOfDivs := sum; + //Sort. Insertsort much faster than QuickSort in this special case + InsertSort(pDivs,0,len-1); +end; + +Function GetDivisors(n:Uint32;var Divs:tDivisors):Int32; +var + i:Int32; +Begin + PrimeDecomposition(n,primeDecomp); + i := DivCount(primeDecomp); + IF i > Length(Divs) then + setlength(Divs,i+1); + GetDivs(primeDecomp,Divs); + result := DivCount(primeDecomp); +end; + +procedure AllFacsOut(n: Uint32;Divs:tDivisors;proper:boolean=true); +var + k,j: Int32; +Begin + k := GetDivisors(n,Divs)-1;// zero based + PrimeFacOut(proper); + IF proper then + dec(k); + IF k > 0 then + Begin + For j := 0 to k-1 do + write(Divs[j],','); + writeln(Divs[k]); + end; +end; + +procedure SpeedTest(Limit:Uint32); +var + Ticks,SumDivCnt : Int64; + Divisors : tDivisors; + number: UInt32; +Begin + Ticks := GetTickCount64; + SumDivCnt := 0; + For number := 1 to Limit do + inc(SumDivCnt,GetDivisors(number,Divisors)); + writeln('SpeedTest ',(GetTickCount64-Ticks)/1000:0:3,' secs for 1..',Limit); + writeln('mean count of divisors ',SumDivCnt/limit:0:3); + writeln; +end; var - FaktorList : array[0..MAXFACTORCNT] of LongWord; - i, number,quot,cnt: LongWord; -begin - writeln('Enter a number between 1 and 4294967295: '); - write('3491888400 is a nice choice '); - readln(number); + Divisors : tDivisors; + number: Int32; +BEGIN + InitSmallPrimes; + setlength(Divisors,1); + SpeedTest(1000*1000); - cnt := 0; - i := 1; - repeat - quot := number div i; - if quot *i-number = 0 then - begin - FaktorList[cnt] := i; - FaktorList[MAXFACTORCNT-cnt] := quot; - inc(cnt); - end; - inc(i); - until i> quot; - writeln(number,' has ',2*cnt,' factors'); - dec(cnt); - For i := 0 to cnt do - write(FaktorList[i],' ,'); - For i := cnt downto 1 do - write(FaktorList[MAXFACTORCNT-i],' ,'); -{ the last without ','} - writeln(FaktorList[MAXFACTORCNT]); -end. + writeln('Enter a number between 1 and 4294967295: '); + writeln('3491888400 is a nice choice :'); + readln(number); + IF number >= 0 then + Begin + writeln('Proper number version'); + AllFacsOut(number,Divisors); + + writeln('including n version'); + AllFacsOut(number,Divisors,false); + end; + //https://en.wikipedia.org/wiki/Highly_composite_number <= HCN + //http://wwwhomes.uni-bielefeld.de/achim/highly.txt the first 1200 HCN +END. 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 e89a005a8c..29c36adf45 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,23 +1,23 @@ /*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(high)+2; numeric digits max(9, w-2); $='∞' /*decimal digits for // */ -@.=left('',7); @.1="{unity}"; @.2='[prime]'; @.$=" {"$'} ' /*define some literals. */ +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. */ p#=0 /*count of prime numbers. */ do n=LO to HI by inc; divs=divisors(n); #=words(divs) /*get list of divs; # divs*/ - if divs==$ then do; #=$ ; divs= ' (infinite)'; end /*handle case for infinity*/ - p=@.#; if n<0 then if n\==-1 then p=@.. /* " " " negative*/ - if p==@.2 then p#=p#+1 /*Prime? Then bump counter*/ + if divs==$ then do; #= $; divs= ' (infinite)'; end /*handle case for infinity*/ + p= @.#; if n<0 then if n\==-1 then p= @.. /* " " " negative*/ + if p==@.2 then p#= p# + 1 /*Prime? Then bump counter*/ say center(n, w) center('['#"]", 9) "──► " p ' ' divs end /*n*/ /* [↑] process a range of integers. */ say -say left('', 17) p# ' primes were found.' /*display the number of primes found. */ +say right(p#, 20) ' primes were found.' /*display the number of primes found. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -divisors: procedure; 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 +divisors: procedure; 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 j*j [1, 97] +say divisors(2695) #=> [1, 5, 7, 11, 35, 49, 55, 77, 245, 385, 539, 2695] diff --git a/Task/Factors-of-an-integer/Sidef/factors-of-an-integer.sidef b/Task/Factors-of-an-integer/Sidef/factors-of-an-integer-2.sidef similarity index 53% rename from Task/Factors-of-an-integer/Sidef/factors-of-an-integer.sidef rename to Task/Factors-of-an-integer/Sidef/factors-of-an-integer-2.sidef index e2724b4cbc..0c4e909ef7 100644 --- a/Task/Factors-of-an-integer/Sidef/factors-of-an-integer.sidef +++ b/Task/Factors-of-an-integer/Sidef/factors-of-an-integer-2.sidef @@ -1,4 +1,4 @@ -func factors(n) { +func divisors(n) { gather { { |d| take(d, n//d) if d.divides(n) @@ -6,6 +6,6 @@ func factors(n) { }.sort.uniq }   -for n [53, 64, 32766] { - say "factors(#{n}): #{factors(n)}" +[53, 64, 32766].each {|n| + say "divisors(#{n}): #{divisors(n)}" } diff --git a/Task/Factors-of-an-integer/Standard-ML/factors-of-an-integer-1.ml b/Task/Factors-of-an-integer/Standard-ML/factors-of-an-integer-1.ml new file mode 100644 index 0000000000..a8dcd377d0 --- /dev/null +++ b/Task/Factors-of-an-integer/Standard-ML/factors-of-an-integer-1.ml @@ -0,0 +1,18 @@ +fun printIntList ls = + ( + List.app (fn n => print(Int.toString n ^ " ")) ls; + print "\n" + ); + +fun factors n = + let + fun factors'(n, k) = + if k > n then + [] + else if n mod k = 0 then + k :: factors'(n, k+1) + else + factors'(n, k+1) + in + factors'(n,1) + end; diff --git a/Task/Factors-of-an-integer/Standard-ML/factors-of-an-integer-2.ml b/Task/Factors-of-an-integer/Standard-ML/factors-of-an-integer-2.ml new file mode 100644 index 0000000000..c94b206a30 --- /dev/null +++ b/Task/Factors-of-an-integer/Standard-ML/factors-of-an-integer-2.ml @@ -0,0 +1,2 @@ +printIntList(factors 12345) +printIntList(factors 120) diff --git a/Task/Factors-of-an-integer/X86-Assembly/factors-of-an-integer.x86 b/Task/Factors-of-an-integer/X86-Assembly/factors-of-an-integer.x86 new file mode 100644 index 0000000000..d7a630f3b0 --- /dev/null +++ b/Task/Factors-of-an-integer/X86-Assembly/factors-of-an-integer.x86 @@ -0,0 +1,32 @@ +section .bss + factorArr resd 250 ;big buffer against seg fault + +section .text +global _main +_main: + mov ebp, esp; for correct debugging + mov eax, 0x7ffffffe ;number of which we want to know the factors, max num this program works with + mov ebx, eax ;save eax + mov ecx, 1 ;n, factor we test for + mov [factorArr], dword 0 + looping: + mov eax, ebx ;restore eax + xor edx, edx ;clear edx + div ecx + cmp edx, 0 ;test if our number % n == 0 + jne next + mov edx, [factorArr] ;if yes, we increment the size of the array and append n + inc edx + mov [factorArr+edx*4], ecx ;appending n + mov [factorArr], edx ;storing the new size + next: + mov eax, ecx + cmp eax, ebx ;is n bigger then our number ? + jg end ;if yes we end + inc ecx + jmp looping + end: + mov ecx, factorArr ;pass arr address by ecx + xor eax, eax ;clear eax + mov esp, ebp ;garbage collecting + ret diff --git a/Task/Fast-Fourier-transform/Julia/fast-fourier-transform-1.julia b/Task/Fast-Fourier-transform/Julia/fast-fourier-transform-1.julia index 8343c6d267..980db6365c 100644 --- a/Task/Fast-Fourier-transform/Julia/fast-fourier-transform-1.julia +++ b/Task/Fast-Fourier-transform/Julia/fast-fourier-transform-1.julia @@ -1 +1,3 @@ +using FFTW # or using DSP + fft([1,1,1,1,0,0,0,0]) diff --git a/Task/Fast-Fourier-transform/Julia/fast-fourier-transform-3.julia b/Task/Fast-Fourier-transform/Julia/fast-fourier-transform-3.julia index c08eac3f95..0539d7e622 100644 --- a/Task/Fast-Fourier-transform/Julia/fast-fourier-transform-3.julia +++ b/Task/Fast-Fourier-transform/Julia/fast-fourier-transform-3.julia @@ -1,2 +1,15 @@ -]add FFTW -using FFTW +function fft(a) + y1 = Any[]; y2 = Any[] + n = length(a) + if n ==1 return a end + wn(n) = exp(-2*π*im/n) + y_even = fft(a[1:2:end]) + y_odd = fft(a[2:2:end]) + w = 1 + for k in 1:Int(n/2) + push!(y1, y_even[k] + w*y_odd[k]) + push!(y2, y_even[k] - w*y_odd[k]) + w = w*wn(n) + end + return vcat(y1,y2) +end diff --git a/Task/Fast-Fourier-transform/PHP/fast-fourier-transform-1.php b/Task/Fast-Fourier-transform/PHP/fast-fourier-transform-1.php new file mode 100644 index 0000000000..b3ea2ddb80 --- /dev/null +++ b/Task/Fast-Fourier-transform/PHP/fast-fourier-transform-1.php @@ -0,0 +1,40 @@ +real = $real; + $this->imaginary = $imaginary; + } + + function Add($other, $dst){ + $dst->real = $this->real + $other->real; + $dst->imaginary = $this->imaginary + $other->imaginary; + return $dst; + } + + function Subtract($other, $dst){ + + $dst->real = $this->real - $other->real; + $dst->imaginary = $this->imaginary - $other->imaginary; + return $dst; + } + + function Multiply($other, $dst){ + //cache real in case dst === this + $r = $this->real * $other->real - $this->imaginary * $other->imaginary; + $dst->imaginary = $this->real * $other->imaginary + $this->imaginary * $other->real; + $dst->real = $r; + return $dst; + } + + function ComplexExponential($dst){ + $er = exp($this->real); + $dst->real = $er * cos($this->imaginary); + $dst->imaginary = $er * sin($this->imaginary); + return $dst; + } +} diff --git a/Task/Fast-Fourier-transform/PHP/fast-fourier-transform-2.php b/Task/Fast-Fourier-transform/PHP/fast-fourier-transform-2.php new file mode 100644 index 0000000000..91e85cce67 --- /dev/null +++ b/Task/Fast-Fourier-transform/PHP/fast-fourier-transform-2.php @@ -0,0 +1,101 @@ +imaginary = -$amplitudes[$i]->imaginary; + } + } + + // Apply Fourier Transform + $amplitudes = FFT($amplitudes); + + for($i = 0; $i < $N; ++$i){ + //Conjugate again + $amplitudes[$i]->imaginary = -$amplitudes[$i]->imaginary; + // Scale + $amplitudes[$i]->real *= $iN; + $amplitudes[$i]->imaginary *= $iN; + } + return $amplitudes; +} + + +function FFT($amplitudes) +{ + $N = count($amplitudes); + if($N <= 1){ + return $amplitudes; + } + + $hN = $N / 2; + + $even = array_pad(array() , $hN, 0); + $odd = array_pad(array() , $hN, 0); + for($i = 0; $i < $hN; ++$i){ + $even[$i] = $amplitudes[$i*2]; + $odd[$i] = $amplitudes[$i*2+1]; + } + $even = FFT($even); + $odd = FFT($odd); + + $a = -2*PI(); + for($k = 0; $k < $hN; ++$k){ + if(!($even[$k] instanceof Complex)){ + $even[$k] = new Complex($even[$k], 0); + } + + if(!($odd[$k] instanceof Complex)){ + $odd[$k] = new Complex($odd[$k], 0); + } + $p = $k/$N; + $t = new Complex(0, $a * $p); + + $t->ComplexExponential($t); + $t->Multiply($odd[$k], $t); + + + $amplitudes[$k] = $even[$k]->Add($t, $odd[$k]); + $amplitudes[$k + $hN] = $even[$k]->Subtract($t, $even[$k]); + } + return $amplitudes; +} + +function EchoSamples(&$samples){ + echo "Index\tReal\t\t\t\tImaginary" . PHP_EOL; + foreach($samples as $key=>&$sample){ + echo "$key\t" . number_format($sample->real, 13) . "\t\t\t\t" . number_format($sample->imaginary, 13) . PHP_EOL; + } +} + + +// Input Amplitudes +$time_amplitude_samples = array(1,1,1,1,0,0,0,0); + + +// echo input for reference +echo 'Input '. PHP_EOL; +echo "Index\tReal" . PHP_EOL; +foreach($time_amplitude_samples as $key=>&$sample){ + echo "$key\t" . number_format($sample, 13) . PHP_EOL; +} +echo PHP_EOL; + +// Do FFT and echo results +echo 'FFT '. PHP_EOL; +$frequency_amplitude_samples = FFT($time_amplitude_samples); +EchoSamples($frequency_amplitude_samples); +echo PHP_EOL; + +// Do inverse FFT and echo results +echo 'Inverse FFT '. PHP_EOL; +$frequency_back_to_time_amplitude_samples = IFFT($frequency_amplitude_samples); +EchoSamples($frequency_back_to_time_amplitude_samples); +echo PHP_EOL; diff --git a/Task/Fast-Fourier-transform/REXX/fast-fourier-transform.rexx b/Task/Fast-Fourier-transform/REXX/fast-fourier-transform.rexx index 0ddd0ff3de..3bc67bc2ac 100644 --- a/Task/Fast-Fourier-transform/REXX/fast-fourier-transform.rexx +++ b/Task/Fast-Fourier-transform/REXX/fast-fourier-transform.rexx @@ -1,14 +1,14 @@ /*REXX program performs a fast Fourier transform (FFT) on a set of complex numbers. */ -numeric digits length( pi() ) - 1 /*limited by the PI function result. */ +numeric digits length( pi() ) - length(.) /*limited by the PI function result. */ arg data /*ARG verb uppercases the DATA from CL.*/ -if data='' then data=1 1 1 1 0 /*Not specified? Then use the default.*/ -size=words(data); pad=left('', 6) /*PAD: for indenting and padding SAYs.*/ - do p=0 until 2**p>=size ; end /*number of args exactly a power of 2? */ - do j=size+1 to 2**p; data=data 0; end /*add zeroes to DATA 'til a power of 2.*/ -size=words(data); ph=p%2 ; call hdr /*╔═══════════════════════════╗*/ +if data='' then data= 1 1 1 1 0 /*Not specified? Then use the default.*/ +size=words(data); pad= left('', 5) /*PAD: for indenting and padding SAYs.*/ + do p=0 until 2**p>=size ; end /*number of args exactly a power of 2? */ + do j=size+1 to 2**p; data= data 0; end /*add zeroes to DATA 'til a power of 2.*/ +size= words(data); ph= p % 2 ; call hdr /*╔═══════════════════════════╗*/ /* [↓] TRANSLATE allows I & J*/ /*║ Numbers in data can be in ║*/ do j=0 for size /*║ seven formats: real ║*/ - _=translate( word(data, j+1), 'J', "I") /*║ real,imag ║*/ + _= translate( word(data, j+1), 'J', "I") /*║ real,imag ║*/ parse var _ #.1.j '' $ 1 "," #.2.j /*║ ,imag ║*/ if $=='J' then parse var #.1.j #2.j "J" #.1.j /*║ nnnJ ║*/ /*║ nnnj ║*/ @@ -18,51 +18,51 @@ size=words(data); ph=p%2 ; call hdr /*╔══════ say pad ' FFT in ' center(j+1, 7) pad fmt(#.1.j) fmt(#.2.j, "i") end /*j*/ say -tran=pi()*2 / 2**p; !.=0; hp=2**p %2; A=2**(p-ph); ptr=A; dbl=1 +tran= pi()*2 / 2**p; !.=0; hp= 2**p %2; A= 2**(p-ph); ptr= A; dbl= 1 say do p-ph; halfPtr=ptr % 2 - do i=halfPtr by ptr to A-halfPtr; _=i - halfPtr; !.i=!._ + dbl - end /*i*/ - ptr=halfPtr; dbl=dbl+dbl + do i=halfPtr by ptr to A-halfPtr; _= i - halfPtr; !.i= !._ + dbl + end /*i*/ + ptr= halfPtr; dbl= dbl + dbl end /*p-ph*/ - do j=0 to 2**p%4; cmp.j=cos(j*tran); _=hp - j; cmp._= -cmp.j - _=hp + j; cmp._= -cmp.j + do j=0 to 2**p%4; cmp.j= cos(j*tran); _= hp - j; cmp._= -cmp.j + _= hp + j; cmp._= -cmp.j end /*j*/ -B=2**ph - do i=0 for A; q=i * B - do j=0 for B; h=q+j; _=!.j*B+!.i; if _<=h then iterate +B= 2**ph + do i=0 for A; q= i * B + do j=0 for B; h=q+j; _= !.j*B+!.i; if _<=h then iterate parse value #.1._ #.1.h #.2._ #.2.h with #.1.h #.1._ #.2.h #.2._ end /*j*/ /* [↑] swap two sets of values. */ end /*i*/ -dbl=1 - do p ; w= hp % dbl - do k=0 for dbl ; Lb= w * k ; Lh= Lb + 2**p % 4 - do j=0 for w ; a= j * dbl * 2 + k ; b= a + dbl - r=#.1.a; i=#.2.a ; c1= cmp.Lb * #.1.b ; c4= cmp.Lb * #.2.b +dbl= 1 + do p ; w= hp % dbl + do k=0 for dbl ; Lb= w * k ; Lh= Lb + 2**p % 4 + do j=0 for w ; a= j * dbl * 2 + k ; b= a + dbl + r= #.1.a; i= #.2.a ; c1= cmp.Lb * #.1.b ; c4= cmp.Lb * #.2.b c2= cmp.Lh * #.2.b ; c3= cmp.Lh * #.1.b #.1.a= r + c1 - c2 ; #.2.a= i + c3 + c4 #.1.b= r - c1 + c2 ; #.2.b= i - c3 - c4 end /*j*/ end /*k*/ - dbl=dbl+dbl + dbl= dbl + dbl end /*p*/ call hdr - do i=0 for size - say pad " FFT out " center(i+1,7) pad fmt(#.1.i) fmt(#.2.i,'j') - end /*i*/ /*[↑] #s are shown with 10 decimal digs*/ + do z=0 for size + say pad " FFT out " center(z+1,7) pad fmt(#.1.z) fmt(#.2.z,'j') + end /*z*/ /*[↑] #s are shown with ≈20 dec. digits*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -cos: procedure; parse arg x; q=r2r(x)**2; z=1; _=1; p=1 /*bare bones COS. */ +cos: procedure; parse arg x; q= r2r(x)**2; z=1; _=1; p=1 /*bare bones COS. */ do k=2 by 2; _=-_*q/(k*(k-1)); z=z+_; if z=p then return z; p=z; end /*k*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ -fmt: procedure; parse arg y,j; y=y/1 /*prettifies complex numbers for output*/ - if abs(y) < '1e-'digits()%4 then y=0; if y=0 & j\=='' then return '' - y=format(y, , 10); if pos(.,y)\==0 then y=strip(y, 'T', 0) - y=strip(y, , .); if y>=0 then y=' 'y; return left(y || j, 12) +fmt: procedure; parse arg y,j; y= y/1 /*prettifies complex numbers for output*/ + if abs(y) < '1e-'digits() %4 then y= 0; if y=0 & j\=='' then return '' + dp= digits()%3; y= format(y, dp%6+1, dp); if pos(.,y)\==0 then y= strip(y, 'T', 0) + y= strip(y, 'T', .); return left(y || j, dp) /*──────────────────────────────────────────────────────────────────────────────────────*/ -hdr: _= '───data─── num real─part imaginary─part'; say pad _ - say pad translate(_, " "copies('═', 256), " "xrange()); return +hdr: _=pad '   data    num' pad "  real─part  " pad pad '        imaginary─part       ' + say _; say translate(_, " "copies('═', 256), " "xrange()); return /*──────────────────────────────────────────────────────────────────────────────────────*/ pi: return 3.1415926535897932384626433832795028841971693993751058209749445923078164062862 -r2r: return arg(1) // ( pi()*2 ) /*reduce the radians to a unit circle. */ +r2r: return arg(1) // ( pi() * 2 ) /*reduce the radians to a unit circle. */ diff --git a/Task/Fibonacci-n-step-number-sequences/Scala/fibonacci-n-step-number-sequences-1.scala b/Task/Fibonacci-n-step-number-sequences/Scala/fibonacci-n-step-number-sequences-1.scala index c8d6cb76d2..c3d74f1dc6 100644 --- a/Task/Fibonacci-n-step-number-sequences/Scala/fibonacci-n-step-number-sequences-1.scala +++ b/Task/Fibonacci-n-step-number-sequences/Scala/fibonacci-n-step-number-sequences-1.scala @@ -1,7 +1,8 @@ -//we rely on implicit conversion from Int to BigInt. -//BigInt is preferable since the numbers get very big, very fast. -//(though for a small example of the first few numbers it's not needed) -def fibStream(init: BigInt*): Stream[BigInt] = { - def inner(prev: Vector[BigInt]): Stream[BigInt] = prev.head #:: inner(prev.tail :+ prev.sum) - inner(init.toVector) -} + //we rely on implicit conversion from Int to BigInt. + //BigInt is preferable since the numbers get very big, very fast. + //(though for a small example of the first few numbers it's not needed) + def fibStream(init: BigInt*): LazyList[BigInt] = { + def inner(prev: Vector[BigInt]): LazyList[BigInt] = prev.head #:: inner(prev.tail :+ prev.sum) + + inner(init.toVector) + } diff --git a/Task/Fibonacci-n-step-number-sequences/Scala/fibonacci-n-step-number-sequences-2.scala b/Task/Fibonacci-n-step-number-sequences/Scala/fibonacci-n-step-number-sequences-2.scala index c48fb45336..27f8e0e85c 100644 --- a/Task/Fibonacci-n-step-number-sequences/Scala/fibonacci-n-step-number-sequences-2.scala +++ b/Task/Fibonacci-n-step-number-sequences/Scala/fibonacci-n-step-number-sequences-2.scala @@ -1,10 +1,11 @@ -//in the optimized version we don't compute values until it's needed. -//the unoptimized version, computed k elements ahead, where k being -//the number of elements to sum (fibonacci: k=2, tribonacci: k=3, ...). -def fibStream(init: BigInt*): Stream[BigInt] = { - def inner(prev: Vector[BigInt]): Stream[BigInt] = { - val sum = prev.sum - sum #:: inner(prev.tail :+ sum) + //in the optimized version we don't compute values until it's needed. + //the unoptimized version, computed k elements ahead, where k being + //the number of elements to sum (fibonacci: k=2, tribonacci: k=3, ...). + def fib2Stream(init: BigInt*): LazyList[BigInt] = { + def inner(prev: Vector[BigInt]): LazyList[BigInt] = { + val sum = prev.sum + sum #:: inner(prev.tail :+ sum) + } + + init.to(LazyList) #::: inner(init.toVector) } - init.toStream #::: inner(init.toVector) -} diff --git a/Task/Fibonacci-n-step-number-sequences/Scala/fibonacci-n-step-number-sequences-3.scala b/Task/Fibonacci-n-step-number-sequences/Scala/fibonacci-n-step-number-sequences-3.scala index 94871fc0ad..464b8a8029 100644 --- a/Task/Fibonacci-n-step-number-sequences/Scala/fibonacci-n-step-number-sequences-3.scala +++ b/Task/Fibonacci-n-step-number-sequences/Scala/fibonacci-n-step-number-sequences-3.scala @@ -1,11 +1,12 @@ -//instead of summing k elements each phase, we exploit the fact -//that the last element is already the sum of all k preceding elements -def fib2Stream(init: BigInt*): Stream[BigInt] = { - def inner(prev: Vector[BigInt]): Stream[BigInt] = { - val n = prev.last * 2 - prev.head - n #:: inner(prev.tail :+ n) + //instead of summing k elements each phase, we exploit the fact + //that the last element is already the sum of all k preceding elements + def fib3Stream(init: BigInt*): LazyList[BigInt] = { + def inner(prev: Vector[BigInt]): LazyList[BigInt] = { + val n = prev.last * 2 - prev.head + n #:: inner(prev.tail :+ n) + } + + //last element must be the sum of k preceding elements, vector size should be k+1 + val v = init.toVector :+ init.sum + v.to(LazyList) #::: inner(v) } - //last element must be the sum of k preceding elements, vector size should be k+1 - val v = init.toVector :+ init.sum - v.toStream #::: inner(v) -} diff --git a/Task/Fibonacci-n-step-number-sequences/Sidef/fibonacci-n-step-number-sequences.sidef b/Task/Fibonacci-n-step-number-sequences/Sidef/fibonacci-n-step-number-sequences-1.sidef similarity index 58% rename from Task/Fibonacci-n-step-number-sequences/Sidef/fibonacci-n-step-number-sequences.sidef rename to Task/Fibonacci-n-step-number-sequences/Sidef/fibonacci-n-step-number-sequences-1.sidef index ebee6300a1..5f3369d4fd 100644 --- a/Task/Fibonacci-n-step-number-sequences/Sidef/fibonacci-n-step-number-sequences.sidef +++ b/Task/Fibonacci-n-step-number-sequences/Sidef/fibonacci-n-step-number-sequences-1.sidef @@ -1,8 +1,8 @@ -func fib(n, xs=[1]) { +func fib(n, xs=[1], k=20) { loop { var len = xs.len - len >= 20 && break - xs.append(xs.ft(0.max(len - n)).sum) + len >= k && break + xs << xs.ft(max(0, len - n)).sum } return xs } diff --git a/Task/Fibonacci-n-step-number-sequences/Sidef/fibonacci-n-step-number-sequences-2.sidef b/Task/Fibonacci-n-step-number-sequences/Sidef/fibonacci-n-step-number-sequences-2.sidef new file mode 100644 index 0000000000..2e31214173 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Sidef/fibonacci-n-step-number-sequences-2.sidef @@ -0,0 +1,14 @@ +func fibonacci_matrix(k) is cached { + Matrix.build(k,k, {|i,j| + ((i == k-1) || (i == j-1)) ? 1 : 0 + }) +} + +func fibonacci_kth_order(n, k=2) { + var A = fibonacci_matrix(k) + (A**n)[0][-1] +} + +for k in (2..9) { + say ("Fibonacci of k=#{k} order: ", (15+k).of { fibonacci_kth_order(_, k) }) +} diff --git a/Task/Fibonacci-n-step-number-sequences/Sidef/fibonacci-n-step-number-sequences-3.sidef b/Task/Fibonacci-n-step-number-sequences/Sidef/fibonacci-n-step-number-sequences-3.sidef new file mode 100644 index 0000000000..5410c60460 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Sidef/fibonacci-n-step-number-sequences-3.sidef @@ -0,0 +1,20 @@ +func fibonacci_kth_order (n, k = 2) { + + return 0 if (n < k-1) + + var f = (1..(k+1) -> map {|j| + j < k ? 2**j : 1 + }) + + k += 1 + + for i in (2*(k-1) .. n) { + f[i%k] = (2*f[(i-1)%k] - f[i%k]) + } + + return f[n%k] +} + +for k in (2..9) { + say ("Fibonacci of k=#{k} order: ", (15+k).of { fibonacci_kth_order(_, k) }) +} diff --git a/Task/Fibonacci-sequence/APL/fibonacci-sequence-1.apl b/Task/Fibonacci-sequence/APL/fibonacci-sequence-1.apl index 5b4caf7c2d..030afc8adc 100644 --- a/Task/Fibonacci-sequence/APL/fibonacci-sequence-1.apl +++ b/Task/Fibonacci-sequence/APL/fibonacci-sequence-1.apl @@ -1 +1 @@ -↑+.×/N/⊂2 2⍴1 1 1 0 +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 a30ddaceb7..5b4caf7c2d 100644 --- a/Task/Fibonacci-sequence/APL/fibonacci-sequence-2.apl +++ b/Task/Fibonacci-sequence/APL/fibonacci-sequence-2.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-3.apl b/Task/Fibonacci-sequence/APL/fibonacci-sequence-3.apl index 3eff61d5ef..a30ddaceb7 100644 --- a/Task/Fibonacci-sequence/APL/fibonacci-sequence-3.apl +++ b/Task/Fibonacci-sequence/APL/fibonacci-sequence-3.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-4.apl b/Task/Fibonacci-sequence/APL/fibonacci-sequence-4.apl new file mode 100644 index 0000000000..3eff61d5ef --- /dev/null +++ b/Task/Fibonacci-sequence/APL/fibonacci-sequence-4.apl @@ -0,0 +1 @@ +⌊.5+(((1+PHI)÷2)*⍳N)÷PHI←5*.5 diff --git a/Task/Fibonacci-sequence/Elena/fibonacci-sequence.elena b/Task/Fibonacci-sequence/Elena/fibonacci-sequence.elena index 5f02436468..6dff262616 100644 --- a/Task/Fibonacci-sequence/Elena/fibonacci-sequence.elena +++ b/Task/Fibonacci-sequence/Elena/fibonacci-sequence.elena @@ -2,7 +2,7 @@ import extensions; fibu(n) { - int[] ac := new int[] { 0,1 }; + int[] ac := new int[]::( 0,1 ); if (n < 2) { ^ ac[n] diff --git a/Task/Fibonacci-sequence/Nial/fibonacci-sequence-1.nial b/Task/Fibonacci-sequence/Nial/fibonacci-sequence-1.nial new file mode 100644 index 0000000000..ac063c14c2 --- /dev/null +++ b/Task/Fibonacci-sequence/Nial/fibonacci-sequence-1.nial @@ -0,0 +1,12 @@ +fibi is op n { + if n<2 then + n + else + x1:=0; x2:=1; + for i with tell (n - 1) do + x:=x1+x2; + x1:=x2; + x2:=x; + endfor; + x2 + endif}; diff --git a/Task/Fibonacci-sequence/Nial/fibonacci-sequence-2.nial b/Task/Fibonacci-sequence/Nial/fibonacci-sequence-2.nial new file mode 100644 index 0000000000..242649687e --- /dev/null +++ b/Task/Fibonacci-sequence/Nial/fibonacci-sequence-2.nial @@ -0,0 +1 @@ +fibf is op n {1 pick ((n- 1) fold [1 pick, +] 0 1)}; diff --git a/Task/Fibonacci-sequence/Nial/fibonacci-sequence-3.nial b/Task/Fibonacci-sequence/Nial/fibonacci-sequence-3.nial new file mode 100644 index 0000000000..2f4802cf56 --- /dev/null +++ b/Task/Fibonacci-sequence/Nial/fibonacci-sequence-3.nial @@ -0,0 +1 @@ +fibf2 is 1 pick fold [1 pick, +] reverse (0 1 hitch) (-1+); diff --git a/Task/Fibonacci-sequence/Nial/fibonacci-sequence-4.nial b/Task/Fibonacci-sequence/Nial/fibonacci-sequence-4.nial new file mode 100644 index 0000000000..d9ebe5e275 --- /dev/null +++ b/Task/Fibonacci-sequence/Nial/fibonacci-sequence-4.nial @@ -0,0 +1 @@ +fibr is op n {fork [2>, +, + [fibr (-1 +), fibr (-2 +)]] n}; diff --git a/Task/Fibonacci-sequence/Nial/fibonacci-sequence-5.nial b/Task/Fibonacci-sequence/Nial/fibonacci-sequence-5.nial new file mode 100644 index 0000000000..74257c2924 --- /dev/null +++ b/Task/Fibonacci-sequence/Nial/fibonacci-sequence-5.nial @@ -0,0 +1 @@ +fibr2 is fork [2>, +, + [fibr2 (-1 +), fibr2 (-2 +)]]; diff --git a/Task/Fibonacci-sequence/Nial/fibonacci-sequence-6.nial b/Task/Fibonacci-sequence/Nial/fibonacci-sequence-6.nial new file mode 100644 index 0000000000..0f4c89802a --- /dev/null +++ b/Task/Fibonacci-sequence/Nial/fibonacci-sequence-6.nial @@ -0,0 +1 @@ +fibm is op n {floor (0 1 pick (reduce ip (n reshape [2 2 reshape 1 1 1 0])))}; diff --git a/Task/Fibonacci-sequence/Nial/fibonacci-sequence-7.nial b/Task/Fibonacci-sequence/Nial/fibonacci-sequence-7.nial new file mode 100644 index 0000000000..0b81b648bd --- /dev/null +++ b/Task/Fibonacci-sequence/Nial/fibonacci-sequence-7.nial @@ -0,0 +1,5 @@ +$ is reshape; +~ is tr f op a b {b f a}; % Goes before verb, rather than after like in J; +_ is floor; % Not really J, but J-ish? (Cannot redefine "<.".); + +fibm2 is _(0 1 pick reduce ip([2 2$1 1 1 0](~$))); diff --git a/Task/Fibonacci-sequence/Nial/fibonacci-sequence-8.nial b/Task/Fibonacci-sequence/Nial/fibonacci-sequence-8.nial new file mode 100644 index 0000000000..21b2db3fed --- /dev/null +++ b/Task/Fibonacci-sequence/Nial/fibonacci-sequence-8.nial @@ -0,0 +1 @@ +fibm3 is op n {a:=2 2$1 1 1 0; _(0 1 pick ((n- 1) fold (a ip) a))}; diff --git a/Task/Fibonacci-sequence/OCaml/fibonacci-sequence-2.ocaml b/Task/Fibonacci-sequence/OCaml/fibonacci-sequence-2.ocaml index bb210b6820..e0d551db8b 100644 --- a/Task/Fibonacci-sequence/OCaml/fibonacci-sequence-2.ocaml +++ b/Task/Fibonacci-sequence/OCaml/fibonacci-sequence-2.ocaml @@ -1,19 +1,11 @@ -open Num +let rec fib_rec n = + if n < 2 then + n + else + fib_rec (n - 1) + fib_rec (n - 2) -let fib = - let rec fib_aux f0 f1 = function - | 0 -> f0 - | 1 -> f1 - | n -> fib_aux f1 (f1 +/ f0) (n - 1) - in - fib_aux (num_of_int 0) (num_of_int 1) - -(* support for negatives *) -let fib n = - if n < 0 && n mod 2 = 0 then minus_num (fib (abs n)) - else fib (abs n) -;; -(* It can be called from the command line with an argument *) -(* Result is send to standart output *) -let n = int_of_string Sys.argv.(1) in -print_endline (string_of_num (fib n)) +let rec fib = function + 0 -> 0 + | 1 -> 1 + | n -> if n > 0 then fib (n-1) + fib (n-2) + else fib (n+2) - fib (n+1) diff --git a/Task/Fibonacci-sequence/OCaml/fibonacci-sequence-3.ocaml b/Task/Fibonacci-sequence/OCaml/fibonacci-sequence-3.ocaml index 78872a7853..bb210b6820 100644 --- a/Task/Fibonacci-sequence/OCaml/fibonacci-sequence-3.ocaml +++ b/Task/Fibonacci-sequence/OCaml/fibonacci-sequence-3.ocaml @@ -1,16 +1,19 @@ open Num -let mul (a,b,c) (d,e,f) = let bxe = b*/e in - (a*/d +/ bxe, a*/e +/ b*/f, bxe +/ c*/f) - -let id = (Int 1, Int 0, Int 1) -let rec pow a n = - if n=0 then id else - let b = pow a (n/2) in - if (n mod 2) = 0 then mul b b else mul a (mul b b) +let fib = + let rec fib_aux f0 f1 = function + | 0 -> f0 + | 1 -> f1 + | n -> fib_aux f1 (f1 +/ f0) (n - 1) + in + fib_aux (num_of_int 0) (num_of_int 1) +(* support for negatives *) let fib n = - let (_,y,_) = (pow (Int 1, Int 1, Int 0) n) in - string_of_num y + if n < 0 && n mod 2 = 0 then minus_num (fib (abs n)) + else fib (abs n) ;; -Printf.printf "fib %d = %s\n" 300 (fib 300) +(* It can be called from the command line with an argument *) +(* Result is send to standart output *) +let n = int_of_string Sys.argv.(1) in +print_endline (string_of_num (fib n)) diff --git a/Task/Fibonacci-sequence/OCaml/fibonacci-sequence-4.ocaml b/Task/Fibonacci-sequence/OCaml/fibonacci-sequence-4.ocaml new file mode 100644 index 0000000000..78872a7853 --- /dev/null +++ b/Task/Fibonacci-sequence/OCaml/fibonacci-sequence-4.ocaml @@ -0,0 +1,16 @@ +open Num + +let mul (a,b,c) (d,e,f) = let bxe = b*/e in + (a*/d +/ bxe, a*/e +/ b*/f, bxe +/ c*/f) + +let id = (Int 1, Int 0, Int 1) +let rec pow a n = + if n=0 then id else + let b = pow a (n/2) in + if (n mod 2) = 0 then mul b b else mul a (mul b b) + +let fib n = + let (_,y,_) = (pow (Int 1, Int 1, Int 0) n) in + string_of_num y +;; +Printf.printf "fib %d = %s\n" 300 (fib 300) diff --git a/Task/Fibonacci-sequence/PL-pgSQL/fibonacci-sequence-1.sql b/Task/Fibonacci-sequence/PL-pgSQL/fibonacci-sequence-1.sql new file mode 100644 index 0000000000..6eaf6451f8 --- /dev/null +++ b/Task/Fibonacci-sequence/PL-pgSQL/fibonacci-sequence-1.sql @@ -0,0 +1,8 @@ +CREATE OR REPLACE FUNCTION fib(n INTEGER) RETURNS INTEGER AS $$ +BEGIN + IF (n < 2) THEN + RETURN n; + END IF; + RETURN fib(n - 1) + fib(n - 2); +END; +$$ LANGUAGE plpgsql; diff --git a/Task/Fibonacci-sequence/PL-pgSQL/fibonacci-sequence-2.sql b/Task/Fibonacci-sequence/PL-pgSQL/fibonacci-sequence-2.sql new file mode 100644 index 0000000000..a974005674 --- /dev/null +++ b/Task/Fibonacci-sequence/PL-pgSQL/fibonacci-sequence-2.sql @@ -0,0 +1,5 @@ +CREATE OR REPLACE FUNCTION fibFormula(n INTEGER) RETURNS INTEGER AS $$ +BEGIN + RETURN round(pow((pow(5, .5) + 1) / 2, n) / pow(5, .5)); +END; +$$ LANGUAGE plpgsql; diff --git a/Task/Fibonacci-sequence/PL-pgSQL/fibonacci-sequence-3.sql b/Task/Fibonacci-sequence/PL-pgSQL/fibonacci-sequence-3.sql new file mode 100644 index 0000000000..e7ab6b0f9f --- /dev/null +++ b/Task/Fibonacci-sequence/PL-pgSQL/fibonacci-sequence-3.sql @@ -0,0 +1,17 @@ +CREATE OR REPLACE FUNCTION fibLinear(n INTEGER) RETURNS INTEGER AS $$ +DECLARE + prevFib INTEGER := 0; + fib INTEGER := 1; +BEGIN + IF (n < 2) THEN + RETURN n; + END IF; + + WHILE n > 1 LOOP + SELECT fib, prevFib + fib INTO prevFib, fib; + n := n - 1; + END LOOP; + + RETURN fib; +END; +$$ LANGUAGE plpgsql; diff --git a/Task/Fibonacci-sequence/PL-pgSQL/fibonacci-sequence-4.sql b/Task/Fibonacci-sequence/PL-pgSQL/fibonacci-sequence-4.sql new file mode 100644 index 0000000000..095e00ca29 --- /dev/null +++ b/Task/Fibonacci-sequence/PL-pgSQL/fibonacci-sequence-4.sql @@ -0,0 +1,9 @@ +CREATE OR REPLACE FUNCTION fibTailRecursive(n INTEGER, prevFib INTEGER DEFAULT 0, fib INTEGER DEFAULT 1) +RETURNS INTEGER AS $$ +BEGIN + IF (n = 0) THEN + RETURN prevFib; + END IF; + RETURN fibTailRecursive(n - 1, fib, prevFib + fib); +END; +$$ LANGUAGE plpgsql; diff --git a/Task/Fibonacci-sequence/Rust/fibonacci-sequence-4.rust b/Task/Fibonacci-sequence/Rust/fibonacci-sequence-4.rust index 926c587f81..6e1b801901 100644 --- a/Task/Fibonacci-sequence/Rust/fibonacci-sequence-4.rust +++ b/Task/Fibonacci-sequence/Rust/fibonacci-sequence-4.rust @@ -1,14 +1,9 @@ -#![feature(conservative_impl_trait)] - -fn main() { - for num in fibonacci_gen(10) { - println!("{}", num); +fn fib_tail_recursive(nth: usize) -> usize { + fn fib_tail_iter(n: usize, prev_fib: usize, fib: usize) -> usize { + match n { + 0 => prev_fib, + n => fib_tail_iter(n - 1, fib, prev_fib + fib), } -} - -fn fibonacci_gen(terms: i32) -> impl Iterator { - let sqrt_5 = 5.0f64.sqrt(); - let p = (1.0 + sqrt_5) / 2.0; - let q = 1.0/p; - (1..terms).map(move |n| ((p.powi(n) + q.powi(n)) / sqrt_5 + 0.5) as u64) + } + fib_tail_iter(nth, 0, 1) } diff --git a/Task/Fibonacci-sequence/Rust/fibonacci-sequence-5.rust b/Task/Fibonacci-sequence/Rust/fibonacci-sequence-5.rust index 933fd50c9b..926c587f81 100644 --- a/Task/Fibonacci-sequence/Rust/fibonacci-sequence-5.rust +++ b/Task/Fibonacci-sequence/Rust/fibonacci-sequence-5.rust @@ -1,29 +1,14 @@ -use std::mem; - -struct Fib { - prev: usize, - curr: usize, -} - -impl Fib { - fn new() -> Self { - Fib {prev: 0, curr: 1} - } -} - -impl Iterator for Fib { - type Item = usize; - fn next(&mut self) -> Option{ - mem::swap(&mut self.curr, &mut self.prev); - self.curr.checked_add(self.prev).map(|n| { - self.curr = n; - n - }) - } -} +#![feature(conservative_impl_trait)] fn main() { - for num in Fib::new() { + for num in fibonacci_gen(10) { println!("{}", num); } } + +fn fibonacci_gen(terms: i32) -> impl Iterator { + let sqrt_5 = 5.0f64.sqrt(); + let p = (1.0 + sqrt_5) / 2.0; + let q = 1.0/p; + (1..terms).map(move |n| ((p.powi(n) + q.powi(n)) / sqrt_5 + 0.5) as u64) +} diff --git a/Task/Fibonacci-sequence/Rust/fibonacci-sequence-6.rust b/Task/Fibonacci-sequence/Rust/fibonacci-sequence-6.rust new file mode 100644 index 0000000000..933fd50c9b --- /dev/null +++ b/Task/Fibonacci-sequence/Rust/fibonacci-sequence-6.rust @@ -0,0 +1,29 @@ +use std::mem; + +struct Fib { + prev: usize, + curr: usize, +} + +impl Fib { + fn new() -> Self { + Fib {prev: 0, curr: 1} + } +} + +impl Iterator for Fib { + type Item = usize; + fn next(&mut self) -> Option{ + mem::swap(&mut self.curr, &mut self.prev); + self.curr.checked_add(self.prev).map(|n| { + self.curr = n; + n + }) + } +} + +fn main() { + for num in Fib::new() { + println!("{}", num); + } +} diff --git a/Task/Fibonacci-sequence/XPL0/fibonacci-sequence.xpl0 b/Task/Fibonacci-sequence/XPL0/fibonacci-sequence.xpl0 new file mode 100644 index 0000000000..eeca24dea9 --- /dev/null +++ b/Task/Fibonacci-sequence/XPL0/fibonacci-sequence.xpl0 @@ -0,0 +1,23 @@ +func Fib1(N); \Return Nth Fibonacci number using iteration +int N; +int Fn, F0, F1; +[F0:= 0; F1:= 1; Fn:= N; +while N > 1 do + [Fn:= F0 + F1; + F0:= F1; + F1:= Fn; + N:= N-1; + ]; +return Fn; +]; + +func Fib2(N); \Return Nth Fibonacci number using recursion +int N; +return if N < 2 then N else Fib2(N-1) + Fib2(N-2); + +int N; +[for N:= 0 to 20 do [IntOut(0, Fib1(N)); ChOut(0, ^ )]; + CrLf(0); + for N:= 0 to 20 do [IntOut(0, Fib2(N)); ChOut(0, ^ )]; + CrLf(0); +] diff --git a/Task/Fibonacci-word/Swift/fibonacci-word.swift b/Task/Fibonacci-word/Swift/fibonacci-word.swift new file mode 100644 index 0000000000..17a1470502 --- /dev/null +++ b/Task/Fibonacci-word/Swift/fibonacci-word.swift @@ -0,0 +1,42 @@ +import Foundation + +struct Fib: Sequence, IteratorProtocol { + private var cur: String + private var nex: String + + init(cur: String, nex: String) { + self.cur = cur + self.nex = nex + } + + mutating func next() -> String? { + let ret = cur + + cur = nex + nex = "\(ret)\(nex)" + + return ret + } +} + +func getEntropy(_ s: [Int]) -> Double { + var entropy = 0.0 + var hist = Array(repeating: 0.0, count: 256) + + for i in 0.. 0 { + let rat = hist[i] / Double(s.count) + entropy -= rat * log2(rat) + } + + return entropy +} + +for (i, str) in Fib(cur: "1", nex: "0").prefix(37).enumerated() { + let ent = getEntropy(str.map({ Int($0.asciiValue!) })) + + print("i: \(i) len: \(str.count) entropy: \(ent)") +} diff --git a/Task/File-input-output/Julia/file-input-output-1.julia b/Task/File-input-output/Julia/file-input-output-1.julia index 9abbf8ab39..df767c838a 100644 --- a/Task/File-input-output/Julia/file-input-output-1.julia +++ b/Task/File-input-output/Julia/file-input-output-1.julia @@ -1,2 +1,2 @@ -string = open(readall, "file1", "r") -open(io->write(io, string), "file2", "w") +mystring = read("file1", String) +open(io->write(io, mystring), "file2", "w") diff --git a/Task/File-input-output/Julia/file-input-output-3.julia b/Task/File-input-output/Julia/file-input-output-3.julia index 90a64659d0..ed36fe3a3f 100644 --- a/Task/File-input-output/Julia/file-input-output-3.julia +++ b/Task/File-input-output/Julia/file-input-output-3.julia @@ -1,5 +1,5 @@ infile = open("file1", "r") outfile = open("file2", "w") -write(outfile, readall(infile)) +write(outfile, read(infile, String)) close(outfile) close(infile) diff --git a/Task/File-input-output/Julia/file-input-output-4.julia b/Task/File-input-output/Julia/file-input-output-4.julia index 62e6874d4a..b5188895ca 100644 --- a/Task/File-input-output/Julia/file-input-output-4.julia +++ b/Task/File-input-output/Julia/file-input-output-4.julia @@ -1 +1 @@ -open(IO ->write(IO, open(readall, "file1", "r")), "file2", "w") +open(IO ->write(IO, read("file1", String)), "file2", "w") diff --git a/Task/File-input-output/Pike/file-input-output.pike b/Task/File-input-output/Pike/file-input-output.pike new file mode 100644 index 0000000000..5b1d687640 --- /dev/null +++ b/Task/File-input-output/Pike/file-input-output.pike @@ -0,0 +1,4 @@ +object lines = Stdio.File("input.txt")->line_iterator(); +object out = Stdio.File("output.txt", "cw"); +foreach(lines; int line_number; string line) + out->write(line + "\n"); diff --git a/Task/File-modification-time/Julia/file-modification-time.julia b/Task/File-modification-time/Julia/file-modification-time.julia index efb007d6ed..ee11d0b67c 100644 --- a/Task/File-modification-time/Julia/file-modification-time.julia +++ b/Task/File-modification-time/Julia/file-modification-time.julia @@ -1,3 +1,5 @@ +using Dates + fname, _ = mktemp() println("The modification time of $fname is ", Dates.unix2datetime(mtime(fname))) diff --git a/Task/File-modification-time/Rust/file-modification-time.rust b/Task/File-modification-time/Rust/file-modification-time.rust new file mode 100644 index 0000000000..467c673c8c --- /dev/null +++ b/Task/File-modification-time/Rust/file-modification-time.rust @@ -0,0 +1,12 @@ +use std::fs; + +fn main() -> std::io::Result<()> { + let metadata = fs::metadata("foo.txt")?; + + if let Ok(time) = metadata.accessed() { + println!("{:?}", time); + } else { + println!("Not supported on this platform"); + } + Ok(()) +} diff --git a/Task/Filter/Elena/filter-1.elena b/Task/Filter/Elena/filter-1.elena index 0d72130bc1..5cf495cf26 100644 --- a/Task/Filter/Elena/filter-1.elena +++ b/Task/Filter/Elena/filter-1.elena @@ -5,7 +5,7 @@ import extensions'routines; public program() { - auto array := new int[]{1,2,3,4,5}; + auto array := new int[]::(1,2,3,4,5); var evens := array.filterBy:(n => n.mod:2 == 0).toArray(); diff --git a/Task/Filter/Elena/filter-2.elena b/Task/Filter/Elena/filter-2.elena index 2c3fdf4087..3ad9bf53f0 100644 --- a/Task/Filter/Elena/filter-2.elena +++ b/Task/Filter/Elena/filter-2.elena @@ -5,7 +5,7 @@ import extensions; public program() { - int[] array := new int[]{1,2,3,4,5}; + int[] array := new int[]::(1,2,3,4,5); array .filterBy:(int n => n.mod:2 == 0) diff --git a/Task/Filter/Visual-Basic-.NET/filter.visual b/Task/Filter/Visual-Basic-.NET/filter.visual new file mode 100644 index 0000000000..6679d0206c --- /dev/null +++ b/Task/Filter/Visual-Basic-.NET/filter.visual @@ -0,0 +1,41 @@ +Module Filter + + Sub Main() + Dim array() As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} + Dim newEvenArray() As Integer + + Console.WriteLine("Current Array:") + For Each i As Integer In array + Console.WriteLine(i) + Next + + newEvenArray = filterArrayIntoNewArray(array) + + Console.WriteLine("New Filtered Array:") + For Each i As Integer In newEvenArray + Console.WriteLine(i) + Next + + array = changeExistingArray(array) + + Console.WriteLine("Orginal Array After Filtering:") + For Each i As Integer In array + Console.WriteLine(i) + Next + End Sub + + Private Function changeExistingArray(array() As Integer) As Integer() + Return filterArrayIntoNewArray(array) + End Function + + Private Function filterArrayIntoNewArray(array() As Integer) As Integer() + Dim result As New List(Of Integer) + For Each element As Integer In array + If element Mod 2 = 0 Then + result.Add(element) + End If + Next + Return result.ToArray + End Function + +End Module diff --git a/Task/Find-common-directory-path/Haskell/find-common-directory-path-2.hs b/Task/Find-common-directory-path/Haskell/find-common-directory-path-2.hs index 687279cf58..eb3382e0fb 100644 --- a/Task/Find-common-directory-path/Haskell/find-common-directory-path-2.hs +++ b/Task/Find-common-directory-path/Haskell/find-common-directory-path-2.hs @@ -1,19 +1,16 @@ import Data.List (transpose, intercalate) import Data.List.Split (splitOn) +import Data.Bool (bool) cdp :: [String] -> String -cdp xs - | null xs = [] - | otherwise = - (intercalate "/" . - fmap head . takeWhile same . transpose . fmap (splitOn "/")) - xs - -same - :: Eq a - => [a] -> Bool -same [] = True -same (x:xs) = all (x ==) xs +cdp = + flip + (bool . + intercalate "/" . + fmap head . + takeWhile ((all . (==) . head) <*> tail) . transpose . fmap (splitOn "/")) + ([]) <*> + null main :: IO () main = diff --git a/Task/Find-common-directory-path/Nim/find-common-directory-path.nim b/Task/Find-common-directory-path/Nim/find-common-directory-path.nim index ba0579de94..22925075ea 100644 --- a/Task/Find-common-directory-path/Nim/find-common-directory-path.nim +++ b/Task/Find-common-directory-path/Nim/find-common-directory-path.nim @@ -3,11 +3,11 @@ import strutils proc commonprefix(paths: openarray[string], sep = "/"): string = if paths.len == 0: return "" block outer: - for i in 0..paths[0].len: - result = paths[0][0..i] + for i in 0 ..< paths[0].len: + result = paths[0][0 .. i] for path in paths: if not path.startsWith(result): break outer - result = result[0 .. +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 + } } - -# Main Entry Point -"The common directory path is " + (Get-CommonDirectoryPath ("/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members")) diff --git a/Task/Find-common-directory-path/PowerShell/find-common-directory-path-2.psh b/Task/Find-common-directory-path/PowerShell/find-common-directory-path-2.psh index c365a556ce..8aa11bb8de 100644 --- a/Task/Find-common-directory-path/PowerShell/find-common-directory-path-2.psh +++ b/Task/Find-common-directory-path/PowerShell/find-common-directory-path-2.psh @@ -1 +1,2 @@ -The common directory path is /home/user1/tmp +"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-largest-left-truncatable-prime-in-a-given-base/Julia/find-largest-left-truncatable-prime-in-a-given-base.julia b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Julia/find-largest-left-truncatable-prime-in-a-given-base.julia index 858802b8ce..d1f3620156 100644 --- a/Task/Find-largest-left-truncatable-prime-in-a-given-base/Julia/find-largest-left-truncatable-prime-in-a-given-base.julia +++ b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Julia/find-largest-left-truncatable-prime-in-a-given-base.julia @@ -1,7 +1,7 @@ -using Primes +using Primes, Printf function addmsdigit(p::Integer, b::Integer, s::Integer) - a = Vector{typeof(p)}(0) + a = Vector{typeof(p)}() q = p for i in 1:(b-1) q += s @@ -12,7 +12,7 @@ function addmsdigit(p::Integer, b::Integer, s::Integer) end function lefttruncprime(pbase::Integer) - a = Vector{BigInt}(0) + a = Vector{BigInt}() append!(a, primes(pbase - 1)) mlt = zero(BigInt) s = one(BigInt) @@ -20,7 +20,7 @@ function lefttruncprime(pbase::Integer) mlt = maximum(a) s *= pbase for i in 1:length(a) - p = shift!(a) + p = popfirst!(a) append!(a, addmsdigit(p, pbase, s)) end end @@ -31,5 +31,5 @@ lo, hi = 3, 17 println("The largest left truncatable primes for bases", @sprintf(" %d to %d.", lo, hi)) for i in lo:hi mlt = lefttruncprime(i) - @printf("%10d %-30d (%s)\n", i, mlt, base(i, mlt)) + @printf("%10d %-30d (%s)\n", i, mlt, string(mlt, base=i)) end diff --git a/Task/Find-limit-of-recursion/Python/find-limit-of-recursion-5.py b/Task/Find-limit-of-recursion/Python/find-limit-of-recursion-5.py new file mode 100644 index 0000000000..bacc99433e --- /dev/null +++ b/Task/Find-limit-of-recursion/Python/find-limit-of-recursion-5.py @@ -0,0 +1,7 @@ +def recurseDeeper(counter): + try: + print(counter) + recurseDeeper(counter + 1) + except RecursionError: + print("RecursionError at depth", counter) + recurseDeeper(counter + 1) diff --git a/Task/Find-limit-of-recursion/Python/find-limit-of-recursion-6.py b/Task/Find-limit-of-recursion/Python/find-limit-of-recursion-6.py new file mode 100644 index 0000000000..253592a2f6 --- /dev/null +++ b/Task/Find-limit-of-recursion/Python/find-limit-of-recursion-6.py @@ -0,0 +1,2 @@ +1045 +Fatal Python error: Cannot recover from stack overflow. diff --git a/Task/Find-the-last-Sunday-of-each-month/Factor/find-the-last-sunday-of-each-month.factor b/Task/Find-the-last-Sunday-of-each-month/Factor/find-the-last-sunday-of-each-month.factor index 4628f18273..370ff97462 100644 --- a/Task/Find-the-last-Sunday-of-each-month/Factor/find-the-last-sunday-of-each-month.factor +++ b/Task/Find-the-last-Sunday-of-each-month/Factor/find-the-last-sunday-of-each-month.factor @@ -2,10 +2,10 @@ USING: calendar calendar.format command-line io kernel math math.parser sequences ; IN: rosetta-code.last-sunday -: parse-year ( -- ts ) (command-line) second string>number ; -: print-last-sun ( ts -- ) last-sunday-of-month (timestamp>ymd) nl ; +: parse-year ( -- ts ) (command-line) second string>number ; +: print-last-sun ( ts -- ) last-sunday-of-month (timestamp>ymd) nl ; : inc-month ( ts -- ts' ) 1 months time+ ; : process-month ( ts -- ts' ) dup print-last-sun inc-month ; -: main ( -- ) parse-year 12 [ process-month ] times drop ; +: main ( -- ) parse-year 12 [ process-month ] times drop ; MAIN: main diff --git a/Task/Find-the-last-Sunday-of-each-month/JavaScript/find-the-last-sunday-of-each-month-3.js b/Task/Find-the-last-Sunday-of-each-month/JavaScript/find-the-last-sunday-of-each-month-3.js index a484e0e80c..41f51bcd8e 100644 --- a/Task/Find-the-last-Sunday-of-each-month/JavaScript/find-the-last-sunday-of-each-month-3.js +++ b/Task/Find-the-last-Sunday-of-each-month/JavaScript/find-the-last-sunday-of-each-month-3.js @@ -1,16 +1,36 @@ (() => { 'use strict' + // MAIN ----------------------------------------------- + // main :: IO () + const main = () => + console.log(unlines( + map( + compose( + intercalate('\t'), + map(isoDateString) + ) + )( + transpose( + map(lastWeekDaysOfYear(days.sunday))( + enumFromTo(2019)(2022) + ) + ) + ) + )); + + // WEEKDAYS ------------------------------------------- + // lastWeekDaysOfYear :: Int -> Int -> [Date] - const lastWeekDaysOfYear = (iWeekDay, y) => [ + const lastWeekDaysOfYear = iWeekDay => + y => map((d, m) => + new Date(Date.UTC( + y, m, d - ((new Date(Date.UTC(y, m, d)) + .getDay() + (7 - iWeekDay)) % 7))))([ 31, 0 === y % 4 && 0 !== y % 100 || 0 === y % 400 ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 - ] - .map((d, m) => - new Date(Date.UTC( - y, m, d - ((new Date(Date.UTC(y, m, d)) - .getDay() + (7 - iWeekDay)) % 7)))); + ]); const days = { sunday: 0, @@ -22,34 +42,65 @@ saturday: 6 }; - // GENERIC FUNCTIONS + // GENERIC FUNCTIONS----------------------------------- - // curry :: ((a, b) -> c) -> a -> b -> c - const curry = f => a => b => f(a, b); + // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c + const compose = (...fs) => + x => fs.reduceRight((a, f) => f(a), x); + + // enumFromTo :: Int -> Int -> [Int] + const enumFromTo = m => n => + Array.from({ + length: 1 + n - m + }, (_, i) => m + i); + + // intercalate :: String -> [String] -> String + const intercalate = s => xs => + xs.join(s); // isoDateString :: Date -> String const isoDateString = dte => dte.toISOString() .substr(0, 10); - // range :: Int -> Int -> [Int] - const range = (m, n) => - Array.from({ - length: Math.floor(n - m) + 1 - }, (_, i) => m + i); + // map :: (a -> b) -> [a] -> [b] + const map = f => xs => + (Array.isArray(xs) ? ( + xs + ) : xs.split('')).map(f); + + // If some of the rows are shorter than the following rows, + // their elements are skipped: + // > transpose [[10,11],[20],[],[30,31,32]] == [[10,20,30],[11,31],[32]] // transpose :: [[a]] -> [[a]] - const transpose = lst => - lst[0].map((_, iCol) => - lst.map(row => row[iCol])); + const transpose = xss => { + const go = xss => + 0 < xss.length ? (() => { + const + h = xss[0], + t = xss.slice(1); + return 0 < h.length ? ( + [ + [h[0]].concat(t.reduce( + (a, xs) => a.concat( + 0 < xs.length ? ( + [xs[0]] + ) : [] + ), + [] + )) + ].concat(go([h.slice(1)].concat( + t.map(xs => xs.slice(1)) + ))) + ) : go(t); + })() : []; + return go(xss); + }; - // TEST - return transpose( - range(2015, 2019) - .map(curry(lastWeekDaysOfYear)(days.sunday)) - ) - .map(row => row - .map(isoDateString) - .join('\t')) - .join('\n'); + // unlines :: [String] -> String + const unlines = xs => xs.join('\n'); + + // MAIN --- + return main(); })(); diff --git a/Task/Find-the-last-Sunday-of-each-month/Phix/find-the-last-sunday-of-each-month.phix b/Task/Find-the-last-Sunday-of-each-month/Phix/find-the-last-sunday-of-each-month.phix index 1db8f921ee..96d6e761e4 100644 --- a/Task/Find-the-last-Sunday-of-each-month/Phix/find-the-last-sunday-of-each-month.phix +++ b/Task/Find-the-last-Sunday-of-each-month/Phix/find-the-last-sunday-of-each-month.phix @@ -1,6 +1,6 @@ include timedate.e -constant SUNDAY=1 +constant SUNDAY=7 procedure showlast(integer dow, integer doy, timedate td) td = adjust_timedate(td,timedelta(days:=doy-1)) diff --git a/Task/Find-the-missing-permutation/Julia/find-the-missing-permutation-1.julia b/Task/Find-the-missing-permutation/Julia/find-the-missing-permutation-1.julia index 248f785cbd..d5f0ec9220 100644 --- a/Task/Find-the-missing-permutation/Julia/find-the-missing-permutation-1.julia +++ b/Task/Find-the-missing-permutation/Julia/find-the-missing-permutation-1.julia @@ -1,8 +1,8 @@ -using Combinatorics +using BenchmarkTools, Combinatorics + function missingperm(arr::Vector) - allperms = permutations(arr[1]) + allperms = String.(permutations(arr[1])) # revised for type safety for perm in allperms - perm = convert(eltype(arr), perm) if perm ∉ arr return perm end end end diff --git a/Task/Find-the-missing-permutation/Julia/find-the-missing-permutation-2.julia b/Task/Find-the-missing-permutation/Julia/find-the-missing-permutation-2.julia index da8c559608..c588f2403f 100644 --- a/Task/Find-the-missing-permutation/Julia/find-the-missing-permutation-2.julia +++ b/Task/Find-the-missing-permutation/Julia/find-the-missing-permutation-2.julia @@ -10,8 +10,3 @@ function missingperm1(arr::Vector{<:AbstractString}) end return missperm end - -using BenchmarkTools - -@btime missingperm(arr) -@btime missingperm1(arr) diff --git a/Task/Find-the-missing-permutation/Julia/find-the-missing-permutation-3.julia b/Task/Find-the-missing-permutation/Julia/find-the-missing-permutation-3.julia new file mode 100644 index 0000000000..48e84da94b --- /dev/null +++ b/Task/Find-the-missing-permutation/Julia/find-the-missing-permutation-3.julia @@ -0,0 +1,16 @@ +function missingperm2(arr::Vector) + len = length(arr[1]) + xorval = zeros(UInt8, len) + for perm in [Vector{UInt8}(s) for s in arr], i in 1:len + xorval[i] ⊻= perm[i] + end + return String(xorval) +end + +@show missingperm(arr) +@show missingperm1(arr) +@show missingperm2(arr) + +@btime missingperm(arr) +@btime missingperm1(arr) +@btime missingperm2(arr) diff --git a/Task/First-class-environments/Factor/first-class-environments.factor b/Task/First-class-environments/Factor/first-class-environments.factor new file mode 100644 index 0000000000..52700a28fd --- /dev/null +++ b/Task/First-class-environments/Factor/first-class-environments.factor @@ -0,0 +1,21 @@ +USING: assocs continuations formatting io kernel math +math.ranges sequences ; + +: (next-hailstone) ( count value -- count' value' ) + [ 1 + ] [ dup even? [ 2/ ] [ 3 * 1 + ] if ] bi* ; + +: next-hailstone ( count value -- count' value' ) + dup 1 = [ (next-hailstone) ] unless ; + +: make-environments ( -- seq ) 12 [ 0 ] replicate 12 [1,b] zip ; + +: step ( seq -- new-seq ) + [ [ dup "%4d " printf next-hailstone ] with-datastack ] map + nl ; + +: done? ( seq -- ? ) [ second 1 = ] all? ; + +make-environments +[ dup done? ] [ step ] until nl +"Counts:" print +[ [ drop "%4d " printf ] with-datastack drop ] each nl diff --git a/Task/First-class-functions-Use-numbers-analogously/00DESCRIPTION b/Task/First-class-functions-Use-numbers-analogously/00DESCRIPTION index 916a54bc79..52f8d659a9 100644 --- a/Task/First-class-functions-Use-numbers-analogously/00DESCRIPTION +++ b/Task/First-class-functions-Use-numbers-analogously/00DESCRIPTION @@ -19,3 +19,4 @@ Applying the multiplier of a number and its inverse from the two ordered collect '''Compare and contrast the resultant program with the corresponding entry in [[First-class functions]].''' They should be close. To paraphrase the task description: Do what was done before, but with numbers rather than functions +

diff --git a/Task/First-class-functions-Use-numbers-analogously/Elena/first-class-functions-use-numbers-analogously.elena b/Task/First-class-functions-Use-numbers-analogously/Elena/first-class-functions-use-numbers-analogously.elena index 38782326bc..bf8e8d9929 100644 --- a/Task/First-class-functions-Use-numbers-analogously/Elena/first-class-functions-use-numbers-analogously.elena +++ b/Task/First-class-functions-Use-numbers-analogously/Elena/first-class-functions-use-numbers-analogously.elena @@ -10,8 +10,8 @@ public program() real z := x + y; real zi := 1.0r / (x + y); - var numlist := new real[]{ x, y, z }; - var numlisti := new real[]{ xi, yi, zi }; + var numlist := new real[]::( x, y, z ); + var numlisti := new real[]::( xi, yi, zi ); var multiplied := numlist.zipBy(numlisti, (n1,n2 => (m => n1 * n2 * m) )).toArray(); diff --git a/Task/First-class-functions-Use-numbers-analogously/REXX/first-class-functions-use-numbers-analogously.rexx b/Task/First-class-functions-Use-numbers-analogously/REXX/first-class-functions-use-numbers-analogously.rexx new file mode 100644 index 0000000000..1509507cdd --- /dev/null +++ b/Task/First-class-functions-Use-numbers-analogously/REXX/first-class-functions-use-numbers-analogously.rexx @@ -0,0 +1,13 @@ +/*REXX program to use a first-class function to use numbers analogously. */ +nums= 2.0 4.0 6.0 /*various numbers, can have fractions.*/ +invs= 1/2.0 1/4.0 1/6.0 /*inverses of the above (real) numbers.*/ + m= 0.5 /*multiplier when invoking new function*/ + do j=1 for words(nums); num= word(nums, j); inv= word(invs, j) + nf= multiplier(num, inv); interpret call nf m /*sets the var RESULT.*/ + say 'number=' @(num) 'inverse=' @(inv) 'm=' @(m) 'result=' @(result) + end /*j*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +@: return left( arg(1) / 1, 15) /*format the number, left justified. */ +multiplier: procedure expose n1n2; parse arg n1,n2; n1n2= n1 * n2; return 'a_new_func' +a_new_func: return n1n2 * arg(1) diff --git a/Task/First-class-functions/Elena/first-class-functions.elena b/Task/First-class-functions/Elena/first-class-functions.elena index 1e9992b695..6d6d634478 100644 --- a/Task/First-class-functions/Elena/first-class-functions.elena +++ b/Task/First-class-functions/Elena/first-class-functions.elena @@ -1,24 +1,18 @@ import system'routines; import system'math; import extensions'routines; +import extensions'math; extension op { compose(f,g) - = mixin f(mixin g(self).eval()).eval(); + = f(g(self)); } public program() { - var fs := new object[]{ - mssgconst sin[0], - mssgconst cos[0], - new:{ eval() { ^ __target.power:3.0r } }}; - - var gs := new object[]{ - mssgconst arcsin[0], - mssgconst arccos[0], - new:{ eval(){ ^ __target.power(1.0r / 3) } }}; + var fs := new::( mssgconst sin[0], mssgconst cos[0], (x => power(x, 3.0r)) ); + var gs := new::( mssgconst arcsin[0], mssgconst arccos[0], (x => power(x, 1.0r / 3)) ); fs.zipBy(gs, (f,g => 0.5r.compose(f,g))) .forEach:printingLn diff --git a/Task/Five-weekends/Rust/five-weekends.rust b/Task/Five-weekends/Rust/five-weekends.rust new file mode 100644 index 0000000000..e96d61032d --- /dev/null +++ b/Task/Five-weekends/Rust/five-weekends.rust @@ -0,0 +1,45 @@ +extern crate chrono; +use chrono::prelude::*; + +/// Months with 31 days +const LONGMONTHS: [u32; 7] = [1, 3, 5, 7, 8, 10, 12]; + +/// Get all the tuples (year, month) in wich there is five Fridays, five Saturdays and five Sundays +/// between the years start and end (inclusive). +fn five_weekends(start: i32, end: i32) -> Vec<(i32, u32)> { + let mut out = vec![]; + + for year in start..=end { + for month in LONGMONTHS.iter() { + // Five weekends if a 31-days month starts with a Friday. + if Local.ymd(year, *month, 1).weekday() == Weekday::Fri { + out.push((year, *month)); + } + } + } + + out +} + +fn main() { + let out = five_weekends(1900, 2100); + + let len = out.len(); + println!( + "There are {} months of which the first and last five are:", + len + ); + for (y, m) in &out[..5] { + println!("\t{} / {}", y, m); + } + println!("..."); + for (y, m) in &out[(len - 5..)] { + println!("\t{} / {}", y, m); + } +} + +#[test] +fn test() { + let out = five_weekends(1900, 2100); + assert_eq!(out.len(), 201); +} diff --git a/Task/FizzBuzz/Crystal/fizzbuzz.crystal b/Task/FizzBuzz/Crystal/fizzbuzz-1.crystal similarity index 100% rename from Task/FizzBuzz/Crystal/fizzbuzz.crystal rename to Task/FizzBuzz/Crystal/fizzbuzz-1.crystal diff --git a/Task/FizzBuzz/Crystal/fizzbuzz-2.crystal b/Task/FizzBuzz/Crystal/fizzbuzz-2.crystal new file mode 100644 index 0000000000..40cef5df0d --- /dev/null +++ b/Task/FizzBuzz/Crystal/fizzbuzz-2.crystal @@ -0,0 +1,12 @@ +1.upto(100) do |n| + case + when n % 15 == 0 + puts "FizzBuzz" + when n % 5 == 0 + puts "Buzz" + when n % 3 == 0 + puts "Fizz" + else + puts n + end +end diff --git a/Task/FizzBuzz/Erlang/fizzbuzz.erl b/Task/FizzBuzz/Erlang/fizzbuzz.erl index fa64317f37..9f070223e0 100644 --- a/Task/FizzBuzz/Erlang/fizzbuzz.erl +++ b/Task/FizzBuzz/Erlang/fizzbuzz.erl @@ -1,7 +1,8 @@ +-spec fizzbuzz() -> Result :: string(). fizzbuzz() -> F = fun(N) when N rem 15 == 0 -> "FizzBuzz"; (N) when N rem 3 == 0 -> "Fizz"; (N) when N rem 5 == 0 -> "Buzz"; (N) -> integer_to_list(N) end, - [F(N)++"\n" || N <- lists:seq(1,100)]. + lists:flatten([[F(N)] ++ ["\n"] || N <- lists:seq(1,100)]). diff --git a/Task/FizzBuzz/Java/fizzbuzz.java b/Task/FizzBuzz/Java/fizzbuzz.java index e46423d652..9e9a4e3165 100644 --- a/Task/FizzBuzz/Java/fizzbuzz.java +++ b/Task/FizzBuzz/Java/fizzbuzz.java @@ -1,16 +1,14 @@ -class FizzBuzz { - +public class FizzBuzz { public static void main(String[] args) { - - for (int i = 1; i < 101; i++) { - if ((i % 3 == 0) && (i % 5 == 0)) { - System.out.print("'fizz buzz', "); - } else if (i % 3 == 0) { - System.out.print("'fizz', "); - } else if (i % 5 == 0) { - System.out.print("'buzz', "); + for (int number = 1; number <= 100; number++) { + if (number % 15 == 0) { + System.out.println("FizzBuzz"); + } else if (number % 3 == 0) { + System.out.println("Fizz"); + } else if (number % 5 == 0) { + System.out.println("Buzz"); } else { - System.out.printf("%d, ", i); + System.out.println(number); } } } diff --git a/Task/FizzBuzz/Kotlin/fizzbuzz-1.kotlin b/Task/FizzBuzz/Kotlin/fizzbuzz-1.kotlin index 01c5cf6e46..b13fb69dd6 100644 --- a/Task/FizzBuzz/Kotlin/fizzbuzz-1.kotlin +++ b/Task/FizzBuzz/Kotlin/fizzbuzz-1.kotlin @@ -1,10 +1,12 @@ fun fizzBuzz() { - for (i in 1..100) { - when { - i % 15 == 0 -> println("FizzBuzz") - i % 3 == 0 -> println("Fizz") - i % 5 == 0 -> println("Buzz") - else -> println(i) - } + for (number in 1..100) { + println( + when { + number % 15 == 0 -> "FizzBuzz" + number % 3 == 0 -> "Fizz" + number % 5 == 0 -> "Buzz" + else -> number + } + ) } } diff --git a/Task/FizzBuzz/Kotlin/fizzbuzz-4.kotlin b/Task/FizzBuzz/Kotlin/fizzbuzz-4.kotlin index a9062c1606..bf07be3613 100644 --- a/Task/FizzBuzz/Kotlin/fizzbuzz-4.kotlin +++ b/Task/FizzBuzz/Kotlin/fizzbuzz-4.kotlin @@ -1,3 +1,3 @@ fun fizzBuzz() { - println((1..100).map{i->mapOf(0 to i,i%3 to "Fizz",i%5 to "Buzz",i%15 to "FizzBuzz")[0]}) + (1..100).forEach { println(mapOf(0 to it, it % 3 to "Fizz", it % 5 to "Buzz", it % 15 to "FizzBuzz")[0]) } } diff --git a/Task/FizzBuzz/Lua/fizzbuzz-5.lua b/Task/FizzBuzz/Lua/fizzbuzz-5.lua new file mode 100644 index 0000000000..70b1536063 --- /dev/null +++ b/Task/FizzBuzz/Lua/fizzbuzz-5.lua @@ -0,0 +1,20 @@ +#!/usr/bin/env luajit +local to=arg[1] or tonumber(arg[1]) or 100 +local CF,CB=3,5 +local cf,cb=CF,CB +for i=1,to do + cf,cb=cf-1,cb-1 + if cf~=0 and cb~=0 then + io.write(i) + else + if cf==0 then + cf=CF + io.write("Fizz") + end + if cb==0 then + cb=CB + io.write("Buzz") + end + end + io.write(", ") +end diff --git a/Task/FizzBuzz/Processing/fizzbuzz-4 b/Task/FizzBuzz/Processing/fizzbuzz-4 index a4d226ddf1..bebe6a22f1 100644 --- a/Task/FizzBuzz/Processing/fizzbuzz-4 +++ b/Task/FizzBuzz/Processing/fizzbuzz-4 @@ -1,11 +1,10 @@ for(int i = 1; i <= 100; i++){ - String output = ""; - - if(i % 3 == 0) output += "Fizz"; - if(i % 5 == 0) output += "Buzz"; - // copy & paste above line to add more tests - - if(output == "") output = int(i); - println(output); -} + String output = ""; + + if(i % 3 == 0) output += "Fizz"; + if(i % 5 == 0) output += "Buzz"; + // copy & paste above line to add more tests + + if(output == "") output = str(i); + println(output); } diff --git a/Task/FizzBuzz/Python/fizzbuzz-10.py b/Task/FizzBuzz/Python/fizzbuzz-10.py index f5123bf731..7169325b93 100644 --- a/Task/FizzBuzz/Python/fizzbuzz-10.py +++ b/Task/FizzBuzz/Python/fizzbuzz-10.py @@ -1 +1,52 @@ -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 n, + cycle([''] * 2 + ['Fizz']), + cycle([''] * 4 + ['Buzz']), + map(str, count(1)) + ) + + +# main :: IO () +def main(): + '''Display of first 100 terms of the fizzbuzz series. + ''' + print(unlines( + take(100)( + fizzBuzz() + ) + )) + + +# GENERIC ------------------------------------------------- + +# 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. + ''' + return lambda xs: ( + xs[0:n] + if isinstance(xs, (list, tuple)) + else list(islice(xs, n)) + ) + + +# unlines :: [String] -> String +def unlines(xs): + '''A single string formed by the intercalation + of a list of strings with the newline character. + ''' + return '\n'.join(xs) + + +if __name__ == '__main__': + main() diff --git a/Task/FizzBuzz/Python/fizzbuzz-11.py b/Task/FizzBuzz/Python/fizzbuzz-11.py new file mode 100644 index 0000000000..f5123bf731 --- /dev/null +++ b/Task/FizzBuzz/Python/fizzbuzz-11.py @@ -0,0 +1 @@ +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-12.py b/Task/FizzBuzz/Python/fizzbuzz-12.py new file mode 100644 index 0000000000..1bd2e48a8c --- /dev/null +++ b/Task/FizzBuzz/Python/fizzbuzz-12.py @@ -0,0 +1,12 @@ +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-3.py b/Task/FizzBuzz/Python/fizzbuzz-3.py index 45b2d7051a..c5a2a3a627 100644 --- a/Task/FizzBuzz/Python/fizzbuzz-3.py +++ b/Task/FizzBuzz/Python/fizzbuzz-3.py @@ -1 +1,9 @@ -for i in range(1,101): print("Fizz"*(i%3==0) + "Buzz"*(i%5==0) or i) +for n in range(1,101): + response = '' + + if not n%3: + response += 'Fizz' + if not n%5: + response += 'Buzz' + + print(response or n) diff --git a/Task/FizzBuzz/Python/fizzbuzz-4.py b/Task/FizzBuzz/Python/fizzbuzz-4.py index dc80287fec..45b2d7051a 100644 --- a/Task/FizzBuzz/Python/fizzbuzz-4.py +++ b/Task/FizzBuzz/Python/fizzbuzz-4.py @@ -1 +1 @@ -for i in range(100):print(i%3//2*'Fizz'+i%5//4*'Buzz'or i+1) +for i in range(1,101): print("Fizz"*(i%3==0) + "Buzz"*(i%5==0) or i) diff --git a/Task/FizzBuzz/Python/fizzbuzz-5.py b/Task/FizzBuzz/Python/fizzbuzz-5.py index 96cb0268bd..dc80287fec 100644 --- a/Task/FizzBuzz/Python/fizzbuzz-5.py +++ b/Task/FizzBuzz/Python/fizzbuzz-5.py @@ -1,3 +1 @@ -for n in range(1, 100): - fb = ''.join([ denom[1] if n % denom[0] == 0 else '' for denom in [(3,'fizz'),(5,'buzz')] ]) - print fb if fb else n +for i in range(100):print(i%3//2*'Fizz'+i%5//4*'Buzz'or i+1) diff --git a/Task/FizzBuzz/Python/fizzbuzz-6.py b/Task/FizzBuzz/Python/fizzbuzz-6.py index fefd4a687a..96cb0268bd 100644 --- a/Task/FizzBuzz/Python/fizzbuzz-6.py +++ b/Task/FizzBuzz/Python/fizzbuzz-6.py @@ -1 +1,3 @@ -print (', '.join([(x%3<1)*'Fizz'+(x%5<1)*'Buzz' or str(x) for x in range(1,101)])) +for n in range(1, 100): + fb = ''.join([ denom[1] if n % denom[0] == 0 else '' for denom in [(3,'fizz'),(5,'buzz')] ]) + print fb if fb else n diff --git a/Task/FizzBuzz/Python/fizzbuzz-7.py b/Task/FizzBuzz/Python/fizzbuzz-7.py index 746414bdc9..fefd4a687a 100644 --- a/Task/FizzBuzz/Python/fizzbuzz-7.py +++ b/Task/FizzBuzz/Python/fizzbuzz-7.py @@ -1 +1 @@ -[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)] +print (', '.join([(x%3<1)*'Fizz'+(x%5<1)*'Buzz' or str(x) for x in range(1,101)])) diff --git a/Task/FizzBuzz/Python/fizzbuzz-8.py b/Task/FizzBuzz/Python/fizzbuzz-8.py index b29ebd9a54..746414bdc9 100644 --- a/Task/FizzBuzz/Python/fizzbuzz-8.py +++ b/Task/FizzBuzz/Python/fizzbuzz-8.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/Python/fizzbuzz-9.py b/Task/FizzBuzz/Python/fizzbuzz-9.py index 7169325b93..b29ebd9a54 100644 --- a/Task/FizzBuzz/Python/fizzbuzz-9.py +++ b/Task/FizzBuzz/Python/fizzbuzz-9.py @@ -1,52 +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 n, - cycle([''] * 2 + ['Fizz']), - cycle([''] * 4 + ['Buzz']), - map(str, count(1)) - ) - - -# main :: IO () -def main(): - '''Display of first 100 terms of the fizzbuzz series. - ''' - print(unlines( - take(100)( - fizzBuzz() - ) - )) - - -# GENERIC ------------------------------------------------- - -# 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. - ''' - return lambda xs: ( - xs[0:n] - if isinstance(xs, (list, tuple)) - else list(islice(xs, n)) - ) - - -# unlines :: [String] -> String -def unlines(xs): - '''A single string formed by the intercalation - of a list of strings with the newline character. - ''' - return '\n'.join(xs) - - -if __name__ == '__main__': - main() +# print the first 100 +for i in islice(fizzbuzz, 100): + print i diff --git a/Task/FizzBuzz/VHDL/fizzbuzz.vhdl b/Task/FizzBuzz/VHDL/fizzbuzz.vhdl new file mode 100644 index 0000000000..0545f18a81 --- /dev/null +++ b/Task/FizzBuzz/VHDL/fizzbuzz.vhdl @@ -0,0 +1,29 @@ +entity fizzbuzz is +end entity fizzbuzz; + +architecture beh of fizzbuzz is + + procedure fizzbuzz(num : natural) is + begin + if num mod 15 = 0 then + report "FIZZBUZZ"; + elsif num mod 3 = 0 then + report "FIZZ"; + elsif num mod 5 = 0 then + report "BUZZ"; + else + report to_string(num); + end if; + end procedure fizzbuzz; + +begin + + p_fizz : process is + begin + for i in 1 to 100 loop + fizzbuzz(i); + end loop; + wait for 200 us; + end process p_fizz; + +end architecture beh; diff --git a/Task/Flatten-a-list/JavaScript/flatten-a-list-6.js b/Task/Flatten-a-list/JavaScript/flatten-a-list-6.js index 1bf1e4e4bd..b41147d9b6 100644 --- a/Task/Flatten-a-list/JavaScript/flatten-a-list-6.js +++ b/Task/Flatten-a-list/JavaScript/flatten-a-list-6.js @@ -1,5 +1,8 @@ -// flatten :: Nested List a -> [a] +// flatten :: NestedList a -> [a] const flatten = t => { - const go = x => Array.isArray(x) ? x.flatMap(go) : x + const go = x => + Array.isArray(x) ? ( + x.flatMap(go) + ) : x; return go(t); }; diff --git a/Task/Flatten-a-list/Julia/flatten-a-list-1.julia b/Task/Flatten-a-list/Julia/flatten-a-list-1.julia index 40d4af3b02..03d56f5ed1 100644 --- a/Task/Flatten-a-list/Julia/flatten-a-list-1.julia +++ b/Task/Flatten-a-list/Julia/flatten-a-list-1.julia @@ -1 +1,3 @@ -flat(arr::Array) = mapreduce(x -> isa(x, Array) ? flat(x) : x, append!, [], arr) +using BenchmarkTools + +flat(arr) = mapreduce(x -> x == [] || x[1] === x ? x : flat(x), vcat, arr, init=[]) diff --git a/Task/Flatten-a-list/Julia/flatten-a-list-2.julia b/Task/Flatten-a-list/Julia/flatten-a-list-2.julia index 19e66022ef..3284f87c54 100644 --- a/Task/Flatten-a-list/Julia/flatten-a-list-2.julia +++ b/Task/Flatten-a-list/Julia/flatten-a-list-2.julia @@ -1,4 +1,4 @@ -function flat2(arr) +function flat1(arr) rst = Any[] grep(v) = for x in v if isa(x, Array) grep(x) else push!(rst, x) end @@ -6,6 +6,3 @@ function flat2(arr) grep(arr) rst end - -arr = [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] -@show flat(arr) diff --git a/Task/Flatten-a-list/Julia/flatten-a-list-3.julia b/Task/Flatten-a-list/Julia/flatten-a-list-3.julia new file mode 100644 index 0000000000..6a20568d39 --- /dev/null +++ b/Task/Flatten-a-list/Julia/flatten-a-list-3.julia @@ -0,0 +1,11 @@ +flat2(arr) = (while any(a -> a isa Vector, arr) arr = collect(Iterators.flatten(arr)) end; arr) + +arr = [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] + +@show flat(arr) +@show flat1(arr) +@show flat2(arr) + +@btime flat(arr) +@btime flat1(arr) +@btime flat2(arr) diff --git a/Task/Flatten-a-list/Python/flatten-a-list-2.py b/Task/Flatten-a-list/Python/flatten-a-list-2.py index 07044f38ef..93eb895187 100644 --- a/Task/Flatten-a-list/Python/flatten-a-list-2.py +++ b/Task/Flatten-a-list/Python/flatten-a-list-2.py @@ -1,71 +1,14 @@ -'''Flatten a nested list''' +>>> def flat(lst): + i=0 + while i [a] -def flatten(x): - '''A list of atomic values resulting from fully flattening - an arbitrarily nested list.''' - return concatMap(flatten)(x) if isinstance(x, list) else [x] - - -def main(): - '''Test: flatten an arbitrarily nested list.''' - print( - fTable(__doc__ + ':')(showList)(showList)( - flatten - )([ - [[[]]], - [[1, 2, 3]], - [[1], [[2]], [[[3, 4]]]], - [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] - ]) - ) - - -# GENERIC ------------------------------------------------- - -# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c -def compose(g): - '''Right to left function composition.''' - return lambda f: lambda x: g(f(x)) - - -# concatMap :: (a -> [b]) -> [a] -> [b] -def concatMap(f): - '''A concatenated list over which a function has been mapped. - The list monad can be derived by using a function f which - wraps its output in a list, - (using an empty list to represent computational failure).''' - return lambda xs: list( - chain.from_iterable(map(f, xs)) - ) - - -# fTable :: String -> (a -> String) -> -# (b -> String) -> -# (a -> b) -> [a] -> String -def fTable(s): - '''Heading -> x display function -> - fx display function -> - f -> value list -> tabular string.''' - def go(xShow, fxShow, f, xs): - w = max(map(compose(len)(xShow), xs)) - return s + '\n' + '\n'.join([ - xShow(x).rjust(w, ' ') + (' -> ') + fxShow(f(x)) - for x in xs - ]) - return lambda xShow: lambda fxShow: lambda f: lambda xs: go( - xShow, fxShow, f, xs - ) - - -# showList :: [a] -> String -def showList(xs): - '''Stringification of a list.''' - return '[' + ','.join(str(x) for x in xs) + ']' - - -if __name__ == '__main__': - main() +>>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] +>>> flat(lst) +>>> lst +[1, 2, 3, 4, 5, 6, 7, 8] diff --git a/Task/Flatten-a-list/Python/flatten-a-list-3.py b/Task/Flatten-a-list/Python/flatten-a-list-3.py index 93eb895187..4033430e75 100644 --- a/Task/Flatten-a-list/Python/flatten-a-list-3.py +++ b/Task/Flatten-a-list/Python/flatten-a-list-3.py @@ -1,14 +1,12 @@ ->>> def flat(lst): - i=0 - while i>> def flatten(lst): + for x in lst: + if isinstance(x, list): + for x in flatten(x): + yield x + else: + yield x + >>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] ->>> flat(lst) ->>> lst +>>> print list(flatten(lst)) [1, 2, 3, 4, 5, 6, 7, 8] diff --git a/Task/Flatten-a-list/Python/flatten-a-list-4.py b/Task/Flatten-a-list/Python/flatten-a-list-4.py index de8d164e56..07044f38ef 100644 --- a/Task/Flatten-a-list/Python/flatten-a-list-4.py +++ b/Task/Flatten-a-list/Python/flatten-a-list-4.py @@ -1,76 +1,70 @@ -'''Flatten a list''' +'''Flatten a nested list''' -from functools import (reduce) from itertools import (chain) -def flatten(xs): - '''A flat list of atomic values derived - from a nested list. - ''' - return reduce( - lambda a, x: a + list(until(every(notList))( - concatMap(pureList) - )([x])), - xs, [] - ) +# flatten :: NestedList a -> [a] +def flatten(x): + '''A list of atomic values resulting from fully flattening + an arbitrarily nested list.''' + return concatMap(flatten)(x) if isinstance(x, list) else [x] -# TEST ---------------------------------------------------- def main(): - '''From nested list to flattened list''' - - print(main.__doc__ + ':\n\n') - xs = [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] + '''Test: flatten an arbitrarily nested list.''' print( - repr(xs) + ' -> ' + repr(flatten(xs)) + fTable(__doc__ + ':')(showList)(showList)( + flatten + )([ + [[[]]], + [[1, 2, 3]], + [[1], [[2]], [[[3, 4]]]], + [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] + ]) ) # GENERIC ------------------------------------------------- +# compose (<<<) :: (b -> c) -> (a -> b) -> a -> c +def compose(g): + '''Right to left function composition.''' + return lambda f: lambda x: g(f(x)) + + # concatMap :: (a -> [b]) -> [a] -> [b] def concatMap(f): '''A concatenated list over which a function has been mapped. The list monad can be derived by using a function f which wraps its output in a list, - (using an empty list to represent computational failure). - ''' + (using an empty list to represent computational failure).''' return lambda xs: list( chain.from_iterable(map(f, xs)) ) -# every :: (a -> Bool) -> [a] -> Bool -def every(p): - '''True if p(x) holds for every x in xs''' - def go(p, xs): - return all(map(p, xs)) - return lambda xs: go(p, xs) +# fTable :: String -> (a -> String) -> +# (b -> String) -> +# (a -> b) -> [a] -> String +def fTable(s): + '''Heading -> x display function -> + fx display function -> + f -> value list -> tabular string.''' + def go(xShow, fxShow, f, xs): + w = max(map(compose(len)(xShow), xs)) + return s + '\n' + '\n'.join([ + xShow(x).rjust(w, ' ') + (' -> ') + fxShow(f(x)) + for x in xs + ]) + return lambda xShow: lambda fxShow: lambda f: lambda xs: go( + xShow, fxShow, f, xs + ) -# notList :: a -> Bool -def notList(x): - '''True if the value x is not a list.''' - return not isinstance(x, list) - - -# pureList :: a -> [b] -def pureList(x): - '''x if x is a list, othewise [x]''' - return x if isinstance(x, list) else [x] - - -# until :: (a -> Bool) -> (a -> a) -> a -> a -def until(p): - '''The result of repeatedly applying f until p holds. - The initial seed value is x.''' - def go(f, x): - v = x - while not p(v): - v = f(v) - return v - return lambda f: lambda x: go(f, x) +# showList :: [a] -> String +def showList(xs): + '''Stringification of a list.''' + return '[' + ','.join(str(x) for x in xs) + ']' if __name__ == '__main__': diff --git a/Task/Flatten-a-list/Python/flatten-a-list-5.py b/Task/Flatten-a-list/Python/flatten-a-list-5.py index 4033430e75..de8d164e56 100644 --- a/Task/Flatten-a-list/Python/flatten-a-list-5.py +++ b/Task/Flatten-a-list/Python/flatten-a-list-5.py @@ -1,12 +1,77 @@ ->>> def flatten(lst): - for x in lst: - if isinstance(x, list): - for x in flatten(x): - yield x - else: - yield x +'''Flatten a list''' + +from functools import (reduce) +from itertools import (chain) ->>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] ->>> print list(flatten(lst)) -[1, 2, 3, 4, 5, 6, 7, 8] +def flatten(xs): + '''A flat list of atomic values derived + from a nested list. + ''' + return reduce( + lambda a, x: a + list(until(every(notList))( + concatMap(pureList) + )([x])), + xs, [] + ) + + +# TEST ---------------------------------------------------- +def main(): + '''From nested list to flattened list''' + + print(main.__doc__ + ':\n\n') + xs = [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] + print( + repr(xs) + ' -> ' + repr(flatten(xs)) + ) + + +# GENERIC ------------------------------------------------- + +# concatMap :: (a -> [b]) -> [a] -> [b] +def concatMap(f): + '''A concatenated list over which a function has been mapped. + The list monad can be derived by using a function f which + wraps its output in a list, + (using an empty list to represent computational failure). + ''' + return lambda xs: list( + chain.from_iterable(map(f, xs)) + ) + + +# every :: (a -> Bool) -> [a] -> Bool +def every(p): + '''True if p(x) holds for every x in xs''' + def go(p, xs): + return all(map(p, xs)) + return lambda xs: go(p, xs) + + +# notList :: a -> Bool +def notList(x): + '''True if the value x is not a list.''' + return not isinstance(x, list) + + +# pureList :: a -> [b] +def pureList(x): + '''x if x is a list, othewise [x]''' + return x if isinstance(x, list) else [x] + + +# until :: (a -> Bool) -> (a -> a) -> a -> a +def until(p): + '''The result of repeatedly applying f until p holds. + The initial seed value is x.''' + def go(f, x): + v = x + while not p(v): + v = f(v) + return v + return lambda f: lambda x: go(f, x) + + +if __name__ == '__main__': + main() diff --git a/Task/Flatten-a-list/Shen/flatten-a-list.shen b/Task/Flatten-a-list/Shen/flatten-a-list.shen new file mode 100644 index 0000000000..2aff6b1b49 --- /dev/null +++ b/Task/Flatten-a-list/Shen/flatten-a-list.shen @@ -0,0 +1,6 @@ +(define flatten +[] -> [] +[X|Y] -> (append (flatten X) (flatten Y)) +X -> [X]) + +(flatten [[1] 2 [[3 4] 5] [[[]]] [[[6]]] 7 8 []]) diff --git a/Task/Flipping-bits-game/Julia/flipping-bits-game.julia b/Task/Flipping-bits-game/Julia/flipping-bits-game.julia index bf923da648..88d132fe2d 100644 --- a/Task/Flipping-bits-game/Julia/flipping-bits-game.julia +++ b/Task/Flipping-bits-game/Julia/flipping-bits-game.julia @@ -1,8 +1,7 @@ module FlippingBitsGame -using Compat -using Compat.Printf -using Compat.Random +using Printf, Random +import Base.size, Base.show, Base.== struct Configuration M::BitMatrix @@ -34,18 +33,19 @@ end const ColIndex = Index{:C} const RowIndex = Index{:R} -function Base.flipbits!(conf::Configuration, c::ColIndex) +function flipbits!(conf::Configuration, c::ColIndex) col = @view conf.M[:, c.i] @. col = !col return conf end -function Base.flipbits!(conf::Configuration, r::RowIndex) +function flipbits!(conf::Configuration, r::RowIndex) row = @view conf.M[r.i, :] @. row = !row return conf end randomconfig(nrow::Integer, ncol::Integer) = Configuration(bitrand(nrow, ncol)) + function randommoves!(conf::Configuration, nflips::Integer) nrow, ncol = size(conf) for _ in Base.OneTo(nflips) @@ -95,3 +95,7 @@ function play() end end # module FlippingBitsGame + +using .FlippingBitsGame + +FlippingBitsGame.play() diff --git a/Task/Floyds-triangle/Julia/floyds-triangle.julia b/Task/Floyds-triangle/Julia/floyds-triangle.julia index e69de29bb2..37230297b5 100644 --- a/Task/Floyds-triangle/Julia/floyds-triangle.julia +++ b/Task/Floyds-triangle/Julia/floyds-triangle.julia @@ -0,0 +1,12 @@ +function floydtriangle(rows) + r = collect(1:div(rows *(rows + 1), 2)) + spacing = Int(ceil(log10(r[end] + 1))) + 1 + for i in 1:rows + for _ in 1:i + print(lpad(popfirst!(r), spacing)) + end + println() + end +end + +floydtriangle(5); println(); floydtriangle(14) diff --git a/Task/Forest-fire/Haskell/forest-fire.hs b/Task/Forest-fire/Haskell/forest-fire.hs index 62f705af26..609b73473f 100644 --- a/Task/Forest-fire/Haskell/forest-fire.hs +++ b/Task/Forest-fire/Haskell/forest-fire.hs @@ -1,6 +1,6 @@ -import System.Random (randomRIO) +import Control.Monad (replicateM, unless) import Data.List (tails, transpose) -import Control.Monad (liftM2, replicateM, unless) +import System.Random (randomRIO) data Cell = Empty @@ -22,7 +22,7 @@ randomChance = randomRIO (0, 1.0) :: IO Double rim :: a -> [[a]] -> [[a]] rim b = fmap (fb b) . (fb =<< rb) where - fb = liftM2 (.) (:) (flip (++) . return) + fb = (.) <$> (:) <*> (flip (++) . return) rb = fst . unzip . zip (repeat b) . head take3x3 :: [[a]] -> [[[a]]] diff --git a/Task/Forest-fire/Julia/forest-fire.julia b/Task/Forest-fire/Julia/forest-fire.julia index 0ab0740022..d7b6f11129 100644 --- a/Task/Forest-fire/Julia/forest-fire.julia +++ b/Task/Forest-fire/Julia/forest-fire.julia @@ -1,4 +1,4 @@ -# v0.6 +using Printf @enum State empty tree fire @@ -17,7 +17,7 @@ function evolution(nepoch::Int=100, init::Matrix{State}=fill(tree, 30, 50)) end end end - for i in linearindices(forest) + for i in LinearIndices(forest) # A burning cell turns into an empty cell if forest[i] == fire forest[i] = empty end # A tree ignites with probability f even if no neighbor is burning diff --git a/Task/Forest-fire/Perl/forest-fire.pl b/Task/Forest-fire/Perl/forest-fire-1.pl similarity index 100% rename from Task/Forest-fire/Perl/forest-fire.pl rename to Task/Forest-fire/Perl/forest-fire-1.pl diff --git a/Task/Forest-fire/Perl/forest-fire-2.pl b/Task/Forest-fire/Perl/forest-fire-2.pl new file mode 100644 index 0000000000..2bd9ea2a7a --- /dev/null +++ b/Task/Forest-fire/Perl/forest-fire-2.pl @@ -0,0 +1,23 @@ +#!/usr/bin/perl + +use strict; # http://www.rosettacode.org/wiki/Forest_fire +use warnings; + +my $p = 0.01; # probability of empty -> tree +my $f = 0.0001; # probability of tree -> burning + +my ($high, $wide) = split ' ', qx(stty size); # 135 174 tiny font in xterm +my $mask = 0 x $wide . (0 . 7 x ($wide - 2) . 0) x ($high - 5) . 0 x $wide; +my $forest = $mask =~ s/7/ rand() < 0.5 ? 2 : 1 /ger; + +for( 1 .. 1e3 ) + { # 0=border 1=empty 2=tree 3=burning + print "\e[H", $forest =~ tr/0123/ ^#/r, "\n"; # ^=tree #=burning tree + my $n = $forest =~ tr/123/004/r; # 4=a neighbor is burning + $forest |= 0 x $_ . $n | substr $n, $_ for 1, $wide - 1 .. $wide + 1; + $forest &= $mask; # clear borders and trim + $forest =~ tr/1-7/et10e31/; # step to next generation + $forest =~ s/t/ rand() < $f ? 3 : 2 /ge; # rule 3) tree cell to burning + $forest =~ s/e/ rand() < $p ? 2 : 1 /ge; # rule 4) empty cell to tree + select undef, undef, undef, 0.1; # comment out for full speed + } diff --git a/Task/Formal-power-series/Julia/formal-power-series-1.julia b/Task/Formal-power-series/Julia/formal-power-series-1.julia index 54056544d0..d40069e490 100644 --- a/Task/Formal-power-series/Julia/formal-power-series-1.julia +++ b/Task/Formal-power-series/Julia/formal-power-series-1.julia @@ -1,27 +1,29 @@ module FormalPowerSeries +using Printf +import Base.iterate, Base.eltype, Base.one, Base.show, Base.IteratorSize +import Base.IteratorEltype, Base.length, Base.size, Base.convert + _div(a, b) = a / b _div(a::Union{Integer,Rational}, b::Union{Integer,Rational}) = a // b abstract type AbstractFPS{T<:Number} end -Base.iteratorsize(::AbstractFPS) = Base.IsInfinite() -Base.done(::AbstractFPS, ::Any) = false -Base.iteratoreltype(::AbstractFPS) = Base.HasEltype() +Base.IteratorSize(::AbstractFPS) = Base.IsInfinite() +Base.IteratorEltype(::AbstractFPS) = Base.HasEltype() Base.eltype(::AbstractFPS{T}) where T = T Base.one(::AbstractFPS{T}) where T = ConstantFPS(one(T)) function Base.show(io::IO, fps::AbstractFPS{T}) where T itr = Iterators.take(fps, 8) - s = start(itr) - a, s = next(itr, s) + a, s = iterate(itr) print(io, a) - a, s = next(itr, s) + a, s = iterate(itr, s) @printf(io, " %s %s⋅x", ifelse(sign(a) ≥ 0, '+', '-'), abs(a)) local i = 2 - while !done(itr, s) - a, s = next(itr, s) + while (it = iterate(itr, s)) != nothing + a, s = it @printf(io, " %s %s⋅x^%i", ifelse(sign(a) ≥ 0, '+', '-'), abs(a), i) i += 1 @@ -34,9 +36,12 @@ struct MinusFPS{T,A<:AbstractFPS{T}} <: AbstractFPS{T} end Base.:-(a::AbstractFPS{T}) where T = MinusFPS{T,typeof(a)}(a) -Base.start(fps::MinusFPS) = start(fps.a) -function Base.next(fps::MinusFPS, st) - v, s = next(fps.a, st) +function Base.iterate(fps::MinusFPS) + v, s = iterate(fps.a) + return -v, s +end +function Base.iterate(fps::MinusFPS, st) + v, s = iterate(fps.a, st) return -v, s end @@ -48,11 +53,15 @@ Base.:+(a::AbstractFPS{A}, b::AbstractFPS{B}) where {A,B} = SumFPS{promote_type(A, B),typeof(a),typeof(b)}(a, b) Base.:-(a::AbstractFPS, b::AbstractFPS) = a + (-b) -Base.start(fps::SumFPS) = (start(fps.a), start(fps.b)) -function Base.next(fps::SumFPS{T,A,B}, st) where {T,A,B} +function Base.iterate(fps::SumFPS{T,A,B}) where {T,A,B} + a1, s1 = iterate(fps.a) + a2, s2 = iterate(fps.b) + return T(a1 + a2), (s1, s2) +end +function Base.iterate(fps::SumFPS{T,A,B}, st) where {T,A,B} stateA, stateB = st - valueA, stateA = next(fps.a, stateA) - valueB, stateB = next(fps.b, stateB) + valueA, stateA = iterate(fps.a, stateA) + valueB, stateB = iterate(fps.b, stateB) return T(valueA + valueB), (stateA, stateB) end @@ -63,13 +72,17 @@ end Base.:*(a::AbstractFPS{A}, b::AbstractFPS{B}) where {A,B} = ProductFPS{promote_type(A, B),typeof(a),typeof(b)}(a, b) -Base.start(fps::ProductFPS{T}) where T = (start(fps.a), start(fps.b), T[], T[]) -function Base.next(fps::ProductFPS{T,A,B}, st) where {T,A,B} +function Base.iterate(fps::ProductFPS{T}) where T + a1, s1 = iterate(fps.a) + a2, s2 = iterate(fps.b) + T(sum(a1 .* a2)), (s1, s2, T[a1], T[a2]) +end +function Base.iterate(fps::ProductFPS{T,A,B}, st) where {T,A,B} stateA, stateB, listA, listB = st - valueA, stateA = next(fps.a, stateA) - valueB, stateB = next(fps.b, stateB) + valueA, stateA = iterate(fps.a, stateA) + valueB, stateB = iterate(fps.b, stateB) push!(listA, valueA) - unshift!(listB, valueB) + pushfirst!(listB, valueB) return T(sum(listA .* listB)), (stateA, stateB, listA, listB) end @@ -78,16 +91,14 @@ struct DifferentiatedFPS{T,A<:AbstractFPS} <: AbstractFPS{T} end differentiate(fps::AbstractFPS{T}) where T = DifferentiatedFPS{T,typeof(fps)}(fps) -function Base.start(fps::DifferentiatedFPS{T,A}) where {T,A} - s = start(fps.a) - _, s = next(fps.a, s) - n = zero(T) - return n, s +function Base.iterate(fps::DifferentiatedFPS{T,A}) where {T,A} + _, s = iterate(fps.a) + return Base.iterate(fps, (zero(T), s)) end -function Base.next(fps::DifferentiatedFPS{T,A}, st) where {T,A} +function Base.iterate(fps::DifferentiatedFPS{T,A}, st) where {T,A} n, s = st n += one(n) - v, s = next(fps.a, s) + v, s = iterate(fps.a, s) return n * v, (n, s) end @@ -99,11 +110,16 @@ integrate(fps::AbstractFPS{T}, k::T=zero(T)) where T = IntegratedFPS{T,typeof(fp integrate(fps::AbstractFPS{T}, k::T=zero(T)) where T <: Integer = IntegratedFPS{Rational{T},typeof(fps)}(fps, k) -Base.start(fps::IntegratedFPS{T,A}) where {T,A} = zero(T), start(fps.a) -function Base.next(fps::IntegratedFPS{T,A}, st) where {T,A} +function Base.iterate(fps::IntegratedFPS{T,A}, st=(0, 0)) where {T,A} + if st == (0, 0) + return fps.k, (one(T), 0) + end n, s = st - iszero(n) && return fps.k, (one(n), s) - v, s = next(fps.a, s) + if n == one(T) + v, s = iterate(fps.a) + else + v, s = iterate(fps.a, s) + end r::T = _div(v, n) n += one(n) return r, (n, s) @@ -114,10 +130,10 @@ end struct FiniteFPS{T} <: AbstractFPS{T} v::NTuple{N,T} where N end -Base.start(fps::FiniteFPS) = 1 -Base.next(fps::FiniteFPS{T}, st) where T = - st > endof(fps.v) ? (zero(T), st) : (fps.v[st], st + 1) +Base.iterate(fps::FiniteFPS{T}, st=1) where T = + st > lastindex(fps.v) ? (zero(T), st) : (fps.v[st], st + 1) Base.convert(::Type{FiniteFPS}, x::Real) = FiniteFPS{typeof(x)}((x,)) +FiniteFPS(r) = convert(FiniteFPS, r) for op in (:+, :-, :*) @eval Base.$op(x::Number, a::AbstractFPS) = $op(FiniteFPS(x), a) @eval Base.$op(a::AbstractFPS, x::Number) = $op(a, FiniteFPS(x)) @@ -126,13 +142,11 @@ end struct ConstantFPS{T} <: AbstractFPS{T} k::T end -Base.start(::ConstantFPS) = nothing -Base.next(c::ConstantFPS, ::Any) = c.k, nothing +Base.iterate(c::ConstantFPS, ::Any=nothing) = c.k, nothing struct SineFPS{T} <: AbstractFPS{T} end SineFPS() = SineFPS{Rational{Int}}() -Base.start(::SineFPS) = 0, 1, 1 -function Base.next(::SineFPS{T}, st) where T +function Base.iterate(::SineFPS{T}, st=(0, 1, 1)) where T n, fac, s = st local r::T if iseven(n) @@ -148,8 +162,7 @@ end struct CosineFPS{T} <: AbstractFPS{T} end CosineFPS() = CosineFPS{Rational{Int}}() -Base.start(::CosineFPS) = 0, 1, 1 -function Base.next(::CosineFPS{T}, st) where T +function Base.iterate(::CosineFPS{T}, st=(0, 1, 1)) where T n, fac, s = st local r::T if iseven(n) diff --git a/Task/Formal-power-series/Julia/formal-power-series-2.julia b/Task/Formal-power-series/Julia/formal-power-series-2.julia index 847b66f25b..b2dd200728 100644 --- a/Task/Formal-power-series/Julia/formal-power-series-2.julia +++ b/Task/Formal-power-series/Julia/formal-power-series-2.julia @@ -1,7 +1,10 @@ +using .FormalPowerSeries + @show cosine = FormalPowerSeries.CosineFPS() @show sine = FormalPowerSeries.SineFPS() intcosine = FormalPowerSeries.integrate(cosine) +intsine = FormalPowerSeries.integrate(sine) uminintsine = 1 - FormalPowerSeries.integrate(sine) # Check coefficients up to the 20th term diff --git a/Task/Formal-power-series/Perl-6/formal-power-series.pl6 b/Task/Formal-power-series/Perl-6/formal-power-series.pl6 index f2019d0092..f2144a22e0 100644 --- a/Task/Formal-power-series/Perl-6/formal-power-series.pl6 +++ b/Task/Formal-power-series/Perl-6/formal-power-series.pl6 @@ -8,10 +8,10 @@ role FPS { method pretty($n) { sub super($i) { $i.trans('0123456789' => '⁰¹²³⁴⁵⁶⁷⁸⁹') } - my $str = $.coeffs[0].perl; - for 1..$n Z $.coeffs[1..$n] -> $i, $_ { - when * > 0 { $str ~= " + {(+$_).perl}∙x{super($i)}" } - when * < 0 { $str ~= " - {(-$_).perl}∙x{super($i)}" } + my $str = $.coeffs[0]; + for flat 1..$n Z $.coeffs[1..$n] -> $p, $c { + when $c > 0 { $str ~= " + { $c .nude.join: '/'}∙x{super($p)}" } + when $c < 0 { $str ~= " - {-$c .nude.join: '/'}∙x{super($p)}" } } $str; } @@ -38,8 +38,8 @@ class InvFPS does FPS { has FPS $.x; method coeffs { # see http://en.wikipedia.org/wiki/Formal_power_series#Inverting_series - gather { - my @a := $.x.coeffs; + flat gather { + my @a = $.x.coeffs; @a[0] != 0 or fail "Cannot invert power series with zero constant term."; take my @b = (1 / @a[0]); take @b[$_] = -@b[0] * [+] (@a[1..$_] Z* @b[$_-1...0]) for 1..*; @@ -54,7 +54,7 @@ class DerFPS does FPS { class IntFPS does FPS { has FPS $.x; - method coeffs { 0, (0..*).map: { $.x.coeffs[$_] / ($_+1) } } + method coeffs { 0, |(0..*).map: { $.x.coeffs[$_] / ($_+1) } } } class DeferredFPS does FPS { @@ -69,7 +69,7 @@ multi infix:<*>(FPS $x, FPS $y) { ProFPS.new(:$x, :$y) } multi infix:(FPS $x, FPS $y) { $x * InvFPS.new(:x($y)) } # an example of a mixed-type operator: -multi infix:<->(Numeric $x, FPS $y) { ExplicitFPS.new(:coeffs($x, 0 xx *)) - $y } +multi infix:<->(Numeric $x, FPS $y) { ExplicitFPS.new(:coeffs(lazy flat $x, 0 xx *)) - $y } # define sine and cosine in terms of each other my $sin = DeferredFPS.new; @@ -79,6 +79,6 @@ $sin.realized = $cos.integrate; # define tangent in terms of sine and cosine my $tan = $sin / $cos; -say 'sin(x) ≈ ', $sin.pretty(10); -say 'cos(x) ≈ ', $cos.pretty(10); -say 'tan(x) ≈ ', $tan.pretty(10); +say 'sin(x) ≈ ' ~ $sin.pretty(10); +say 'cos(x) ≈ ' ~ $cos.pretty(10); +say 'tan(x) ≈ ' ~ $tan.pretty(10); diff --git a/Task/Formal-power-series/Perl/formal-power-series.pl b/Task/Formal-power-series/Perl/formal-power-series.pl index a6ac3d597f..2264acc9c3 100644 --- a/Task/Formal-power-series/Perl/formal-power-series.pl +++ b/Task/Formal-power-series/Perl/formal-power-series.pl @@ -108,7 +108,7 @@ print "cos(x) ~= $cos\n"; print "tan(x) ~= $tan\n"; print "exp(x) ~= $exp\n"; -print "sin^2 + cos^s = ", $sin*$sin + $cos*$cos, "\n"; +print "sin^2 + cos^2 = ", $sin*$sin + $cos*$cos, "\n"; 1; __END__ diff --git a/Task/Formatted-numeric-output/Julia/formatted-numeric-output.julia b/Task/Formatted-numeric-output/Julia/formatted-numeric-output.julia index 92f3a5b764..de23f03bab 100644 --- a/Task/Formatted-numeric-output/Julia/formatted-numeric-output.julia +++ b/Task/Formatted-numeric-output/Julia/formatted-numeric-output.julia @@ -1,3 +1,4 @@ +using Printf test = [7.125, [rand()*10^rand(0:4) for i in 1:9]] println("Formatting some numbers with the @sprintf macro (using \"%09.3f\"):") diff --git a/Task/Formatted-numeric-output/XPL0/formatted-numeric-output.xpl0 b/Task/Formatted-numeric-output/XPL0/formatted-numeric-output.xpl0 new file mode 100644 index 0000000000..bc2b181358 --- /dev/null +++ b/Task/Formatted-numeric-output/XPL0/formatted-numeric-output.xpl0 @@ -0,0 +1,9 @@ +int C; +[Format(5, 3); \5 places before decimal point and 3 after +RlOut(8, 7.125); \output real number to internal buffer +loop [C:= ChIn(8); \read character from internal buffer + if C = ^ then C:= ^0; \change leading space characters to zeros + if C = $1A then quit; \exit loop on end-of-file (EOF = end of chars) + ChOut(0, C); \display digit character on terminal + ]; +] diff --git a/Task/Four-bit-adder/Julia/four-bit-adder-1.julia b/Task/Four-bit-adder/Julia/four-bit-adder-1.julia index da2f03738e..b5858d1631 100644 --- a/Task/Four-bit-adder/Julia/four-bit-adder-1.julia +++ b/Task/Four-bit-adder/Julia/four-bit-adder-1.julia @@ -1,3 +1,5 @@ +using Printf + xor{T<:Bool}(a::T, b::T) = (a&~b)|(~a&b) halfadder{T<:Bool}(a::T, b::T) = (xor(a,b), a&b) diff --git a/Task/Four-bit-adder/Swift/four-bit-adder.swift b/Task/Four-bit-adder/Swift/four-bit-adder.swift new file mode 100644 index 0000000000..5ce1ce3683 --- /dev/null +++ b/Task/Four-bit-adder/Swift/four-bit-adder.swift @@ -0,0 +1,26 @@ +typealias FourBit = (Int, Int, Int, Int) + +func halfAdder(_ a: Int, _ b: Int) -> (Int, Int) { + return (a ^ b, a & b) +} + +func fullAdder(_ a: Int, _ b: Int, carry: Int) -> (Int, Int) { + let (s0, c0) = halfAdder(a, b) + let (s1, c1) = halfAdder(s0, carry) + + return (s1, c0 | c1) +} + +func fourBitAdder(_ a: FourBit, _ b: FourBit) -> (FourBit, carry: Int) { + let (sum1, carry1) = halfAdder(a.3, b.3) + let (sum2, carry2) = fullAdder(a.2, b.2, carry: carry1) + let (sum3, carry3) = fullAdder(a.1, b.1, carry: carry2) + let (sum4, carryOut) = fullAdder(a.0, b.0, carry: carry3) + + return ((sum4, sum3, sum2, sum1), carryOut) +} + +let a = (0, 1, 1, 0) +let b = (0, 1, 1, 0) + +print("\(a) + \(b) = \(fourBitAdder(a, b))") diff --git a/Task/Fractal-tree/Ada/fractal-tree.ada b/Task/Fractal-tree/Ada/fractal-tree.ada new file mode 100644 index 0000000000..aa3eca5e8e --- /dev/null +++ b/Task/Fractal-tree/Ada/fractal-tree.ada @@ -0,0 +1,81 @@ +with Ada.Numerics.Elementary_Functions; + +with SDL.Video.Windows.Makers; +with SDL.Video.Renderers.Makers; +with SDL.Video.Rectangles; +with SDL.Events.Events; + +procedure Fractal_Tree is + + Width : constant := 600; + Height : constant := 600; + Level : constant := 13; + Length : constant := 130.0; + X_Start : constant := 475.0; + Y_Start : constant := 580.0; + A_Start : constant := -1.54; + Angle_1 : constant := 0.10; + Angle_2 : constant := 0.35; + C_1 : constant := 0.71; + C_2 : constant := 0.87; + + Window : SDL.Video.Windows.Window; + Renderer : SDL.Video.Renderers.Renderer; + Event : SDL.Events.Events.Events; + + procedure Draw_Tree (Level : in Natural; + Length : in Float; + Angle : in Float; + X, Y : in Float) + is + use SDL; + use Ada.Numerics.Elementary_Functions; + Pi : constant := Ada.Numerics.Pi; + X_2 : constant Float := X + Length * Cos (Angle, 2.0 * Pi); + Y_2 : constant Float := Y + Length * Sin (Angle, 2.0 * Pi); + Line : constant SDL.Video.Rectangles.Line_Segment + := ((C.int (X), C.int (Y)), (C.int (X_2), C.int (Y_2))); + begin + if Level > 0 then + Renderer.Set_Draw_Colour (Colour => (0, 220, 0, 255)); + Renderer.Draw (Line => Line); + + Draw_Tree (Level - 1, C_1 * Length, Angle + Angle_1, X_2, Y_2); + Draw_Tree (Level - 1, C_2 * Length, Angle - Angle_2, X_2, Y_2); + end if; + end Draw_Tree; + + 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; + delay 0.100; + 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 => "Fractal 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)); + + Draw_Tree (Level, Length, A_Start, X_Start, Y_Start); + Window.Update_Surface; + + Wait; + Window.Finalize; + SDL.Finalise; +end Fractal_Tree; diff --git a/Task/Fractal-tree/Frink/fractal-tree.frink b/Task/Fractal-tree/Frink/fractal-tree.frink new file mode 100644 index 0000000000..a9c2c6ac7b --- /dev/null +++ b/Task/Fractal-tree/Frink/fractal-tree.frink @@ -0,0 +1,27 @@ +// Draw Fractal Tree in Frink + +// Define the tree function +FractalTree[x1, y1, angleval, lengthval, graphicsobject] := +{ + if lengthval > 1 + { + // Define current line end points (x2 and y2) + x2 = x1 + ((cos[angleval degrees]) * lengthval) + y2 = y1 + ((sin[angleval degrees]) * lengthval) + // Draw line - notice that graphicsobject is the graphics object passed into the function. + graphicsobject.line[x1,y1,x2,y2] + + // Calculate branches. You can change the lengthval multiplier factor and angleval summand to create different trees + FractalTree[x2, y2, angleval - 20, lengthval * 0.7, graphicsobject] + FractalTree[x2, y2, angleval + 20, lengthval * 0.7, graphicsobject] + } +} + +// Create graphics object +g = new graphics + +// Start the recursive function. In Frink, a -90° angle moves from the bottom of the screen to the top. +FractalTree[0, 0, -90, 30, g] + +// Show the final tree +g.show[] diff --git a/Task/Fractran/Prolog/fractran.pro b/Task/Fractran/Prolog/fractran.pro new file mode 100644 index 0000000000..bcdace313e --- /dev/null +++ b/Task/Fractran/Prolog/fractran.pro @@ -0,0 +1,50 @@ +load(Program, Fractions) :- + re_split("[ ]+", Program, Split), odd_items(Split, TextualFractions), + maplist(convert_frac, TextualFractions, Fractions). + +odd_items(L, L) :- L = [_], !. % remove the even elements from a list. +odd_items([X,_|L], [X|R]) :- odd_items(L, R). + +convert_frac(Text, Frac) :- + re_matchsub("([0-9]+)/([0-9]+)"/t, Text, Match, []), + Frac is Match.1 rdiv Match.2. + +step(_, [], stop) :- !. +step(N, [F|Fs], R) :- + A is N*F, + (integer(A) -> R = A; step(N, Fs, R)). + +exec(Prg, Start, Lz) :- + lazy_list(transition, Prg/Start, Lz). + +transition(Prg/N0, Prg/N1, N1) :- + step(N0, Prg, N1). + +steps(K, Start, Prg, Seq) :- + exec(Prg, Start, Values), + length(Seq, K), Seq = [Start|Rest], prefix(Rest, Values), !. + + +% The actual PRIMEGEN program follows... + +primegen(Prg) :- + load("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", Prg). + +primes(N, Primes) :- + primegen(Prg), exec(Prg, 2, Steps), + length(Primes, N), capture_primes(Primes, Steps). + +capture_primes([], _) :- !. +capture_primes([P|Ps], [Q|Qs]) :- pow2(Q), !, P is lsb(Q), capture_primes(Ps, Qs). +capture_primes(Ps, [_|Qs]) :- capture_primes(Ps, Qs). + +pow2(X) :- X /\ (X-1) =:= 0. + +main :- + primegen(Prg), steps(15, 2, Prg, Steps), + format("The first 15 steps from PRIMEGEN are: ~w~n", [Steps]), + primes(20, Primes), + format("By running PRIMEGEN we found these primes: ~w~n", [Primes]), + halt. + +?- main. diff --git a/Task/Function-composition/Bracmat/function-composition.bracmat b/Task/Function-composition/Bracmat/function-composition.bracmat new file mode 100644 index 0000000000..a5384f75c4 --- /dev/null +++ b/Task/Function-composition/Bracmat/function-composition.bracmat @@ -0,0 +1,20 @@ +( ( compose + = f g + . !arg:(?f.?g)&'(.($f)$(($g)$!arg)) + ) +& compose + $ ( (=.flt$(!arg,2)) + . compose$((=.!arg*5/9).(=.!arg+-32)) + ) + : (=?FahrenheitToCelsius) +& ( FahrenheitToCelsiusExample + = deg + . chu$(x2d$b0):?deg + & out + $ ( str + $ (!arg " " !deg "F in " !deg "C = " FahrenheitToCelsius$!arg) + ) + ) +& FahrenheitToCelsiusExample$0 +& FahrenheitToCelsiusExample$100 +) diff --git a/Task/Function-composition/Python/function-composition-5.py b/Task/Function-composition/Python/function-composition-5.py new file mode 100644 index 0000000000..5659c6d6e8 --- /dev/null +++ b/Task/Function-composition/Python/function-composition-5.py @@ -0,0 +1,23 @@ +# Contents of `pip install compositions' + +class Compose(object): + def __init__(self, func): + self.func = func + + def __call__(self, x): + return self.func(x) + + def __mul__(self, neighbour): + return Compose(lambda x: self.func(neighbour.func(x))) + +# from composition.composition import Compose +if __name__ == "__main__": + # Syntax 1 + @Compose + def f(x): + return x + + # Syntax 2 + g = Compose(lambda x: x) + + print((f * g)(2)) diff --git a/Task/Function-definition/AppleScript/function-definition.applescript b/Task/Function-definition/AppleScript/function-definition.applescript index 143248de7f..cb9b2b72be 100644 --- a/Task/Function-definition/AppleScript/function-definition.applescript +++ b/Task/Function-definition/AppleScript/function-definition.applescript @@ -1,3 +1,3 @@ -on multiply(a, b) +to multiply(a as number, b as number) return a * b end diff --git a/Task/Function-frequency/Julia/function-frequency.julia b/Task/Function-frequency/Julia/function-frequency.julia index c8de1499a4..9c7e6537af 100644 --- a/Task/Function-frequency/Julia/function-frequency.julia +++ b/Task/Function-frequency/Julia/function-frequency.julia @@ -1,4 +1,4 @@ -using DataStructures +using Printf, DataStructures function funcfreqs(expr::Expr) cnt = counter(Symbol) diff --git a/Task/Gamma-function/Stata/gamma-function-1.stata b/Task/Gamma-function/Stata/gamma-function-1.stata new file mode 100644 index 0000000000..b517412c64 --- /dev/null +++ b/Task/Gamma-function/Stata/gamma-function-1.stata @@ -0,0 +1,61 @@ +mata +_gamma_coef = 1.0, + 5.772156649015328606065121e-1, +-6.558780715202538810770195e-1, +-4.200263503409523552900393e-2, + 1.665386113822914895017008e-1, +-4.219773455554433674820830e-2, +-9.621971527876973562114922e-3, + 7.218943246663099542395010e-3, +-1.165167591859065112113971e-3, +-2.152416741149509728157300e-4, + 1.280502823881161861531986e-4, +-2.013485478078823865568939e-5, +-1.250493482142670657345359e-6, + 1.133027231981695882374130e-6, +-2.056338416977607103450154e-7, + 6.116095104481415817862499e-9, + 5.002007644469222930055665e-9, +-1.181274570487020144588127e-9, + 1.04342671169110051049154e-10, + 7.782263439905071254049937e-12, +-3.696805618642205708187816e-12, + 5.100370287454475979015481e-13, +-2.05832605356650678322243e-14, +-5.348122539423017982370017e-15, + 1.226778628238260790158894e-15, +-1.181259301697458769513765e-16, + 1.186692254751600332579777e-18, + 1.412380655318031781555804e-18, +-2.298745684435370206592479e-19, + 1.714406321927337433383963e-20 + +function gamma_(x_) { + external _gamma_coef + x = x_ + y = 1 + while (x<0.5) y = y/x++ + while (x>1.5) y = --x*y + z = _gamma_coef[30] + x-- + for (i=29; i>=1; i--) z = z*x+_gamma_coef[i] + return(y/z) +} + +function map(f,a) { + n = rows(a) + p = cols(a) + b = J(n,p,.) + for (i=1; i<=n; i++) { + for (j=1; j<=p; j++) { + b[i,j] = (*f)(a[i,j]) + } + } + return(b) +} + +x=(1::1000)/100 +u=map(&gamma(),x) +v=map(&gamma_(),x) +max(abs((v-u):/u)) +end diff --git a/Task/Gamma-function/Stata/gamma-function-2.stata b/Task/Gamma-function/Stata/gamma-function-2.stata new file mode 100644 index 0000000000..58d9a017dd --- /dev/null +++ b/Task/Gamma-function/Stata/gamma-function-2.stata @@ -0,0 +1,31 @@ +from mpmath import mp + +mp.dps = 50 + +def gamma_coef(n): + a = [mp.mpf(1), mp.mpf(mp.euler)] + for k in range(3, n + 1): + s = sum((-1)**j * mp.zeta(j) * a[k - j - 1] for j in range(2, k)) + a.append((s - a[1] * a[k - 2]) / (1 - k * a[0])) + return a + +def horner(a, x): + y = 0 + for s in reversed(a): + y = y * x + s + return y + +gc = gamma_coef(30) + +def gamma_approx(x): + y = mp.mpf(1) + while x < 0.5: + y /= x + x += 1 + while x > 1.5: + x -= 1 + y *= x + return y / horner(gc, x - 1) + +for x in gc: + print(mp.nstr(x, 25)) diff --git a/Task/Gamma-function/Stata/gamma-function.stata b/Task/Gamma-function/Stata/gamma-function.stata deleted file mode 100644 index e7b0914f22..0000000000 --- a/Task/Gamma-function/Stata/gamma-function.stata +++ /dev/null @@ -1,42 +0,0 @@ -mata -_gamma_coef = 1.0, -5.7721566490153286061e-1,-6.5587807152025388108e-1, --4.2002635034095235529e-2,1.665386113822914895e-1, --4.2197734555544336748e-2,-9.6219715278769735621e-3, -7.2189432466630995424e-3,-1.1651675918590651121e-3, --2.1524167411495097282e-4,1.2805028238811618615e-4, --2.0134854780788238656e-5,-1.2504934821426706573e-6, -1.1330272319816958824e-6,-2.0563384169776071035e-7, -6.1160951044814158179e-9,5.0020076444692229301e-9, --1.1812745704870201446e-9,1.0434267116911005105e-10, -7.782263439905071254e-12,-3.6968056186422057082e-12, -5.100370287454475979e-13,-2.0583260535665067832e-14, --5.3481225394230179824e-15 - -function gamma_(x_) { - external _gamma_coef - x = x_ - for (y=1; x>2;) y = --x*y - z = _gamma_coef[24] - x-- - for (i=23; i>=1; i--) z = z*x+_gamma_coef[i] - return(y/z) -} - -function map(f,a) { - n = rows(a) - p = cols(a) - b = J(n,p,.) - for (i=1; i<=n; i++) { - for (j=1; j<=p; j++) { - b[i,j] = (*f)(a[i,j]) - } - } - return(b) -} - -x=(1::10000)/100 -u=map(&gamma(),x) -v=map(&gamma_(),x) -max(abs((u-v):/u)) -end diff --git a/Task/Gaussian-elimination/Ada/gaussian-elimination.ada b/Task/Gaussian-elimination/Ada/gaussian-elimination.ada new file mode 100644 index 0000000000..3a1b250679 --- /dev/null +++ b/Task/Gaussian-elimination/Ada/gaussian-elimination.ada @@ -0,0 +1,119 @@ +with Ada.Text_IO; +with Ada.Numerics.Generic_Real_Arrays; + +procedure Gaussian_Eliminations is + + type Real is new Float; + + package Real_Arrays is + new Ada.Numerics.Generic_Real_Arrays (Real); + use Real_Arrays; + + function Gaussian_Elimination (A : in Real_Matrix; + B : in Real_Vector) return Real_Vector + is + + procedure Swap_Row (A : in out Real_Matrix; + B : in out Real_Vector; + R_1, R_2 : in Integer) + is + Temp : Real; + begin + if R_1 = R_2 then return; end if; + + -- Swal matrix row + for Col in A'Range (1) loop + Temp := A (R_1, Col); + A (R_1, Col) := A (R_2, Col); + A (R_2, Col) := Temp; + end loop; + + -- Swap vector row + Temp := B (R_1); + B (R_1) := B (R_2); + B (R_2) := Temp; + end Swap_Row; + + AC : Real_Matrix := A; + BC : Real_Vector := B; + X : Real_Vector (A'Range (1)) := BC; + Max, Tmp : Real; + Max_Row : Integer; + begin + if + A'Length (1) /= A'Length (2) or + A'Length (1) /= B'Length + then + raise Constraint_Error with "Dimensions do not match"; + end if; + + if + A'First (1) /= A'First (2) or + A'First (1) /= B'First + then + raise Constraint_Error with "First index must be same"; + end if; + + for Dia in Ac'Range (1) loop + Max_Row := Dia; + Max := Ac (Dia, Dia); + + for Row in Dia + 1 .. Ac'Last (1) loop + Tmp := abs (Ac (Row, Dia)); + if Tmp > Max then + Max_Row := Row; + Max := Tmp; + end if; + end loop; + Swap_Row (Ac, Bc, Dia, Max_Row); + + for Row in Dia + 1 .. Ac'Last (1) loop + Tmp := Ac (Row, Dia) / Ac (Dia, Dia); + for Col in Dia + 1 .. Ac'Last (1) loop + Ac (Row, Col) := Ac (Row, Col) - Tmp * Ac (Dia, Col); + end loop; + Ac (Row, Dia) := 0.0; + Bc (Row) := Bc (Row) - Tmp * Bc (Dia); + end loop; + end loop; + + for Row in reverse Ac'Range (1) loop + Tmp := Bc (Row); + for J in reverse Row + 1 .. Ac'Last (1) loop + Tmp := Tmp - X (J) * Ac (Row, J); + end loop; + X (Row) := Tmp / Ac (Row, Row); + end loop; + + return X; + end Gaussian_Elimination; + + procedure Put (V : in 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 => 6); + Put (" "); + end loop; + Put (" ]"); + New_Line; + end Put; + + A : constant Real_Matrix := + ((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 : constant Real_Vector := + ( -0.01, 0.61, 0.91, 0.99, 0.60, 0.02 ); + + X : constant Real_Vector := Gaussian_Elimination (A, B); +begin + Put (X); +end Gaussian_Eliminations; diff --git a/Task/Gaussian-elimination/Haskell/gaussian-elimination-1.hs b/Task/Gaussian-elimination/Haskell/gaussian-elimination-1.hs index d9a7961e75..517f66c77c 100644 --- a/Task/Gaussian-elimination/Haskell/gaussian-elimination-1.hs +++ b/Task/Gaussian-elimination/Haskell/gaussian-elimination-1.hs @@ -1,57 +1,20 @@ -foldlZipWith::(a -> b -> c) -> (d -> c -> d) -> d -> [a] -> [b] -> d -foldlZipWith _ _ u [] _ = u -foldlZipWith _ _ u _ [] = u -foldlZipWith f g u (x:xs) (y:ys) = foldlZipWith f g (g u (f x y)) xs ys +isMatrix xs = null xs || all ((== (length.head $ xs)).length) xs -foldl1ZipWith::(a -> b -> c) -> (c -> c -> c) -> [a] -> [b] -> c -foldl1ZipWith _ _ [] _ = error "First list is empty" -foldl1ZipWith _ _ _ [] = error "Second list is empty" -foldl1ZipWith f g (x:xs) (y:ys) = foldlZipWith f g (f x y) xs ys - -multAdd::(a -> b -> c) -> (c -> c -> c) -> [[a]] -> [[b]] -> [[c]] -multAdd f g xs ys = map (\us -> foldl1ZipWith (\u vs -> map (f u) vs) (zipWith g) us ys) xs +isSquareMatrix xs = null xs || all ((== (length xs)).length) xs mult:: Num a => [[a]] -> [[a]] -> [[a]] -mult xs ys = multAdd (*) (+) xs ys +mult uss vss = map ((\xs -> if null xs then [] else foldl1 (zipWith (+)) xs). zipWith (\vs u -> map (u*) vs) vss) uss -bubble::([a] -> c) -> (c -> c -> Bool) -> [[a]] -> [[b]] -> ([[a]],[[b]]) -bubble _ _ [] ts = ([],ts) -bubble _ _ rs [] = (rs,[]) -bubble f g (r:rs) (t:ts) = bub r t (f r) rs ts [] [] - where - bub l k _ [] _ xs ys = (l:xs,k:ys) - bub l k _ _ [] xs ys = (l:xs,k:ys) - bub l k m (u:us) (v:vs) xs ys = ans - where - mu = f u - ans | g m mu = bub l k m us vs (u:xs) (v:ys) - | otherwise = bub u v mu us vs (l:xs) (k:ys) +gauss::[[Double]] -> [[Double]] -> [[Double]] +gauss xs bs = map (map fromRational) $ solveGauss (toR xs) (toR bs) + where toR = map $ map toRational -pivot::Num a => [a] -> [a] -> [[a]] -> [[a]] -> ([[a]],[[a]]) -pivot xs ks ys ls = go ys ls [] [] - where - x = head xs - fun r = zipWith (\u v -> u*r - v*x) - val rs ts = let f = fun (head rs) in (tail $ f xs rs,f ks ts) - go [] _ us vs = (us,vs) - go _ [] us vs = (us,vs) - go rs ts us vs = go (tail rs) (tail ts) (es:us) (fs:vs) - where (es,fs) = val (head rs) (head ts) - -triangle::(Num a,Ord a) => [[a]] -> [[a]] -> ([[a]],[[a]]) -triangle as bs = go (as,bs) [] [] - where - go ([],_) us vs = (us,vs) - go (_,[]) us vs = (us,vs) - go (rs,ts) us vs = ans - where - (xs:ys,ks:ls) = bubble (abs.head) (>=) rs ts - ans = go (pivot xs ks ys ls) (xs:us) (ks:vs) +solveGauss:: (Fractional a, Ord a) => [[a]] -> [[a]] -> [[a]] +solveGauss xs bs | null xs || null bs || length xs /= length bs || (not $ isSquareMatrix xs) || (not $ isMatrix bs) = [] + | otherwise = uncurry solveTriangle $ triangle xs bs solveTriangle::(Fractional a,Eq a) => [[a]] -> [[a]] -> [[a]] -solveTriangle [] _ = [] -solveTriangle _ [] = [] -solveTriangle as _ | not.null.dropWhile ((/= 0).head) $ as = [] +solveTriangle us _ | not.null.dropWhile ((/= 0).head) $ us = [] solveTriangle ([c]:as) (b:bs) = go as bs [map (/c) b] where val us vs ws = let u = head us in map (/u) $ zipWith (-) vs (head $ mult [tail us] ws) @@ -59,45 +22,19 @@ solveTriangle ([c]:as) (b:bs) = go as bs [map (/c) b] go _ [] zs = zs go (x:xs) (y:ys) zs = go xs ys $ (val x y zs):zs -solveGauss:: (Fractional a, Ord a) => [[a]] -> [[a]] -> [[a]] -solveGauss as bs = uncurry solveTriangle $ triangle as bs +triangle::(Num a, Ord a) => [[a]] -> [[a]] -> ([[a]],[[a]]) +triangle xs bs = triang ([],[]) (xs,bs) + where + triang ts (_,[]) = ts + triang ts ([],_) = ts + triang (os,ps) zs = triang (us:os,cs:ps).unzip $ [(fun tus vs, fun cs es) | (v:vs,es) <- zip uss css,let fun = zipWith (\x y -> v*x - u*y)] + where ((us@(u:tus)):uss,cs:css) = bubble zs -matI::(Num a) => Int -> [[a]] -matI n = [ [fromIntegral.fromEnum $ i == j | j <- [1..n]] | i <- [1..n]] - -task::[[Rational]] -> [[Rational]] -> IO() -task a b = do - let x = solveGauss a b - let u = map (map fromRational) x - let y = mult a x - let identity = matI (length x) - let a1 = solveGauss a identity - let h = mult a a1 - let z = mult a1 b - putStrLn "a =" - mapM_ print a - putStrLn "b =" - mapM_ print b - putStrLn "solve: a * x = b => x = solveGauss a b =" - mapM_ print x - putStrLn "u = fromRationaltoDouble x =" - mapM_ print u - putStrLn "verification: y = a * x = mult a x =" - mapM_ print y - putStrLn $ "test: y == b = " - print $ y == b - putStrLn "identity matrix: identity =" - mapM_ print identity - putStrLn "find: a1 = inv(a) => solve: a * a1 = identity => a1 = solveGauss a identity =" - mapM_ print a1 - putStrLn "verification: h = a * a1 = mult a a1 =" - mapM_ print h - putStrLn $ "test: h == identity = " - print $ h == identity - putStrLn "z = a1 * b = mult a1 b =" - mapM_ print z - putStrLn "test: z == x =" - print $ z == x +bubble::(Num a, Ord a) => ([[a]],[[a]]) -> ([[a]],[[a]]) +bubble (xs,bs) = (go xs, go bs) + where + idmax = snd.minimum.flip zip [0..].map (negate.abs.head) $ xs + go ys = let (us,vs) = splitAt idmax ys in vs ++ us main = do let a = [[1.00, 0.00, 0.00, 0.00, 0.00, 0.00], @@ -107,4 +44,4 @@ main = do [1.00, 2.51, 6.32, 15.88, 39.90, 100.28], [1.00, 3.14, 9.87, 31.01, 97.41, 306.02]] let b = [[-0.01], [0.61], [0.91], [0.99], [0.60], [0.02]] - task a b + mapM_ print $ gauss a b diff --git a/Task/Gaussian-elimination/Haskell/gaussian-elimination-2.hs b/Task/Gaussian-elimination/Haskell/gaussian-elimination-2.hs index 41fa96b929..8e73bdede3 100644 --- a/Task/Gaussian-elimination/Haskell/gaussian-elimination-2.hs +++ b/Task/Gaussian-elimination/Haskell/gaussian-elimination-2.hs @@ -1,70 +1,66 @@ -foldlZipWith::(a -> b -> c) -> (d -> c -> d) -> d -> [a] -> [b] -> d -foldlZipWith _ _ u [] _ = u -foldlZipWith _ _ u _ [] = u -foldlZipWith f g u (x:xs) (y:ys) = foldlZipWith f g (g u (f x y)) xs ys - -foldl1ZipWith::(a -> b -> c) -> (c -> c -> c) -> [a] -> [b] -> c -foldl1ZipWith _ _ [] _ = error "First list is empty" -foldl1ZipWith _ _ _ [] = error "Second list is empty" -foldl1ZipWith f g (x:xs) (y:ys) = foldlZipWith f g (f x y) xs ys - -multAdd::(a -> b -> c) -> (c -> c -> c) -> [[a]] -> [[b]] -> [[c]] -multAdd f g xs ys = map (\us -> foldl1ZipWith (\u vs -> map (f u) vs) (zipWith g) us ys) xs - mult:: Num a => [[a]] -> [[a]] -> [[a]] -mult xs ys = multAdd (*) (+) xs ys +mult uss vss = map ((\xs -> if null xs then [] else foldl1 (zipWith (+)) xs). zipWith (\vs u -> map (u*) vs) vss) uss -triangle::(Fractional a, Ord a) => [[a]] -> [[a]] -> (a,[(([a],[a]),Int)]) -triangle as bs = pivot 1 [] $ zipWith3 (\x y i -> ((x,y),i)) as bs [(0::Int)..] +bubble::([a] -> c) -> (c -> c -> Bool) -> [[a]] -> [[b]] -> ([[a]],[[b]]) +bubble _ _ [] ts = ([],ts) +bubble _ _ rs [] = (rs,[]) +bubble f g (r:rs) (t:ts) = bub r t (f r) rs ts [] [] where - good rs ts = (abs.head.fst.fst $ ts) <= (abs.head.fst.fst $ rs) - go (us,vs) ((os,ps),i) = if o == 0 then ((rs,f vs ps),i) else ((f us rs,f vs ps),i) + bub l k _ [] _ xs ys = (l:xs,k:ys) + bub l k _ _ [] xs ys = (l:xs,k:ys) + bub l k m (u:us) (v:vs) xs ys = ans where - (o,rs) = (head os,tail os) - f = zipWith (\x y -> y - x*o) - change i (ys:zs) = map (\xs -> if (==i).snd $ xs then ys else xs) zs - pivot d ls [] = (d,ls) - pivot d ls zs@((_,j):ys) = if u == 0 then (0,ls) else pivot e (ps:ls) ws - where - e = if i == j then u*d else -u*d - ws = map (go (map (/u) us,map (/u) vs)) $ if i == j then ys else change i zs - ps@((u:us,vs),i) = foldl1 (\rs ts -> if good rs ts then rs else ts) zs + mu = f u + ans | g m mu = bub l k m us vs (u:xs) (v:ys) + | otherwise = bub u v mu us vs (l:xs) (k:ys) --- ((det,sol),permutation) = gauss as bs --- det = determinant as --- sol is solution of: as * sol = bs --- perm is a permutation with: (matPerm perm) * as * sol = (matPerm perm) * bs -gauss::(Fractional a,Ord a) => [[a]] -> [[a]] -> ((a,[[a]]),[Int]) -gauss as bs = if 0 == det then ((0,[]),[]) else solveTriangle ms +pivot::Num a => [a] -> [a] -> [[a]] -> [[a]] -> ([[a]],[[a]]) +pivot xs ks ys ls = go ys ls [] [] where - (det,ms) = triangle as bs - solveTriangle ((([c],b),i):sys) = go sys [map (/c) b] [i] + x = head xs + fun r = zipWith (\u v -> u*r - v*x) + val rs ts = let f = fun (head rs) in (tail $ f xs rs,f ks ts) + go [] _ us vs = (us,vs) + go _ [] us vs = (us,vs) + go rs ts us vs = go (tail rs) (tail ts) (es:us) (fs:vs) + where (es,fs) = val (head rs) (head ts) + +triangle::(Num a,Ord a) => [[a]] -> [[a]] -> ([[a]],[[a]]) +triangle as bs = go (as,bs) [] [] + where + go ([],_) us vs = (us,vs) + go (_,[]) us vs = (us,vs) + go (rs,ts) us vs = ans where - val us vs ws = let u = head us in map (/u) $ zipWith (-) vs (head $ mult [tail us] ws) - go [] zs is = ((det,zs),is) - go (((x,y),i):sys) zs is = go sys ((val x y zs):zs) (i:is) + (xs:ys,ks:ls) = bubble (abs.head) (>=) rs ts + ans = go (pivot xs ks ys ls) (xs:us) (ks:vs) -solveGauss::(Fractional a,Ord a) => [[a]] -> [[a]] -> [[a]] -solveGauss as = snd.fst.gauss as +solveTriangle::(Fractional a,Eq a) => [[a]] -> [[a]] -> [[a]] +solveTriangle [] _ = [] +solveTriangle _ [] = [] +solveTriangle as _ | not.null.dropWhile ((/= 0).head) $ as = [] +solveTriangle ([c]:as) (b:bs) = go as bs [map (/c) b] + where + val us vs ws = let u = head us in map (/u) $ zipWith (-) vs (head $ mult [tail us] ws) + go [] _ zs = zs + go _ [] zs = zs + go (x:xs) (y:ys) zs = go xs ys $ (val x y zs):zs -matI::Num a => Int -> [[a]] -matI n = [ [fromIntegral.fromEnum $ i == j | i <- [1..n]] | j <- [1..n]] +solveGauss:: (Fractional a, Ord a) => [[a]] -> [[a]] -> [[a]] +solveGauss as bs = uncurry solveTriangle $ triangle as bs -matPerm::Num a => [Int] -> [[a]] -matPerm ns = [ [fromIntegral.fromEnum $ i == j | (j,_) <- zip [0..] ns] | i <- ns] +matI::(Num a) => Int -> [[a]] +matI n = [ [fromIntegral.fromEnum $ i == j | j <- [1..n]] | i <- [1..n]] task::[[Rational]] -> [[Rational]] -> IO() task a b = do - let ((d,x),perm) = gauss a b - let ps = matPerm perm - let u = map (map fromRational) x - let y = mult a x - let identity = matI (length x) - let a1 = solveGauss a identity - let h = mult a a1 - let z = mult a1 b - putStrLn "d = determinant a =" - print d + let x = solveGauss a b + let u = map (map fromRational) x + let y = mult a x + let identity = matI (length x) + let a1 = solveGauss a identity + let h = mult a a1 + let z = mult a1 b putStrLn "a =" mapM_ print a putStrLn "b =" @@ -77,8 +73,6 @@ task a b = do mapM_ print y putStrLn $ "test: y == b = " print $ y == b - putStrLn "ps is the permutation associated to matrix a and ps =" - mapM_ print ps putStrLn "identity matrix: identity =" mapM_ print identity putStrLn "find: a1 = inv(a) => solve: a * a1 = identity => a1 = solveGauss a identity =" @@ -99,5 +93,5 @@ main = do [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]] - let b = [[-0.01], [0.61], [0.91], [0.99], [0.60], [0.02]] + let b = [[-0.01], [0.61], [0.91], [0.99], [0.60], [0.02]] task a b diff --git a/Task/Gaussian-elimination/Haskell/gaussian-elimination-3.hs b/Task/Gaussian-elimination/Haskell/gaussian-elimination-3.hs new file mode 100644 index 0000000000..8ff73ef931 --- /dev/null +++ b/Task/Gaussian-elimination/Haskell/gaussian-elimination-3.hs @@ -0,0 +1,90 @@ +mult:: Num a => [[a]] -> [[a]] -> [[a]] +mult uss vss = map ((\xs -> if null xs then [] else foldl1 (zipWith (+)) xs). zipWith (\vs u -> map (u*) vs) vss) uss + +triangle::(Fractional a, Ord a) => [[a]] -> [[a]] -> (a,[(([a],[a]),Int)]) +triangle as bs = pivot 1 [] $ zipWith3 (\x y i -> ((x,y),i)) as bs [(0::Int)..] + where + good rs ts = (abs.head.fst.fst $ ts) <= (abs.head.fst.fst $ rs) + go (us,vs) ((os,ps),i) = if o == 0 then ((rs,f vs ps),i) else ((f us rs,f vs ps),i) + where + (o,rs) = (head os,tail os) + f = zipWith (\x y -> y - x*o) + change i (ys:zs) = map (\xs -> if (==i).snd $ xs then ys else xs) zs + pivot d ls [] = (d,ls) + pivot d ls zs@((_,j):ys) = if u == 0 then (0,ls) else pivot e (ps:ls) ws + where + e = if i == j then u*d else -u*d + ws = map (go (map (/u) us,map (/u) vs)) $ if i == j then ys else change i zs + ps@((u:us,vs),i) = foldl1 (\rs ts -> if good rs ts then rs else ts) zs + +-- ((det,sol),permutation) = gauss as bs +-- det = determinant as +-- sol is solution of: as * sol = bs +-- perm is a permutation with: (matPerm perm) * as * sol = (matPerm perm) * bs +gauss::(Fractional a,Ord a) => [[a]] -> [[a]] -> ((a,[[a]]),[Int]) +gauss as bs = if 0 == det then ((0,[]),[]) else solveTriangle ms + where + (det,ms) = triangle as bs + solveTriangle ((([c],b),i):sys) = go sys [map (/c) b] [i] + where + val us vs ws = let u = head us in map (/u) $ zipWith (-) vs (head $ mult [tail us] ws) + go [] zs is = ((det,zs),is) + go (((x,y),i):sys) zs is = go sys ((val x y zs):zs) (i:is) + +solveGauss::(Fractional a,Ord a) => [[a]] -> [[a]] -> [[a]] +solveGauss as = snd.fst.gauss as + +matI::Num a => Int -> [[a]] +matI n = [ [fromIntegral.fromEnum $ i == j | i <- [1..n]] | j <- [1..n]] + +matPerm::Num a => [Int] -> [[a]] +matPerm ns = [ [fromIntegral.fromEnum $ i == j | (j,_) <- zip [0..] ns] | i <- ns] + +task::[[Rational]] -> [[Rational]] -> IO() +task a b = do + let ((d,x),perm) = gauss a b + let ps = matPerm perm + let u = map (map fromRational) x + let y = mult a x + let identity = matI (length x) + let a1 = solveGauss a identity + let h = mult a a1 + let z = mult a1 b + putStrLn "d = determinant a =" + print d + putStrLn "a =" + mapM_ print a + putStrLn "b =" + mapM_ print b + putStrLn "solve: a * x = b => x = solveGauss a b =" + mapM_ print x + putStrLn "u = fromRationaltoDouble x =" + mapM_ print u + putStrLn "verification: y = a * x = mult a x =" + mapM_ print y + putStrLn $ "test: y == b = " + print $ y == b + putStrLn "ps is the permutation associated to matrix a and ps =" + mapM_ print ps + putStrLn "identity matrix: identity =" + mapM_ print identity + putStrLn "find: a1 = inv(a) => solve: a * a1 = identity => a1 = solveGauss a identity =" + mapM_ print a1 + putStrLn "verification: h = a * a1 = mult a a1 =" + mapM_ print h + putStrLn $ "test: h == identity = " + print $ h == identity + putStrLn "z = a1 * b = mult a1 b =" + mapM_ print z + putStrLn "test: z == x =" + print $ z == x + +main = do + let 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]] + let b = [[-0.01], [0.61], [0.91], [0.99], [0.60], [0.02]] + task a b diff --git a/Task/Gaussian-elimination/R/gaussian-elimination.r b/Task/Gaussian-elimination/R/gaussian-elimination.r new file mode 100644 index 0000000000..9148959371 --- /dev/null +++ b/Task/Gaussian-elimination/R/gaussian-elimination.r @@ -0,0 +1,35 @@ +gauss <- function(a, b) { + n <- nrow(a) + det <- 1 + + for (i in seq_len(n - 1)) { + j <- which.max(a[i:n, i]) + i - 1 + if (j != i) { + a[c(i, j), i:n] <- a[c(j, i), i:n] + b[c(i, j), ] <- b[c(j, i), ] + det <- -det + } + + k <- seq(i + 1, n) + for (j in k) { + s <- a[[j, i]] / a[[i, i]] + a[j, k] <- a[j, k] - s * a[i, k] + b[j, ] <- b[j, ] - s * b[i, ] + } + } + + for (i in seq(n, 1)) { + if (i < n) { + for (j in seq(i + 1, n)) { + b[i, ] <- b[i, ] - a[[i, j]] * b[j, ] + } + } + b[i, ] <- b[i, ] / a[[i, i]] + det <- det * a[[i, i]] + } + + list(x=b, det=det) +} + +a <- matrix(c(2, 9, 4, 7, 5, 3, 6, 1, 8), 3, 3, byrow=T) +gauss(a, diag(3)) diff --git a/Task/Gaussian-elimination/REXX/gaussian-elimination-2.rexx b/Task/Gaussian-elimination/REXX/gaussian-elimination-2.rexx index 1f05d31cef..f73e64b932 100644 --- a/Task/Gaussian-elimination/REXX/gaussian-elimination-2.rexx +++ b/Task/Gaussian-elimination/REXX/gaussian-elimination-2.rexx @@ -1,39 +1,38 @@ /*REXX program solves Ax=b with Gaussian elimination and backwards substitution. */ -parse arg iFID . /*obtain optional argument from the CL.*/ numeric digits 1000 /*heavy─duty decimal digits precision. */ +parse arg iFID . /*obtain optional argument from the CL.*/ if iFID=='' | iFID=="," then iFID= 'GAUSS_E.DAT' /*Not specified? Then use the default.*/ - do rec=1 while lines(iFID) \== 0 /*read the equation sets. */ - #=0 /*the number of equations (so far). */ + do rec=1 while lines(iFID) \== 0 /*read the equation sets. */ + #= 0 /*the number of equations (so far). */ do $=1 while lines(iFID) \== 0 /*process the equation. */ - z=linein(iFID); if z='' then leave /*Is this a blank line? end─of─data.*/ + z= linein(iFID); if z='' then leave /*Is this a blank line? end─of─data.*/ if $==1 then do; say; say center(' equations ', 75, "▓"); say end /* [↑] if 1st equation, then show hdr.*/ say z /*display an equation to the terminal. */ if left(space(z), 1)=='*' then iterate /*Is this a comment? Then ignore it.*/ - #=# + 1; n=words(z) - 1 /*assign equation #; calculate # items.*/ + #= # + 1; n= words(z) - 1 /*assign equation #; calculate # items.*/ do e=1 for n; a.#.e= word(z, e) end /*e*/ /* [↑] process A numbers. */ - b.#=word(z, n + 1) /* ◄─── " B " */ + b.#= word(z, n + 1) /* ◄─── " B " */ end /*$*/ if #\==0 then call Gauss_elim /*Not zero? Then display the results. */ end /*rec*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -Gauss_elim: do j=1 for n; jp=j + 1 - do i=jp to n; _=a.j.j / a.i.j - do k=jp to n; a.i.k=a.j.k - _ * a.i.k +Gauss_elim: say; do j=1 for n; jp= j + 1 + do i=jp to n; _= a.j.j / a.i.j + do k=jp to n; a.i.k= a.j.k - _ * a.i.k end /*k*/ - b.i=b.j - _ * b.i + b.i= b.j - _ * b.i end /*i*/ end /*j*/ - x.n=b.n / a.n.n - do j=n-1 to 1 by -1; _=0 - do i=j+1 to n; _=_ + a.j.i * x.i + x.n= b.n / a.n.n + do j=n-1 to 1 by -1; _= 0 + do i=j+1 to n; _= _ + a.j.i * x.i end /*i*/ - x.j=(b.j - _) / a.j.j + x.j= (b.j - _) / a.j.j end /*j*/ /* [↑] uses backwards substitution. */ - say - numeric digits 8 /*for the display, only use 8 digits. */ + numeric digits /*for the display, only use 8 digits. */ say center('solution', 75, "═"); say /*a title line for articulated output. */ do o=1 for n; say right('x['o"] = ", 38) left('', x.o>=0) x.o/1 end /*o*/ diff --git a/Task/Gaussian-elimination/REXX/gaussian-elimination-3.rexx b/Task/Gaussian-elimination/REXX/gaussian-elimination-3.rexx index 62b0ddf25e..92f34eb5c6 100644 --- a/Task/Gaussian-elimination/REXX/gaussian-elimination-3.rexx +++ b/Task/Gaussian-elimination/REXX/gaussian-elimination-3.rexx @@ -2,46 +2,45 @@ numeric digits 1000 /*heavy─duty decimal digits precision. */ parse arg iFID . /*obtain optional argument from the CL.*/ if iFID=='' | iFID=="," then iFID= 'GAUSS_E.DAT' /*Not specified? Then use the default.*/ -pad=left('', 23) /*used for indenting residual numbers. */ +pad= left('', 23) /*used for indenting residual numbers. */ do rec=1 while lines(iFID) \== 0 /*read the equation sets. */ #=0 /*the number of equations (so far). */ do $=1 while lines(iFID) \== 0 /*process the equation. */ - z=linein(iFID); if z='' then leave /*Is this a blank line? end─of─data.*/ + z= linein(iFID); if z='' then leave /*Is this a blank line? end─of─data.*/ if $==1 then do; say; say center(' equations ', 75, "▓"); say end /* [↑] if 1st equation, then show hdr.*/ say z /*display an equation to the terminal. */ if left(space(z), 1)=='*' then iterate /*Is this a comment? Then ignore it.*/ - #=# + 1; n=words(z) - 1 /*assign equation #; calculate # items.*/ + #= # + 1; n= words(z) - 1 /*assign equation #; calculate # items.*/ do e=1 for n; a.#.e= word(z, e); oa.#.e= a.#.e end /*e*/ /* [↑] process A numbers; save orig.*/ - b.#=word(z, n + 1); ob.#=b.# /* ◄─── " B " " " */ + b.#= word(z, n+1); ob.#=b.# /* ◄─── " B " " " */ end /*$*/ if #\==0 then call Gauss_elim /*Not zero? Then display the results. */ say do i=1 for n; r=0 /*display the residuals to the terminal*/ - do j=1 for n; r=r + oa.i.j * x.j /* ┌───◄ don't display a fraction if */ - end /*j*/ /* ↓ res ≤ 5% of significant digs.*/ - r=format(r - ob.i, , digits() - digits() * 0.05 % 1 , 0) / 1 /*should be tiny*/ + do j=1 for n; r=r + oa.i.j * x.j /* ┌───◄ don't display a fraction if */ + end /*j*/ /* ↓ res ≤ 5% of significant digs.*/ + r= format(r-ob.i, , digits() - digits() * 0.05 % 1 , 0) / 1 /*should be tiny*/ say pad 'residual['right(i, length(n) )"] = " left('', r>=0) r /*right justify.*/ end /*i*/ end /*rec*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -Gauss_elim: do j=1 for n; jp=j + 1 - do i=jp to n; _=a.j.j / a.i.j - do k=jp to n; a.i.k=a.j.k - _ * a.i.k +Gauss_elim: say; do j=1 for n; jp= j + 1 + do i=jp to n; _= a.j.j / a.i.j + do k=jp to n; a.i.k= a.j.k - _ * a.i.k end /*k*/ - b.i=b.j - _ * b.i + b.i= b.j - _ * b.i end /*i*/ end /*j*/ - x.n=b.n / a.n.n - do j=n-1 to 1 by -1; _=0 - do i=j+1 to n; _=_ + a.j.i * x.i + x.n= b.n / a.n.n + do j=n-1 to 1 by -1; _= 0 + do i=j+1 to n; _= _ + a.j.i * x.i end /*i*/ - x.j=(b.j - _) / a.j.j + x.j= (b.j - _) / a.j.j end /*j*/ /* [↑] uses backwards substitution. */ - say - numeric digits 8 /*for the display, only use 8 digits. */ + numeric digits /*for the display, only use 8 digits. */ say center('solution', 75, "═"); say /*a title line for articulated output. */ do o=1 for n; say right('x['o"] = ", 38) left('', x.o>=0) x.o/1 end /*o*/ diff --git a/Task/Generate-Chess960-starting-position/Factor/generate-chess960-starting-position-1.factor b/Task/Generate-Chess960-starting-position/Factor/generate-chess960-starting-position-1.factor new file mode 100644 index 0000000000..3f7ae93aab --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Factor/generate-chess960-starting-position-1.factor @@ -0,0 +1,28 @@ +USING: io kernel math random sequences ; +IN: rosetta-code.chess960 + +: empty ( seq -- n ) 32 swap indices random ; ! return a random empty index (i.e. equal to 32) of seq +: next ( seq -- n ) 32 swap index ; ! return the leftmost empty index of seq +: place ( seq elt n -- seq' ) rot [ set-nth ] keep ; ! set nth member of seq to elt, keeping seq on the stack + +: white-bishop ( -- elt n ) CHAR: ♗ 4 random 2 * ; +: black-bishop ( -- elt n ) white-bishop 1 + ; +: queen ( seq -- seq elt n ) CHAR: ♕ over empty ; +: knight ( seq -- seq elt n ) CHAR: ♘ over empty ; +: rook ( seq -- seq elt n ) CHAR: ♖ over next ; +: king ( seq -- seq elt n ) CHAR: ♔ over next ; + +: chess960 ( -- str ) + " " clone + black-bishop place + white-bishop place + queen place + knight place + knight place + rook place + king place + rook place ; + +: chess960-demo ( -- ) 5 [ chess960 print ] times ; + +MAIN: chess960-demo diff --git a/Task/Generate-Chess960-starting-position/Factor/generate-chess960-starting-position-2.factor b/Task/Generate-Chess960-starting-position/Factor/generate-chess960-starting-position-2.factor new file mode 100644 index 0000000000..caf5d61eb8 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Factor/generate-chess960-starting-position-2.factor @@ -0,0 +1,3 @@ +USING: chess960 prettyprint ; + +chess960-position . diff --git a/Task/Generate-lower-case-ASCII-alphabet/Elena/generate-lower-case-ascii-alphabet.elena b/Task/Generate-lower-case-ASCII-alphabet/Elena/generate-lower-case-ascii-alphabet.elena index 01a605e504..b7f572c435 100644 --- a/Task/Generate-lower-case-ASCII-alphabet/Elena/generate-lower-case-ascii-alphabet.elena +++ b/Task/Generate-lower-case-ASCII-alphabet/Elena/generate-lower-case-ascii-alphabet.elena @@ -3,7 +3,7 @@ import system'collections; singleton Alphabet : Enumerable { - Enumerator enumerator() = new Enumerator: + Enumerator enumerator() = new Enumerator:: { char current; diff --git a/Task/Generate-lower-case-ASCII-alphabet/Frink/generate-lower-case-ascii-alphabet-1.frink b/Task/Generate-lower-case-ASCII-alphabet/Frink/generate-lower-case-ascii-alphabet-1.frink new file mode 100644 index 0000000000..10c3b48e1e --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Frink/generate-lower-case-ascii-alphabet-1.frink @@ -0,0 +1 @@ +map["char", char["a"] to char["z"]] diff --git a/Task/Generate-lower-case-ASCII-alphabet/Frink/generate-lower-case-ascii-alphabet-2.frink b/Task/Generate-lower-case-ASCII-alphabet/Frink/generate-lower-case-ascii-alphabet-2.frink new file mode 100644 index 0000000000..37b18dea62 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Frink/generate-lower-case-ascii-alphabet-2.frink @@ -0,0 +1 @@ +toArray[map["char", char["a"] to char["z"]]] diff --git a/Task/Generate-lower-case-ASCII-alphabet/Lua/generate-lower-case-ascii-alphabet.lua b/Task/Generate-lower-case-ASCII-alphabet/Lua/generate-lower-case-ascii-alphabet-1.lua similarity index 100% rename from Task/Generate-lower-case-ASCII-alphabet/Lua/generate-lower-case-ascii-alphabet.lua rename to Task/Generate-lower-case-ASCII-alphabet/Lua/generate-lower-case-ascii-alphabet-1.lua diff --git a/Task/Generate-lower-case-ASCII-alphabet/Lua/generate-lower-case-ascii-alphabet-2.lua b/Task/Generate-lower-case-ASCII-alphabet/Lua/generate-lower-case-ascii-alphabet-2.lua new file mode 100644 index 0000000000..714cb54f6e --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Lua/generate-lower-case-ascii-alphabet-2.lua @@ -0,0 +1,5 @@ +#!/usr/bin/env luajit +local function ascii(f,t) local tab={} for i=f,t do tab[#tab+1]=string.char(i) end + return table.concat(tab) +end +print(ascii(97,122)) diff --git a/Task/Generate-lower-case-ASCII-alphabet/MUMPS/generate-lower-case-ascii-alphabet.mumps b/Task/Generate-lower-case-ASCII-alphabet/MUMPS/generate-lower-case-ascii-alphabet.mumps index c6fc47ad40..45fb59da4a 100644 --- a/Task/Generate-lower-case-ASCII-alphabet/MUMPS/generate-lower-case-ascii-alphabet.mumps +++ b/Task/Generate-lower-case-ASCII-alphabet/MUMPS/generate-lower-case-ascii-alphabet.mumps @@ -1,5 +1,5 @@ LOWASCMIN - set lowstr = "" - for i = 97:1:122 set delim = $select(i=97:"",1:",") set lowstr = lowstr_delim_$char(i) - write lowstr - quit + set lowstr = "" + for i = 97:1:122 set delim = $select(i=97:"",1:",") set lowstr = lowstr_delim_$char(i) + write lowstr + quit diff --git a/Task/Generate-lower-case-ASCII-alphabet/Maple/generate-lower-case-ascii-alphabet.maple b/Task/Generate-lower-case-ASCII-alphabet/Maple/generate-lower-case-ascii-alphabet.maple new file mode 100644 index 0000000000..8ebed80ed2 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Maple/generate-lower-case-ascii-alphabet.maple @@ -0,0 +1 @@ +seq(StringTools:-Char(c), c = 97 .. 122); diff --git a/Task/Generate-lower-case-ASCII-alphabet/Visual-Basic-.NET/generate-lower-case-ascii-alphabet.visual b/Task/Generate-lower-case-ASCII-alphabet/Visual-Basic-.NET/generate-lower-case-ascii-alphabet.visual new file mode 100644 index 0000000000..ee6606d2f3 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Visual-Basic-.NET/generate-lower-case-ascii-alphabet.visual @@ -0,0 +1,11 @@ +Module LowerASCII + + Sub Main() + Dim alphabets As New List(Of Char) + For i As Integer = Asc("a") To Asc("z") + alphabets.Add(Chr(i)) + Next + Console.WriteLine(String.Join("", alphabets.ToArray)) + End Sub + +End Module diff --git a/Task/Generic-swap/Elena/generic-swap.elena b/Task/Generic-swap/Elena/generic-swap.elena index 6dd18a3508..2bb2f219bd 100644 --- a/Task/Generic-swap/Elena/generic-swap.elena +++ b/Task/Generic-swap/Elena/generic-swap.elena @@ -1,14 +1,11 @@ import extensions; -singleton swap +swap(ref object v1, ref object v2) { - eval(ref object v1, ref object v2) - { - var tmp := v1.Value; + var tmp := v1; - v1 := v2.Value; - v2 := tmp - } + v1 := v2; + v2 := tmp } public program() @@ -18,7 +15,7 @@ public program() console.printLine(n," ",s); - swap.eval(ref n, ref s); + swap(ref n, ref s); console.printLine(n," ",s) } diff --git a/Task/Generic-swap/JavaScript/generic-swap-3.js b/Task/Generic-swap/JavaScript/generic-swap-3.js new file mode 100644 index 0000000000..e9b04f9f58 --- /dev/null +++ b/Task/Generic-swap/JavaScript/generic-swap-3.js @@ -0,0 +1,8 @@ +function swap(a, b) { + var tmp = window[a]; + window[a] = window[b]; + window[b] = tmp; +} +var x = 1; +var y = 2; +swap('x', 'y'); diff --git a/Task/Generic-swap/Visual-Basic-.NET/generic-swap-1.visual b/Task/Generic-swap/Visual-Basic-.NET/generic-swap-1.visual new file mode 100644 index 0000000000..3ec91a1fce --- /dev/null +++ b/Task/Generic-swap/Visual-Basic-.NET/generic-swap-1.visual @@ -0,0 +1,5 @@ +Sub Swap(Of T)(ByRef a As T, ByRef b As T) + Dim temp = a + a = b + b = temp +End Sub diff --git a/Task/Generic-swap/Visual-Basic-.NET/generic-swap-2.visual b/Task/Generic-swap/Visual-Basic-.NET/generic-swap-2.visual new file mode 100644 index 0000000000..2d020ff88c --- /dev/null +++ b/Task/Generic-swap/Visual-Basic-.NET/generic-swap-2.visual @@ -0,0 +1,2 @@ +Dim a = 1, b = 2 +Swap(a, b) diff --git a/Task/Globally-replace-text-in-several-files/Factor/globally-replace-text-in-several-files.factor b/Task/Globally-replace-text-in-several-files/Factor/globally-replace-text-in-several-files.factor new file mode 100644 index 0000000000..b097aaecb1 --- /dev/null +++ b/Task/Globally-replace-text-in-several-files/Factor/globally-replace-text-in-several-files.factor @@ -0,0 +1,12 @@ +USING: fry io.encodings.utf8 io.files kernel qw sequences +splitting ; + +: global-replace ( files old new -- ) + '[ + [ utf8 file-contents _ _ replace ] + [ utf8 set-file-contents ] bi + ] each ; + + +qw{ a.txt b.txt c.txt } +"Goodbye London!" "Hello New York!" global-replace diff --git a/Task/Globally-replace-text-in-several-files/Java/globally-replace-text-in-several-files.java b/Task/Globally-replace-text-in-several-files/Java/globally-replace-text-in-several-files-1.java similarity index 100% rename from Task/Globally-replace-text-in-several-files/Java/globally-replace-text-in-several-files.java rename to Task/Globally-replace-text-in-several-files/Java/globally-replace-text-in-several-files-1.java diff --git a/Task/Globally-replace-text-in-several-files/Java/globally-replace-text-in-several-files-2.java b/Task/Globally-replace-text-in-several-files/Java/globally-replace-text-in-several-files-2.java new file mode 100644 index 0000000000..4b43a03035 --- /dev/null +++ b/Task/Globally-replace-text-in-several-files/Java/globally-replace-text-in-several-files-2.java @@ -0,0 +1,5 @@ +for (String fn : List.of("file1.txt","file2.txt")) { + Path path = Path.of(fn); + Files.writeString(path, + Files.readString(path).replace("Goodbye London!", "Hello New York!")); +} diff --git a/Task/Gray-code/AWK/gray-code.awk b/Task/Gray-code/AWK/gray-code.awk new file mode 100644 index 0000000000..1c4a6e6839 --- /dev/null +++ b/Task/Gray-code/AWK/gray-code.awk @@ -0,0 +1,37 @@ +# Tested using GAWK + +function bits2str(bits, data, mask) +{ + # Source: https://www.gnu.org/software/gawk/manual/html_node/Bitwise-Functions.html + if (bits == 0) + return "0" + + mask = 1 + for (; bits != 0; bits = rshift(bits, 1)) + data = (and(bits, mask) ? "1" : "0") data + + while ((length(data) % 8) != 0) + data = "0" data + + return data +} + +function gray_encode(n){ + # Source: https://en.wikipedia.org/wiki/Gray_code#Converting_to_and_from_Gray_code + return xor(n,rshift(n,1)) +} + +function gray_decode(n){ + # Source: https://en.wikipedia.org/wiki/Gray_code#Converting_to_and_from_Gray_code + mask = rshift(n,1) + while(mask != 0){ + n = xor(n,mask) + mask = rshift(mask,1) + } + return n +} + +BEGIN{ + for (i=0; i < 32; i++) + printf "%-3s => %05d => %05d => %05d\n",i, bits2str(i),bits2str(gray_encode(i)), bits2str(gray_decode(gray_encode(i))) +} diff --git a/Task/Gray-code/Lobster/gray-code.lobster b/Task/Gray-code/Lobster/gray-code.lobster new file mode 100644 index 0000000000..74bea0007f --- /dev/null +++ b/Task/Gray-code/Lobster/gray-code.lobster @@ -0,0 +1,19 @@ +def grey_encode(n) -> int: + return n ^ (n >> 1) + +def grey_decode(n) -> int: + var p = n + n = n >> 1 + while n != 0: + p = p ^ n + n = n >> 1 + return p + +for(32) i: + let g = grey_encode(i) + let b = grey_decode(g) + print(number_to_string(i, 10, 2) + " : " + + number_to_string(i, 2, 5) + " ⇾ " + + number_to_string(g, 2, 5) + " ⇾ " + + number_to_string(b, 2, 5) + " : " + + number_to_string(b, 10, 2)) diff --git a/Task/Gray-code/PureBasic/gray-code.purebasic b/Task/Gray-code/PureBasic/gray-code.purebasic index 9e185b5bf4..b126c67f9d 100644 --- a/Task/Gray-code/PureBasic/gray-code.purebasic +++ b/Task/Gray-code/PureBasic/gray-code.purebasic @@ -15,7 +15,7 @@ Procedure.i gray_decode(g) EndProcedure If OpenConsole() - PrintN("Number Binary Gray Decoded") + PrintN("Number Gray Binary Decoded") Define i, n For i = 0 To 31 g = gray_encode(i) diff --git a/Task/Gray-code/Swift/gray-code.swift b/Task/Gray-code/Swift/gray-code.swift new file mode 100644 index 0000000000..4b22b93460 --- /dev/null +++ b/Task/Gray-code/Swift/gray-code.swift @@ -0,0 +1,22 @@ +func grayEncode(_ i: Int) -> Int { + return (i >> 1) ^ i +} + +func grayDecode(_ i: Int) -> Int { + switch i { + case 0: + return 0 + case _: + return i ^ grayDecode(i >> 1) + } +} + +for i in 0..<32 { + let iStr = String(i, radix: 2) + let encode = grayEncode(i) + let encodeStr = String(encode, radix: 2) + let decode = grayDecode(encode) + let decodeStr = String(decode, radix: 2) + + print("\(i) (\(iStr)) => \(encode) (\(encodeStr)) => \(decode) (\(decodeStr))") +} diff --git a/Task/Grayscale-image/Liberty-BASIC/grayscale-image.liberty b/Task/Grayscale-image/Liberty-BASIC/grayscale-image.liberty new file mode 100644 index 0000000000..81ac2ad65e --- /dev/null +++ b/Task/Grayscale-image/Liberty-BASIC/grayscale-image.liberty @@ -0,0 +1,21 @@ +nomainwin +WindowWidth = 400 +WindowHeight = 400 +open "Bitmap" for graphics_nf_nsb as #1 +h=hwnd(#1) +calldll #user32, "GetDC", h as ulong, DC as ulong +#1 "trapclose [q]" +loadbmp "clr","MLcolor.bmp" +#1 "drawbmp clr 1 1;flush" +for x = 1 to 150 + for y = 1 to 200 + calldll #gdi32, "GetPixel", DC as ulong, x as long, y as long, PX as ulong + B = int(PX/(256*256)) + G = int((PX-B*256*256) / 256) + R = int(PX-B*256*256-G*256) + L = 0.2126*R+0.7152*G+0.0722*B + #1 "down;color ";L;" ";L;" ";L;";set ";x;" ";y + next y +next x +wait +[q] unloadbmp "clr":close #1:end diff --git a/Task/Greatest-common-divisor/EDSAC-order-code/greatest-common-divisor.edsac b/Task/Greatest-common-divisor/EDSAC-order-code/greatest-common-divisor.edsac new file mode 100644 index 0000000000..5649e4203f --- /dev/null +++ b/Task/Greatest-common-divisor/EDSAC-order-code/greatest-common-divisor.edsac @@ -0,0 +1,151 @@ + [Greatest common divisor for Rosetta Code. + Program for EDSAC, Initial Orders 2.] + + [Library subroutine R2. Reads positive integers during input of orders, + and is then overwritten (so doesn't take up any memory). + Negative numbers can be input by adding 2^35. + Each integer is followed by 'F', except the last is followed by '#TZ'.] + T 45 K [store address in location 45 + values are then accessed by code letter H] + P 220 F [<------ address here] + GKT20FVDL8FA40DUDTFI40FA40FS39FG@S2FG23FA5@T5@E4@E13Z + T #H [Tell R2 the storage location defined above] + + [Integers to be read by R2. First item is count, then pairs for GCD algo.] + 4F 1066F 2019F 1815F 1914F 103785682F 167928761F 109876463F 177777648#TZ + + [---------------------------------------------------------------------- + Library subroutine P7. + Prints long strictly positive integer at 0D. + 10 characters, right justified, padded left with spaces. + Closed, even; 35 storage locations; working position 4D.] + T 56 K + GKA3FT26@H28#@NDYFLDT4DS27@TFH8@S8@T1FV4DAFG31@SFLDUFOFFFSFL4F + T4DA1FA27@G11@XFT28#ZPFT27ZP1024FP610D@524D!FO30@SFL8FE22@ + + [--------------------------------------------------------------- + Subroutine to return GCD of two non-negative 35-bit integers. + Input: Integers at 4D, 6D. + Output: GCD at 4D; changes 6D. + 41 locations; working location 0D.] + T 100 K + G K + A 3 F [plant link] + T 39 @ + S 4 D [test for 4D = 0] + E 37 @ [if so, quick exit, GCD = 6D] + T 40 @ [clear acc] + [5] A 4 D [load divisor] + [6] T D [initialize shifted divisor] + A 6 D [load dividend] + R D [shift 1 right] + S D [shifted divisor > dividend/2 yet?] + G 15 @ [yes, start subtraction] + T 40 @ [no, clear acc] + A D [shift divisor 1 more] + L D + E 6 @ [loop back (always, since acc = 0)] + [15] T 40 @ [clear acc] + [16] A 6 D [load remainder (initially = dividend)] + S D [trial subtraction] + G 20 @ [skip if can't subtract] + T 6 D [update remainder] + [20] T 40 @ [clear acc] + A 4 D [load original divisor] + S D [is shifted divisor back to original?] + E 29 @ [yes, jump out with acc = 0] + T 40 @ [no, clear acc] + A D [shift divisor 1 right] + R D + T D + E 16 @ [loop back (always, since acc = 0)] + [Here when finished dividing 6D by 4D. + Remainder is at 6D; acc = 0.] + [29] S 6 D [test for 6D = 0] + E 39 @ [if so, exit with GCD in 4D] + T D [else swap 4D and 6D] + A 4 D + T 6 D + S D + T 4 D + E 5 @ [loop back] + [37] A 6 D [here if 4D = 0 at start; GCD is 6D] + T 4 D [return in 4D as GCD] + [39] E F + [40] P F [junk word, to clear accumulator] + + [---------------------------------------------------------------------- + Main routine] + T 150 K + G K + [Variable] + [0] P F + [Constants] + [1] P D [single-word 1] + [2] A 2#H [order to load first number of first pair] + [3] P 2 F [to inc addresses by 2] + [4] # F [figure shift] + [5] K 2048 F [letter shift] + [6] G F [letters to print 'GCD'] + [7] C F + [8] D F + [9] V F [equals sign (in figures mode)] + [10] ! F [space] + [11] @ F [carriage return] + [12] & F [line feed] + [13] K 4096 F [null char] + [Enter here with acc = 0] + [14] O 4 @ [set teleprinter to figures] + S H [negative of number of pairs] + T @ [initialize counter] + A 2 @ [initial load order] + [18] U 23 @ [plant order to load 1st integer] + U 32 @ + A 3 @ [inc address by 2] + U 28 @ [plant order to load 2nd integer] + T 34 @ + [23] A #H [load 1st integer (order set up at runtime)] + T D [to 0D for printing] + A 25 @ [for return from print subroutine] + G 56 F [print 1st number] + O 10 @ [followed by space] + [28] A #H [load 2nd integer (order set up at runtime)] + T D [to 0D for printing] + A 30 @ [for return from print subroutine] + G 56 F [print 2nd number] + [32] A #H [load 1st integer (order set up at runtime)] + T 4 D [to 4D for GCD subroutine] + [34] A #H [load 2nd integer (order set up at runtime)] + T 6 D [to 6D for GCD subroutine] + [36] A 36 @ [for return from subroutine] + G 100 F [call subroutine for GCD] + [Cosmetic printing, add ' GCD = '] + O 10 @ + O 10 @ + O 5 @ + O 6 @ + O 7 @ + O 8 @ + O 4 @ + O 10 @ + O 9 @ + O 10 @ + A 4 D [load GCD] + T D [to 0D for printing] + A 50 @ [for return from print subroutine] + G 56 F [print GCD] + O 11 @ [followed by new line] + O 12 @ + [On to next pair] + A @ [load negative count of c.f.s] + A 1 @ [add 1] + E 62 @ [exit if count = 0] + T @ [store back] + A 23 @ [order to load first of pair] + A 3 @ [inc address by 4 for next c.f.] + A 3 @ + G 18 @ [loop back (always, since 'A' < 0)] + [62] O 13 @ [null char to flush teleprinter buffer] + Z F [stop] + E 14 Z [define entry point] + P F [acc = 0 on entry] diff --git a/Task/Greatest-element-of-a-list/Elena/greatest-element-of-a-list.elena b/Task/Greatest-element-of-a-list/Elena/greatest-element-of-a-list.elena index ac93225e37..eeee587dd6 100644 --- a/Task/Greatest-element-of-a-list/Elena/greatest-element-of-a-list.elena +++ b/Task/Greatest-element-of-a-list/Elena/greatest-element-of-a-list.elena @@ -26,5 +26,5 @@ extension op public program() { - console.printLine(new int[]{1,2,3,4,20,10,9,8}.Maximal) + console.printLine(new int[]::(1,2,3,4,20,10,9,8).Maximal) } diff --git a/Task/Greatest-element-of-a-list/Go/greatest-element-of-a-list-1.go b/Task/Greatest-element-of-a-list/Go/greatest-element-of-a-list-1.go index 25725517e6..3eb64a3288 100644 --- a/Task/Greatest-element-of-a-list/Go/greatest-element-of-a-list-1.go +++ b/Task/Greatest-element-of-a-list/Go/greatest-element-of-a-list-1.go @@ -7,5 +7,6 @@ import ( ) func main() { - fmt.Println(floats.Max([]float64{3, 1, 4, 1})) + fmt.Println(floats.Max([]float64{63, 70, 37, 34, 83, 27, 19, 97, 9, 17})) // prt 97 + fmt.Println(floats.Min([]float64{63, 70, 37, 34, 83, 27, 19, 97, 9, 17})) // prt 9 } diff --git a/Task/Greatest-element-of-a-list/Go/greatest-element-of-a-list-2.go b/Task/Greatest-element-of-a-list/Go/greatest-element-of-a-list-2.go index b96a6ee0c0..bf101135ff 100644 --- a/Task/Greatest-element-of-a-list/Go/greatest-element-of-a-list-2.go +++ b/Task/Greatest-element-of-a-list/Go/greatest-element-of-a-list-2.go @@ -1,38 +1,25 @@ package main -import ( - "fmt" - "math/rand" - "time" -) - -// function, per task description -func largest(a []int) (lg int, ok bool) { - if len(a) == 0 { - return - } - lg = a[0] - for _, e := range a[1:] { - if e > lg { - lg = e - } - } - return lg, true -} +import "fmt" func main() { - // random size slice - rand.Seed(time.Now().UnixNano()) - a := make([]int, rand.Intn(11)) - for i := range a { - a[i] = rand.Intn(101) - 100 // fill with random numbers - } + x := []int{ + 48, 96, 86, 68, + 57, 82, 63, 70, + 37, 34, 83, 27, + 19, 97, 9, 17, + } - fmt.Println(a) - lg, ok := largest(a) - if ok { - fmt.Println(lg) - } else { - fmt.Println("empty list. no maximum.") - } + smallest, biggest := x[0], x[0] + for _, v := range x { + if v > biggest { + biggest = v + } + if v < smallest { + smallest = v + } + } + + fmt.Println("The biggest number is ", biggest) // prt 97 + fmt.Println("The smallest number is ", smallest) // prt 9 } diff --git a/Task/Greatest-element-of-a-list/Go/greatest-element-of-a-list-3.go b/Task/Greatest-element-of-a-list/Go/greatest-element-of-a-list-3.go index 563ff2f853..b96a6ee0c0 100644 --- a/Task/Greatest-element-of-a-list/Go/greatest-element-of-a-list-3.go +++ b/Task/Greatest-element-of-a-list/Go/greatest-element-of-a-list-3.go @@ -2,63 +2,37 @@ package main import ( "fmt" - "math" "math/rand" "time" ) -// Function, per task description. Interesting with the float64 type because -// of the NaN value. NaNs do not compare to other values, so the result of -// a "largest" function on a set containing a NaN might be open to -// interpretation. The solution provided here is to return the largest -// of the non-NaNs, and also return a bool indicating the presense of a NaN. -func largest(s map[float64]bool) (lg float64, ok, nan bool) { - if len(s) == 0 { +// function, per task description +func largest(a []int) (lg int, ok bool) { + if len(a) == 0 { return } - for e := range s { - switch { - case math.IsNaN(e): - nan = true - case !ok || e > lg: + lg = a[0] + for _, e := range a[1:] { + if e > lg { lg = e - ok = true } } - return + return lg, true } func main() { + // random size slice rand.Seed(time.Now().UnixNano()) - // taking "set" literally from task description - s := map[float64]bool{} - // pick number of elements to add to set - n := rand.Intn(11) - // add random numbers, also throw in an occasional NaN or Inf. - for i := 0; i < n; i++ { - switch rand.Intn(10) { - case 0: - s[math.NaN()] = true - case 1: - s[math.Inf(1)] = true - default: - s[rand.ExpFloat64()] = true - } + a := make([]int, rand.Intn(11)) + for i := range a { + a[i] = rand.Intn(101) - 100 // fill with random numbers } - fmt.Print("s:") - for e := range s { - fmt.Print(" ", e) - } - fmt.Println() - switch lg, ok, nan := largest(s); { - case ok && !nan: - fmt.Println("largest:", lg) - case ok: - fmt.Println("largest:", lg, "(NaN present in data)") - case nan: - fmt.Println("no largest, all data NaN") - default: - fmt.Println("no largest, empty set") + fmt.Println(a) + lg, ok := largest(a) + if ok { + fmt.Println(lg) + } else { + fmt.Println("empty list. no maximum.") } } diff --git a/Task/Greatest-element-of-a-list/Go/greatest-element-of-a-list-4.go b/Task/Greatest-element-of-a-list/Go/greatest-element-of-a-list-4.go new file mode 100644 index 0000000000..563ff2f853 --- /dev/null +++ b/Task/Greatest-element-of-a-list/Go/greatest-element-of-a-list-4.go @@ -0,0 +1,64 @@ +package main + +import ( + "fmt" + "math" + "math/rand" + "time" +) + +// Function, per task description. Interesting with the float64 type because +// of the NaN value. NaNs do not compare to other values, so the result of +// a "largest" function on a set containing a NaN might be open to +// interpretation. The solution provided here is to return the largest +// of the non-NaNs, and also return a bool indicating the presense of a NaN. +func largest(s map[float64]bool) (lg float64, ok, nan bool) { + if len(s) == 0 { + return + } + for e := range s { + switch { + case math.IsNaN(e): + nan = true + case !ok || e > lg: + lg = e + ok = true + } + } + return +} + +func main() { + rand.Seed(time.Now().UnixNano()) + // taking "set" literally from task description + s := map[float64]bool{} + // pick number of elements to add to set + n := rand.Intn(11) + // add random numbers, also throw in an occasional NaN or Inf. + for i := 0; i < n; i++ { + switch rand.Intn(10) { + case 0: + s[math.NaN()] = true + case 1: + s[math.Inf(1)] = true + default: + s[rand.ExpFloat64()] = true + } + } + + fmt.Print("s:") + for e := range s { + fmt.Print(" ", e) + } + fmt.Println() + switch lg, ok, nan := largest(s); { + case ok && !nan: + fmt.Println("largest:", lg) + case ok: + fmt.Println("largest:", lg, "(NaN present in data)") + case nan: + fmt.Println("no largest, all data NaN") + default: + fmt.Println("no largest, empty set") + } +} diff --git a/Task/Greyscale-bars-Display/AWK/greyscale-bars-display.awk b/Task/Greyscale-bars-Display/AWK/greyscale-bars-display.awk new file mode 100644 index 0000000000..cd6001213f --- /dev/null +++ b/Task/Greyscale-bars-Display/AWK/greyscale-bars-display.awk @@ -0,0 +1,25 @@ +BEGIN { + nrcolors = 8 + direction = 1 + + for (quarter=0; quarter<4; quarter++) { + for (height=0; height<5; height++) { + for (width=0; width 0) && (guess < 101) { - ; increment attempts - set tries = tries + 1 - - ; evaluate the guess - set resp = $select(guess < target:"too low.",guess > target:"too high.",1:"correct!") - - ; display result, conditionally exit loop - write !,"Your guess was "_resp - quit:resp="correct!" - } - else { - write !,"Please enter an integer between 1 and 100." - } - } ; guess loop - - write !!,"You guessed the number in "_tries_" attempts." - quit + ; get a random number between 1 and 100 + set target = ($random(100) + 1) ; $r(100) gives 0-99 + + ; loop until correct + set tries = 0 + for { + write !,"Guess the integer between 1 and 100: " + read "",guess ; gets input following write + + ; validate input + if (guess?.N) && (guess > 0) && (guess < 101) { + ; increment attempts + set tries = tries + 1 + + ; evaluate the guess + set resp = $select(guess < target:"too low.",guess > target:"too high.",1:"correct!") + + ; display result, conditionally exit loop + write !,"Your guess was "_resp + quit:resp="correct!" + } + else { + write !,"Please enter an integer between 1 and 100." + } + } ; guess loop + + write !!,"You guessed the number in "_tries_" attempts." + quit diff --git a/Task/Guess-the-number-With-feedback/Smalltalk/guess-the-number-with-feedback.st b/Task/Guess-the-number-With-feedback/Smalltalk/guess-the-number-with-feedback.st new file mode 100644 index 0000000000..25b3d7787a --- /dev/null +++ b/Task/Guess-the-number-With-feedback/Smalltalk/guess-the-number-with-feedback.st @@ -0,0 +1,96 @@ +'From Pharo7.0.3 of 12 April 2019 [Build information: Pharo-7.0.3+build.158.sha.0903ade8a6c96633f07e0a7f1baa9a5d48cfdf55 (64 Bit)] on 30 October 2019 at 4:24:17.115807 pm'! +Object subclass: #GuessingGame + instanceVariableNames: 'min max uiManager tries' + classVariableNames: '' + poolDictionaries: '' + category: 'GuessingGame'! + +!GuessingGame methodsFor: 'initialization' stamp: 'EduardoPadoan 10/26/2019 23:51'! +initialize + uiManager := UIManager default. + tries := 0! ! + + +!GuessingGame methodsFor: 'services' stamp: 'EduardoPadoan 10/26/2019 23:40'! +alert: aString + uiManager alert: aString! ! + + +!GuessingGame methodsFor: 'accessing' stamp: 'EduardoPadoan 10/26/2019 23:36'! +max + ^ max! ! + +!GuessingGame methodsFor: 'accessing' stamp: 'EduardoPadoan 10/26/2019 23:36'! +min + ^ min! ! + +!GuessingGame methodsFor: 'accessing' stamp: 'EduardoPadoan 10/26/2019 23:36'! +min: anObject + min := anObject! ! + +!GuessingGame methodsFor: 'accessing' stamp: 'EduardoPadoan 10/26/2019 23:36'! +max: anObject + max := anObject! ! + + +!GuessingGame methodsFor: 'playing-main' stamp: 'EduardoPadoan 10/27/2019 00:18'! +play + | toGuess | + toGuess := self selectNumber. + [ :break | + | choice | + [ + choice := self getGuessOrExitWith: break. + choice + ifNil: [ self alert: 'Invalid Input' ] + ifNotNil: [ + self incrementTries. + choice = toGuess + ifTrue: [ self congratulateForGuess: choice andExitWith: break ] + ifFalse: [ choice > toGuess ifTrue: [ self alert: 'Too high' ] + ifFalse: [ self alert: 'Too low' ] ] + ] + ] repeat. + ] valueWithExit.! ! + + +!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/26/2019 23:39'! +makeRequest: aString + ^ uiManager request: aString! ! + +!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/26/2019 23:48'! +getGuessOrExitWith: anExitBlock + ^ [(self makeRequest: 'Guess number a between , min,' and ', max, '.') asInteger] + on: MessageNotUnderstood "nil" + do: [ + self sayGoodbye. + anExitBlock value ].! ! + +!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/26/2019 23:51'! +incrementTries + tries := tries + 1! ! + +!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/27/2019 00:05'! +sayGoodbye + self alert: 'Gave up? Sad.'.! ! + +!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/27/2019 00:15'! +congratulateForGuess: anInteger andExitWith: anExitBlock + self alert: 'Correct!! The value was indeed ', anInteger asString, '. Took you only ', tries asString, ' tries.'. + ^ anExitBlock value! ! + +!GuessingGame methodsFor: 'as yet unclassified' stamp: 'EduardoPadoan 10/26/2019 23:35'! +selectNumber + ^ (min to: max) atRandom ! ! + +"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- "! + +GuessingGame class + slots: { }! + +!GuessingGame class methodsFor: 'creating' stamp: 'EduardoPadoan 10/27/2019 00:15'! +playFrom: aMinNumber to: aMaxNumber + self new + min: aMinNumber; + max: aMaxNumber; + play! ! diff --git a/Task/Guess-the-number/BASIC/guess-the-number-2.basic b/Task/Guess-the-number/BASIC/guess-the-number-2.basic index bd8aa108b5..b362bd3d41 100644 --- a/Task/Guess-the-number/BASIC/guess-the-number-2.basic +++ b/Task/Guess-the-number/BASIC/guess-the-number-2.basic @@ -1,7 +1,9 @@ -100 PROGRAM "Guess.bas" -110 RANDOMIZE -120 LET N=RND(10)+1 -130 DO -140 INPUT PROMPT "Guess a number that's between 1-10: ":G -150 LOOP UNTIL N=G -160 PRINT "Well guessed!" +10 n% = int(rnd(1)*10)+1 +20 print chr$(147);chr$(14) +30 print "I have chosen a number from 1 to 10." +40 print +50 for q = 0 TO -1 step 0 +60 input "What is your guess";g% +70 q = g% = n% +80 next +90 print "WELL GUESSED!" diff --git a/Task/Guess-the-number/BASIC/guess-the-number-3.basic b/Task/Guess-the-number/BASIC/guess-the-number-3.basic index e8be5d44e1..bd8aa108b5 100644 --- a/Task/Guess-the-number/BASIC/guess-the-number-3.basic +++ b/Task/Guess-the-number/BASIC/guess-the-number-3.basic @@ -1,37 +1,7 @@ -supervisor: -GOSUB initialize -GOSUB guessing -GOTO continue - -initialize: -RANDOMIZE TIMER -n = 0: r = INT(RND * 100 + 1): g = 0: c$ = "" -RETURN - -guessing: -WHILE g <> r - INPUT "Pick a number between 1 and 100"; g - IF g = r THEN - PRINT "You got it!" - n = n + 1 - PRINT "It took "; n; "tries to pick the right number." - ELSEIF g < r THEN - PRINT "Try a larger number." - n = n + 1 - ELSE - PRINT "Try a smaller number." - n = n + 1 - END IF -WEND -RETURN - -continue: -WHILE c$ <> "YES" AND c$ <> "NO" - INPUT "Do you want to continue? (YES/NO)"; c$ - c$ = UCASE$(c$) - IF c$ = "YES" THEN - GOTO supervisor - ELSEIF c$ = "NO" THEN - STOP - END IF -WEND +100 PROGRAM "Guess.bas" +110 RANDOMIZE +120 LET N=RND(10)+1 +130 DO +140 INPUT PROMPT "Guess a number that's between 1-10: ":G +150 LOOP UNTIL N=G +160 PRINT "Well guessed!" diff --git a/Task/Guess-the-number/BASIC/guess-the-number-4.basic b/Task/Guess-the-number/BASIC/guess-the-number-4.basic index 91d15b35f9..e8be5d44e1 100644 --- a/Task/Guess-the-number/BASIC/guess-the-number-4.basic +++ b/Task/Guess-the-number/BASIC/guess-the-number-4.basic @@ -1,5 +1,37 @@ -10 LET n=INT (RND*10)+1 -20 INPUT "Guess a number that's between 1 and 10: ",g -30 IF g=n THEN PRINT "That's my number!": STOP -40 PRINT "Guess again!" -50 GO TO 20 +supervisor: +GOSUB initialize +GOSUB guessing +GOTO continue + +initialize: +RANDOMIZE TIMER +n = 0: r = INT(RND * 100 + 1): g = 0: c$ = "" +RETURN + +guessing: +WHILE g <> r + INPUT "Pick a number between 1 and 100"; g + IF g = r THEN + PRINT "You got it!" + n = n + 1 + PRINT "It took "; n; "tries to pick the right number." + ELSEIF g < r THEN + PRINT "Try a larger number." + n = n + 1 + ELSE + PRINT "Try a smaller number." + n = n + 1 + END IF +WEND +RETURN + +continue: +WHILE c$ <> "YES" AND c$ <> "NO" + INPUT "Do you want to continue? (YES/NO)"; c$ + c$ = UCASE$(c$) + IF c$ = "YES" THEN + GOTO supervisor + ELSEIF c$ = "NO" THEN + STOP + END IF +WEND diff --git a/Task/Guess-the-number/BASIC/guess-the-number-5.basic b/Task/Guess-the-number/BASIC/guess-the-number-5.basic new file mode 100644 index 0000000000..7a0e9aa301 --- /dev/null +++ b/Task/Guess-the-number/BASIC/guess-the-number-5.basic @@ -0,0 +1,49 @@ +' OPTION EXPLICIT ' Remove remark for VB-DOS/PDS 7.1 + +' Var +DIM n AS INTEGER, g AS INTEGER, t AS INTEGER, a AS STRING +CONST c = 10 + +' Functions +DECLARE FUNCTION getNumber () AS INTEGER + +' Program to guess a number between 1 and 10 +DO + CLS + PRINT "Program to guess a number between 1 and 10" + n = getNumber() + t = 0 + DO + t = t + 1 + DO + PRINT "Type a number (between 1 and " + FORMAT$(c) + "): "; + INPUT "", g + IF g < 1 OR g > c THEN BEEP + LOOP UNTIL g > 0 AND g < (c + 1) + + ' Compares the number + SELECT CASE g + CASE IS > n: PRINT "Try a lower number..." + CASE IS < n: PRINT "Try a higher number..." + CASE ELSE: PRINT "You got it! Attempts: " + FORMAT$(t) + END SELECT + LOOP UNTIL n = g + PRINT + PRINT "Do you want to try again? (Y/n)" + DO + a = UCASE$(INKEY$) + IF a <> "" AND a <> "Y" AND a <> "N" THEN BEEP + LOOP UNTIL a = "Y" OR a = "N" +LOOP UNTIL a = "N" +PRINT +PRINT "End of the program. Thanks for playing." +END + +FUNCTION getNumber () AS INTEGER + ' Generates a random number + ' between 1 and the c Constant + + RANDOMIZE TIMER + getNumber = INT(RND * c) + 1 + +END FUNCTION diff --git a/Task/Guess-the-number/BASIC/guess-the-number-6.basic b/Task/Guess-the-number/BASIC/guess-the-number-6.basic new file mode 100644 index 0000000000..91d15b35f9 --- /dev/null +++ b/Task/Guess-the-number/BASIC/guess-the-number-6.basic @@ -0,0 +1,5 @@ +10 LET n=INT (RND*10)+1 +20 INPUT "Guess a number that's between 1 and 10: ",g +30 IF g=n THEN PRINT "That's my number!": STOP +40 PRINT "Guess again!" +50 GO TO 20 diff --git a/Task/Guess-the-number/Common-Lisp/guess-the-number.lisp b/Task/Guess-the-number/Common-Lisp/guess-the-number.lisp index aac07548d0..f15494abc5 100644 --- a/Task/Guess-the-number/Common-Lisp/guess-the-number.lisp +++ b/Task/Guess-the-number/Common-Lisp/guess-the-number.lisp @@ -1,15 +1,9 @@ -(defun guess-the-number () - (let ((num-guesses 0) - (num (1+ (random 9))) - (guess nil)) - (format t "Try to guess a number from 1 to 10!~%") - (loop do (format t "Guess? ") - (incf num-guesses) - (setf guess (read)) - (cond ((not (numberp guess)) - (format t "Your guess is not a number!~%")) - ((not (= guess num)) - (format t "Your guess was wrong. Try again.~%"))) - until (and (numberp guess) - (= guess num))) - (format t "You guessed correctly on the ~:r try!~%" num-guesses))) +(defun guess-the-number (max) + (format t "Try to guess a number from 1 to ~a!~%Guess? " max) + (loop with num = (1+ (random max)) + for guess = (read) + as num-guesses from 1 + until (and (numberp guess) (= guess num)) + do (format t "Your guess was wrong. Try again.~%Guess? ") + (force-output) + finally (format t "Well guessed! You took ~a ~:*~[~;try~:;tries~].~%" num-guesses))) diff --git a/Task/HTTP/Frink/http.frink b/Task/HTTP/Frink/http.frink index bd2862cd94..0a32ef1e35 100644 --- a/Task/HTTP/Frink/http.frink +++ b/Task/HTTP/Frink/http.frink @@ -1 +1 @@ -print[read["http://futureboy.us/frinkdocs/"]] +print[read["http://frinklang.org/"]] diff --git a/Task/HTTPS-Authenticated/Visual-Basic/https-authenticated.vb b/Task/HTTPS-Authenticated/Visual-Basic/https-authenticated.vb index 33764d9f02..1c3a423923 100644 --- a/Task/HTTPS-Authenticated/Visual-Basic/https-authenticated.vb +++ b/Task/HTTPS-Authenticated/Visual-Basic/https-authenticated.vb @@ -1,11 +1,17 @@ Sub Main() - Dim HttpReq As WinHttp.WinHttpRequest ' in the "references" dialog of the IDE, check ' "Microsoft WinHTTP Services, version 5.1" (winhttp.dll) -Const HTTPREQUEST_PROXYSETTING_PROXY As Long = 2 +Dim HttpReq As WinHttp.WinHttpRequest +Const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 As Long = &H80& +Const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 As Long = &H200& +Const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 As Long = &H800& +Const HTTPREQUEST_PROXYSETTING_PROXY As Long = 2 #Const USE_PROXY = 1 Set HttpReq = New WinHttp.WinHttpRequest HttpReq.Open "GET", "https://www.abc.com/xyz/index.html" + HttpReq.Option(WinHttpRequestOption_SecureProtocols) = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 Or _ + WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 Or _ + WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 HttpReq.SetCredentials "", "", 0& #If USE_PROXY Then HttpReq.SetProxy HTTPREQUEST_PROXYSETTING_PROXY, "10.167.1.1:80" diff --git a/Task/HTTPS/Visual-Basic/https.vb b/Task/HTTPS/Visual-Basic/https.vb index a31d433a4b..5274ac21e9 100644 --- a/Task/HTTPS/Visual-Basic/https.vb +++ b/Task/HTTPS/Visual-Basic/https.vb @@ -2,10 +2,16 @@ Sub Main() Dim HttpReq As WinHttp.WinHttpRequest ' in the "references" dialog of the IDE, check ' "Microsoft WinHTTP Services, version 5.1" (winhttp.dll) -Const HTTPREQUEST_PROXYSETTING_PROXY As Long = 2 +Const HTTPREQUEST_PROXYSETTING_PROXY As Long = 2 +Const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 As Long = &H80& +Const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 As Long = &H200& +Const WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 As Long = &H800& #Const USE_PROXY = 1 Set HttpReq = New WinHttp.WinHttpRequest HttpReq.Open "GET", "https://groups.google.com/robots.txt" + HttpReq.Option(WinHttpRequestOption_SecureProtocols) = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1 Or _ + WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_1 Or _ + WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 #If USE_PROXY Then HttpReq.SetProxy HTTPREQUEST_PROXYSETTING_PROXY, "my_proxy:80" #End If diff --git a/Task/Hailstone-sequence/EDSAC-order-code/hailstone-sequence.edsac b/Task/Hailstone-sequence/EDSAC-order-code/hailstone-sequence.edsac new file mode 100644 index 0000000000..9ad1ff5987 --- /dev/null +++ b/Task/Hailstone-sequence/EDSAC-order-code/hailstone-sequence.edsac @@ -0,0 +1,260 @@ + [Hailstone (or Collatz) task for Rosetta Code. + EDSAC program, Initial Orders 2.] + + [This program shows how subroutines can be called via the + phi, H, N, ..., V parameters, so that the code doesn't have + to be changed if the subroutines are moved about in store. + See Wilkes, Wheeler and Gill, 1951 edition, page 18.] + + [Library subroutine P7, prints long strictly positive integer; + 10 characters, right justified, padded left with spaces. + Input: 0D = integer to be printed. + Closed, even; 35 storage locations; working position 4D.] + T 55 K [call subroutine via V parameter] + P 56 F [address of subroutine] + E 25 K + T V + GKA3FT26@H28#@NDYFLDT4DS27@TFH8@S8@T1FV4DAFG31@SFLDUFOFFFSFL4F + T4DA1FA27@G11@XFT28#ZPFT27ZP1024FP610D@524D!FO30@SFL8FE22@ + + [Subroutine to print a string placed after the subroutine call. + One location per character, with character in top 5 bits. + Last character flagged by having bit 0 set. + 17 locations, workspace 0F.] + T 54 K [call subroutine via C parameter] + P 91 F [address of subroutine] + E 25 K + T C + GKH16@A2FG4@A6@A2FT6@AFTFOFCFSFE3@A6@A3FT15@EFV2047F + + [************ Rosetta Code task ************ + Subroutine to generate and optionally store the hailstone + (Collatz) sequence for the passed-in initial term n. + Input: 4D = n, 35-bit positive integer + 6F = start address of sequence if stored; + must be even; 0 = don't store + Output: 7F = number of terms in sequence, or -1 if error + Workspace: 0D (general), 8D (term of sequence) + Must be loaded at an even address.] + T 45 K [call subroutine via H parameter] + P 108 F [address of subroutine] + E 25 K + T H + G K + A 3 F + T 46 @ + H 54#@ [mult reg := 1 to test odd/even] + A 4 D [load n passed in by caller] + T 8 D [term := n] + A 54 @ [load 1 (single)] + T 7 F [include initial term in count] + A 6 F [load address for store] + S 56 @ [test for 0; allow for pre-inc] + G 11 @ [skip next if storing not wanted] + A 12 @ [make 'T addr D' order] + [11] T 21 @ [plant T order, or -ve value if not storing + (note that a T order is +ve as an integer)] + [Loop: deal with current term in sequence + First store it, if user requested that] + [12] T D [clear acc; also serves to make 'T addr D' order] + A 21 @ [load T order to store term] + G 22 @ [jump if caller doesn't want store] + A 56 @ [pre-inc the address] + U 21 @ [update T order] + S 51 @ [check not gone beyond max EDSAC address] + E 47 @ [error exit if it has] + T F [clear acc] + A 8 D [load term] + [21] T D [store] + [22] T F [clear acc] + A 54#@ [load 1 (double)] + S 8 D [1 - term] + E 46 @ [if term = 1, jump out with acc = 0] + T F [clear acc] + C 8 D [acc := term AND 1] + S 54#@ [test whether 0 or 1] + G 38 @ [jump if term is even] + [Here if term is odd; acc = 0] + A 8 D [load term] + S 52#@ [guard against numeric overflow] + E 47 @ [jump if overflow] + A 52#@ [restore term after test] + L D [term*2] + A 8 D [term*3] + A 54#@ [plus 1] + E 41 @ [join common code] + [Here if term is even] + [38] T F [clear acc] + A 8 D [load term] + R D [term/2] + [Common code, acc = new term] + [41] T 8 D [store new term] + A 7 F [load count] + A 54 @ [add 1] + T 7 F [update count] + E 12 @ [loop back] + [Here when sequence has reached 1 + Assume jump here with acc = 0] + [46] E F [return with acc = 0] + [47] T F [here on error] + S 54 F [acc := -1] + T 7 F [return that as count] + E 46 @ + [Arrange the following to ensure even addresses for 35-bit values] + [51] T 1024 F [for checking valid address] + [52] H 682 DT 682 D [(2^34 - 1)/3] + [54] P DP F [1] + [56] P 2 F [to change addresses by 2] + + [Program to demonstrate Rosetta Code subroutine] + T 180 K + G K + [Double constants] + [P 500 F P F] [maximum n = 1000"] + [0] & 848 F PF [maximum n = 100000] + [2] P 13 D PF [n = 27 as demo of sequence] + [4] P D PF [1] + [Double variables] + [6] P F P F [n, start of Collatz sequence] + [8] P F P F [n with maximum count] + [Single constants] + [10] P 400 F [where to store sequence] + [11] P 2 F [to change addresses by 2] + [12] @ F [carriage return] + [13] & F [line feed] + [14] K 4096 F [null char] + [15] A D [used for maiking 'A addr D' order] + [16] P 8 F [ used for adding 8 to address] + [Single variables] + [17] P F [maximum number of terms] + [18] P F [temporary store] + [19] P F [marks end of printing] + + [Subroutine to print 4 numbers starting at address in 6F. + Prints new line (CR, LF) at end.] + [20] A 3 F [plant link for return] + T 40 @ + A 6 F [load start address] + A 15 @ [make 'A addr D' order] + A 16 @ [inc address by 8 (4 double values)] + U 19 @ [store as test for end] + S 16 @ [restore 'A addr D' order for start] + [27] U 31 @ [plant 'A addr D' order in code] + S 19 @ [test for end] + E 38 @ [out if so] + T F [clear acc] + [31] A D [load number] + T D [to 0D for printing] + [33] A 33 @ [call print subroutine] + G V + A 31 @ [load 'A addr D' order] + A 11 @ [inc address to next double value] + G 27 @ [loop back] + [38] O 12 @ [here when done, print CR LF] + O 13 @ + [40] E F [return] + + [Enter with acc = 0] + [PART 1] + [41] A 2#@ [load demo value of n] + T 4 D [to 4D for subroutine] + A 10 @ [address to store sequence] + T 6 F [to 6F for subroutine] + [45] A 45 @ [call subroutine to generate sequence] + G H + A 7 F [load length of sequence] + G 198 @ [out if error] + T 18 @ + [Print result] + [50] A 50 @ [print 'start' message] + G C + K2048F SF TF AF RF TF !F !F #D + A 2#@ [load demo value of n] + T D [to 0D for printing] + [63] A 63 @ [print demo n] + G V + [65] A 65 @ [print 'length' string] + G C + K2048F @F &F LF EF NF GF TF HF !F #D + T D [ensure 1F and sandwich bit are 0] + A 18 @ [load length] + T F [to 0F (effectively 0D) for printing] + [81] A 81 @ + G V + [83] A 83 @ [print 'first and last four' string] + G C + K2048F @F &F FF IF RF SF TF !F AF NF DF !F LF AF SF TF !F FF OF UF RF @F &F #D + A 18 @ [load length of sequence] + L 1 F [times 4] + A 6 F [make address of last 4] + S 16 @ + T 18 @ [store address of last 4] + [115] A 115 @ [print first 4 terms] + G 20 @ + A 18 @ [retrieve address of last 4] + T 6 F [pass as parameter] + [119] A 119 @ [print last 4 terms] + G 20 @ + + [PART 2] + T F + T 17 @ [max count := 0] + T 6#@ [n := 0] + [Loop: update n, start new sequence] + [124] T F [clear acc] + A 6#@ [load n] + A 4#@ [add 1 (double)] + U 6#@ [update n] + T 4 D [n to 4D for subroutine] + T 6 F [say no store] + [130] A 130 @ [call subroutine to generate sequence] + G H + A 7 F [load count returned by subroutine] + G 198 @ [out if error] + S 17 @ [compare with max count so far] + G 140 @ [skip if less] + A 17 @ [restore count after test] + T 17 @ [update max count] + A 6#@ [load n] + T 8#@ [remember n that gave max count] + [140] T F [clear acc] + A 6#@ [load n just done] + S #@ [compare with max(n)] + G 124 @ [loop back if n < max(n) + else fall through with acc = 0] + [Here whan reached maximum n. Print result.] + [144] A 144 @ [print 'max n' message] + G C + K2048F MF AF XF !F NF !F !F #D + A #@ [load maximum n] + T D [to 0D for printing] + [157] A 157 @ [call print subroutine] + G V + [159] A 159 @ [print 'max len' message] + G C + K2048F @F &F MF AF XF !F LF EF NF #D + T D [clear 1F and sandwich bit] + A 17 @ [load max count (single)] + T F [to 0F, effectively to 0D] + [175] A 175 @ [call print subroutine] + G V + [177] A 177 @ [print 'at n =' message] + G C + K2048F @F &F AF TF !F NF !F #F VF !D + A 8#@ [load n for which max count occurred] + T D [to 0D for printing] + [192] A 192 @ [call print subroutine] + G V + [194] O 12 @ [print CR, LF] + O 13 @ + O 14 @ [print null to flush teleprinter buffer] + Z F [stop] + [Here if term would overflow EDSAC 35-bit value. + With a maximum n of 100,000 this doesn't happen.] + [198] A 198 @ [print 'overflow' message] + G C + K2048F @F &F OF VF EF RF FF LF OF WD + E 194 @ [jump to exit] + + E 41 Z [define entry point] + P F [acc = 0 on entry] diff --git a/Task/Hailstone-sequence/REXX/hailstone-sequence-1.rexx b/Task/Hailstone-sequence/REXX/hailstone-sequence-1.rexx index 905f25444f..9ecdacf041 100644 --- a/Task/Hailstone-sequence/REXX/hailstone-sequence-1.rexx +++ b/Task/Hailstone-sequence/REXX/hailstone-sequence-1.rexx @@ -3,24 +3,23 @@ numeric digits 20 /*be able to handle gihugeic nu parse arg x y . /*get optional arguments from the C.L. */ if x=='' | x=="," then x= 27 /*No 1st argument? Then use default.*/ if y=='' | y=="," then y= 100000 - 1 /* " 2nd " " " " */ -$=hailstone(x) /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒task 1▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ -say x ' has a hailstone sequence of ' words($) -say ' and starts with: ' subword($, 1, 4) " ∙∙∙" -say ' and ends with: ∙∙∙' subword($, max(5, words($)-3)) +$= hailstone(x) /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒task 1▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ +say x ' has a hailstone sequence of ' words($) +say ' and starts with: ' subword($, 1, 4) " ∙∙∙" +say ' and ends with: ∙∙∙' subword($, max(5, words($)-3)) if y==0 then exit /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒task 2▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ say -w=0; do j=1 for y /*traipse through the range of numbers.*/ - call hailstone j /*compute the hailstone sequence for J.*/ +w= 0; do j=1 for y; call hailstone j /*traipse through the range of numbers.*/ if #hs<=w then iterate /*Not big 'nuff? Then keep traipsing.*/ - bigJ=j; w=#hs /*remember what # has biggest hailstone*/ + bigJ= j; w= #hs /*remember what # has biggest hailstone*/ end /*j*/ -say '(between 1 ──►' y") " bigJ ' has the longest hailstone sequence: ' w +say '(between 1 ──►' y") " bigJ ' has the longest hailstone sequence: ' w exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ hailstone: procedure expose #hs; parse arg n 1 s /*N and S: are set to the 1st argument.*/ do #hs=1 while n\==1 /*keep loop while N isn't unity. */ - if n//2 then n=n*3 + 1 /*N is odd ? Then calculate 3*n + 1 */ - else n=n%2 /*" " even? Then calculate fast ÷ */ - s=s n /* [↑] % is REXX integer division. */ + if n//2 then n= n * 3 + 1 /*N is odd ? Then calculate 3*n + 1 */ + else n= n % 2 /*" " even? Then calculate fast ÷ */ + s= s n /* [↑] % is REXX integer division. */ end /*#hs*/ /* [↑] append N to the sequence list*/ return s /*return the S string to the invoker.*/ diff --git a/Task/Hailstone-sequence/REXX/hailstone-sequence-2.rexx b/Task/Hailstone-sequence/REXX/hailstone-sequence-2.rexx index 4291b2db38..0800df9ecb 100644 --- a/Task/Hailstone-sequence/REXX/hailstone-sequence-2.rexx +++ b/Task/Hailstone-sequence/REXX/hailstone-sequence-2.rexx @@ -1,37 +1,36 @@ /*REXX program tests a number and also a range for hailstone (Collatz) sequences. */ !.=0; !.0=1; !.2=1; !.4=1; !.6=1; !.8=1 /*assign even numerals to be "true". */ -numeric digits 20; @.=0 /*handle big numbers; initialize array.*/ -parse arg x y z .; !.h=y /*get optional arguments from the C.L. */ -if x=='' | x=="," then x= 27 /*No 1st argument? Then use default.*/ -if y=='' | y=="," then y=100000 - 1 /* " 2nd " " " " */ -if z=='' | z=="," then z= 12 /*head/tail number? " " " */ -hm=max(y, 40000) /*use memoization (maximum num for @.)*/ -$=hailstone(x) /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒task 1▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ -say x ' has a hailstone sequence of ' words($) -say ' and starts with: ' subword($, 1, z) " ∙∙∙" -say ' and ends with: ∙∙∙' subword($, max(z+1, words($)-z+1)) +numeric digits 20; @.= 0 /*handle big numbers; initialize array.*/ +parse arg x y z .; !.h= y /*get optional arguments from the C.L. */ +if x=='' | x=="," then x= 27 /*No 1st argument? Then use default.*/ +if y=='' | y=="," then y= 100000 - 1 /* " 2nd " " " " */ +if z=='' | z=="," then z= 12 /*head/tail number? " " " */ +hm= max(y, 500000) /*use memoization (maximum num for @.)*/ +$= hailstone(x) /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒task 1▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ +say x ' has a hailstone sequence of ' words($) +say ' and starts with: ' subword($, 1, z) " ∙∙∙" +say ' and ends with: ∙∙∙' subword($, max(z+1, words($)-z+1)) if y==0 then exit /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒task 2▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒*/ say -w=0; do j=1 for y; $=hailstone(j) /*traipse through the range of numbers.*/ - #hs=words($) /*find the length of the hailstone seq.*/ +w= 0; do j=1 for y; $= hailstone(j) /*traipse through the range of numbers.*/ + #hs= words($) /*find the length of the hailstone seq.*/ if #hs<=w then iterate /*Not big enough? Then keep traipsing.*/ - bigJ=j; w=#hs /*remember what # has biggest hailstone*/ + bigJ= j; w= #hs /*remember what # has biggest hailstone*/ end /*j*/ -say '(between 1 ──►' y") " bigJ ' has the longest hailstone sequence: ' w +say '(between 1 ──►' y") " bigJ ' has the longest hailstone sequence: ' w exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ hailstone: procedure expose @. !. hm; parse arg n 1 s 1 o,@.1 /*N,S,O: are the 1st arg*/ - do while @.n==0 /*loop while the residual is unknown. */ - parse var n '' -1 L /*extract the last decimal digit of N.*/ - if !.L then n=n%2 /*N is even? Then calculate fast ÷ */ - else n=n*3 + 1 /*" " odd ? " " 3*n + 1 */ - s=s n /* [↑] %: is the REXX integer division*/ - end /*while*/ /* [↑] append N to the sequence list*/ - s=s @.n /*append the number to a sequence list.*/ - @.o=subword(s, 2); parse var s _ r /*use memoization for this hailstone #.*/ + do while @.n==0 /*loop while the residual is unknown. */ + parse var n '' -1 L /*extract the last decimal digit of N.*/ + if !.L then n= n % 2 /*N is even? Then calculate fast ÷ */ + else n= n * 3 + 1 /*" " odd ? " " 3*n + 1 */ + s= s n /* [↑] %: is the REXX integer division*/ + end /*while*/ /* [↑] append N to the sequence list*/ + s= s @.n /*append the number to a sequence list.*/ + @.o= subword(s, 2); parse var s _ r /*use memoization for this hailstone #.*/ do while r\==''; parse var r _ r /*obtain the next hailstone sequence. */ if @._\==0 then leave /*Was number already found? Return S.*/ if _>hm then iterate /*Is number out of range? Ignore it.*/ - @._=r /*assign subsequence number to array. */ - end /*while*/ - return s + @._= r /*assign subsequence number to array. */ + end /*while*/; return s diff --git a/Task/Hamming-numbers/00META.yaml b/Task/Hamming-numbers/00META.yaml index 2fbf0ffd71..70905bed7e 100644 --- a/Task/Hamming-numbers/00META.yaml +++ b/Task/Hamming-numbers/00META.yaml @@ -1 +1,2 @@ ---- {} +--- +note: Prime numbers diff --git a/Task/Hamming-numbers/Phix/hamming-numbers-1.phix b/Task/Hamming-numbers/Phix/hamming-numbers-1.phix index 0a5dc215b0..7ceb73decc 100644 --- a/Task/Hamming-numbers/Phix/hamming-numbers-1.phix +++ b/Task/Hamming-numbers/Phix/hamming-numbers-1.phix @@ -5,19 +5,15 @@ integer i = 1, j = 1, k = 1 for n=2 to N do hn = min(x2,min(x3,x5)) h[n] = hn - if hn=x2 then i += 1 x2 = 2*h[i] end if - if hn=x3 then j += 1 x3 = 3*h[j] end if - if hn=x5 then k += 1 x5 = 5*h[k] end if + if hn==x2 then i += 1 x2 = 2*h[i] end if + if hn==x3 then j += 1 x3 = 3*h[j] end if + if hn==x5 then k += 1 x5 = 5*h[k] end if end for return h[N] end function include builtins\mpfr.e -function mpz_min(mpz a, b) - return iff(mpz_cmp(a,b)<0?a:b) -end function - function mpz_hamming(integer N) sequence h = mpz_inits(N,1) mpz x2 = mpz_init(2), @@ -26,7 +22,7 @@ mpz x2 = mpz_init(2), hn = mpz_init() integer i = 1, j = 1, k = 1 for n=2 to N do - mpz_set(hn,mpz_min(x2,mpz_min(x3,x5))) + mpz_set(hn,mpz_min({x2,x3,x5})) mpz_set(h[n],hn) if mpz_cmp(hn,x2)=0 then i += 1 mpz_mul_si(x2,h[i],2) end if if mpz_cmp(hn,x3)=0 then j += 1 mpz_mul_si(x3,h[j],3) end if @@ -40,8 +36,8 @@ for i=1 to 20 do s = append(s,hamming(i)) end for ?s -?hamming(1691) -?{hamming(1000000),"wrong!"} --(the hn=x2 etc fail, so multiplies are all wrong) +printf(1,"%d\n",hamming(1691)) +printf(1,"%d (wrong!)\n",hamming(1000000)) --(the hn==x2 etc fail, so multiplies are all wrong) mpfr_printf(1,"%Zd\n",mpz_hamming(1691)) mpfr_printf(1,"%Zd\n",mpz_hamming(1000000)) diff --git a/Task/Handle-a-signal/Common-Lisp/handle-a-signal.lisp b/Task/Handle-a-signal/Common-Lisp/handle-a-signal.lisp index 222d7c9c3a..039c498bf4 100644 --- a/Task/Handle-a-signal/Common-Lisp/handle-a-signal.lisp +++ b/Task/Handle-a-signal/Common-Lisp/handle-a-signal.lisp @@ -1,6 +1,6 @@ (ql:quickload :cffi) -(defvar *SIGINT* 2) +(defconstant +SIGINT+ 2) (defmacro set-signal-handler (signo &body body) (let ((handler (gensym "HANDLER"))) @@ -12,13 +12,11 @@ (defvar *initial* (get-internal-real-time)) -(set-signal-handler *SIGINT* +(set-signal-handler +SIGINT+ (format t "Ran for ~a seconds~&" (/ (- (get-internal-real-time) *initial*) internal-time-units-per-second)) (quit)) (let ((i 0)) (loop do (format t "~a~&" (incf i)) - (sleep 0.5) - ) -) + (sleep 0.5))) diff --git a/Task/Handle-a-signal/Crystal/handle-a-signal.crystal b/Task/Handle-a-signal/Crystal/handle-a-signal.crystal new file mode 100644 index 0000000000..8963b2c1e1 --- /dev/null +++ b/Task/Handle-a-signal/Crystal/handle-a-signal.crystal @@ -0,0 +1,24 @@ +start = Time.utc +ch = Channel(Int32 | Symbol).new + +spawn do + i = 0 + loop do + sleep 1 + ch.send(i += 1) + end +end + +Signal::INT.trap do + Signal::INT.reset + ch.send(:kill) +end + +loop do + x = ch.receive + break if x == :kill + puts x +end + +elapsed = Time.utc - start +puts "Program has run for %5.3f seconds." % elapsed.total_seconds diff --git a/Task/Handle-a-signal/Julia/handle-a-signal.julia b/Task/Handle-a-signal/Julia/handle-a-signal.julia index 5c53e47529..82918f4d2d 100644 --- a/Task/Handle-a-signal/Julia/handle-a-signal.julia +++ b/Task/Handle-a-signal/Julia/handle-a-signal.julia @@ -1,12 +1,16 @@ -ccall(:jl_exit_on_sigint, Void, (Cint,), 0) -tic() -ticks = 0 -try - while true - sleep(0.5) - ticks += 1 - println(ticks) +ccall(:jl_exit_on_sigint, Cvoid, (Cint,), 0) + +function timeit() + ticks = 0 + try + while true + sleep(0.5) + ticks += 1 + println(ticks) + end + catch end end -println() -toc() + +@time timeit() +println("Done.") diff --git a/Task/Happy-numbers/APL/happy-numbers.apl b/Task/Happy-numbers/APL/happy-numbers-1.apl similarity index 100% rename from Task/Happy-numbers/APL/happy-numbers.apl rename to Task/Happy-numbers/APL/happy-numbers-1.apl diff --git a/Task/Happy-numbers/APL/happy-numbers-2.apl b/Task/Happy-numbers/APL/happy-numbers-2.apl new file mode 100644 index 0000000000..c0b9711775 --- /dev/null +++ b/Task/Happy-numbers/APL/happy-numbers-2.apl @@ -0,0 +1,14 @@ + HappyNumbers←{ ⍝ return the first ⍵ Happy Numbers + ⍺←⍬ ⍝ initial list + ⍵=+/⍺:⍸⍺ ⍝ 1's mark happy numbers + sq←×⍨ ⍝ square function (times selfie) + isHappy←{ ⍝ is ⍵ a happy number? + ⍺←⍬ ⍝ previous sums + ⍵=1:1 ⍝ if we get to 1, it's happy + n←+/sq∘⍎¨⍕⍵ ⍝ sum of the square of the digits + n∊⍺:0 ⍝ if we hit this sum before, it's not happy + (⍺,n)∇ n} ⍝ recurse until it's happy or not + (⍺,isHappy 1+≢⍺)∇ ⍵ ⍝ recurse until we have ⍵ happy numbers + } + HappyNumbers 8 +1 7 10 13 19 23 28 31 diff --git a/Task/Happy-numbers/Pascal/happy-numbers-2.pascal b/Task/Happy-numbers/Pascal/happy-numbers-2.pascal index 23fa4dd968..8d3fd2b507 100644 --- a/Task/Happy-numbers/Pascal/happy-numbers-2.pascal +++ b/Task/Happy-numbers/Pascal/happy-numbers-2.pascal @@ -1,78 +1,141 @@ Program HappyNumbers (output); -// NativeUInt: LongWord 32-Bit-OS/ Uint64 64-Bit-OS {$IFDEF FPC} {$MODE DELPHI} - {$OPTIMIZATION ON,Regvar,PEEPHOLE,CSE,ASMCSE} - {$CODEALIGN proc=32} + {$OPTIMIZATION ON,All} {$ELSE} - //for Delphi {$APPLICATION CONSOLE} {$ENDIF} +//{$DEFINE Use1E9} +uses + sysutils,//Timing + strutils;//Numb2USA + const - HighCache = 19*(9*9);//sum sqrdigt of Uint64 - cDigit = 1000; + base = 10; + HighCache = 20*(sqr(base-1));//sum of sqr digit of Uint64 +{$IFDEF Use1E9} + cDigit1 = sqr(base)*sqr(base);//must be power of base + cDigit2 = Base*sqr(cDigit1);// 1e9 + cMaxPot = 18; +{$ELSE} + cDigit1 = base*sqr(base);//must be power of base + cDigit2 = sqr(cDigit1);// 1e6 + cMaxPot = 14; +{$ENDIF} + type - tCache = array[0..HighCache] of Word; - tSqrdCache = array[0..cDigit] of Word; - tSqrdSumCache = array[0..HighCache] of Word; + tSumSqrDgts = array[0..cDigit2] of word; + tCache = array[0..2*HighCache] of word; + tSqrdSumCache = array[0..2*HighCache] of Uint32; + var + SumSqrDgts :tSumSqrDgts; Cache : tCache; - SqrdCache :tSqrdCache; - SqrdSumCache :tSqrdSumCache; -function find(n: NativeUint;const cache: tCache): boolean; -var - i: NativeUint; -begin - find := false; - for i := low(cache) to high(cache) do - if cache[i] = n then - find := true; - writeln(i:10,n:10); -end; + SqrdSumCache1, + SqrdSumCache2 :tSqrdSumCache; -procedure InitSqrdCache; + T1,T0 : TDateTime; + MAX2,Max1 : NativeInt; + +procedure InitSumSqrDgts; +//calc all sum of squared digits 0..cDigits2 +//using already calculated values var - i,n,sum,r: NativeUint; + i,j,n,sq,Base1: NativeInt; begin - For i := 0 to cDigit do - Begin - sum := 0; - n := i; - while n > 0 do - begin - r := n; - n := n div 10; - r := r-10*n; - sum := sum + r*r; + For i := 0 to Base-1 do + SumSqrDgts[i] := i*i; + Base1 := Base; + n := Base; + repeat + For i := 1 to base-1 do + Begin + sq := SumSqrDgts[i]; + For j := 0 to base1-1 do + Begin + SumSqrDgts[n] := sq+SumSqrDgts[j]; + inc(n); + end; end; - SqrdCache[i] := sum; - end; + Base1 := Base1*base; + until Base1 >= cDigit2; + SumSqrDgts[n] := 1; end; -function SumSqrdDgt(n: NativeUint): NativeUint; +function SumSqrdDgt(n: Uint64):NativeUint;inline; var - sum,r: NativeUint; + r: Uint64; begin - sum := 0; - while n > cDigit do - begin + result := 0; + while n>cDigit2 do + Begin r := n; - n := n div cDigit; - r := r-cDigit*n; - sum := sum + SqrdCache[r]; + n := n div cDigit2; + r := r-n*cDigit2; + inc(result,SumSqrDgts[r]); end; - SumSqrdDgt := sum + SqrdCache[n]; + inc(result,SumSqrDgts[n]); end; +procedure CalcSqrdSumCache1; +var + Count : tSqrdSumCache; + i,sq,result : NativeInt; +begin + For i :=High(Count) downto 0 do + Count[i] := 0; + //count the manifold + For i := cDigit1-1 downto 0 do + inc(count[SumSqrDgts[i]]); + For i := High(Count) downto 0 do + if count[i] <> 0 then + Begin + Max1 := i; + BREAK; + end; + For sq := 0 to (20-3)*81 do + Begin + result := 0; + For i := Max1 downto 0 do + inc(result,Count[i]*Cache[sq+i]); + SqrdSumCache1[sq] := result; + end; +end; + +procedure CalcSqrdSumCache2; +var + Count : tSqrdSumCache; + i,sq,result : NativeInt; +begin + For i :=High(Count) downto 0 do + Count[i] := 0; + For i := cDigit2-1 downto 0 do + inc(count[SumSqrDgts[i]]); + For i := High(Count) downto 0 do + if count[i] <> 0 then + Begin + Max2 := i; + BREAK; + end; + For sq := 0 to (20-6)*81 do + Begin + result := 0; + For i := Max2 downto 0 do + inc(result,Count[i]*Cache[sq+i]); + SqrdSumCache2[sq] := result; + end; +end; procedure Inithappy; var n,s,p : NativeUint; Begin - fillchar(SqrdSumCache,SizeOf(SqrdSumCache),#0); - InitSqrdCache; + fillchar(SqrdSumCache1,SizeOf(SqrdSumCache1),#0); + fillchar(SqrdSumCache2,SizeOf(SqrdSumCache2),#0); + InitSumSqrDgts; fillChar(Cache,SizeOf(Cache),#0); + Cache[1] := 1; For n := 1 to High(Cache) do Begin @@ -100,57 +163,67 @@ Begin end; end; end; -end; - -function nextCdigits(sqSum: NativeUint):NativeUint; -var - i,cnt : LongInt; -Begin - cnt:= SqrdSumCache[sqSum]; - If cnt = 0 then - Begin - For i := 0 to Cdigit-1 do - cnt := cnt + Ord(Cache[sqSum+SqrdCache[i]]=1); - //saving calculation->speed up x100 - SqrdSumCache[sqSum] := cnt; - end; - nextCdigits := cnt; + //mark all unhappy numbers with 0 + For n := 1 to High(Cache) do + If Cache[n] <> 1 then + Cache[n] := 0; + CalcSqrdSumCache1; + CalcSqrdSumCache2; end; function is_happy(n: NativeUint): boolean;inline; begin - is_happy := Cache[SumSqrdDgt(n)]=1 + is_happy := Boolean(Cache[SumSqrdDgt(n)]) end; -function nthHappy(Limit: NativeUint):NativeUint; +function nthHappy(Limit: Uint64):Uint64; var - n, - count : NativeUint; + d,e,sE: NativeUint; begin - n:= 0; - count := 0; - // big steps - IF limit>cDigit then - repeat - inc(count,nextCdigits(SumSqrdDgt(n))); - inc(n,cDigit); - until count >= Limit-cDigit; - // small steps - repeat - if is_happy(n) then - inc(count); - inc(n); - until count >= Limit; - nthHappy:= n-1; + result := 0; + d := 0; + e := 0; + sE := SumSqrDgts[e]; + //big steps + while Limit >= cDigit2 do + begin + dec(Limit,SqrdSumCache2[SumSqrDgts[d]+sE]); + inc(result,cDigit2); + inc(d); + IF d >=cDigit2 then + Begin + inc(e); + sE := SumSqrdDgt(e);//SumSqrDgts[e]; + d :=0; + end; + end; + //small steps + while Limit >= cDigit1 do + Begin + dec(Limit,SqrdSumCache1[SumSqrdDgt(result)]); + inc(result,cDigit1); + end; + //ONE BY ONE + while Limit > 0 do + begin + dec(Limit,Cache[SumSqrdDgt(result)]); + inc(result); + end; + result -= 1; end; var - n, count,Limit: NativeUint; + n, count :Uint64; + Limit: NativeUint; begin + write('cDigit1 = ',Numb2USA(IntToStr(cDigit1))); + writeln(' cDigit2 = ',Numb2USA(IntToStr(cDigit2))); + T0 := now; Inithappy; + writeln('Init takes ',FormatDateTime(' HH:NN:SS.ZZZ',now-T0)); n := 1; count := 0; - while count < 8 do + while count < 10 do begin if is_happy(n) then begin @@ -161,11 +234,16 @@ begin end; writeln; + T0 := now; + T1 := T0; n := 1; - Limit := 10;// 1En + Limit := 10; repeat - writeln('10e',n,' nth happy number ',nthHappy(limit):13); + writeln('1E',n:2,' n.th happy number ',Numb2USA(IntToStr(nthHappy(Limit))):26, + FormatDateTime(' HH:NN:SS.ZZZ',now-T1)); + T1 := now; inc(n); Limit := limit*10; - until n> 8; + until n> cMaxPot; + writeln('Total time counting ',FormatDateTime('HH:NN:SS.ZZZ',now-T0)); end. diff --git a/Task/Happy-numbers/Sidef/happy-numbers.sidef b/Task/Happy-numbers/Sidef/happy-numbers.sidef index fc799226c0..a30ad3545b 100644 --- a/Task/Happy-numbers/Sidef/happy-numbers.sidef +++ b/Task/Happy-numbers/Sidef/happy-numbers.sidef @@ -8,6 +8,4 @@ func happy(n) is cached { happy(n.digits.sum { _*_ }) } -say 8.defs {|i| - happy(i) ? i : nil -} +say happy.first(8) diff --git a/Task/Harshad-or-Niven-series/00DESCRIPTION b/Task/Harshad-or-Niven-series/00DESCRIPTION index fb47fb33cf..3894dc5f12 100644 --- a/Task/Harshad-or-Niven-series/00DESCRIPTION +++ b/Task/Harshad-or-Niven-series/00DESCRIPTION @@ -15,4 +15,10 @@ The task is to create a function/method/procedure to generate successive members Use it to list the first twenty members of the sequence and list the first Harshad number greater than 1000. Show your output here. -

+ +;Related task +:*   [https://rosettacode.org/wiki/Increasing_gaps_between_consecutive_Niven_numbers Increasing gaps between consecutive Niven numbers] + +;See also +* [[oeis:A005349| OEIS: A005349]] +
diff --git a/Task/Harshad-or-Niven-series/Haskell/harshad-or-niven-series-2.hs b/Task/Harshad-or-Niven-series/Haskell/harshad-or-niven-series-2.hs index 12e16c5044..221dc0a085 100644 --- a/Task/Harshad-or-Niven-series/Haskell/harshad-or-niven-series-2.hs +++ b/Task/Harshad-or-Niven-series/Haskell/harshad-or-niven-series-2.hs @@ -1,9 +1,13 @@ -harshadSeries :: [Int] -harshadSeries = filter ((0 ==) . (rem <*> (sum . digitList))) [1 ..] +import Data.List (unfoldr) +import Data.Tuple (swap) +import Data.Bool (bool) -digitList :: Int -> [Int] -digitList 0 = [] -digitList n = rem n 10 : digitList (quot n 10) +harshads :: [Int] +harshads = filter ((0 ==) . (rem <*> digitSum)) [1 ..] + +digitSum :: Int -> Int +digitSum = + sum . unfoldr ((bool Nothing . Just . swap . flip quotRem 10) <*> (0 <)) main :: IO () -main = mapM_ print $ [take 20, take 1 . dropWhile (<= 1000)] <*> [harshadSeries] +main = mapM_ print $ [take 20, take 1 . dropWhile (<= 1000)] <*> [harshads] diff --git a/Task/Harshad-or-Niven-series/Python/harshad-or-niven-series-3.py b/Task/Harshad-or-Niven-series/Python/harshad-or-niven-series-3.py index a5e3bcab84..e51c2274a3 100644 --- a/Task/Harshad-or-Niven-series/Python/harshad-or-niven-series-3.py +++ b/Task/Harshad-or-Niven-series/Python/harshad-or-niven-series-3.py @@ -1,31 +1,24 @@ '''Harshad or Niven series''' -from itertools import dropwhile, islice +from itertools import chain, count, dropwhile, islice -# harshads :: () -> Gen [Int] +# harshads :: () -> [Int] def harshads(): - '''Harshad series.''' - x = 1 - while True: - if 0 == (x % digitSum(x)): - yield x - x = 1 + x + '''Harshad series''' + def go(x): + return [x] if 0 == (x % digitSum(x)) else [] + return chain.from_iterable( + map(go, count(1)) + ) # digitSum :: Int -> Int def digitSum(n): - '''The Sum of the decimal digits of n.''' - def plusDigit(ra): - r = ra[0] - return (r // 10, ra[1] + (r % 10)) - - def remZero(ra): - return 0 == ra[0] - - return until(remZero)(plusDigit)( - (n, 0) - )[1] + '''Sum of the decimal digits of n.''' + def go(x): + return Nothing() if 0 == x else Just(divmod(x, 10)) + return sum(unfoldl(go)(n)) # TEST ---------------------------------------------------- @@ -53,6 +46,22 @@ def main(): # GENERIC ------------------------------------------------- +# Just :: a -> Maybe a +def Just(x): + '''Constructor for an inhabited Maybe (option type) value. + Wrapper containing the result of a computation. + ''' + return {'type': 'Maybe', 'Nothing': False, 'Just': x} + + +# Nothing :: Maybe a +def Nothing(): + '''Constructor for an empty Maybe (option type) value. + Empty wrapper returned where a computation is not possible. + ''' + return {'type': 'Maybe', 'Nothing': True} + + # take :: Int -> [a] -> [a] # take :: Int -> String -> String def take(n): @@ -66,17 +75,30 @@ def take(n): ) -# until :: (a -> Bool) -> (a -> a) -> a -> a -def until(p): - '''The result of repeatedly applying f until p holds. - The initial seed value is x. +# unfoldl(lambda x: Just(((x - 1), x)) if 0 != x else Nothing())(10) +# -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +# unfoldl :: (b -> Maybe (b, a)) -> b -> [a] +def unfoldl(f): + '''Dual to reduce or foldl. + Where these reduce a list to a summary value, unfoldl + builds a list from a seed value. + Where f returns Just(a, b), a is appended to the list, + and the residual b is used as the argument for the next + application of f. + When f returns Nothing, the completed list is returned. ''' - def go(f, x): - v = x - while not p(v): - v = f(v) - return v - return lambda f: lambda x: go(f, x) + def go(v): + x, r = v, v + xs = [] + while True: + mb = f(x) + if mb.get('Nothing'): + return xs + else: + x, r = mb.get('Just') + xs.insert(0, r) + return xs + return lambda x: go(x) # DISPLAY ------------------------------------------------- diff --git a/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-1.rexx b/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-1.rexx index 9d67f5192b..895b3de7b0 100644 --- a/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-1.rexx +++ b/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-1.rexx @@ -1,18 +1,16 @@ /*REXX program finds the first A Niven numbers; it also finds first Niven number > B.*/ parse arg A B . /*obtain optional arguments from the CL*/ -if A=='' | A==',' then A= 20 /*Not specified? Then use the default.*/ -if B=='' | B==',' then B=1000 /* " " " " " " */ -numeric digits 1+max(8, length(A), length(B)) /*enable the use of any sized numbers. */ -#=0; $= /*set Niven numbers count; Niven list.*/ - do j=1 until #==A /*◄───── let's go Niven number hunting.*/ - if j//sumDigs(j)==0 then do; #=#+1; $=$ j; end - end /*j*/ /* [↑] bump count; append J ──► list.*/ - -say 'first' A 'Niven numbers:' $ - - do t=B+1 until t//sumDigs(t)==0; end /*hunt for a Niven (or Harshad) number.*/ - -say 'first Niven number >' B " is: " t +if A=='' | A==',' then A= 20 /*Not specified? Then use the default.*/ +if B=='' | B==',' then B= 1000 /* " " " " " " */ +numeric digits 1+max(8, length(A), length(B) ) /*enable the use of any sized numbers. */ +#= 0; $= /*set Niven numbers count; Niven list.*/ + do j=1 until #==A /*◄───── let's go Niven number hunting.*/ + if j // sumDigs(j)==0 then do; #= #+1; $= $ j; end + end /*j*/ /* [↑] bump count; append J ──► list.*/ +say 'first' A 'Niven numbers:' $ /*display list of Niven numbers──►term.*/ + do t=B+1 until t//sumDigs(t)==0 /*hunt for a Niven (or Harshad) number.*/ + end /*t*/ +say 'first Niven number >' B " is: " t /*display 1st Niven number > B. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -sumDigs: procedure; parse arg x; s=0; do k=1 for length(x); s=s+substr(x,k,1); end /*k*/ +sumDigs: parse arg x 1 s 2 q; do k=1 for length(q); s= s+substr(q,k,1); end; return s diff --git a/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-2.rexx b/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-2.rexx index bf139e07a0..dd58eb033d 100644 --- a/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-2.rexx +++ b/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-2.rexx @@ -1,19 +1,17 @@ /*REXX program finds the first A Niven numbers; it also finds first Niven number > B.*/ parse arg A B . /*obtain optional arguments from the CL*/ -if A=='' | A==',' then A= 20 /*Not specified? Then use the default.*/ -if B=='' | B==',' then B=1000 /* " " " " " " */ +if A=='' | A==',' then A= 20 /*Not specified? Then use the default.*/ +if B=='' | B==',' then B= 1000 /* " " " " " " */ numeric digits 1+max(8, length(A), length(B)) /*enable the use of any sized numbers. */ -#=0; $= /*set Niven numbers count; Niven list.*/ - do j=1 until #==A /*◄───── let's go Niven number hunting.*/ - if isNiven(j) then do; #=#+1; $=$ j; end - end /*j*/ /* [↑] bump count; append J ──► list.*/ +#= 0; $= /*set Niven numbers count; Niven list.*/ + do j=1 until #==A /*◄───── let's go Niven number hunting.*/ + if isNiven(j) then do; #= #+1; $= $ j; end + end /*j*/ /* [↑] bump count; append J ──► list.*/ +say 'first' A 'Niven numbers:' $ /*display list of Niven numbers──►term.*/ -say 'first' A 'Niven numbers:' $ - - do t=B+1 until isNiven(t); end /*hunt for a Niven (or Harshad) number.*/ - -say 'first Niven number >' B " is: " t + do t=B+1 until isNiven(t) /*hunt for a Niven (or Harshad) number.*/ + end /*t*/ +say 'first Niven number >' B " is: " t /*display 1st Niven number > B. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -isNiven: procedure; parse arg x; s=0; do k=1 for length(x); s=s+substr(x,k,1); end /*k*/ - return x//s==0 +isNiven: parse arg x 1 s 2 q; do k=1 for length(q); s=s+substr(q,k,1); end; return x//s==0 diff --git a/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-3.rexx b/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-3.rexx index a43893666c..f78015531d 100644 --- a/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-3.rexx +++ b/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-3.rexx @@ -1,21 +1,20 @@ /*REXX program finds the first A Niven numbers; it also finds first Niven number > B.*/ parse arg A B . /*obtain optional arguments from the CL*/ -if A=='' | A==',' then A= 20 /*Not specified? Then use the default.*/ -if B=='' | B==',' then B=1000 /* " " " " " " */ -numeric digits 1+max(8, length(A), length(B)) /*enable the use of any sized numbers. */ -#=0; $= /*set Niven numbers count; Niven list.*/ - do j=1 until #==A /*◄───── let's go Niven number hunting.*/ - if isNiven(j) then do; #=#+1; $=$ j; end - end /*j*/ /* [↑] bump count; append J ──► list.*/ +if A=='' | A==',' then A= 20 /*Not specified? Then use the default.*/ +if B=='' | B==',' then B= 1000 /* " " " " " " */ +numeric digits 1+max(8, length(A), length(B) ) /*enable the use of any sized numbers. */ +#= 0; $= /*set Niven numbers count; Niven list.*/ + do j=1 until #==A /*◄───── let's go Niven number hunting.*/ + if isNiven(j) then do; #= #+1; $= $ j; end + end /*j*/ /* [↑] bump count; append J ──► list.*/ +say 'first' A 'Niven numbers:' $ /*display list of Niven numbers──►term.*/ -say 'first' A 'Niven numbers:' $ - - do t=B+1 until isNiven(t); end /*hunt for a Niven (or Harshad) number.*/ - -say 'first Niven number >' B " is: " t + do t=B+1 until isNiven(t) /*hunt for a Niven (or Harshad) number.*/ + end +say 'first Niven number >' B " is: " t /*display 1st Niven number > B. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -isNiven: procedure; parse arg x 1 sum 2 q /*use the first decimal digit for SUM.*/ - do while q\==''; parse var q _ 2 q; sum=sum+_; end /*k*/ - /* ↑ */ - return x//sum==0 /* └───◄ is destructively parsed. */ +isNiven: parse arg x 1 sum 2 q /*use the 1st decimal digit for SUM. */ + do length(q); parse var q _ 2 q; sum= sum + _ + end /*length(q)*/ /* ↑ */ + return x // sum == 0 /* └──────◄ is destructively parsed. */ diff --git a/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-4.rexx b/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-4.rexx index 9de9dc9972..f3ae3a1898 100644 --- a/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-4.rexx +++ b/Task/Harshad-or-Niven-series/REXX/harshad-or-niven-series-4.rexx @@ -1,26 +1,26 @@ /*REXX program finds the first A Niven numbers; it also finds first Niven number > B.*/ parse arg A B . /*obtain optional arguments from the CL*/ -if A=='' | A==',' then A= 20 /*Not specified? Then use the default.*/ -if B=='' | B==',' then B=1000 /* " " " " " " */ -tell= A>0; A=abs(A) /*flag for showing a Niven numbers list*/ -A=abs(a) -numeric digits 1+max(8, length(A), length(B)) /*enable the use of any sized numbers. */ -#=0; $= /*set Niven numbers count; Niven list.*/ +if A=='' | A==',' then A= 20 /*Not specified? Then use the default.*/ +if B=='' | B==',' then B= 1000 /* " " " " " " */ +tell= A>0; A= abs(A) /*flag for showing a Niven numbers list*/ +A= abs(a) +numeric digits 1+max(8, length(A), length(B) ) /*enable the use of any sized numbers. */ +#= 0; $= /*set Niven numbers count; Niven list.*/ do j=1 until #==A /*◄───── let's go Niven number hunting.*/ - if isNiven(j) then do; #=#+1; !.#=j; end + if isNiven(j) then do; #= #+1; !.#= j; end end /*j*/ /* [↑] bump count; append J ──► list.*/ -w=length(!.w) /*W: is the width of largest Niven #.*/ +w= length(!.w) /*W: is the width of largest Niven #.*/ if tell then do say 'first' A 'Niven numbers:'; do k=1 for #; say right(!.k, w); end /*k*/ end else say 'last of the' A 'Niven numbers: ' !.# say - do t=B+1 until isNiven(t); end /*hunt for a Niven (or Harshad) number.*/ - + do t=B+1 until isNiven(t) /*hunt for a Niven (or Harshad) number.*/ + end say 'first Niven number >' B " is: " t exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -isNiven: procedure; parse arg x 1 sum 2 q /*use the first decimal digit for SUM.*/ - do while q\==''; parse var q _ 2 q; sum=sum+_; end /*k*/ - /* ↑ */ - return x//sum==0 /* └───◄ is destructively parsed. */ +isNiven: parse arg x 1 sum 2 q /*use the first decimal digit for SUM.*/ + do while q\==''; parse var q _ 2 q; sum= sum + _ + end /*while*/ /* ↑ */ + return x // sum == 0 /* └──────◄ is destructively parsed.*/ diff --git a/Task/Hash-from-two-arrays/C-sharp/hash-from-two-arrays-1.cs b/Task/Hash-from-two-arrays/C-sharp/hash-from-two-arrays-1.cs index 6d49c3db16..a93dd24e91 100644 --- a/Task/Hash-from-two-arrays/C-sharp/hash-from-two-arrays-1.cs +++ b/Task/Hash-from-two-arrays/C-sharp/hash-from-two-arrays-1.cs @@ -1,14 +1,17 @@ -System.Collections.HashTable h = new System.Collections.HashTable(); +static class Program +{ + static void Main() + { + System.Collections.Hashtable h = new System.Collections.Hashtable(); -string[] arg_keys = {"foo","bar","val"}; -string[] arg_values = {"little", "miss", "muffet"}; + string[] keys = { "foo", "bar", "val" }; + string[] values = { "little", "miss", "muffet" }; -//Some basic error checking -int arg_length = 0; -if ( arg_keys.Length == arg_values.Length ) { - arg_length = arg_keys.Length; -} - -for( int i = 0; i < arg_length; i++ ){ - h.add( arg_keys[i], arg_values[i] ); + System.Diagnostics.Trace.Assert(keys.Length == values.Length, "Arrays are not same length."); + + for (int i = 0; i < keys.Length; i++) + { + h.Add(keys[i], values[i]); + } + } } diff --git a/Task/Hash-from-two-arrays/C-sharp/hash-from-two-arrays-2.cs b/Task/Hash-from-two-arrays/C-sharp/hash-from-two-arrays-2.cs index 6e9e7eab61..ffc4937947 100644 --- a/Task/Hash-from-two-arrays/C-sharp/hash-from-two-arrays-2.cs +++ b/Task/Hash-from-two-arrays/C-sharp/hash-from-two-arrays-2.cs @@ -1,3 +1 @@ -for( int i = 0; i < arg_length; i++ ){ - h[ arg_keys[i] ] = arg_values[i]; -} +h[keys[i]] = values[i]; diff --git a/Task/Hash-from-two-arrays/C-sharp/hash-from-two-arrays-3.cs b/Task/Hash-from-two-arrays/C-sharp/hash-from-two-arrays-3.cs new file mode 100644 index 0000000000..050280d10d --- /dev/null +++ b/Task/Hash-from-two-arrays/C-sharp/hash-from-two-arrays-3.cs @@ -0,0 +1,14 @@ +using System.Linq; + +static class Program +{ + static void Main() + { + string[] keys = { "foo", "bar", "val" }; + string[] values = { "little", "miss", "muffet" }; + + var h = keys + .Zip(values, (k, v) => (k, v)) + .ToDictionary(keySelector: kv => kv.k, elementSelector: kv => kv.v); + } +} diff --git a/Task/Hash-from-two-arrays/Crystal/hash-from-two-arrays.crystal b/Task/Hash-from-two-arrays/Crystal/hash-from-two-arrays.crystal new file mode 100644 index 0000000000..70ed01ad25 --- /dev/null +++ b/Task/Hash-from-two-arrays/Crystal/hash-from-two-arrays.crystal @@ -0,0 +1,5 @@ +keys = ('a'..'z').to_a # => a, b, c ... z +vals = (1..26).to_a # => 1, 2, 3 ... 26 + +hash = Hash.zip(keys, vals) +p hash diff --git a/Task/Hash-from-two-arrays/Pike/hash-from-two-arrays.pike b/Task/Hash-from-two-arrays/Pike/hash-from-two-arrays.pike new file mode 100644 index 0000000000..0d11b5930e --- /dev/null +++ b/Task/Hash-from-two-arrays/Pike/hash-from-two-arrays.pike @@ -0,0 +1,4 @@ +array indices = ({ "a", "b", 42 }); +array values = ({ Image.Color(0,0,0), "hello", "world" }); +mapping m = mkmapping( indices, values ); +write("%O\n", m); diff --git a/Task/Hash-join/Prolog/hash-join.pro b/Task/Hash-join/Prolog/hash-join.pro new file mode 100644 index 0000000000..b2c890ea65 --- /dev/null +++ b/Task/Hash-join/Prolog/hash-join.pro @@ -0,0 +1,20 @@ +% Name/Age +person_age('Jonah', 27). +person_age('Alan', 18). +person_age('Glory', 28). +person_age('Popeye', 18). +person_age('Alan', 28). + +% Character/Nemesis +character_nemisis('Jonah', 'Whales'). +character_nemisis('Jonah', 'Spiders'). +character_nemisis('Alan', 'Ghosts'). +character_nemisis('Alan', 'Zombies'). +character_nemisis('Glory', 'Buffy'). + +join_and_print :- + format('Age\tName\tCharacter\tNemisis\n\n'), + forall( + (person_age(Person, Age), character_nemisis(Person, Nemesis)), + format('~w\t~w\t~w\t\t~w\n', [Age, Person, Person, Nemesis]) + ). diff --git a/Task/Hello-world-Graphical/Smalltalk/hello-world-graphical-2.st b/Task/Hello-world-Graphical/Smalltalk/hello-world-graphical-2.st index a09f4e8f77..b599128888 100644 --- a/Task/Hello-world-Graphical/Smalltalk/hello-world-graphical-2.st +++ b/Task/Hello-world-Graphical/Smalltalk/hello-world-graphical-2.st @@ -1 +1 @@ -Dialog information: 'Goodbye, world.' +'Hello World' asMorph openInWindow diff --git a/Task/Hello-world-Graphical/Smalltalk/hello-world-graphical-3.st b/Task/Hello-world-Graphical/Smalltalk/hello-world-graphical-3.st new file mode 100644 index 0000000000..a09f4e8f77 --- /dev/null +++ b/Task/Hello-world-Graphical/Smalltalk/hello-world-graphical-3.st @@ -0,0 +1 @@ +Dialog information: 'Goodbye, world.' diff --git a/Task/Hello-world-Graphical/XPL0/hello-world-graphical.xpl0 b/Task/Hello-world-Graphical/XPL0/hello-world-graphical.xpl0 new file mode 100644 index 0000000000..3cfcdc9ef3 --- /dev/null +++ b/Task/Hello-world-Graphical/XPL0/hello-world-graphical.xpl0 @@ -0,0 +1 @@ +[SetVid($13); Text(6, "Goodbye, World!")] diff --git a/Task/Hello-world-Newbie/ARM-Assembly/hello-world-newbie.arm b/Task/Hello-world-Newbie/ARM-Assembly/hello-world-newbie.arm index 2a8aa89acd..1832cf16b1 100644 --- a/Task/Hello-world-Newbie/ARM-Assembly/hello-world-newbie.arm +++ b/Task/Hello-world-Newbie/ARM-Assembly/hello-world-newbie.arm @@ -6,14 +6,13 @@ szMessage: .asciz "Hello world. \n" .text .global main main: - mov r0, #1 @ output std linux + mov r0, #1 @ output std linux ldr r1, iAdrMessage @ adresse of message mov r2, #LGMESSAGE @ sizeof(message) mov r7, #4 @ select system call 'write' swi #0 @ perform the system call mov r0, #0 @ return code - mov r7, #1 @ request to exit program + mov r7, #1 @ request to exit program swi 0 iAdrMessage: .int szMessage -} diff --git a/Task/Hello-world-Newline-omission/PHP/hello-world-newline-omission.php b/Task/Hello-world-Newline-omission/PHP/hello-world-newline-omission.php new file mode 100644 index 0000000000..2070a0eb81 --- /dev/null +++ b/Task/Hello-world-Newline-omission/PHP/hello-world-newline-omission.php @@ -0,0 +1 @@ +echo "Goodbye, World !"; diff --git a/Task/Hello-world-Newline-omission/Pike/hello-world-newline-omission.pike b/Task/Hello-world-Newline-omission/Pike/hello-world-newline-omission.pike new file mode 100644 index 0000000000..9d9f00ef55 --- /dev/null +++ b/Task/Hello-world-Newline-omission/Pike/hello-world-newline-omission.pike @@ -0,0 +1 @@ +write("Goodbye, World!"); diff --git a/Task/Hello-world-Standard-error/Pike/hello-world-standard-error.pike b/Task/Hello-world-Standard-error/Pike/hello-world-standard-error.pike new file mode 100644 index 0000000000..63b7337f77 --- /dev/null +++ b/Task/Hello-world-Standard-error/Pike/hello-world-standard-error.pike @@ -0,0 +1 @@ +werror("Goodbye, World!"); diff --git a/Task/Hello-world-Text/COBOL/hello-world-text.cobol b/Task/Hello-world-Text/COBOL/hello-world-text-1.cobol similarity index 100% rename from Task/Hello-world-Text/COBOL/hello-world-text.cobol rename to Task/Hello-world-Text/COBOL/hello-world-text-1.cobol diff --git a/Task/Hello-world-Text/COBOL/hello-world-text-2.cobol b/Task/Hello-world-Text/COBOL/hello-world-text-2.cobol new file mode 100644 index 0000000000..1f71e5fe9f --- /dev/null +++ b/Task/Hello-world-Text/COBOL/hello-world-text-2.cobol @@ -0,0 +1 @@ +display"Hello, world". diff --git a/Task/Hello-world-Text/Kotlin/hello-world-text.kotlin b/Task/Hello-world-Text/Kotlin/hello-world-text.kotlin index 0476fd7c36..acf03f8cf9 100644 --- a/Task/Hello-world-Text/Kotlin/hello-world-text.kotlin +++ b/Task/Hello-world-Text/Kotlin/hello-world-text.kotlin @@ -1,3 +1,3 @@ -fun main(args: Array) { +fun main() { println("Hello world!") } diff --git a/Task/Hello-world-Text/Ol/hello-world-text.ol b/Task/Hello-world-Text/Ol/hello-world-text.ol new file mode 100644 index 0000000000..d441299f14 --- /dev/null +++ b/Task/Hello-world-Text/Ol/hello-world-text.ol @@ -0,0 +1 @@ +(print "Hello world!") diff --git a/Task/Hello-world-Text/Perl-6/hello-world-text.pl6 b/Task/Hello-world-Text/Perl-6/hello-world-text-1.pl6 similarity index 100% rename from Task/Hello-world-Text/Perl-6/hello-world-text.pl6 rename to Task/Hello-world-Text/Perl-6/hello-world-text-1.pl6 diff --git a/Task/Hello-world-Text/Perl-6/hello-world-text-2.pl6 b/Task/Hello-world-Text/Perl-6/hello-world-text-2.pl6 new file mode 100644 index 0000000000..9d2a9b2b1c --- /dev/null +++ b/Task/Hello-world-Text/Perl-6/hello-world-text-2.pl6 @@ -0,0 +1 @@ +"Hello, World!".say(); diff --git a/Task/Hello-world-Web-server/Phix/hello-world-web-server.phix b/Task/Hello-world-Web-server/Phix/hello-world-web-server.phix new file mode 100644 index 0000000000..4384621d93 --- /dev/null +++ b/Task/Hello-world-Web-server/Phix/hello-world-web-server.phix @@ -0,0 +1,45 @@ +-- demo\rosetta\SimpleHttpServer.exw +include builtins\sockets.e -- added for 0.8.1 (not yet documented) + +constant MAX_QUEUE = 100, + ESCAPE = #1B, + BUFFER_SIZE = 2048, + buffer = allocate(BUFFER_SIZE), + sock_addr = new_sock_addr(AF_INET, 8080, NULL), + peerAddr = new_sock_addr(), + +response = substitute(""" +HTTP/1.1 200 OK +Content-Type: text/html; charset=UTF-8 + + + + + Bye-bye baby bye-bye + + + +

Goodbye, world!

+ + + +""","\n","\r\n") + +atom sock = socket(AF_INET,SOCK_STREAM,NULL) +bind(sock,sock_addr) +listen(sock,MAX_QUEUE) +while get_key()!=ESCAPE do + atom peer = accept(sock,peerAddr), + ip = get_sin_addr(sock_addr) + integer len = recv(peer,buffer,BUFFER_SIZE,0) + string request = peek({buffer,len}) + printf(1,"Client IP: %s\n%s\n",{ip_to_string(ip),request}) + if length(request)>3 and request[1..4]="GET " then + poke(buffer,response) + send(peer,buffer,length(response),0) + end if +end while diff --git a/Task/Hello-world-Web-server/Pike/hello-world-web-server.pike b/Task/Hello-world-Web-server/Pike/hello-world-web-server.pike new file mode 100644 index 0000000000..7800b9c882 --- /dev/null +++ b/Task/Hello-world-Web-server/Pike/hello-world-web-server.pike @@ -0,0 +1,11 @@ +void handle_request(Protocols.HTTP.Server.Request request) +{ + request->response_and_finish( ([ "data":"Goodbye, World!", + "type":"text/html" ]) ); +} + +int main() +{ + Protocols.HTTP.Server.Port(handle_request, 8080); + return -1; // -1 is a special case that retirns control to the backend +} diff --git a/Task/Hello-world-Web-server/R/hello-world-web-server.r b/Task/Hello-world-Web-server/R/hello-world-web-server.r new file mode 100644 index 0000000000..b6d49e6f79 --- /dev/null +++ b/Task/Hello-world-Web-server/R/hello-world-web-server.r @@ -0,0 +1,9 @@ +library(httpuv) + +runServer("0.0.0.0", 5000, + list( + call = function(req) { + list(status = 200L, headers = list('Content-Type' = 'text/html'), body = "Hello world!") + } + ) +) diff --git a/Task/Here-document/00DESCRIPTION b/Task/Here-document/00DESCRIPTION index 050b6467d9..fc8edf3ba6 100644 --- a/Task/Here-document/00DESCRIPTION +++ b/Task/Here-document/00DESCRIPTION @@ -1,10 +1,3 @@ -{{omit from|BBC BASIC}} -{{omit from|Déjà Vu}} -{{omit from|Gambas}} -{{omit from|GW-BASIC}} -{{omit from|Pascal}} -{{omit from|MATLAB|MATLAB has no multiline string literal functionality}} -{{omit from|VBA|VBA can't create a console application}} A   ''here document''   (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a   ''here document''   is constructed using a command followed by "<<" (or some other symbol) followed by a token string. diff --git a/Task/Here-document/00META.yaml b/Task/Here-document/00META.yaml index 7ce58b5b90..2fbf0ffd71 100644 --- a/Task/Here-document/00META.yaml +++ b/Task/Here-document/00META.yaml @@ -1,3 +1 @@ ---- -category: -- Syntax elements +--- {} diff --git a/Task/Here-document/Lua/here-document.lua b/Task/Here-document/Lua/here-document.lua index c3e461b99b..601152115c 100644 --- a/Task/Here-document/Lua/here-document.lua +++ b/Task/Here-document/Lua/here-document.lua @@ -6,6 +6,8 @@ same line breaks and spacing as you set in this block. ]]) +print([=[by using equals signs, ]] may be embedded.]=]) + local msg = [[this is a message that spans multiple lines and will have the next lines preserved as they were entered, so be careful diff --git a/Task/Here-document/Rust/here-document.rust b/Task/Here-document/Rust/here-document.rust index d2716edda3..e662236471 100644 --- a/Task/Here-document/Rust/here-document.rust +++ b/Task/Here-document/Rust/here-document.rust @@ -1,3 +1,7 @@ let x = r#" This is a "raw string literal," roughly equivalent to a heredoc. - "#; +"#; + +let y = r##" + This string contains a #. +"##; diff --git a/Task/Hickerson-series-of-almost-integers/Ada/hickerson-series-of-almost-integers.ada b/Task/Hickerson-series-of-almost-integers/Ada/hickerson-series-of-almost-integers.ada new file mode 100644 index 0000000000..b23fe56866 --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/Ada/hickerson-series-of-almost-integers.ada @@ -0,0 +1,62 @@ +with Ada.Text_IO; +with Ada.Numerics.Generic_Elementary_Functions; + +procedure Almost_Integers is + + type Real is new Long_Long_Float; + + package Real_IO is + new Ada.Text_IO.Float_IO (Real); + package Integer_IO is + new Ada.Text_IO.Integer_IO (Integer); + + function Faculty (N : in Long_Long_Integer) return Long_Long_Integer is + (if N < 2 then N else N * Faculty (N - 1)); + + function Hickerson (N : in Integer) return Real + is + package Math is + new Ada.Numerics.Generic_Elementary_Functions (Real); + LN2 : constant Real := Math.Log (2.0, Base => Ada.Numerics.E); + Numerator : constant Real := Real (Faculty (Long_Long_Integer (N))); + Denominator : constant Real := 2.0 * LN2 ** (N + 1); + begin + return Numerator / Denominator; + end Hickerson; + + function Is_Almost_Integer (N : Real) return Boolean is + Image : String (1 .. 100); + begin + Real_IO.Put (Image, N, Exp => 0, Aft => 2); + + pragma Assert (Image (Image'Last - 2) = '.'); + case Image (Image'Last - 1) is + when '0' | '9' => return True; + when others => return False; + end case; + end Is_Almost_Integer; + + use Ada.Text_IO; + Placeholder : String := " n h(n) almost"; + Image_N : String renames Placeholder ( 1 .. 2); + Image_H : String renames Placeholder ( 4 .. 31); + Image_A : String renames Placeholder (34 .. 39); +begin + Put_Line (Placeholder); + Image_N := (others => '-'); + Image_H := (others => '-'); + Image_A := (others => '-'); + Put_Line (Placeholder); + + for N in 1 .. 17 loop + declare + H : constant Real := Hickerson (N); + I : constant Boolean := Is_Almost_Integer (H); + begin + Integer_IO.Put (Image_N, N); + Real_IO.Put (Image_H, H, Exp => 0, Aft => 4); + Image_A := (if I then "TRUE " else "FALSE"); + Put_Line (Placeholder); + end; + end loop; +end Almost_Integers; diff --git a/Task/Hickerson-series-of-almost-integers/Fortran/hickerson-series-of-almost-integers.f b/Task/Hickerson-series-of-almost-integers/Fortran/hickerson-series-of-almost-integers.f index a19d0672cb..decdc8bb70 100644 --- a/Task/Hickerson-series-of-almost-integers/Fortran/hickerson-series-of-almost-integers.f +++ b/Task/Hickerson-series-of-almost-integers/Fortran/hickerson-series-of-almost-integers.f @@ -1,23 +1,23 @@ -Program Hickerson -! 3 February 2014 -! not all Fortran compilers provide REAL*16 and INTEGER*8 -implicit none -real(kind=kind(1q0)) :: s -integer(kind=kind(1_8)) :: i,n,f,is +program hickerson + implicit none + integer, parameter :: q = selected_real_kind(30) + integer, parameter :: l = selected_int_kind(15) + real(q) :: s, l2 + integer :: i, n, k -do n = 1, 17 - s = 0.5q0 / log(2q0) - do i = 1,n - s = (s * i) / log(2q0) - end do + l2 = log(2.0_q) + do n = 1, 17 + s = 0.5_q / l2 + do i = 1, n + s = (s * i) / l2 + end do - is = s - f = (s-is)*10 !first digit after decimal point - if (f == 0 .or. f == 9) then - write(*,10)n,s,'' - else - write(*,10)n,s,' NOT' - endif -end do -10 format('h(',i2,') = ',F23.3,' is',A,' an almost-integer') -end program Hickerson + k = floor((s - floor(s, l)) * 10) + if (k == 0 .or. k == 9) then + print 1, n, s, "" + else + print 1, n, s, " NOT" + endif + end do + 1 format('h(',I2,') = ',F23.3,' is',A,' an almost-integer') +end program diff --git a/Task/Higher-order-functions/Elena/higher-order-functions.elena b/Task/Higher-order-functions/Elena/higher-order-functions.elena index f49681f6e2..b2911dbbe5 100644 --- a/Task/Higher-order-functions/Elena/higher-order-functions.elena +++ b/Task/Higher-order-functions/Elena/higher-order-functions.elena @@ -3,6 +3,6 @@ import extensions; public program() { var first := (f => f()); - var second := (^ "second"); + var second := {"second"}; console.printLine(first(second)) } diff --git a/Task/History-variables/Elena/history-variables.elena b/Task/History-variables/Elena/history-variables.elena index 074fc0d848..074ca28a1e 100644 --- a/Task/History-variables/Elena/history-variables.elena +++ b/Task/History-variables/Elena/history-variables.elena @@ -8,7 +8,7 @@ class HistoryVariable Stack previous := new Stack(); object value; - prop object Value + prop Value { get() = value; diff --git a/Task/Hofstadter-Conway-$10,000-sequence/Factor/hofstadter-conway-$10,000-sequence.factor b/Task/Hofstadter-Conway-$10,000-sequence/Factor/hofstadter-conway-$10,000-sequence.factor new file mode 100644 index 0000000000..a11adf9cd8 --- /dev/null +++ b/Task/Hofstadter-Conway-$10,000-sequence/Factor/hofstadter-conway-$10,000-sequence.factor @@ -0,0 +1,19 @@ +USING: combinators formatting io kernel locals math math.ranges +prettyprint sequences splitting ; + +MEMO:: a ( n -- a(n) ) ! memoize the recurrence relation + n { + { 1 [ 1 ] } + { 2 [ 1 ] } + [ 1 - a a n n 1 - a - a + ] + } case ; + +20 2^ [1,b] [ [ a ] [ 1 + / ] bi* ] map-index +[ + { 1/2 } split harvest rest-slice + [ supremum ] map 1 19 [a,b] + [ dup 1 + [ 2^ ] bi@ "%f max in (%d, %d)\n" printf ] + 2each +] +[ "Mallow's number: " write [ 0.55 >= ] find-last drop 1 + . ] +bi diff --git a/Task/Hofstadter-Q-sequence/R/hofstadter-q-sequence.r b/Task/Hofstadter-Q-sequence/R/hofstadter-q-sequence.r new file mode 100644 index 0000000000..5be2b708ac --- /dev/null +++ b/Task/Hofstadter-Q-sequence/R/hofstadter-q-sequence.r @@ -0,0 +1,27 @@ +cache <- vector("integer", 0) +cache[1] <- 1 +cache[2] <- 1 + +Q <- function(n) { + if (is.na(cache[n])) { + value <- Q(n-Q(n-1)) + Q(n-Q(n-2)) + cache[n] <<- value + } + cache[n] +} + +for (i in 1:1e5) { + Q(i) +} + +for (i in 1:10) { + cat(Q(i)," ",sep = "") +} +cat("\n") +cat(Q(1000),"\n") + +count <- 0 +for (i in 2:1e5) { + if (Q(i) < Q(i-1)) count <- count + 1 +} +cat(count,"terms is less than its preceding term\n") diff --git a/Task/Holidays-related-to-Easter/COBOL/holidays-related-to-easter.cobol b/Task/Holidays-related-to-Easter/COBOL/holidays-related-to-easter.cobol new file mode 100644 index 0000000000..b81068f58a --- /dev/null +++ b/Task/Holidays-related-to-Easter/COBOL/holidays-related-to-easter.cobol @@ -0,0 +1,123 @@ + identification division. + program-id. Easter. + + environment division. + configuration section. + repository. + function date-of-integer intrinsic + function integer-of-date intrinsic + function mod intrinsic. + + data division. + working-storage section. + 77 days pic 9(2). + 77 a pic 9(2). + 77 b pic 9(2). + 77 c pic 9(2). + 77 d pic 9(2). + 77 e pic 9(2). + 77 f pic 9(2). + 77 g pic 9(2). + 77 h pic 9(2). + 77 i pic 9(2). + 77 k pic 9(2). + 77 l pic 9(2). + 77 m pic 9(2). + 77 week-day pic 9(1). + 77 numerator pic 9(4). + 77 integer-date pic 9(18). + + 01 month-tab value "JanFebMarAprMayJunJulAugSepOctNovDec". + 05 month-abreviated pic x(3) occurs 12. + + 01 week-day-tab value "SunMonTueWedThuFriSat". + 05 week-day-abreviated pic x(3) occurs 7. + + 01 easter-date pic 9(8). + 01 filler redefines easter-date. + 05 easter-year pic 9(4). + 05 easter-month pic 9(2). + 05 easter-day pic 9(2). + + 01 holiday-date pic 9(8). + 01 filler redefines holiday-date. + 05 holiday-year pic 9(4). + 05 holiday-month pic 9(2). + 05 holiday-day pic 9(2). + + 01 edt-date. + 05 edt-week-day pic x(3). + 05 filler pic x value space. + 05 edt-day pic z(2). + 05 filler pic x value space. + 05 edt-month pic x(3). + + procedure division. + main. + display "Christian holidays, related to Easter, for each centennial from 1700 to 2100 CE:" + perform varying easter-year from 1700 by 100 until easter-year > 2100 + perform output-holydays + end-perform + display " " + + display "Christian holidays, related to Easter, for years from 2010 to 2020 CE:" + perform varying easter-year from 2010 by 1 until easter-year > 2020 + perform output-holydays + end-perform + display " " + + stop run + . + output-holydays. + display easter-year " " no advancing + perform calculate-easter + + move 0 to days + perform add-days + display " Easter: " edt-date no advancing + + move 39 to days + perform add-days + display " Ascension: " edt-date no advancing + + move 49 to days + perform add-days + display " Pentecost: " edt-date no advancing + + move 56 to days + perform add-days + display " Trinity: " edt-date no advancing + + move 60 to days + perform add-days + display " Corpus: " edt-date + . + calculate-easter. + compute a = mod(easter-year, 19) + compute b = easter-year / 100 + compute c = mod(easter-year, 100) + compute d = b / 4 + compute e = mod(b, 4) + compute f = (b + 8) / 25 + compute g = (b - f + 1) / 3 + compute h = mod((19 * a + b - d - g + 15), 30) + compute i = c / 4 + compute k = mod(c, 4) + compute l = mod((32 + 2 * e + 2 * i - h - k), 7) + compute m = (a + 11 * h + 22 * l) / 451 + compute numerator = h + l - 7 * m + 114 + compute easter-month = numerator / 31 + compute easter-day = mod(numerator, 31) + 1 + . + add-days. + if days = 0 + move easter-date to holiday-date + move 1 to week-day + else + compute holiday-date = date-of-integer(integer-of-date(easter-date) + days) + compute week-day = mod(integer-of-date(easter-date) + days, 7) + 1 + end-if + move week-day-abreviated(week-day) to edt-week-day + move month-abreviated(holiday-month) to edt-month + move holiday-day to edt-day + . diff --git a/Task/Holidays-related-to-Easter/Factor/holidays-related-to-easter.factor b/Task/Holidays-related-to-Easter/Factor/holidays-related-to-easter.factor new file mode 100644 index 0000000000..771fca6b04 --- /dev/null +++ b/Task/Holidays-related-to-Easter/Factor/holidays-related-to-easter.factor @@ -0,0 +1,34 @@ +USING: calendar formatting io kernel locals math math.ranges +sequences ; + +! Calculate Easter. +:: my-easter ( year -- timestamp ) + year 19 mod :> a + year 100 /i :> b + year 100 mod :> c + b 4 /i :> d + b 4 mod :> e + b 8 + 25 /i :> f + b f - 1 + 3 /i :> g + 19 a * b + d - g - 15 + 30 mod :> h + c 4 /i :> i + c 4 mod :> k + 32 2 e * + 2 i * + h - k - 7 mod :> l + a 11 h * + 22 l * + 451 /i :> m + h l + 7 m * - 114 + :> n + n 31 /i :> month + n 31 mod 1 + :> day + year month day ; + +: show-related ( timestamp days-offset -- ) + days time+ " %d %b " strftime write ; + +: holidays ( from to step -- ) + "Year Easter Ascension Pentecost Trinity Corpus" print + [ + dup "%4d: " printf my-easter + { 0 39 49 56 60 } [ show-related ] with each nl + ] each ; + +400 2100 100 holidays nl +2010 2020 1 holidays diff --git a/Task/Honeycombs/Ada/honeycombs.ada b/Task/Honeycombs/Ada/honeycombs.ada new file mode 100644 index 0000000000..7a319d4b95 --- /dev/null +++ b/Task/Honeycombs/Ada/honeycombs.ada @@ -0,0 +1,205 @@ +with Ada.Numerics.Elementary_Functions; +with Ada.Numerics.Discrete_Random; + +with SDL.Video.Windows.Makers; +with SDL.Video.Renderers.Makers; +with SDL.Video.Surfaces; +with SDL.Video.Rectangles; +with SDL.TTFs.Makers; +with SDL.Events.Events; +with SDL.Events.Keyboards; +with SDL.Events.Mice; + +procedure Honeycombs is + use SDL.Video.Rectangles; + use SDL.C; + + Width : constant := 560; + Height : constant := 595; + Offset_X : constant := 10.0; + Offset_Y : constant := 40.0; + Radius : constant := 60.0; + Rows : constant := 4; + Cols : constant := 5; + TTF_File : constant String := "NotoSans-Bold.ttf"; + TTF_Size_Cell : constant := 72; + TTF_Size_Sum : constant := 38; + Offset_Sum_X : constant := 35; + Offset_Sum_Y : constant := 530; + + type Node_Id is mod 6; + type Shape_List is array (Node_Id) of Point; + + type Cell_Info is record + Center : Point; + Marked : Boolean; + Label : String (1 .. 1); + end record; + type Cell_List is array (Positive range <>) of Cell_Info; + + function Make_Shape return Shape_List is + use Ada.Numerics.Elementary_Functions; + Shape : Shape_List; + begin + for I in Shape'Range loop + Shape (I) := (X => int (Radius * Cos (Float (I), Cycle => 6.0)), + Y => int (Radius * Sin (Float (I), Cycle => 6.0))); + end loop; + return Shape; + end Make_Shape; + + function Make_Cells (Rows, Cols : in Positive) return Cell_List is + subtype Label_Type is Character range 'A' .. 'Z'; + package Randoms is new Ada.Numerics.Discrete_Random (Label_Type); + use Randoms; + Y_Scale : constant Float := Ada.Numerics.Elementary_Functions.Sqrt (3.0); + List : Cell_List (1 .. Rows * Cols); + Info : Cell_Info; + Gen : Generator; + begin + Reset (Gen); + for R in 1 .. Rows loop + for C in 1 .. Cols loop + Info.Center.X := int (Offset_X + Radius * 1.5 * Float (C)); + Info.Center.Y := int (Offset_Y + Radius * Y_Scale * (Float (R) - + Float (C mod 2) / 2.0)); + Info.Marked := False; + Info.Label (1) := Random (Gen); + List ((R - 1) * Cols + C) := Info; + end loop; + end loop; + return List; + end Make_Cells; + + Window : SDL.Video.Windows.Window; + Win_Surf : SDL.Video.Surfaces.Surface; + Renderer : SDL.Video.Renderers.Renderer; + Font_Cell : SDL.TTFs.Fonts; + Font_Sum : SDL.TTFs.Fonts; + + Cells : Cell_List := Make_Cells (Rows, Cols); + Shape : constant Shape_List := Make_Shape; + Sum_Text : String (1 .. Rows * Cols); + Sum_Last : Natural := Sum_Text'First - 1; + + function Orient_2D (A, B, C : Point) return int is + ((B.X - A.X) * (C.Y - A.Y) - (B.Y - A.Y) * (C.X - A.X)); + + function "+" (Left, Right : Point) return Point is + ((Left.X + Right.X, Left.Y + Right.Y)); + + function Inside (P : Point; Cell : Cell_Info) return Boolean is + Count : Natural := 0; + begin + for Node in Shape'Range loop + Count := Count + + (if Orient_2D (Cell.Center + Shape (Node), + Cell.Center + Shape (Node + 1), + P) > 0 then 1 else 0); + end loop; + return Count = 6; + end Inside; + + procedure Draw (Cell : Cell_Info) is + Surface : constant SDL.Video.Surfaces.Surface := + Font_Cell.Render_Solid (Cell.Label, (30, 230, 230, 255)); + Self_Area : SDL.Video.Rectangles.Rectangle; + Source_Area : SDL.Video.Rectangles.Rectangle := (0, 0, 0, 0); + begin + -- Fill + for Y in int (-Radius) .. int (Radius) loop + for X in int (-Radius) .. int (Radius) loop + if Inside (Cell.Center + (X, Y), Cell) then + Renderer.Draw (Point => Cell.Center + (X, Y)); + end if; + end loop; + end loop; + + -- Label + Self_Area := (Cell.Center.X - Surface.Size.Width / 2, + Cell.Center.Y - Surface.Size.Height / 2, 0, 0); + Win_Surf.Blit (Self_Area, Surface, Source_Area); + + -- Outline + Renderer.Set_Draw_Colour ((0, 0, 0, 255)); + for Id in Shape'Range loop + Renderer.Draw (Line => (Cell.Center + Shape (Id), + Cell.Center + Shape (Id + 1))); + end loop; + end Draw; + + procedure Find_And_Mark (Click : Point; Key : String) is + Self_Area : SDL.Video.Rectangles.Rectangle; + Source_Area : SDL.Video.Rectangles.Rectangle := (0, 0, 0, 0); + begin + for Cell of Cells loop + if not Cell.Marked and then (Inside (Click, Cell) or Cell.Label = Key) then + Cell.Marked := True; + Sum_Last := Sum_Last + 1; + Sum_Text (Sum_Last) := Cell.Label (1); + Renderer.Set_Draw_Colour ((230, 20, 220, 255)); + Draw (Cell); + + -- Update sum text + Self_Area := (Offset_Sum_X, Offset_Sum_Y, 0, 0); + Win_Surf.Blit + (Self_Area, Font_Sum.Render_Solid (Sum_Text (Sum_Text'First .. Sum_Last), + (0, 200, 200, 255)), Source_Area); + Window.Update_Surface; + exit; + end if; + end loop; + end Find_And_Mark; + + procedure Wait is + use type SDL.Events.Event_Types; + use SDL.Events.Keyboards; + Event : SDL.Events.Events.Events; + begin + loop + SDL.Events.Events.Wait (Event); + case Event.Common.Event_Type is + when SDL.Events.Quit => return; + when SDL.Events.Mice.Button_Down => + Find_And_Mark + ((Event.Mouse_Button.X, + Event.Mouse_Button.Y), ""); + when SDL.Events.Keyboards.Key_Down => + Find_And_Mark + ((0, 0), Image (Event.Keyboard.Key_Sym.Key_Code)); + null; + when others => null; + end case; + end loop; + end Wait; + +begin + if not SDL.Initialise (Flags => SDL.Enable_Screen) then + return; + end if; + if not SDL.TTFs.Initialise then + null; + end if; + SDL.TTFs.Makers.Create (Font_Cell, TTF_File, TTF_Size_Cell); + SDL.TTFs.Makers.Create (Font_Sum, TTF_File, TTF_Size_Sum); + + SDL.Video.Windows.Makers.Create (Win => Window, + Title => "Honeycombs", + Position => SDL.Natural_Coordinates'(X => 10, Y => 10), + Size => SDL.Positive_Sizes'(Width, Height), + Flags => 0); + Win_Surf := Window.Get_Surface; + SDL.Video.Renderers.Makers.Create (Renderer, Window.Get_Surface); + Renderer.Set_Draw_Colour ((0, 0, 0, 255)); + Renderer.Fill (Rectangle => (0, 0, Width, Height)); + + for Cell of Cells loop + Renderer.Set_Draw_Colour ((230, 230, 0, 255)); + Draw (Cell); + end loop; + Window.Update_Surface; + + Wait; + Window.Finalize; + SDL.Finalise; +end Honeycombs; diff --git a/Task/Honeycombs/Go/honeycombs.go b/Task/Honeycombs/Go/honeycombs.go index c38500b3e4..1d09885d74 100644 --- a/Task/Honeycombs/Go/honeycombs.go +++ b/Task/Honeycombs/Go/honeycombs.go @@ -36,6 +36,12 @@ func inHexagon(pts []rl.Vector2, pt rl.Vector2) bool { return false } +func DrawLineStrip(points []rl.Vector2, pointsCount int32, color rl.Color) { + for i := int32(0); i < pointsCount - 1; i++ { + rl.DrawLineV(points[i], points[i+1], color) + } +} + func main() { screenWidth := int32(600) screenHeight := int32(600) @@ -75,7 +81,7 @@ func main() { ctr := pts[i][0] ctr.X -= r index := -1 - if key := rl.GetKeyPressed(); key != -1 { + if key := rl.GetKeyPressed(); key > 0 { if key >= 97 && key <= 122 { key -= 32 } @@ -107,7 +113,7 @@ func main() { rl.DrawPoly(ctr, 6, r-1, 30, rl.Magenta) } rl.DrawText(string(c.letter), int32(c.x)-5, int32(c.y)-10, 32, rl.Black) - rl.DrawPolyExLines(pts[i], 7, rl.Black) + DrawLineStrip(pts[i], 7, rl.Black) rl.DrawText(sChosen, 100, 525, 24, rl.Black) rl.DrawText(lChosen, 100, 565, 24, rl.Black) } diff --git a/Task/Horners-rule-for-polynomial-evaluation/Elena/horners-rule-for-polynomial-evaluation.elena b/Task/Horners-rule-for-polynomial-evaluation/Elena/horners-rule-for-polynomial-evaluation.elena index 876815343c..1152f3740c 100644 --- a/Task/Horners-rule-for-polynomial-evaluation/Elena/horners-rule-for-polynomial-evaluation.elena +++ b/Task/Horners-rule-for-polynomial-evaluation/Elena/horners-rule-for-polynomial-evaluation.elena @@ -8,5 +8,5 @@ horner(coefficients,variable) public program() { - console.printLine(horner(new real[]{-19.0r, 7.0r, -4.0r, 6.0r}, 3.0r)) + console.printLine(horner(new real[]::(-19.0r, 7.0r, -4.0r, 6.0r), 3.0r)) } diff --git a/Task/Hostname/Crystal/hostname.crystal b/Task/Hostname/Crystal/hostname.crystal new file mode 100644 index 0000000000..a5a16ec4f9 --- /dev/null +++ b/Task/Hostname/Crystal/hostname.crystal @@ -0,0 +1 @@ +hostname = System.hostname diff --git a/Task/Hostname/Frink/hostname.frink b/Task/Hostname/Frink/hostname.frink new file mode 100644 index 0000000000..3ef551688c --- /dev/null +++ b/Task/Hostname/Frink/hostname.frink @@ -0,0 +1 @@ +callJava["java.net.InetAddress", "getLocalHost"].getHostName[] diff --git a/Task/Huffman-coding/Factor/huffman-coding.factor b/Task/Huffman-coding/Factor/huffman-coding.factor new file mode 100644 index 0000000000..fccc733506 --- /dev/null +++ b/Task/Huffman-coding/Factor/huffman-coding.factor @@ -0,0 +1,132 @@ +USING: kernel sequences combinators accessors assocs math hashtables math.order +sorting.slots classes formatting prettyprint ; + +IN: huffman + +! ------------------------------------- +! CLASSES ----------------------------- +! ------------------------------------- + +TUPLE: huffman-node + weight element encoding left right ; + +! For nodes +: ( left right -- huffman ) + huffman-node new [ left<< ] [ swap >>right ] bi ; + +! For leafs +: ( element -- huffman ) + 1 swap f f f huffman-node boa ; + + +! -------------------------------------- +! INITIAL HASHTABLE -------------------- +! -------------------------------------- + + swap ] dip set-at ] if ; + +! Curry node-hash. Then each over the seq +! to get the weighted values +: (huffman) ( nodes seq -- nodes ) + dup [ [ huffman-gen ] curry each ] dip ; + +! --------------------------------------- +! TREE GENERATION ----------------------- +! --------------------------------------- + +: (huffman-weight) ( node1 node2 -- weight ) + [ weight>> ] dup bi* + ; + +! Combine two nodes into the children of a parent +! node which has a weight equal to their collective +! weight +: (huffman-combine) ( node1 node2 -- node3 ) + [ (huffman-weight) ] + [ ] 2bi + swap >>weight ; + +! Generate a tree by combining nodes +! in the priority queue until we're +! left with the root node +: (huffman-tree) ( nodes -- tree ) + dup rest empty? + [ first ] [ + { { weight>> <=> } } sort-by + [ rest rest ] [ first ] + [ second ] tri + (huffman-combine) prefix + (huffman-tree) + ] if ; recursive + +! -------------------------------------- +! ENCODING ----------------------------- +! -------------------------------------- + +: (huffman-leaf?) ( node -- bool ) + [ left>> huffman-node instance? ] + [ right>> huffman-node instance? ] bi and not ; + +: (huffman-leaf) ( leaf bit -- ) + swap encoding<< ; + +DEFER: (huffman-encoding) + +! Recursively walk the nodes left and right +: (huffman-node) ( bit nodes -- ) + [ 0 suffix ] [ 1 suffix ] bi + [ [ left>> ] [ right>> ] bi ] 2dip + [ swap ] dip + [ (huffman-encoding) ] 2bi@ ; + +: (huffman-encoding) ( bit nodes -- ) + over (huffman-leaf?) + [ (huffman-leaf) ] + [ (huffman-node) ] if ; + +PRIVATE> + +! ------------------------------- +! USER WORDS -------------------- +! ------------------------------- + +: huffman-print ( nodes -- ) + "Element" "Weight" "Code" "\n%10s\t%10s\t%6s\n" printf + { { weight>> >=< } } sort-by + [ [ encoding>> ] [ element>> ] [ weight>> ] tri + "%8c\t%7d\t\t" printf pprint "\n" printf ] each ; + +: huffman ( sequence -- nodes ) + H{ } clone (huffman) values + [ (huffman-tree) { } (huffman-encoding) ] keep ; + +! --------------------------------- +! USAGE --------------------------- +! --------------------------------- + +! { 1 2 3 4 } huffman huffman-print +! "this is an example of a huffman tree" huffman huffman-print + +! Element Weight Code +! 7 { 0 0 0 } +! a 4 { 1 1 1 } +! e 4 { 1 1 0 } +! f 3 { 0 0 1 0 } +! h 2 { 1 0 1 0 } +! i 2 { 0 1 0 1 } +! m 2 { 0 1 0 0 } +! n 2 { 0 1 1 1 } +! s 2 { 0 1 1 0 } +! t 2 { 0 0 1 1 } +! l 1 { 1 0 1 1 1 } +! o 1 { 1 0 1 1 0 } +! p 1 { 1 0 0 0 1 } +! r 1 { 1 0 0 0 0 } +! u 1 { 1 0 0 1 1 } +! x 1 { 1 0 0 1 0 } diff --git a/Task/Huffman-coding/Ol/huffman-coding-1.ol b/Task/Huffman-coding/Ol/huffman-coding-1.ol new file mode 100644 index 0000000000..7d32293f87 --- /dev/null +++ b/Task/Huffman-coding/Ol/huffman-coding-1.ol @@ -0,0 +1,38 @@ +(define phrase "this is an example for huffman encoding") + +; prepare initial probabilities table +(define table (ff->list + (fold (lambda (ff x) + (put ff x (+ (ff x 0) 1))) + {} + (string->runes phrase)))) + +; just sorter... +(define (resort l) + (sort (lambda (x y) (< (cdr x) (cdr y))) l)) +; ...to sort table +(define table (resort table)) + +; build huffman tree +(define tree + (let loop ((table table)) + (if (null? (cdr table)) + (car table) + (loop (resort (cons + (cons + { 1 (car table) 0 (cadr table)} + (+ (cdar table) (cdadr table))) + (cddr table))))))) + +; huffman codes +(define codes + (map (lambda (i) + (call/cc (lambda (return) + (let loop ((prefix #null) (tree tree)) + (if (ff? (car tree)) + (begin + (loop (cons 0 prefix) ((car tree) 0)) + (loop (cons 1 prefix) ((car tree) 1))) + (if (eq? (car tree) i) + (return (reverse prefix)))))))) + (map car table))) diff --git a/Task/Huffman-coding/Ol/huffman-coding-2.ol b/Task/Huffman-coding/Ol/huffman-coding-2.ol new file mode 100644 index 0000000000..ee70b2fe0c --- /dev/null +++ b/Task/Huffman-coding/Ol/huffman-coding-2.ol @@ -0,0 +1,10 @@ +(print "weights: ---------------------------") +(for-each (lambda (ch) + (print (string (car ch)) ": " (cdr ch))) + (reverse table)) + +(print "codes: -----------------------------") +(map (lambda (char code) + (print (string char) ": " code)) + (reverse (map car table)) + (reverse codes)) diff --git a/Task/IBAN/Kotlin/iban.kotlin b/Task/IBAN/Kotlin/iban.kotlin index 3a7d8b32de..2cf89be6fd 100644 --- a/Task/IBAN/Kotlin/iban.kotlin +++ b/Task/IBAN/Kotlin/iban.kotlin @@ -2,39 +2,43 @@ import java.math.BigInteger -object Iban { +object IBAN { /* List updated to release 73, January 2017, of IBAN Registry (75 countries) */ - private val countryCodes = - "AD24 AE23 AL28 AT20 AZ28 BA20 BE16 BG22 BH22 BR29 BY28 CH21 CR22 CY28 CZ24 DE22 " + - "DK18 DO28 EE20 ES24 FI18 FO18 FR27 GB22 GE22 GI23 GL18 GR27 GT28 HR21 HU28 IE22 " + - "IL23 IQ23 IS26 IT27 JO30 KW30 KZ20 LB28 LC32 LI21 LT20 LU20 LV21 MC27 MD24 ME22 " + - "MK19 MR27 MT31 MU30 NL18 NO15 PK24 PL28 PS29 PT25 QA29 RO24 RS22 SA24 SC31 SE24 " + - "SI19 SK24 SM27 ST25 SV28 TL23 TN24 TR26 UA29 VG24 XK20" + private const val countryCodes = "" + + "AD24 AE23 AL28 AT20 AZ28 BA20 BE16 BG22 BH22 BR29 " + + "BY28 CH21 CR22 CY28 CZ24 DE22 DK18 DO28 EE20 ES24 " + + "FI18 FO18 FR27 GB22 GE22 GI23 GL18 GR27 GT28 HR21 " + + "HU28 IE22 IL23 IQ23 IS26 IT27 JO30 KW30 KZ20 LB28 " + + "LC32 LI21 LT20 LU20 LV21 MC27 MD24 ME22 MK19 MR27 " + + "MT31 MU30 NL18 NO15 PK24 PL28 PS29 PT25 QA29 RO24 " + + "RS22 SA24 SC31 SE24 SI19 SK24 SM27 ST25 SV28 TL23 " + + "TN24 TR26 UA29 VG24 XK20" - private fun checkCountryCode(cc: String) = cc in countryCodes - - fun validate(iban: String): Boolean { + fun isValid(iban: String): Boolean { // remove spaces from IBAN var s = iban.replace(" ", "") - // check country code - if (!checkCountryCode(s.substring(0, 2) + s.length)) return false + // check country code and length + s.substring(0, 2) + s.length in countryCodes || return false - // move first 4 characters to end + // move first 4 characters to the end s = s.substring(4) + s.substring(0, 4) // replace A to Z with numbers 10 To 35 - for (ch in 'A'..'Z') s = s.replace(ch.toString(), (ch - 55).toInt().toString()) + s = s.replace(Regex("[A-Z]")) { (10 + (it.value[0] - 'A')).toString() } // check whether mod 97 calculation gives a remainder of 1 return BigInteger(s) % BigInteger.valueOf(97L) == BigInteger.ONE } } -fun main(args: Array) { - val ibans = arrayOf("GB82 WEST 1234 5698 7654 32", "GB82 TEST 1234 5698 7654 32") +fun main() { + val ibans = arrayOf( + "GB82 WEST 1234 5698 7654 32", + "GB82 TEST 1234 5698 7654 32" + ) for (iban in ibans) { - val isValid = Iban.validate(iban) - println(iban + if(isValid) " may be valid" else " is not valid") + val valid = IBAN.isValid(iban) + println(iban + if (valid) " may be valid" else " is not valid") } } diff --git a/Task/IBAN/Lobster/iban.lobster b/Task/IBAN/Lobster/iban.lobster new file mode 100644 index 0000000000..9b05611787 --- /dev/null +++ b/Task/IBAN/Lobster/iban.lobster @@ -0,0 +1,59 @@ +let 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"] +let 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 ] + +def ccToLen(s: string) -> int: + let cnt, idx = binary_search(cc, s.substring(0, 2)) + if cnt == 1: + return ln[idx] + else: + return -1 + +def strip(s: string) -> string: + let t = s.tokenize(" ", " ") // splits on spaces and trims spaces from segments + return t.concat_string("") // joins it back together + +def rotmod97step(accumu: int, c: int) -> int: + accumu *= 10 + if '0' <= c and c <= '9': + accumu += c - '0' + else: if 'A' <= c and c <= 'Z': + accumu *= 10 + accumu += c + 10 - 'A' + else: + return -1 + while accumu >= 97: + accumu -= 97 + return accumu + +def rotmod97(s: string) -> int: + // the first four chars come last + // all chars from 'A' to 'Z' => "10" to "35" + let len = s.length + var accumu = 0 // result; negative indicates error + var i = 4 // starting index + while i < len and accumu >= 0: + accumu = rotmod97step(accumu, s[i]) + i += 1 + i = 0 + while i < 4 and accumu >= 0: + accumu = rotmod97step(accumu, s[i]) + i += 1 + return accumu + +def isValidIBAN(iban: string) -> bool: + let s = strip(uppercase(iban)) + if s.length == ccToLen(s): + return rotmod97(s) == 1 + else: + return false + +assert isValidIBAN("GB82 WEST 1234 5698 7654 32") +assert isValidIBAN("GB82 West 1234 5698 7654 32") +assert not isValidIBAN("GB82 TEST 1234 5698 7654 32") +assert not isValidIBAN("GB82 WEST 1243 5698 7654 32") diff --git a/Task/Identity-matrix/Julia/identity-matrix-1.julia b/Task/Identity-matrix/Julia/identity-matrix-1.julia index 39cd537d90..64b7edf07f 100644 --- a/Task/Identity-matrix/Julia/identity-matrix-1.julia +++ b/Task/Identity-matrix/Julia/identity-matrix-1.julia @@ -1 +1,2 @@ -eye(3) +using LinearAlgebra +I(3) diff --git a/Task/Identity-matrix/Julia/identity-matrix-2.julia b/Task/Identity-matrix/Julia/identity-matrix-2.julia index ce95023887..8fa8cec9b8 100644 --- a/Task/Identity-matrix/Julia/identity-matrix-2.julia +++ b/Task/Identity-matrix/Julia/identity-matrix-2.julia @@ -1 +1 @@ -eye(int(readline(STDIN))) +I(parse(Int, readline(stdin))) diff --git a/Task/Identity-matrix/Ol/identity-matrix.ol b/Task/Identity-matrix/Ol/identity-matrix.ol new file mode 100644 index 0000000000..9321592ca2 --- /dev/null +++ b/Task/Identity-matrix/Ol/identity-matrix.ol @@ -0,0 +1,7 @@ +(define (make-identity-matrix n) + (map (lambda (i) + (append (repeat 0 i) '(1) (repeat 0 (- n i 1)))) + (iota n))) + +(for-each print (make-identity-matrix 3)) +(for-each print (make-identity-matrix 17)) diff --git a/Task/Image-convolution/Perl-6/image-convolution-1.pl6 b/Task/Image-convolution/Perl-6/image-convolution-1.pl6 new file mode 100644 index 0000000000..94f49e9485 --- /dev/null +++ b/Task/Image-convolution/Perl-6/image-convolution-1.pl6 @@ -0,0 +1,8 @@ +use PDL:from; +use PDL::Image2D:from; + +my $kernel = pdl [[-2, -1, 0],[-1, 1, 1], [0, 1, 2]]; # emboss + +my $image = rpic 'frog.png'; +my $smoothed = conv2d $image, $kernel, {Boundary => 'Truncate'}; +wpic $smoothed, 'frog_convolution.png'; diff --git a/Task/Image-convolution/Perl-6/image-convolution.pl6 b/Task/Image-convolution/Perl-6/image-convolution-2.pl6 similarity index 86% rename from Task/Image-convolution/Perl-6/image-convolution.pl6 rename to Task/Image-convolution/Perl-6/image-convolution-2.pl6 index 7a9b0f0a79..14bdc4dbe5 100644 --- a/Task/Image-convolution/Perl-6/image-convolution.pl6 +++ b/Task/Image-convolution/Perl-6/image-convolution-2.pl6 @@ -1,5 +1,4 @@ -#!/usr/bin/env perl6 - +# Note: must install version from github NOT version from CPAN which needs to be updated. # Reference: # https://github.com/azawawi/perl6-magickwand # http://www.imagemagick.org/Usage/convolve/ diff --git a/Task/Image-convolution/Perl/image-convolution.pl b/Task/Image-convolution/Perl/image-convolution.pl new file mode 100644 index 0000000000..6f95dd3777 --- /dev/null +++ b/Task/Image-convolution/Perl/image-convolution.pl @@ -0,0 +1,11 @@ +use strict; +use warnings; + +use PDL; +use PDL::Image2D; + +my $kernel = pdl [[-2, -1, 0],[-1, 1, 1], [0, 1, 2]]; # emboss + +my $image = rpic 'pythagoras_tree.png'; +my $smoothed = conv2d $image, $kernel, {Boundary => 'Truncate'}; +wpic $smoothed, 'pythagoras_convolution.png'; diff --git a/Task/Include-a-file/Crystal/include-a-file.crystal b/Task/Include-a-file/Crystal/include-a-file.crystal new file mode 100644 index 0000000000..73ddffb6f8 --- /dev/null +++ b/Task/Include-a-file/Crystal/include-a-file.crystal @@ -0,0 +1,2 @@ +require "socket" # includes a file from standard library or /lib relative to current directory +require "./myfile" # includes a file relative to current directory diff --git a/Task/Include-a-file/Go/include-a-file-1.go b/Task/Include-a-file/Go/include-a-file-1.go new file mode 100644 index 0000000000..fd300f6c16 --- /dev/null +++ b/Task/Include-a-file/Go/include-a-file-1.go @@ -0,0 +1,13 @@ +// main.go +package main + +import "fmt" + +func hello() { + fmt.Println("Hello from main.go") +} + +func main() { + hello() + hello2() +} diff --git a/Task/Include-a-file/Go/include-a-file-2.go b/Task/Include-a-file/Go/include-a-file-2.go new file mode 100644 index 0000000000..1e8abba08a --- /dev/null +++ b/Task/Include-a-file/Go/include-a-file-2.go @@ -0,0 +1,8 @@ +// main2.go +package main + +import "fmt" + +func hello2() { + fmt.Println("Hello from main2.go") +} diff --git a/Task/Include-a-file/Ol/include-a-file-1.ol b/Task/Include-a-file/Ol/include-a-file-1.ol new file mode 100644 index 0000000000..b25066f537 --- /dev/null +++ b/Task/Include-a-file/Ol/include-a-file-1.ol @@ -0,0 +1 @@ +(import (otus random!)) diff --git a/Task/Include-a-file/Ol/include-a-file-2.ol b/Task/Include-a-file/Ol/include-a-file-2.ol new file mode 100644 index 0000000000..e3e3d949e0 --- /dev/null +++ b/Task/Include-a-file/Ol/include-a-file-2.ol @@ -0,0 +1 @@ +,load "otus/random!.scm" diff --git a/Task/Include-a-file/Pike/include-a-file.pike b/Task/Include-a-file/Pike/include-a-file.pike new file mode 100644 index 0000000000..f8a04aa33d --- /dev/null +++ b/Task/Include-a-file/Pike/include-a-file.pike @@ -0,0 +1 @@ +#include "foo.txt" diff --git a/Task/Increment-a-numerical-string/APL/increment-a-numerical-string.apl b/Task/Increment-a-numerical-string/APL/increment-a-numerical-string.apl new file mode 100644 index 0000000000..660a225b77 --- /dev/null +++ b/Task/Increment-a-numerical-string/APL/increment-a-numerical-string.apl @@ -0,0 +1 @@ +⍕1+⍎'12345' diff --git a/Task/Increment-a-numerical-string/Julia/increment-a-numerical-string.julia b/Task/Increment-a-numerical-string/Julia/increment-a-numerical-string.julia index 18cefbb3a8..cc612e4e70 100644 --- a/Task/Increment-a-numerical-string/Julia/increment-a-numerical-string.julia +++ b/Task/Increment-a-numerical-string/Julia/increment-a-numerical-string.julia @@ -1,5 +1,5 @@ -Base.:+(s::AbstractString, n::Real) = string(parse(s) + n) - +import Base.+ +Base.:+(s::AbstractString, n::Real) = string((x = tryparse(Int, s)) isa Int ? x + 1 : parse(Float64, s) + 1) @show "125" + 1 @show "125.15" + 1 @show "1234567890987654321" + 1 diff --git a/Task/Infinity/Julia/infinity.julia b/Task/Infinity/Julia/infinity.julia new file mode 100644 index 0000000000..c867699615 --- /dev/null +++ b/Task/Infinity/Julia/infinity.julia @@ -0,0 +1,2 @@ +julia> julia> Inf32 == Inf64 == Inf16 == Inf +true diff --git a/Task/Inheritance-Multiple/C/inheritance-multiple.c b/Task/Inheritance-Multiple/C/inheritance-multiple.c new file mode 100644 index 0000000000..367bef20ec --- /dev/null +++ b/Task/Inheritance-Multiple/C/inheritance-multiple.c @@ -0,0 +1,16 @@ +typedef struct{ + double focalLength; + double resolution; + double memory; +}Camera; + +typedef struct{ + double balance; + double batteryLevel; + char** contacts; +}Phone; + +typedef struct{ + Camera cameraSample; + Phone phoneSample; +}CameraPhone; diff --git a/Task/Input-loop/Elena/input-loop-2.elena b/Task/Input-loop/Elena/input-loop-2.elena index fc00130802..87355876e5 100644 --- a/Task/Input-loop/Elena/input-loop-2.elena +++ b/Task/Input-loop/Elena/input-loop-2.elena @@ -2,9 +2,11 @@ import system'io; public program() { - var reader := File.assign:"file.txt".textreader(); - while (reader.Available) + using(var reader := File.assign:"file.txt".textreader()) { - console.writeLine(reader.readLine()) + while (reader.Available) + { + console.writeLine(reader.readLine()) + } } } diff --git a/Task/Input-loop/XPL0/input-loop.xpl0 b/Task/Input-loop/XPL0/input-loop.xpl0 new file mode 100644 index 0000000000..ad36132e4a --- /dev/null +++ b/Task/Input-loop/XPL0/input-loop.xpl0 @@ -0,0 +1,9 @@ +int C; +[repeat \read file + repeat \read line + repeat C:= ChIn(1); \read word + ChOut(0, C); + until (C<^A ! C>^z) & (C<^0 ! C>^9); \non-alphanumeric + until C < $20; \CR, LF, or EOF +until C = \EOF\ $1A; +] diff --git a/Task/Integer-comparison/Go/integer-comparison.go b/Task/Integer-comparison/Go/integer-comparison.go index b5a0ba0655..1ac56558a3 100644 --- a/Task/Integer-comparison/Go/integer-comparison.go +++ b/Task/Integer-comparison/Go/integer-comparison.go @@ -7,9 +7,11 @@ import ( func main() { var n1, n2 int + fmt.Print("enter number: ") if _, err := fmt.Scan(&n1); err != nil { log.Fatal(err) } + fmt.Print("enter number: ") if _, err := fmt.Scan(&n2); err != nil { log.Fatal(err) } diff --git a/Task/Integer-comparison/Julia/integer-comparison.julia b/Task/Integer-comparison/Julia/integer-comparison.julia index f669002038..ceac99d4f2 100644 --- a/Task/Integer-comparison/Julia/integer-comparison.julia +++ b/Task/Integer-comparison/Julia/integer-comparison.julia @@ -1,7 +1,7 @@ function compare() -int1 = readline(STDIN) -int2 = readline(STDIN) -print(int1, " is ", + int1 = readline(stdin) + int2 = readline(stdin) + print(int1, " is ", int1 < int2 ? "less than " : int1 == int2 ? "equal to " : int1 > int2 ? "greater than " : diff --git a/Task/Integer-overflow/Julia/integer-overflow-1.julia b/Task/Integer-overflow/Julia/integer-overflow-1.julia index a56c3072d1..462df00874 100644 --- a/Task/Integer-overflow/Julia/integer-overflow-1.julia +++ b/Task/Integer-overflow/Julia/integer-overflow-1.julia @@ -1,3 +1,4 @@ +using Printf S = subtypes(Signed) U = subtypes(Unsigned) diff --git a/Task/Integer-overflow/Rust/integer-overflow-2.rust b/Task/Integer-overflow/Rust/integer-overflow-2.rust index 895453b79c..1da5805154 100644 --- a/Task/Integer-overflow/Rust/integer-overflow-2.rust +++ b/Task/Integer-overflow/Rust/integer-overflow-2.rust @@ -1,21 +1,9 @@ - // The following will panic!, but only in release mode - let u32_1 : u32 = !4_294_967_295 + 1; - let u32_2 : u32 = 3_000_000_000 + 3_000_000_000; - let u32_3 : u32 = 2_147_483_647 - 4_294_967_295; - let u32_4 : u32 = 65_537 * 65_537; + // The following will never panic! + println!("{:?}", 65_537u32.checked_mul(65_537)); // None + println!("{:?}", 65_537u32.saturating_mul(65_537)); // 4294967295 + println!("{:?}", 65_537u32.wrapping_mul(65_537)); // 131073 - // The following panics! in release mode - let u64_1 : u64 = !18_446_744_073_709_551_615 + 1; - let u64_2 : u64 = 10_000_000_000_000_000_000 + 10_000_000_000_000_000_000; - let u64_3 : u64 = 9_223_372_036_854_775_807 - 18_446_744_073_709_551_615; - let u64_4 : u64 = 4_294_967_296 * 4_294_967_296; - - println!("{}", u32_1); // 1 - println!("{}", u32_2); // 1705032704 - println!("{}", u32_3); // 2147483648 - println!("{}", u32_4); // 131703 - - println!("{}", u64_1); // 1 - println!("{}", u64_2); // 1553255926290448384 - println!("{}", u64_3); // 9223372036854775808 - println!("{}", u64_4); // 0 + // These will never panic! either + println!("{:?}", 65_537i32.checked_mul(65_537)); // None + println!("{:?}", 65_537i32.saturating_mul(65_537)); // 2147483647 + println!("{:?}", 65_537i32.wrapping_mul(-65_537)); // -131073 diff --git a/Task/Integer-sequence/JavaScript/integer-sequence.js b/Task/Integer-sequence/JavaScript/integer-sequence-1.js similarity index 100% rename from Task/Integer-sequence/JavaScript/integer-sequence.js rename to Task/Integer-sequence/JavaScript/integer-sequence-1.js diff --git a/Task/Integer-sequence/JavaScript/integer-sequence-2.js b/Task/Integer-sequence/JavaScript/integer-sequence-2.js new file mode 100644 index 0000000000..749610ac64 --- /dev/null +++ b/Task/Integer-sequence/JavaScript/integer-sequence-2.js @@ -0,0 +1,4 @@ +var i = 0n; + +while (true) + document.write(++i + ' '); diff --git a/Task/Integer-sequence/Pike/integer-sequence.pike b/Task/Integer-sequence/Pike/integer-sequence.pike new file mode 100644 index 0000000000..017148e6de --- /dev/null +++ b/Task/Integer-sequence/Pike/integer-sequence.pike @@ -0,0 +1,3 @@ +int i=1; +while(true) + write("%d\n", i++); diff --git a/Task/Integer-sequence/Ruby/integer-sequence.rb b/Task/Integer-sequence/Ruby/integer-sequence-1.rb similarity index 100% rename from Task/Integer-sequence/Ruby/integer-sequence.rb rename to Task/Integer-sequence/Ruby/integer-sequence-1.rb diff --git a/Task/Integer-sequence/Ruby/integer-sequence-2.rb b/Task/Integer-sequence/Ruby/integer-sequence-2.rb new file mode 100644 index 0000000000..9709efe910 --- /dev/null +++ b/Task/Integer-sequence/Ruby/integer-sequence-2.rb @@ -0,0 +1 @@ +(1..).each{|n| puts n} diff --git a/Task/Interactive-programming/Ol/interactive-programming.ol b/Task/Interactive-programming/Ol/interactive-programming.ol new file mode 100644 index 0000000000..51f8ddf3e1 --- /dev/null +++ b/Task/Interactive-programming/Ol/interactive-programming.ol @@ -0,0 +1,10 @@ +$ ol +Welcome to Otus Lisp 2.1-2282-27a9b6c +type ',help' to help, ',quit' to end session. +> (define (f head tail mid) + (fold string-append "" (list head mid mid tail))) +;; Defined f +> (f "Rosetta" "Code" ":") +"Rosetta::Code" +> ,quit +bye-bye :/ diff --git a/Task/Introspection/Julia/introspection.julia b/Task/Introspection/Julia/introspection.julia index 3e34fd7879..8422a321c3 100644 --- a/Task/Introspection/Julia/introspection.julia +++ b/Task/Introspection/Julia/introspection.julia @@ -1,7 +1,7 @@ @show VERSION VERSION < v"0.4" && exit(1) -if isdefined(:bloop) && !isempty(methods(abs)) +if isdefined(Base, :bloop) && !isempty(methods(abs)) @show abs(bloop) end diff --git a/Task/Iterated-digits-squaring/Ada/iterated-digits-squaring.ada b/Task/Iterated-digits-squaring/Ada/iterated-digits-squaring.ada new file mode 100644 index 0000000000..0a446d83e7 --- /dev/null +++ b/Task/Iterated-digits-squaring/Ada/iterated-digits-squaring.ada @@ -0,0 +1,40 @@ +with Ada.Text_IO; + +procedure Digits_Squaring is + + function Is_89 (Number : in Positive) return Boolean + is + Squares : constant array (0 .. 9) of Natural := + (0, 1, 4, 9, 16, 25, 36, 49, 64, 81); + + Sum : Natural := Number; + Acc : Natural; + begin + loop + Acc := Sum; + Sum := 0; + while Acc > 0 loop + Sum := Sum + Squares (Acc mod 10); + Acc := Acc / 10; + end loop; + + if Sum = 89 then return True; end if; + if Sum = 1 then return False; end if; + end loop; + end Is_89; + + use Ada.Text_IO; + Count : Natural := 0; +begin + for A in 1 .. 99_999_999 loop + if Is_89 (A) then + Count := Count + 1; + end if; + + if A = 999_999 then + Put_Line ("In range 1 .. 999_999: " & Count'Image); + end if; + + end loop; + Put_Line ("In range 1 .. 99_999_999: " & Count'Image); +end Digits_Squaring; diff --git a/Task/Iterated-digits-squaring/X86-Assembly/iterated-digits-squaring.x86 b/Task/Iterated-digits-squaring/X86-Assembly/iterated-digits-squaring.x86 new file mode 100644 index 0000000000..91866d6753 --- /dev/null +++ b/Task/Iterated-digits-squaring/X86-Assembly/iterated-digits-squaring.x86 @@ -0,0 +1,52 @@ +section .data + count dd 0 + +section .text +global _main +_main: + mov ecx, 1 + looping: + mov eax, ecx ;pass parameter in eax + push ecx + call doMath + pop ecx + add [count], eax ;doMath returns 0 or 1 in eax + inc ecx + cmp ecx, 100000001 + jl looping + mov eax, count ;returns memory address of count + ret + +addSquaredDigits: + push ebx + mov ebx, 0 + mov esi, 10 + looping2: + xor edx, edx ;clear edx for division + div esi ;div by 10 to get last digit in edx + mov ecx, eax ;save parameter + mov eax, edx ; get last digit + mul eax ;square last digit + add ebx, eax ;add the square to the result + jecxz aSDend ;if the parameter is 0 we have all digits + mov eax, ecx ;restore parameter before looping + jmp looping2 + aSDend: + mov eax, ebx ;move result to return register + pop ebx + ret + +doMath: + looping3: + call addSquaredDigits ;do until eax is 89 or 1 + cmp eax, 89 + je ret1 + cmp eax, 1 + je ret0 + jmp looping3 + ret1: ;if eax == 89 we return 1 -> inc count + mov eax, 1 + ret + ret0: ;if eax == 1 we return 0 -> don't inc count + mov eax, 0 + ret diff --git a/Task/JSON/Ol/json.ol b/Task/JSON/Ol/json.ol new file mode 100644 index 0000000000..2090a379c4 --- /dev/null +++ b/Task/JSON/Ol/json.ol @@ -0,0 +1,46 @@ +(import (lib json)) +(import (owl parse)) + +(define o (parse json-parser (str-iter " + { + 'name': 'John', + 'full name': 'John Smith', + 'age': 42, + 'married': false, + 'address': { + 'street': '21 2nd Street', + 'city': 'New York', + }, + 'additional staff': [ + { + 'type': 'numbers', + 'numbers': [ 1, 2, 3, 4 ] + }, + { + 'type': 'phone', + 'number': '222 222-2222' + } + ] + }") #f #f #f)) +(print o) + +(print-json-with display o) +(print-json-with display { + 'name "John" + '|full name| "John Smith" + 'age 42 + 'married #false + 'address { + 'street "21 2nd Street" + 'city "New York" + } + '|additional staff| [ + { + 'type "numbers" + 'numbers [ 1 2 3 4 ] + } + { + 'type "phone" + 'number "222 222-2222" + } + ] diff --git a/Task/JSON/XQuery/json.xquery b/Task/JSON/XQuery/json.xquery new file mode 100644 index 0000000000..d7c538581f --- /dev/null +++ b/Task/JSON/XQuery/json.xquery @@ -0,0 +1,28 @@ +let $json := ' +{ + "Astring" : "string-value", + "Anumber" : 5.7, + "Anull" : null, + "Aarray" : ["One","Two", 3], + "Aobject" : { + "key1": "value1", + "key2": "value2" + }, + "Atrue" : true, + "Afalse" : false +} +' +let $xml := json-to-xml($local:json) +return ( + "XPath fn:json-to-xml#1 function:" + ,"" + ,$xml + ,"" + ,"Round trip, using fn:xml-to-json#1:" + ,"" + ,xml-to-json($xml) + ,"" + ,"Using BaseX json:parse#2 function to create an XPath 3.1 map:" + ,"" + ,json:parse($local:json, map{"format":"xquery"}) +) diff --git a/Task/Jensens-Device/Python/jensens-device.py b/Task/Jensens-Device/Python/jensens-device-1.py similarity index 100% rename from Task/Jensens-Device/Python/jensens-device.py rename to Task/Jensens-Device/Python/jensens-device-1.py diff --git a/Task/Jensens-Device/Python/jensens-device-2.py b/Task/Jensens-Device/Python/jensens-device-2.py new file mode 100644 index 0000000000..3cce23eece --- /dev/null +++ b/Task/Jensens-Device/Python/jensens-device-2.py @@ -0,0 +1,5 @@ +def harmonic_sum(i, lo, hi, term): + return sum(term() for i[0] in range(lo, hi + 1)) + +i = [0] +print(harmonic_sum(i, 1, 100, lambda: 1.0 / i[0])) diff --git a/Task/Jensens-Device/Python/jensens-device-3.py b/Task/Jensens-Device/Python/jensens-device-3.py new file mode 100644 index 0000000000..02243a8f6e --- /dev/null +++ b/Task/Jensens-Device/Python/jensens-device-3.py @@ -0,0 +1,5 @@ +def harmonic_sum(i, lo, hi, term): + return sum(eval(term) for i[0] in range(lo, hi + 1)) + +i = [0] +print(harmonic_sum(i, 1, 100, "1.0 / i[0]")) diff --git a/Task/Jensens-Device/REXX/jensens-device.rexx b/Task/Jensens-Device/REXX/jensens-device.rexx index 8efc74750c..9a6e2dc824 100644 --- a/Task/Jensens-Device/REXX/jensens-device.rexx +++ b/Task/Jensens-Device/REXX/jensens-device.rexx @@ -1,15 +1,17 @@ -/*REXX program demonstrates Jensen's device (via call subroutine, and args by name).*/ -parse arg d .; if d=='' | d=="," then d=100 /*Not specified? Then use the default.*/ +/*REXX program demonstrates Jensen's device (via call subroutine, and args by name). */ +parse arg d . /*obtain optional argument from the CL.*/ +if d=='' | d=="," then d= 100 /*Not specified? Then use the default.*/ numeric digits d /*use D decimal digits (9 is default)*/ say 'using ' d " decimal digits:" /*display what's being used for digits.*/ say -say sum( 'i', "1", '100', "1/i" ) /*invoke SUM (100th harmonic number).*/ +say sum( i, 1, 100, "1/i" ) /*invoke SUM (100th harmonic number).*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -sum: procedure; parse arg j,start,finish,exp; $=0 +sum: procedure; parse arg j,start,finish,exp; $= 0 - interpret 'do' j "=" start 'to' finish"; $=$+" exp '; end' - /* ──── ═ ─── ═════ ──── ══════────────── ═══ ───────── */ - /* lit var lit var lit var literal var literal */ + interpret 'do' j "=" start 'to' finish "; $=$+" exp '; end' + + /*comment ──── ═ ─── ═════ ──── ══════ ────────── ═══ ───────── */ + /*comment lit var lit var lit var literal var literal */ return $ diff --git a/Task/Josephus-problem/Frink/josephus-problem.frink b/Task/Josephus-problem/Frink/josephus-problem.frink new file mode 100644 index 0000000000..5a022b7853 --- /dev/null +++ b/Task/Josephus-problem/Frink/josephus-problem.frink @@ -0,0 +1,21 @@ +killingCycle[prisonerCount,killStep = 2] := +{ + i = 0 + killed = new array + prisoners = array[0 to prisonerCount - 1] + while length[prisoners] > 1 + { + i = (i + killStep - 1) mod length[prisoners] + killed.push[prisoners.remove[i]] // Remove the killed prisoner from the prisoners array and add it to the killed array. + } + killedResult = "Killed:" + for kill = killed // Loop through the killed array to format it nicely. + { + killedResult = killedResult + " " + kill + } + aliveResult = "Alive: " + prisoners@0 // Get the only item left in the array + return """$killedResult +$aliveResult""" +} + +println[killingCycle[41,3]] // Enter in total number of prisoners and the number to skip each cycle diff --git a/Task/Josephus-problem/REXX/josephus-problem-1.rexx b/Task/Josephus-problem/REXX/josephus-problem-1.rexx index 0ca74c63a1..7e4ee6de91 100644 --- a/Task/Josephus-problem/REXX/josephus-problem-1.rexx +++ b/Task/Josephus-problem/REXX/josephus-problem-1.rexx @@ -5,6 +5,8 @@ * 09.05.2013 Walter Pachl accept arguments n w s and fix output * thanks for the review/test * I see no need for specifying a start count (actually a start number) +* This task states: n prisoners are standing on a circle, +* sequentially numbered from 0 to n-1. The 1st prisoner is 0. * This program should work on EVERY REXX. * Pls report if this is not the case and let us know what's a problem. **********************************************************************/ diff --git a/Task/Joystick-position/Commodore-BASIC/joystick-position-1.commodore b/Task/Joystick-position/Commodore-BASIC/joystick-position-1.commodore new file mode 100644 index 0000000000..db5b52a955 --- /dev/null +++ b/Task/Joystick-position/Commodore-BASIC/joystick-position-1.commodore @@ -0,0 +1,24 @@ +5 rem joystick - commodore vic-20 (expanded) +6 rem for rosetta code +10 print chr$(147);:poke 37154,peek(37154) and 127 +15 j1=37137:j2=37152:sc=4118:co=37910:x=11:y=11 +20 poke sc+x+y*22,43:poke co+x+y*22,0 +25 j=(not peek(j1) and28)/4 +30 j=j+(not peek(j1) and32)/2 +35 j=j+(not peek(j2) and128)/16 +40 print chr$(19);"joy: "; +45 get k$:if k$="q" then print chr$(147):poke 37154,peek(37154)or128:end +50 ox=x:oy=y +60 if(j and 1) then y=1:ud$="u" +61 if(j and 2) then y=21:ud$="d" +62 if(j and 3)=0 then y=11:ud$=" " +63 if(j and 4) then x=0:lr$="l" +64 if(j and 8) then x=21:lr$="r" +65 if(j and 12)=0 then x=11:lr$=" " +66 if(j and 16) then f$="fire!":c=24 +67 if(j and 16)=0 then f$=" ":c=43 +70 print tab(5);ud$;tab(7);lr$;tab(9);f$; +75 poke sc+x+y*22,c:poke co+x+y*22,0 +80 if (ox=x) and (oy=y) then goto 100 +85 poke sc+ox+oy*22,32 +100 goto 25 diff --git a/Task/Joystick-position/Commodore-BASIC/joystick-position-2.commodore b/Task/Joystick-position/Commodore-BASIC/joystick-position-2.commodore new file mode 100644 index 0000000000..c3982bf631 --- /dev/null +++ b/Task/Joystick-position/Commodore-BASIC/joystick-position-2.commodore @@ -0,0 +1,24 @@ +5 rem joystick - commodore 64 +6 rem for rosetta code +8 rem black bkg, white text, dk. grey border +9 poke 53280,11:poke 53281,0:poke 646,1 +10 print chr$(147);"joystick port 1 or 2";:input jp +11 if jp<1 or jp>2 then print:print"invalid.":print:goto 10 +12 jp=(jp=2)+56321:print chr$(147); +15 sc=1024:x=20:y=12:poke sc+x+y*40,43 +20 j=not peek(jp) and 31 +25 print chr$(19);"{CRSR DOWN 24}joy status: "; +26 get k$:if k$="q" then print chr$(147):end +35 ox=x:oy=y +40 if(j and 1) then y=0:ud$="up " +45 if(j and 2) then y=23:ud$="down" +46 if(j and 3)=0 then y=12:ud$=" " +50 if(j and 4) then x=0:lr$="left " +55 if(j and 8) then x=39:lr$="right" +56 if(j and 12)=0 then x=20:lr$=" " +60 if(j and 16) then f$="fire!":c=24 +61 if(j and 16)=0 then f$=" ":c=43 +65 print tab(12);ud$;tab(17);lr$;tab(23);f$; +85 poke sc+x+y*40,c:if (ox=x) and (oy=y) then goto 100 +90 poke sc+ox+oy*40,32 +100 goto 20 diff --git a/Task/Joystick-position/Commodore-BASIC/joystick-position-3.commodore b/Task/Joystick-position/Commodore-BASIC/joystick-position-3.commodore new file mode 100644 index 0000000000..1e73cdd175 --- /dev/null +++ b/Task/Joystick-position/Commodore-BASIC/joystick-position-3.commodore @@ -0,0 +1,27 @@ +5 rem joystick - commodore plus/4 +6 rem for rosetta code +8 rem black bkg, white text, dk. grey border +9 color 0,1:color 4,2,1:color 1,2,7 +10 print chr$(147);"joystick port 1 or 2";:input jp +11 if jp<1 or jp>2 then print:print"invalid.":print:goto 10 +12 print chr$(147); +15 sc=3072:x=20:y=13:poke sc+x+y*40,43 +20 j=joy(jp) +25 print chr$(19);"joy status: "; +26 get k$:if k$="q" then print chr$(147):end +35 ox=x:oy=y +40 if(j and 15)=1 then d$="up ":x=20:y=1:goto 48 +41 if(j and 15)=2 then d$="up right":x=39:y=1:goto 48 +42 if(j and 15)=3 then d$=" right":x=39:y=13:goto 48 +43 if(j and 15)=4 then d$="down right":x=39:y=24:goto 48 +44 if(j and 15)=5 then d$="down ":x=20:y=24:goto 48 +45 if(j and 15)=6 then d$="down left ":x=0:y=24:goto 48 +46 if(j and 15)=7 then d$=" left ":x=0:y=13:goto 48 +47 if(j and 15)=8 then d$="up left ":x=0:y=1 +48 if(j and 128) then f$="fire!":c=24 +49 if(j and 128)=0 then f$=" ":c=43 +50 if(j=0) then d$=" ":x=20:y=13 +65 print tab(12);d$;tab(23);f$; +85 poke sc+x+y*40,c:if (ox=x) and (oy=y) then goto 100 +90 poke sc+ox+oy*40,32 +100 goto 20 diff --git a/Task/Joystick-position/Commodore-BASIC/joystick-position-4.commodore b/Task/Joystick-position/Commodore-BASIC/joystick-position-4.commodore new file mode 100644 index 0000000000..f31daeccad --- /dev/null +++ b/Task/Joystick-position/Commodore-BASIC/joystick-position-4.commodore @@ -0,0 +1,27 @@ +5 rem joystick - commodore 128 +6 rem for rosetta code +8 rem black bkg, white text, dk. grey border +9 color 0,1:color 4,12:color 1,2:graphic 0:scnclr 0:graphic 5 +10 print chr$(147);"joystick port 1 or 2";:input jp +11 if jp<1 or jp>2 then print:print"invalid.":print:goto 10 +12 print chr$(147); +15 sc=1024:x=20:y=12:poke sc+x+y*40,43 +20 j=joy(jp) +25 print chr$(19);"joy status: "; +26 get k$:if k$="q" then print chr$(147):end +35 ox=x:oy=y +40 if(j and 15)=1 then d$="up ":x=20:y=0:goto 48 +41 if(j and 15)=2 then d$="up right":x=39:y=0:goto 48 +42 if(j and 15)=3 then d$=" right":x=39:y=12:goto 48 +43 if(j and 15)=4 then d$="down right":x=39:y=24:goto 48 +44 if(j and 15)=5 then d$="down ":x=20:y=24:goto 48 +45 if(j and 15)=6 then d$="down left ":x=0:y=24:goto 48 +46 if(j and 15)=7 then d$=" left ":x=0:y=12:goto 48 +47 if(j and 15)=8 then d$="up left ":x=0:y=0 +48 if(j and 128) then f$="fire!":c=24 +49 if(j and 128)=0 then f$=" ":c=43 +50 if(j=0) then d$=" ":x=20:y=12 +65 print tab(12);d$;tab(23);f$; +85 poke sc+x+y*40,c:if (ox=x) and (oy=y)then goto 100 +90 poke sc+ox+oy*40,32 +100 goto 20 diff --git a/Task/Joystick-position/Perl-6/joystick-position.pl6 b/Task/Joystick-position/Perl-6/joystick-position.pl6 new file mode 100644 index 0000000000..87841b0a7e --- /dev/null +++ b/Task/Joystick-position/Perl-6/joystick-position.pl6 @@ -0,0 +1,104 @@ +use experimental :pack; + +# Joysticks generally show up in the /dev/input/ directory as js(n) where n is +# the number assigned by the OS. E.G. /dev/input/js1 . In my particular case: + +my $device = '/dev/input/js0'; + +my $exit = 0; + +my $event-stream = $device.IO.open(:bin); +my $js = $event-stream.Supply(:8size); + +my %config; # joystick configuration: number of axes and buttons +my %event; # global "joystick event" + +%config