From 22f33d4004aeca6ca53182008bbf6530cf2f3ca8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ingy=20d=C3=B6t=20Net?= Date: Fri, 22 Jun 2018 20:57:24 +0000 Subject: [PATCH] June 2018 Update --- Lang/360-Assembly/00DESCRIPTION | 14 +- Lang/360-Assembly/Flow-control-structures | 1 + Lang/360-Assembly/Floyds-triangle | 1 + Lang/360-Assembly/Pythagorean-triples | 1 + Lang/360-Assembly/Sum-multiples-of-3-and-5 | 1 + Lang/360-Assembly/Tokenize-a-string | 1 + Lang/8th/AKS-test-for-primes | 1 + Lang/8th/Arithmetic-geometric-mean | 1 + Lang/8th/Luhn-test-of-credit-card-numbers | 1 + Lang/8th/Parsing-Shunting-yard-algorithm | 1 + Lang/ABAP/Equilibrium-index | 1 + Lang/ABAP/Extend-your-language | 1 + Lang/ABAP/Morse-code | 1 + Lang/ABAP/System-time | 1 + Lang/ALGOL-60/Loops-Break | 1 + Lang/ALGOL-60/Loops-N-plus-one-half | 1 + Lang/ALGOL-60/Loops-Nested | 1 + .../ALGOL-68/Aliquot-sequence-classifications | 1 + Lang/ALGOL-68/Zebra-puzzle | 1 + .../ALGOL-W/Sorting-algorithms-Insertion-sort | 1 + Lang/ALGOL-W/Strip-comments-from-a-string | 1 + Lang/APL/Anagrams | 1 + Lang/APL/Apply-a-callback-to-an-array | 1 + Lang/APL/Arithmetic-Integer | 1 + Lang/APL/Boolean-values | 1 + Lang/APL/Fast-Fourier-transform | 1 + Lang/APL/Polynomial-long-division | 1 + Lang/ARM-Assembly/Address-of-a-variable | 1 + Lang/ARM-Assembly/Arithmetic-Integer | 1 + Lang/ARM-Assembly/Balanced-brackets | 1 + Lang/ARM-Assembly/Call-a-function | 1 + Lang/ARM-Assembly/Comments | 1 + Lang/ARM-Assembly/FizzBuzz | 1 + Lang/ARM-Assembly/Hello-world-Newbie | 1 + Lang/ARM-Assembly/Hello-world-Standard-error | 1 + Lang/ARM-Assembly/Program-name | 1 + Lang/ATS/FizzBuzz | 1 + Lang/ATS/Sierpinski-triangle-Graphical | 1 + Lang/AWK/00DESCRIPTION | 5 +- Lang/AWK/Dutch-national-flag-problem | 1 + Lang/AWK/IBAN | 1 + Lang/AWK/Munching-squares | 1 + Lang/AWK/Pernicious-numbers | 1 + Lang/Ada/Amicable-pairs | 1 + Lang/Ada/String-append | 1 + Lang/Ada/Sudoku | 1 + Lang/Aime/Equilibrium-index | 1 + Lang/Aime/Letter-frequency | 1 + Lang/Aime/Loops-Foreach | 1 + Lang/Aime/Make-directory-path | 1 + Lang/Aime/Move-to-front-algorithm | 1 + Lang/Aime/Multifactorial | 1 + Lang/Aime/Order-two-numerical-lists | 1 + Lang/Aime/Remove-duplicate-elements | 1 + Lang/AppleScript/Mad-Libs | 1 + Lang/AppleScript/Make-directory-path | 1 + Lang/Applesoft-BASIC/Caesar-cipher | 1 + Lang/Applesoft-BASIC/Rot-13 | 1 + Lang/Applesoft-BASIC/Vigen-re-cipher | 1 + Lang/Astro/Sum-of-squares | 1 + Lang/AutoIt/Anonymous-recursion | 1 + Lang/AutoIt/Associative-array-Creation | 1 + Lang/AutoIt/Null-object | 1 + Lang/AutoIt/Speech-synthesis | 1 + Lang/AutoIt/Temperature-conversion | 1 + Lang/BASIC/Animate-a-pendulum | 1 + Lang/BASIC/Arithmetic-geometric-mean | 1 + Lang/BASIC/Dot-product | 1 + Lang/BASIC/Draw-a-clock | 1 + Lang/BASIC/Entropy | 1 + Lang/BASIC/FizzBuzz | 1 + Lang/BASIC/Floyds-triangle | 1 + Lang/BASIC/Fractal-tree | 1 + Lang/BASIC/Josephus-problem | 1 + Lang/BASIC/Magic-squares-of-odd-order | 1 + Lang/BASIC/Maze-generation | 1 + Lang/BASIC256/Conditional-structures | 1 + Lang/BASIC256/Look-and-say-sequence | 1 + .../BASIC256/Sorting-algorithms-Counting-sort | 1 + Lang/BBC-BASIC/Entropy | 1 + Lang/BBC-BASIC/Josephus-problem | 1 + Lang/BBC-BASIC/Multifactorial | 1 + Lang/BaCon/Align-columns | 1 + Lang/BaCon/Anagrams | 1 + Lang/BaCon/Anagrams-Deranged-anagrams | 1 + Lang/BaCon/Averages-Median | 1 + Lang/BaCon/Calendar | 1 + Lang/BaCon/Calendar---for-REAL-programmers | 1 + Lang/BaCon/Color-of-a-screen-pixel | 1 + Lang/BaCon/LZW-compression | 1 + Lang/BaCon/Last-letter-first-letter | 1 + Lang/BaCon/Letter-frequency | 1 + Lang/BaCon/OpenGL | 1 + Lang/BaCon/Rename-a-file | 1 + Lang/BaCon/Rep-string | 1 + Lang/BaCon/Repeat-a-string | 1 + Lang/BaCon/Run-length-encoding | 1 + Lang/BaCon/String-length | 1 + Lang/BaCon/URL-decoding | 1 + Lang/BaCon/Unicode-variable-names | 1 + Lang/Batch-File/Maze-generation | 1 + Lang/Batch-File/Variadic-function | 1 + Lang/Befunge/24-game | 1 + Lang/Befunge/Bitwise-operations | 1 + Lang/Befunge/Box-the-compass | 1 + Lang/Befunge/Determine-if-a-string-is-numeric | 1 + Lang/Befunge/Hello-world-Newline-omission | 1 + Lang/Befunge/Luhn-test-of-credit-card-numbers | 1 + Lang/Befunge/Sum-digits-of-an-integer | 1 + Lang/Befunge/Terminal-control-Preserve-screen | 1 + Lang/Befunge/Towers-of-Hanoi | 1 + Lang/Bracmat/Move-to-front-algorithm | 1 + .../Generate-lower-case-ASCII-alphabet | 1 + Lang/C++/00DESCRIPTION | 2 +- .../Arbitrary-precision-integers--included- | 1 + Lang/C++/Average-loop-length | 1 + Lang/C++/Bernoulli-numbers | 1 + Lang/C++/Hash-join | 1 + Lang/C++/Haversine-formula | 1 + Lang/C++/Order-disjoint-list-items | 1 + Lang/C++/Ordered-Partitions | 1 + Lang/C++/Pattern-matching | 1 + Lang/C++/Soundex | 1 + Lang/C++/Topswops | 1 + Lang/C-sharp/Dynamic-variable-names | 1 + Lang/C-sharp/Element-wise-operations | 1 + Lang/C-sharp/Fibonacci-word | 1 + Lang/C-sharp/Iterated-digits-squaring | 1 + Lang/C-sharp/Modular-inverse | 1 + Lang/C-sharp/Topological-sort | 1 + Lang/C/00DESCRIPTION | 3 + Lang/C/Aliquot-sequence-classifications | 1 + Lang/C/Create-a-file-on-magnetic-tape | 1 + Lang/C/Currying | 1 + Lang/C/Deepcopy | 1 + Lang/C/GUI-Maximum-window-dimensions | 1 + Lang/C/Generate-Chess960-starting-position | 1 + Lang/C/Here-document | 1 + Lang/C/Heronian-triangles | 1 + Lang/C/Parsing-RPN-to-infix-conversion | 1 + Lang/C/Permutations-by-swapping | 1 + Lang/C/Pragmatic-directives | 1 + Lang/C/Ranking-methods | 1 + Lang/C/Read-a-configuration-file | 1 + Lang/C/SOAP | 1 + Lang/C/Send-email | 1 + Lang/C/Simulate-input-Mouse | 1 + Lang/C/Sparkline-in-unicode | 1 + Lang/C/Unicode-variable-names | 1 + Lang/C/Vogels-approximation-method | 1 + Lang/C/Write-to-Windows-event-log | 1 + Lang/C/XML-XPath | 1 + Lang/C/Zhang-Suen-thinning-algorithm | 1 + .../Constrained-random-points-on-a-circle | 1 + Lang/COBOL/Long-multiplication | 1 + Lang/COBOL/Narcissistic-decimal-number | 1 + Lang/COBOL/Write-float-arrays-to-a-text-file | 1 + .../Arbitrary-precision-integers--included- | 1 + Lang/Ceylon/Binary-digits | 1 + Lang/Ceylon/Currying | 1 + Lang/Ceylon/Long-multiplication | 1 + Lang/Ceylon/Look-and-say-sequence | 1 + Lang/Ceylon/Minesweeper-game | 1 + Lang/Ceylon/Odd-word-problem | 1 + Lang/Ceylon/Run-length-encoding | 1 + Lang/Ceylon/Stable-marriage-problem | 1 + Lang/Ceylon/Top-rank-per-group | 1 + Lang/Ceylon/Web-scraping | 1 + Lang/Clojure/Delegates | 1 + Lang/Clojure/Executable-library | 1 + Lang/Clojure/Hello-world-Line-printer | 1 + Lang/Clojure/Last-letter-first-letter | 1 + Lang/Clojure/Multiplicative-order | 1 + Lang/Clojure/Polynomial-long-division | 1 + Lang/Clojure/Range-extraction | 1 + Lang/Clojure/SOAP | 1 + Lang/Clojure/Sorting-algorithms-Pancake-sort | 1 + Lang/Clojure/Sorting-algorithms-Stooge-sort | 1 + Lang/Clojure/Textonyms | 1 + Lang/Clojure/Truncate-a-file | 1 + Lang/Clojure/Twelve-statements | 1 + Lang/Commodore-BASIC/Pascals-triangle | 1 + Lang/Common-Lisp/Atomic-updates | 1 + .../Common-Lisp/Combinations-with-repetitions | 1 + Lang/Crystal/99-Bottles-of-Beer | 1 + Lang/Crystal/Caesar-cipher | 1 + Lang/Crystal/Copy-a-string | 1 + Lang/Crystal/DNS-query | 1 + Lang/Crystal/Generic-swap | 1 + Lang/Crystal/Hello-world-Web-server | 1 + Lang/Crystal/Sum-digits-of-an-integer | 1 + Lang/D/00DESCRIPTION | 9 +- Lang/D/Active-Directory-Connect | 1 + Lang/D/Active-Directory-Search-for-a-user | 1 + Lang/D/Active-object | 1 + .../Append-a-record-to-the-end-of-a-text-file | 1 + ...-Arithmetic-Construct-from-rational-number | 1 + Lang/D/Create-a-file-on-magnetic-tape | 1 + Lang/D/Date-manipulation | 1 + Lang/D/Fork | 1 + Lang/D/Handle-a-signal | 1 + Lang/D/I-before-E-except-after-C | 1 + Lang/D/Inverted-syntax | 1 + Lang/D/Make-directory-path | 1 + Lang/D/Narcissist | 1 + Lang/D/Parsing-Shunting-yard-algorithm | 1 + Lang/D/Polynomial-regression | 1 + Lang/D/Random-number-generator--device- | 1 + Lang/D/Ranking-methods | 1 + Lang/D/Rate-counter | 1 + Lang/D/Safe-addition | 1 + Lang/D/Terminal-control-Cursor-positioning | 1 + Lang/D/Unicode-strings | 1 + Lang/D/Write-to-Windows-event-log | 1 + Lang/D/Zeckendorf-arithmetic | 1 + Lang/DUP/Extend-your-language | 1 + Lang/DUP/Generate-lower-case-ASCII-alphabet | 1 + Lang/Dc/Zero-to-the-zero-power | 1 + Lang/Delphi/00DESCRIPTION | 5 +- Lang/Delphi/Bitcoin-address-validation | 1 + Lang/Elena/00DESCRIPTION | 801 +++++++++++++----- Lang/Elena/AKS-test-for-primes | 1 + ...ficient-and-perfect-number-classifications | 1 + Lang/Elena/Amicable-pairs | 1 + Lang/Elena/Averages-Root-mean-square | 1 + Lang/Elena/Call-a-function | 1 + Lang/Elena/Compound-data-type | 1 + Lang/Elena/Digital-root | 1 + Lang/Elena/Dot-product | 1 + Lang/Elena/Equilibrium-index | 1 + ...Catch-an-exception-thrown-in-a-nested-call | 1 + Lang/Elena/Fibonacci-sequence | 1 + Lang/Elena/File-input-output | 1 + Lang/Elena/Filter | 1 + Lang/Elena/Generate-lower-case-ASCII-alphabet | 1 + Lang/Elena/Greatest-common-divisor | 1 + Lang/Elena/Guess-the-number | 1 + Lang/Elena/Guess-the-number-With-feedback | 1 + Lang/Elena/Hailstone-sequence | 1 + Lang/Elena/Happy-numbers | 1 + Lang/Elena/Haversine-formula | 1 + Lang/Elena/Hello-world-Newline-omission | 1 + Lang/Elena/Higher-order-functions | 1 + Lang/Elena/History-variables | 1 + .../Horners-rule-for-polynomial-evaluation | 1 + Lang/Elena/Increment-a-numerical-string | 1 + Lang/Elena/Integer-sequence | 1 + Lang/Elena/Keyboard-input-Keypress-check | 1 + Lang/Elena/Least-common-multiple | 1 + Lang/Elena/Literals-Floating-point | 1 + Lang/Elena/Logical-operations | 1 + Lang/Elena/Maximum-triangle-path-sum | 1 + Lang/Elena/Middle-three-digits | 1 + Lang/Elena/Mutual-recursion | 1 + Lang/Elena/Nth | 1 + Lang/Elena/Phrase-reversals | 1 + Lang/Elena/Polymorphic-copy | 1 + Lang/Elena/Polymorphism | 1 + Lang/Elena/Quaternion-type | 1 + Lang/Elena/Queue-Definition | 1 + Lang/Elena/Random-number-generator--included- | 1 + Lang/Elena/Random-numbers | 1 + Lang/Elena/Remove-duplicate-elements | 1 + Lang/Elena/Roman-numerals-Decode | 1 + Lang/Elena/Roman-numerals-Encode | 1 + Lang/Elena/Rot-13 | 1 + Lang/Elena/Run-length-encoding | 1 + Lang/Elena/Runtime-evaluation | 1 + .../Runtime-evaluation-In-an-environment | 1 + .../Singly-linked-list-Element-definition | 1 + .../Singly-linked-list-Element-insertion | 1 + Lang/Elena/Singly-linked-list-Traversal | 1 + Lang/Elena/Sleep | 1 + Lang/Elena/Sockets | 1 + Lang/Elena/Sort-disjoint-sublist | 1 + Lang/Elena/Sort-using-a-custom-comparator | 1 + Lang/Elena/Sorting-algorithms-Bogosort | 1 + Lang/Elena/Sorting-algorithms-Cocktail-sort | 1 + Lang/Elena/Sorting-algorithms-Comb-sort | 1 + Lang/Elena/Sorting-algorithms-Counting-sort | 1 + Lang/Elena/Sorting-algorithms-Gnome-sort | 1 + Lang/Elena/Sorting-algorithms-Insertion-sort | 1 + Lang/Elena/Sorting-algorithms-Pancake-sort | 1 + Lang/Elena/Sorting-algorithms-Quicksort | 1 + Lang/Elena/Sorting-algorithms-Selection-sort | 1 + Lang/Elena/Sorting-algorithms-Sleep-sort | 1 + Lang/Elena/Sorting-algorithms-Stooge-sort | 1 + .../Strip-a-set-of-characters-from-a-string | 1 + ...trip-whitespace-from-a-string-Top-and-tail | 1 + Lang/Elena/Substring-Top-and-tail | 1 + Lang/Elena/System-time | 1 + Lang/Elena/Temperature-conversion | 1 + Lang/Elena/Terminal-control-Clear-the-screen | 1 + .../Elena/Terminal-control-Cursor-positioning | 1 + Lang/Elena/Ternary-logic | 1 + Lang/Elena/The-Twelve-Days-of-Christmas | 1 + Lang/Elena/Time-a-function | 1 + Lang/Elena/Towers-of-Hanoi | 1 + Lang/Elena/Trabb-Pardo-Knuth-algorithm | 1 + Lang/Elena/Tree-traversal | 1 + Lang/Elena/Unbias-a-random-generator | 1 + Lang/Elena/Vigen-re-cipher | 1 + Lang/Elena/Wireworld | 1 + Lang/Elena/World-Cup-group-stage | 1 + Lang/Elixir/00DESCRIPTION | 4 + Lang/Elm/Y-combinator | 1 + Lang/Emacs-Lisp/Loops-Infinite | 1 + Lang/Erlang/Bitmap-Read-a-PPM-file | 1 + Lang/Erlang/Bitmap-Write-a-PPM-file | 1 + Lang/Erlang/Kaprekar-numbers | 1 + Lang/Erlang/Sierpinski-triangle-Graphical | 1 + Lang/Erlang/Unix-ls | 1 + Lang/Euphoria/00DESCRIPTION | 1 - Lang/Excel/100-doors | 1 + Lang/Factor/00DESCRIPTION | 1 + Lang/Factor/24-game-Solve | 1 + ...ficient-and-perfect-number-classifications | 1 + Lang/Factor/Almost-prime | 1 + Lang/Factor/Amicable-pairs | 1 + Lang/Factor/Arithmetic-Rational | 1 + Lang/Factor/Arithmetic-geometric-mean | 1 + Lang/Factor/Benfords-law | 1 + Lang/Factor/CSV-data-manipulation | 1 + Lang/Factor/CSV-to-HTML-translation | 1 + Lang/Factor/Caesar-cipher | 1 + Lang/Factor/Call-a-function | 1 + Lang/Factor/Case-sensitivity-of-identifiers | 1 + Lang/Factor/Catalan-numbers-Pascals-triangle | 1 + Lang/Factor/Catamorphism | 1 + Lang/Factor/Chinese-remainder-theorem | 1 + Lang/Factor/Comma-quibbling | 1 + .../Factor/Convert-decimal-number-to-rational | 1 + Lang/Factor/Count-in-factors | 1 + Lang/Factor/Count-in-octal | 1 + Lang/Factor/Currying | 1 + Lang/Factor/Digital-root | 1 + .../Digital-root-Multiplicative-digital-root | 1 + Lang/Factor/Dynamic-variable-names | 1 + Lang/Factor/Empty-directory | 1 + Lang/Factor/Empty-string | 1 + Lang/Factor/Enforced-immutability | 1 + Lang/Factor/Entropy | 1 + Lang/Factor/Enumerations | 1 + Lang/Factor/Evolutionary-algorithm | 1 + Lang/Factor/Extreme-floating-point-values | 1 + Lang/Factor/Fibonacci-word | 1 + .../Factor/Find-the-last-Sunday-of-each-month | 1 + Lang/Factor/Find-the-missing-permutation | 1 + Lang/Factor/Five-weekends | 1 + Lang/Factor/Formatted-numeric-output | 1 + Lang/Factor/Harshad-or-Niven-series | 1 + Lang/Factor/I-before-E-except-after-C | 1 + Lang/Factor/Inverted-syntax | 1 + Lang/Factor/Iterated-digits-squaring | 1 + Lang/Factor/Kaprekar-numbers | 1 + .../Factor/Largest-int-from-concatenated-ints | 1 + Lang/Factor/Last-Friday-of-each-month | 1 + Lang/Factor/Left-factorials | 1 + Lang/Factor/Levenshtein-distance | 1 + Lang/Factor/Literals-Integer | 1 + Lang/Factor/Loops-Nested | 1 + Lang/Factor/Middle-three-digits | 1 + Lang/Factor/Modular-inverse | 1 + Lang/Factor/Multifactorial | 1 + Lang/Factor/Munching-squares | 1 + Lang/Factor/Narcissistic-decimal-number | 1 + Lang/Factor/Parsing-RPN-calculator-algorithm | 1 + Lang/Factor/Partial-function-application | 1 + Lang/Factor/Penneys-game | 1 + Lang/Factor/Pernicious-numbers | 1 + Lang/Factor/Phrase-reversals | 1 + Lang/Factor/Playing-cards | 1 + Lang/Factor/Range-extraction | 1 + Lang/Factor/Regular-expressions | 1 + Lang/Factor/Reverse-words-in-a-string | 1 + Lang/Factor/Run-length-encoding | 1 + Lang/Factor/Self-describing-numbers | 1 + Lang/Factor/Semiprime | 1 + Lang/Factor/Sequence-of-non-squares | 1 + Lang/Factor/Short-circuit-evaluation | 1 + Lang/Factor/Simple-windowed-application | 1 + .../Sorting-algorithms-Permutation-sort | 1 + Lang/Factor/Statistics-Basic | 1 + Lang/Factor/String-append | 1 + Lang/Factor/String-comparison | 1 + .../Strip-a-set-of-characters-from-a-string | 1 + ...odes-and-extended-characters-from-a-string | 1 + Lang/Factor/Substring-Top-and-tail | 1 + Lang/Factor/Sum-multiples-of-3-and-5 | 1 + Lang/Factor/Temperature-conversion | 1 + Lang/Factor/The-Twelve-Days-of-Christmas | 1 + Lang/Factor/Trabb-Pardo-Knuth-algorithm | 1 + Lang/Factor/Truncatable-primes | 1 + Lang/Factor/URL-decoding | 1 + Lang/Factor/Vampire-number | 1 + Lang/Factor/Variadic-function | 1 + Lang/Factor/Vector-products | 1 + Lang/Factor/Vigen-re-cipher | 1 + Lang/Factor/Word-wrap | 1 + Lang/Falcon/Palindrome-detection | 1 + Lang/Falcon/String-append | 1 + Lang/Falcon/String-comparison | 1 + Lang/Falcon/String-concatenation | 1 + Lang/Falcon/String-interpolation--included- | 1 + Lang/Falcon/String-matching | 1 + Lang/Falcon/String-prepend | 1 + Lang/Falcon/Substring | 1 + Lang/Falcon/System-time | 1 + Lang/Falcon/Tokenize-a-string | 1 + Lang/Falcon/Variables | 1 + Lang/Falcon/Zero-to-the-zero-power | 1 + Lang/Forth/CSV-to-HTML-translation | 1 + Lang/Forth/Documentation | 1 + Lang/Forth/Forest-fire | 1 + Lang/Forth/Left-factorials | 1 + Lang/Forth/Lucas-Lehmer-test | 1 + Lang/Forth/Synchronous-concurrency | 1 + Lang/Fortran/00DESCRIPTION | 4 +- Lang/Fortran/Catamorphism | 1 + Lang/Fortran/Element-wise-operations | 1 + Lang/Fortran/Extend-your-language | 1 + Lang/Fortran/IBAN | 1 + Lang/Fortran/Old-lady-swallowed-a-fly | 1 + Lang/Fortran/Tic-tac-toe | 1 + Lang/Fortress/Call-a-function | 1 + Lang/Fortress/Function-composition | 1 + Lang/Fortress/Loops-Do-while | 1 + Lang/Fortress/Loops-Infinite | 1 + Lang/Fortress/Loops-While | 1 + Lang/FreeBASIC/Gaussian-elimination | 1 + Lang/Futhark/Greatest-element-of-a-list | 1 + Lang/GW-BASIC/Almost-prime | 1 + Lang/GW-BASIC/Horizontal-sundial-calculations | 1 + Lang/GW-BASIC/Leap-year | 1 + Lang/GW-BASIC/Least-common-multiple | 1 + Lang/GW-BASIC/Loops-Do-while | 1 + Lang/GW-BASIC/Loops-Downward-for | 1 + Lang/GW-BASIC/Modular-inverse | 1 + Lang/GW-BASIC/Multiplication-tables | 1 + Lang/GW-BASIC/Nth | 1 + Lang/GW-BASIC/Remove-duplicate-elements | 1 + Lang/Gambas/Ackermann-function | 1 + Lang/Gambas/Collections | 1 + Lang/Gambas/Hello-world-Newline-omission | 1 + Lang/Gambas/Price-fraction | 1 + Lang/Gambas/Remove-duplicate-elements | 1 + Lang/Gambas/SEDOLs | 1 + Lang/Gambas/Sorting-algorithms-Bogosort | 1 + Lang/Gambas/Sorting-algorithms-Bubble-sort | 1 + Lang/Gambas/Sorting-algorithms-Cocktail-sort | 1 + Lang/Gambas/Sorting-algorithms-Comb-sort | 1 + Lang/Gambas/Sorting-algorithms-Gnome-sort | 1 + Lang/Gambas/Sorting-algorithms-Selection-sort | 1 + Lang/Gambas/Tokenize-a-string | 1 + Lang/Gambas/Window-management | 1 + Lang/Glee/Combinations | 1 + Lang/Go/00DESCRIPTION | 5 +- Lang/Go/9-billion-names-of-God-the-integer | 1 + Lang/Go/Aliquot-sequence-classifications | 1 + Lang/Go/Calendar | 1 + Lang/Go/Carmichael-3-strong-pseudoprimes | 1 + Lang/Go/Catalan-numbers-Pascals-triangle | 1 + Lang/Go/Combinations-and-permutations | 1 + Lang/Go/Define-a-primitive-data-type | 1 + Lang/Go/Extend-your-language | 1 + ...est-left-truncatable-prime-in-a-given-base | 1 + Lang/Go/HTTPS-Client-authenticated | 1 + Lang/Go/Jump-anywhere | 1 + Lang/Go/Named-parameters | 1 + Lang/Go/Solve-a-Holy-Knights-tour | 1 + Lang/Go/Terminal-control-Unicode-output | 1 + Lang/Go/Vigen-re-cipher-Cryptanalysis | 1 + Lang/Go/Vogels-approximation-method | 1 + Lang/Groovy/00DESCRIPTION | 5 +- Lang/Groovy/Deal-cards-for-FreeCell | 1 + Lang/Haskell/00DESCRIPTION | 13 +- Lang/Haskell/Active-Directory-Connect | 1 + .../Active-Directory-Search-for-a-user | 1 + .../Haskell/Catmull-Clark-subdivision-surface | 1 + Lang/Haskell/Create-a-file-on-magnetic-tape | 1 + Lang/Haskell/HTTPS-Authenticated | 1 + Lang/Haskell/Joystick-position | 1 + Lang/Haskell/Longest-string-challenge | 1 + Lang/Haskell/Natural-sorting | 1 + Lang/Haskell/Object-serialization | 1 + Lang/Haskell/Parametrized-SQL-statement | 1 + Lang/Haskell/Send-email | 1 + Lang/HolyC/00DESCRIPTION | 23 +- Lang/HolyC/100-doors | 1 + Lang/HolyC/Arithmetic-Integer | 1 + Lang/HolyC/Arrays | 1 + Lang/HolyC/Character-codes | 1 + Lang/HolyC/Check-that-file-exists | 1 + Lang/HolyC/Detect-division-by-zero | 1 + Lang/HolyC/Empty-string | 1 + Lang/HolyC/Exceptions | 1 + Lang/HolyC/Execute-a-system-command | 1 + Lang/HolyC/Factorial | 1 + Lang/HolyC/Find-limit-of-recursion | 1 + Lang/HolyC/Function-definition | 1 + Lang/HolyC/Guess-the-number | 1 + Lang/HolyC/Guess-the-number-With-feedback | 1 + Lang/HolyC/Hello-world-Graphical | 1 + Lang/HolyC/Hello-world-Newline-omission | 1 + Lang/HolyC/Hello-world-Text | 1 + Lang/HolyC/Increment-a-numerical-string | 1 + Lang/HolyC/Integer-comparison | 1 + Lang/HolyC/Literals-Integer | 1 + Lang/HolyC/Logical-operations | 1 + Lang/HolyC/Multiplication-tables | 1 + Lang/HolyC/String-length | 1 + Lang/HolyC/System-time | 1 + Lang/HolyC/Towers-of-Hanoi | 1 + Lang/HolyC/User-input-Text | 1 + Lang/HolyC/Variables | 1 + Lang/HolyC/Zero-to-the-zero-power | 1 + Lang/Hy/00DESCRIPTION | 2 +- Lang/I/00DESCRIPTION | 2 +- Lang/Idris/Extend-your-language | 1 + Lang/J/00DESCRIPTION | 27 +- Lang/J/Carmichael-3-strong-pseudoprimes | 1 + Lang/JCL/00DESCRIPTION | 37 +- Lang/JCL/Conditional-structures | 1 + Lang/Java/00DESCRIPTION | 13 +- .../Arithmetic-geometric-mean-Calculate-Pi | 1 + Lang/Java/Averages-Mean-time-of-day | 1 + Lang/Java/Binary-strings | 1 + ...Circles-of-given-radius-through-two-points | 1 + ...-Arithmetic-Construct-from-rational-number | 1 + Lang/Java/History-variables | 1 + Lang/Java/Interactive-programming | 1 + Lang/Java/List-comprehensions | 1 + Lang/Java/Multiplicative-order | 1 + Lang/Java/Permutation-test | 1 + Lang/Java/Polynomial-long-division | 1 + Lang/Java/Polynomial-regression | 1 + Lang/Java/RSA-code | 1 + Lang/Java/Resistor-mesh | 1 + Lang/Java/Runtime-evaluation | 1 + Lang/Java/Safe-addition | 1 + Lang/Java/Special-variables | 1 + Lang/Java/Vigen-re-cipher-Cryptanalysis | 1 + Lang/Java/Zeckendorf-arithmetic | 1 + Lang/JavaScript/Here-document | 1 + Lang/JavaScript/K-means++-clustering | 1 + Lang/JavaScript/Number-names | 1 + Lang/JavaScript/Ulam-spiral--for-primes- | 1 + Lang/Julia/00DESCRIPTION | 7 +- Lang/Julia/Active-object | 1 + ...-a-variable-to-a-class-instance-at-runtime | 1 + Lang/Julia/Animate-a-pendulum | 1 + Lang/Julia/Animation | 1 + .../Append-a-record-to-the-end-of-a-text-file | 1 + Lang/Julia/Arena-storage-pool | 1 + Lang/Julia/Atomic-updates | 1 + Lang/Julia/Averages-Mean-time-of-day | 1 + Lang/Julia/Balanced-ternary | 1 + Lang/Julia/Bitcoin-address-validation | 1 + Lang/Julia/Bitcoin-public-point-to-address | 1 + Lang/Julia/Bitmap-B-zier-curves-Cubic | 1 + Lang/Julia/Bitmap-Flood-fill | 1 + Lang/Julia/Bitmap-Midpoint-circle-algorithm | 1 + .../Bitmap-PPM-conversion-through-a-pipe | 1 + .../Julia/Bitmap-Read-an-image-through-a-pipe | 1 + Lang/Julia/Bulls-and-cows-Player | 1 + Lang/Julia/Call-a-function | 1 + Lang/Julia/Canny-edge-detector | 1 + Lang/Julia/Chat-server | 1 + Lang/Julia/Chinese-remainder-theorem | 1 + Lang/Julia/Classes | 1 + Lang/Julia/Collections | 1 + Lang/Julia/Colour-bars-Display | 1 + Lang/Julia/Concurrent-computing | 1 + Lang/Julia/Conditional-structures | 1 + Lang/Julia/Constrained-genericity | 1 + Lang/Julia/Create-an-HTML-table | 1 + .../Julia/Create-an-object-at-a-given-address | 1 + Lang/Julia/Date-manipulation | 1 + Lang/Julia/Deconvolution-1D | 1 + Lang/Julia/Define-a-primitive-data-type | 1 + Lang/Julia/Delegates | 1 + .../Julia/Dinesmans-multiple-dwelling-problem | 1 + Lang/Julia/Dining-philosophers | 1 + .../Doubly-linked-list-Element-definition | 1 + Lang/Julia/Dragon-curve | 1 + Lang/Julia/Draw-a-cuboid | 1 + Lang/Julia/Dynamic-variable-names | 1 + Lang/Julia/Enforced-immutability | 1 + Lang/Julia/Events | 1 + Lang/Julia/Exceptions | 1 + ...Catch-an-exception-thrown-in-a-nested-call | 1 + Lang/Julia/Executable-library | 1 + Lang/Julia/Execute-Brain---- | 1 + Lang/Julia/Execute-HQ9+ | 1 + Lang/Julia/Execute-a-Markov-algorithm | 1 + Lang/Julia/Extensible-prime-generator | 1 + Lang/Julia/Fibonacci-word-fractal | 1 + ...st-class-functions-Use-numbers-analogously | 1 + Lang/Julia/Flipping-bits-game | 1 + Lang/Julia/Flow-control-structures | 1 + Lang/Julia/Formal-power-series | 1 + Lang/Julia/Fractran | 1 + Lang/Julia/Function-frequency | 1 + Lang/Julia/Image-convolution | 1 + Lang/Julia/Inverted-syntax | 1 + Lang/Julia/Jump-anywhere | 1 + .../Keyboard-input-Flush-the-keyboard-buffer | 1 + .../Keyboard-input-Obtain-a-Y-or-N-response | 1 + Lang/Julia/Knapsack-problem-Unbounded | 1 + Lang/Julia/LZW-compression | 1 + Lang/Julia/Last-letter-first-letter | 1 + Lang/Julia/Literals-Floating-point | 1 + Lang/Julia/Long-multiplication | 1 + Lang/Julia/Longest-increasing-subsequence | 1 + Lang/Julia/Longest-string-challenge | 1 + Lang/Julia/Lucas-Lehmer-test | 1 + Lang/Julia/Mad-Libs | 1 + Lang/Julia/Main-step-of-GOST-28147-89 | 1 + Lang/Julia/Make-directory-path | 1 + Lang/Julia/Maximum-triangle-path-sum | 1 + Lang/Julia/Maze-solving | 1 + Lang/Julia/Median-filter | 1 + Lang/Julia/Memory-allocation | 1 + Lang/Julia/Memory-layout-of-a-data-structure | 1 + Lang/Julia/Menu | 1 + Lang/Julia/Metronome | 1 + Lang/Julia/Move-to-front-algorithm | 1 + Lang/Julia/Multiple-distinct-objects | 1 + Lang/Julia/Narcissist | 1 + Lang/Julia/Object-serialization | 1 + Lang/Julia/Odd-word-problem | 1 + Lang/Julia/Old-lady-swallowed-a-fly | 1 + Lang/Julia/Ordered-Partitions | 1 + Lang/Julia/Parallel-calculations | 1 + Lang/Julia/Parametric-polymorphism | 1 + Lang/Julia/Parametrized-SQL-statement | 1 + Lang/Julia/Parse-an-IP-Address | 1 + Lang/Julia/Parsing-RPN-to-infix-conversion | 1 + Lang/Julia/Parsing-Shunting-yard-algorithm | 1 + Lang/Julia/Partial-function-application | 1 + Lang/Julia/Pascals-triangle-Puzzle | 1 + .../Percentage-difference-between-images | 1 + Lang/Julia/Percolation-Bond-percolation | 1 + Lang/Julia/Percolation-Mean-cluster-density | 1 + Lang/Julia/Percolation-Mean-run-density | 1 + Lang/Julia/Percolation-Site-percolation | 1 + Lang/Julia/Permutations-by-swapping | 1 + Lang/Julia/Pinstripe-Display | 1 + Lang/Julia/Program-termination | 1 + Lang/Julia/Queue-Usage | 1 + Lang/Julia/Quickselect-algorithm | 1 + Lang/Julia/RSA-code | 1 + Lang/Julia/Ray-casting-algorithm | 1 + Lang/Julia/Read-a-configuration-file | 1 + Lang/Julia/Record-sound | 1 + Lang/Julia/Respond-to-an-unknown-method-call | 1 + Lang/Julia/Run-length-encoding | 1 + Lang/Julia/Runtime-evaluation | 1 + .../Runtime-evaluation-In-an-environment | 1 + Lang/Julia/S-Expressions | 1 + Lang/Julia/SEDOLs | 1 + Lang/Julia/SQL-based-authentication | 1 + Lang/Julia/Safe-addition | 1 + Lang/Julia/Same-Fringe | 1 + Lang/Julia/Send-an-unknown-method-call | 1 + Lang/Julia/Send-email | 1 + Lang/Julia/Set-of-real-numbers | 1 + Lang/Julia/Sierpinski-triangle-Graphical | 1 + Lang/Julia/Simple-windowed-application | 1 + Lang/Julia/Singleton | 1 + .../Singly-linked-list-Element-insertion | 1 + Lang/Julia/Singly-linked-list-Traversal | 1 + Lang/Julia/Soundex | 1 + Lang/Julia/Stable-marriage-problem | 1 + Lang/Julia/Stack-traces | 1 + Lang/Julia/Stair-climbing-puzzle | 1 + Lang/Julia/State-name-puzzle | 1 + Lang/Julia/Statistics-Basic | 1 + Lang/Julia/Synchronous-concurrency | 1 + Lang/Julia/Table-creation-Postal-addresses | 1 + Lang/Julia/Ternary-logic | 1 + Lang/Julia/Test-a-function | 1 + Lang/Julia/Text-processing-1 | 1 + Lang/Julia/Text-processing-2 | 1 + .../Julia/Text-processing-Max-licenses-in-use | 1 + Lang/Julia/The-ISAAC-Cipher | 1 + Lang/Julia/Topological-sort | 1 + Lang/Julia/Ulam-spiral--for-primes- | 1 + Lang/Julia/Unbias-a-random-generator | 1 + .../Verify-distribution-uniformity-Naive | 1 + Lang/Julia/Voronoi-diagram | 1 + Lang/Julia/Walk-a-directory-Non-recursively | 1 + Lang/Julia/Walk-a-directory-Recursively | 1 + Lang/Julia/Window-creation-X11 | 1 + Lang/Julia/Word-wrap | 1 + Lang/Julia/XML-Input | 1 + Lang/Julia/Xiaolin-Wus-line-algorithm | 1 + Lang/Julia/Yin-and-yang | 1 + Lang/Julia/Zebra-puzzle | 1 + Lang/Julia/Zhang-Suen-thinning-algorithm | 1 + Lang/K/Dinesmans-multiple-dwelling-problem | 1 + Lang/Kitten/99-Bottles-of-Beer | 1 + Lang/Kitten/Y-combinator | 1 + Lang/Klong/100-doors | 1 + Lang/Klong/Ackermann-function | 1 + Lang/Klong/Anonymous-recursion | 1 + Lang/Klong/Array-concatenation | 1 + Lang/Klong/Command-line-arguments | 1 + Lang/Klong/Gaussian-elimination | 1 + Lang/Klong/Greatest-common-divisor | 1 + Lang/Klong/Loops-For | 1 + Lang/Klong/Matrix-multiplication | 1 + Lang/Klong/Statistics-Basic | 1 + Lang/Kotlin/00DESCRIPTION | 1 + Lang/Kotlin/Active-object | 1 + .../Append-a-record-to-the-end-of-a-text-file | 1 + Lang/Kotlin/Arithmetic-evaluation | 1 + Lang/Kotlin/Atomic-updates | 1 + Lang/Kotlin/Bitmap-B-zier-curves-Cubic | 1 + Lang/Kotlin/Bitmap-B-zier-curves-Quadratic | 1 + Lang/Kotlin/Bitmap-Histogram | 1 + .../Bitmap-PPM-conversion-through-a-pipe | 1 + Lang/Kotlin/Bitmap-Read-a-PPM-file | 1 + .../Bitmap-Read-an-image-through-a-pipe | 1 + Lang/Kotlin/Bitmap-Write-a-PPM-file | 1 + Lang/Kotlin/Bitwise-IO | 1 + .../Call-a-function-in-a-shared-library | 1 + Lang/Kotlin/Checkpoint-synchronization | 1 + ...Circles-of-given-radius-through-two-points | 1 + Lang/Kotlin/Color-quantization | 1 + .../Compare-sorting-algorithms-performance | 1 + ...ontined-Fraction-N1,-Contined-Fraction-N2- | 1 + Lang/Kotlin/Conways-Game-of-Life | 1 + Lang/Kotlin/Deepcopy | 1 + Lang/Kotlin/Delegates | 1 + Lang/Kotlin/Dining-philosophers | 1 + Lang/Kotlin/Documentation | 1 + Lang/Kotlin/Element-wise-operations | 1 + Lang/Kotlin/Execute-a-Markov-algorithm | 1 + Lang/Kotlin/Find-common-directory-path | 1 + Lang/Kotlin/Fork | 1 + Lang/Kotlin/Formal-power-series | 1 + Lang/Kotlin/Four-bit-adder | 1 + .../Kotlin/GUI-enabling-disabling-of-controls | 1 + Lang/Kotlin/Galton-box-animation | 1 + Lang/Kotlin/Gaussian-elimination | 1 + .../Globally-replace-text-in-several-files | 1 + Lang/Kotlin/Grayscale-image | 1 + Lang/Kotlin/HTTPS-Authenticated | 1 + Lang/Kotlin/HTTPS-Client-authenticated | 1 + Lang/Kotlin/Image-convolution | 1 + Lang/Kotlin/Image-noise | 1 + Lang/Kotlin/Inverted-index | 1 + Lang/Kotlin/JSON | 1 + Lang/Kotlin/K-d-tree | 1 + Lang/Kotlin/K-means++-clustering | 1 + Lang/Kotlin/Keyboard-macros | 1 + Lang/Kotlin/LU-decomposition | 1 + Lang/Kotlin/Langtons-ant | 1 + Lang/Kotlin/Main-step-of-GOST-28147-89 | 1 + Lang/Kotlin/Maze-solving | 1 + Lang/Kotlin/Median-filter | 1 + Lang/Kotlin/Metered-concurrency | 1 + Lang/Kotlin/Multiple-regression | 1 + Lang/Kotlin/Multiplicative-order | 1 + Lang/Kotlin/Munching-squares | 1 + Lang/Kotlin/Object-serialization | 1 + Lang/Kotlin/One-dimensional-cellular-automata | 1 + Lang/Kotlin/One-of-n-lines-in-a-file | 1 + Lang/Kotlin/Optional-parameters | 1 + Lang/Kotlin/Parallel-calculations | 1 + Lang/Kotlin/Parametrized-SQL-statement | 1 + Lang/Kotlin/Parsing-RPN-to-infix-conversion | 1 + Lang/Kotlin/Parsing-Shunting-yard-algorithm | 1 + Lang/Kotlin/Pattern-matching | 1 + Lang/Kotlin/Penneys-game | 1 + .../Percentage-difference-between-images | 1 + Lang/Kotlin/Percolation-Bond-percolation | 1 + Lang/Kotlin/Percolation-Mean-cluster-density | 1 + Lang/Kotlin/Percolation-Mean-run-density | 1 + Lang/Kotlin/Percolation-Site-percolation | 1 + Lang/Kotlin/Plot-coordinate-pairs | 1 + Lang/Kotlin/Polynomial-long-division | 1 + Lang/Kotlin/Polynomial-regression | 1 + Lang/Kotlin/Reduced-row-echelon-form | 1 + Lang/Kotlin/Rock-paper-scissors | 1 + Lang/Kotlin/S-Expressions | 1 + Lang/Kotlin/SOAP | 1 + Lang/Kotlin/SQL-based-authentication | 1 + Lang/Kotlin/Simple-database | 1 + Lang/Kotlin/Sockets | 1 + Lang/Kotlin/Sokoban | 1 + Lang/Kotlin/Solve-a-Hidato-puzzle | 1 + Lang/Kotlin/Solve-a-Hopido-puzzle | 1 + Lang/Kotlin/Solve-a-Numbrix-puzzle | 1 + Lang/Kotlin/Solve-the-no-connection-puzzle | 1 + Lang/Kotlin/Sort-disjoint-sublist | 1 + Lang/Kotlin/Sort-stability | 1 + Lang/Kotlin/Sorting-algorithms-Sleep-sort | 1 + Lang/Kotlin/Speech-synthesis | 1 + Lang/Kotlin/Stair-climbing-puzzle | 1 + Lang/Kotlin/State-name-puzzle | 1 + Lang/Kotlin/Subtractive-generator | 1 + Lang/Kotlin/Sudoku | 1 + Lang/Kotlin/Synchronous-concurrency | 1 + Lang/Kotlin/Table-creation-Postal-addresses | 1 + Lang/Kotlin/Take-notes-on-the-command-line | 1 + Lang/Kotlin/Text-processing-1 | 1 + Lang/Kotlin/Text-processing-2 | 1 + .../Text-processing-Max-licenses-in-use | 1 + Lang/Kotlin/Tic-tac-toe | 1 + Lang/Kotlin/Topological-sort | 1 + Lang/Kotlin/Universal-Turing-machine | 1 + Lang/Kotlin/Unix-ls | 1 + Lang/Kotlin/Update-a-configuration-file | 1 + .../Use-another-language-to-call-a-function | 1 + ...y-distribution-uniformity-Chi-squared-test | 1 + Lang/Kotlin/Video-display-modes | 1 + Lang/Kotlin/Visualize-a-tree | 1 + Lang/Kotlin/Walk-a-directory-Recursively | 1 + Lang/Kotlin/Yahoo--search-interface | 1 + Lang/Kotlin/Zeckendorf-arithmetic | 1 + Lang/Limbo/00DESCRIPTION | 2 +- Lang/Limbo/99-Bottles-of-Beer | 1 + Lang/Limbo/Array-concatenation | 1 + Lang/Limbo/Averages-Arithmetic-mean | 1 + Lang/Limbo/Ethiopian-multiplication | 1 + Lang/Limbo/Literals-Integer | 1 + Lang/Limbo/Sieve-of-Eratosthenes | 1 + Lang/Limbo/Singly-linked-list-Traversal | 1 + Lang/Lingo/99-Bottles-of-Beer | 1 + Lang/Lingo/Active-object | 1 + ...-a-variable-to-a-class-instance-at-runtime | 1 + Lang/Lingo/Animate-a-pendulum | 1 + Lang/Lingo/Arithmetic-Integer | 1 + Lang/Lingo/Averages-Arithmetic-mean | 1 + Lang/Lingo/Averages-Median | 1 + Lang/Lingo/Binary-strings | 1 + Lang/Lingo/Extensible-prime-generator | 1 + Lang/Lingo/Factors-of-a-Mersenne-number | 1 + Lang/Lingo/Generator-Exponential | 1 + Lang/Lingo/MD5-Implementation | 1 + Lang/Lingo/OpenGL | 1 + Lang/Lingo/Primality-by-trial-division | 1 + Lang/Lingo/Random-numbers | 1 + Lang/Lingo/SHA-1 | 1 + Lang/Lingo/Semiprime | 1 + Lang/Lingo/Show-the-epoch | 1 + Lang/Lingo/Sieve-of-Eratosthenes | 1 + Lang/Lingo/Tic-tac-toe | 1 + Lang/Lingo/URL-decoding | 1 + Lang/Lingo/Write-to-Windows-event-log | 1 + Lang/Lingo/Zeckendorf-number-representation | 1 + Lang/Logo/Catalan-numbers | 1 + Lang/Lua/00DESCRIPTION | 343 +++++++- Lang/Lua/Averages-Mean-time-of-day | 1 + Lang/Lua/Dinesmans-multiple-dwelling-problem | 1 + Lang/Lua/Huffman-coding | 1 + Lang/Lua/Make-directory-path | 1 + Lang/Lua/Soundex | 1 + Lang/Lua/Table-creation-Postal-addresses | 1 + Lang/MATLAB/Draw-a-sphere | 1 + Lang/MATLAB/Josephus-problem | 1 + ...ical-integration-Gauss-Legendre-Quadrature | 1 + Lang/MATLAB/XML-DOM-serialization | 1 + Lang/MIPS-Assembly/Towers-of-Hanoi | 1 + Lang/Maple/Animation | 1 + Lang/Maple/Bitmap | 1 + Lang/Maple/CSV-to-HTML-translation | 1 + Lang/Maple/Closest-pair-problem | 1 + Lang/Maple/Date-manipulation | 1 + Lang/Maple/Day-of-the-week | 1 + Lang/Maple/Element-wise-operations | 1 + ...est-left-truncatable-prime-in-a-given-base | 1 + Lang/Maple/Find-the-last-Sunday-of-each-month | 1 + Lang/Maple/Find-the-missing-permutation | 1 + Lang/Maple/Five-weekends | 1 + Lang/Maple/GUI-component-interaction | 1 + Lang/Maple/GUI-enabling-disabling-of-controls | 1 + Lang/Maple/Gamma-function | 1 + Lang/Maple/Grayscale-image | 1 + Lang/Maple/Last-Friday-of-each-month | 1 + Lang/Maple/Mandelbrot-set | 1 + Lang/Maple/Map-range | 1 + Lang/Maple/Multifactorial | 1 + Lang/Maple/Mutual-recursion | 1 + Lang/Maple/Narcissistic-decimal-number | 1 + Lang/Maple/Non-decimal-radices-Convert | 1 + Lang/Maple/Ordered-words | 1 + Lang/Maple/Pangram-checker | 1 + Lang/Maple/Quickselect-algorithm | 1 + Lang/Maple/Read-a-file-line-by-line | 1 + Lang/Maple/Regular-expressions | 1 + Lang/Maple/Search-a-list | 1 + Lang/Maple/Sorting-algorithms-Bogosort | 1 + Lang/Maple/Sorting-algorithms-Bubble-sort | 1 + Lang/Maple/Sorting-algorithms-Cocktail-sort | 1 + Lang/Maple/Sorting-algorithms-Comb-sort | 1 + Lang/Maple/Sorting-algorithms-Gnome-sort | 1 + Lang/Maple/Sorting-algorithms-Heapsort | 1 + Lang/Maple/Sorting-algorithms-Insertion-sort | 1 + Lang/Maple/Sorting-algorithms-Merge-sort | 1 + .../Maple/Sorting-algorithms-Permutation-sort | 1 + Lang/Maple/Sorting-algorithms-Quicksort | 1 + Lang/Maple/Sorting-algorithms-Selection-sort | 1 + Lang/Maple/Sorting-algorithms-Shell-sort | 1 + Lang/Maple/Sum-of-a-series | 1 + Lang/Maple/Tokenize-a-string | 1 + Lang/Maple/Towers-of-Hanoi | 1 + Lang/Maple/Trabb-Pardo-Knuth-algorithm | 1 + Lang/Maple/Truncatable-primes | 1 + Lang/Maple/Web-scraping | 1 + Lang/Mathematica/00DESCRIPTION | 9 +- Lang/Mathematica/Formal-power-series | 1 + Lang/Mathematica/Nautical-bell | 1 + .../Sutherland-Hodgman-polygon-clipping | 1 + Lang/Maxima/Parsing-RPN-calculator-algorithm | 1 + Lang/Metapost/Mandelbrot-set | 1 + ...ficient-and-perfect-number-classifications | 1 + Lang/Modula-2/Almost-prime | 1 + Lang/Modula-2/Averages-Pythagorean-means | 1 + Lang/Modula-2/Box-the-compass | 1 + Lang/Modula-2/Caesar-cipher | 1 + Lang/Modula-2/Catalan-numbers | 1 + ...Circles-of-given-radius-through-two-points | 1 + Lang/Modula-2/Combinations | 1 + ...-Arithmetic-Construct-from-rational-number | 1 + Lang/Modula-2/Digital-root | 1 + Lang/Modula-2/Dot-product | 1 + Lang/Modula-2/Ethiopian-multiplication | 1 + Lang/Modula-2/Even-or-odd | 1 + Lang/Modula-2/Factorial | 1 + Lang/Modula-2/Fibonacci-sequence | 1 + Lang/Modula-2/FizzBuzz | 1 + Lang/Modula-2/Floyds-triangle | 1 + Lang/Modula-2/Hello-world-Newline-omission | 1 + Lang/Modula-2/Horizontal-sundial-calculations | 1 + .../Horners-rule-for-polynomial-evaluation | 1 + Lang/Modula-2/Integer-sequence | 1 + Lang/Modula-2/Josephus-problem | 1 + Lang/Modula-2/Kaprekar-numbers | 1 + Lang/Modula-2/Leap-year | 1 + Lang/Modula-2/Least-common-multiple | 1 + Lang/Modula-2/Logical-operations | 1 + Lang/Modula-2/Modular-inverse | 1 + Lang/Modula-2/Morse-code | 1 + Lang/Modula-2/Multiplication-tables | 1 + Lang/Modula-2/Nth | 1 + Lang/Modula-2/Old-lady-swallowed-a-fly | 1 + Lang/Modula-2/Palindrome-detection | 1 + Lang/Modula-2/Pascals-triangle | 1 + Lang/Modula-2/Perfect-numbers | 1 + Lang/Modula-2/Pernicious-numbers | 1 + Lang/Modula-2/Polynomial-regression | 1 + Lang/Modula-2/Remove-duplicate-elements | 1 + Lang/Modula-2/Resistor-mesh | 1 + Lang/Modula-2/Reverse-a-string | 1 + Lang/Modula-2/Reverse-words-in-a-string | 1 + Lang/Modula-2/Roman-numerals-Encode | 1 + Lang/Modula-2/Self-describing-numbers | 1 + Lang/Modula-2/Short-circuit-evaluation | 1 + Lang/Modula-2/Sum-digits-of-an-integer | 1 + Lang/Modula-2/System-time | 1 + Lang/Modula-2/The-ISAAC-Cipher | 1 + Lang/Modula-2/Towers-of-Hanoi | 1 + Lang/Modula-2/Trigonometric-functions | 1 + Lang/Modula-2/Van-der-Corput-sequence | 1 + Lang/Modula-2/Vector-products | 1 + Lang/Modula-2/Write-language-name-in-3D-ASCII | 1 + Lang/N-t-roff/00DESCRIPTION | 35 +- Lang/N-t-roff/99-Bottles-of-Beer | 1 + Lang/N-t-roff/Binary-search | 1 + Lang/N-t-roff/Empty-program | 1 + Lang/N-t-roff/Hello-world-Graphical | 1 + Lang/N-t-roff/Hello-world-Line-printer | 1 + Lang/N-t-roff/Hello-world-Newline-omission | 1 + Lang/N-t-roff/Hello-world-Standard-error | 1 + Lang/N-t-roff/Hello-world-Text | 1 + .../N-t-roff/Parsing-RPN-calculator-algorithm | 1 + Lang/N-t-roff/Sorting-algorithms-Bubble-sort | 1 + .../Sorting-algorithms-Insertion-sort | 1 + .../Sorting-algorithms-Selection-sort | 1 + Lang/NetRexx/Soundex | 1 + Lang/NewLISP/HTTPS | 1 + Lang/Nial/100-doors | 1 + Lang/Nial/Reverse-words-in-a-string | 1 + Lang/Nial/Sort-disjoint-sublist | 1 + Lang/Nial/Tokenize-a-string | 1 + Lang/Nial/Zebra-puzzle | 1 + Lang/Nim/Runge-Kutta-method | 1 + Lang/OCaml/Break-OO-privacy | 1 + Lang/OCaml/Catalan-numbers-Pascals-triangle | 1 + Lang/OCaml/Comma-quibbling | 1 + Lang/OCaml/Execute-HQ9+ | 1 + Lang/OCaml/Flipping-bits-game | 1 + Lang/OCaml/Generate-lower-case-ASCII-alphabet | 1 + Lang/Oberon-2/Average-loop-length | 1 + Lang/Objeck/DNS-query | 1 + Lang/Objeck/Deal-cards-for-FreeCell | 1 + Lang/Objeck/Entropy | 1 + Lang/Objeck/Equilibrium-index | 1 + Lang/Objeck/Fibonacci-word | 1 + Lang/Objeck/Make-directory-path | 1 + Lang/Objeck/Return-multiple-values | 1 + Lang/Objeck/Strip-comments-from-a-string | 1 + Lang/Objeck/Sum-multiples-of-3-and-5 | 1 + Lang/Octave/Semordnilap | 1 + Lang/Octave/Zig-zag-matrix | 1 + Lang/Oforth/Address-of-a-variable | 1 + Lang/PARI-GP/00DESCRIPTION | 134 ++- Lang/PARI-GP/Hello-world-Graphical | 1 + Lang/PARI-GP/Parsing-RPN-calculator-algorithm | 1 + Lang/PHP/Rock-paper-scissors | 1 + Lang/PL-M/00DESCRIPTION | 7 +- Lang/PL-M/Hello-world-Text | 1 + Lang/PL-M/Trabb-Pardo-Knuth-algorithm | 1 + Lang/PL-SQL/00DESCRIPTION | 3 + Lang/PL-SQL/Loops-While | 1 + Lang/Pascal/HTTPS | 1 + Lang/Pascal/Twelve-statements | 1 + Lang/Perl-6/00DESCRIPTION | 19 +- .../Append-a-record-to-the-end-of-a-text-file | 1 + Lang/Perl-6/Bitmap-B-zier-curves-Cubic | 1 + Lang/Perl-6/Bitmap-B-zier-curves-Quadratic | 1 + Lang/Perl-6/Bitmap-Histogram | 1 + Lang/Perl-6/Bitmap-Read-a-PPM-file | 1 + .../Bitmap-Read-an-image-through-a-pipe | 1 + Lang/Perl-6/Distributed-programming | 1 + Lang/Perl-6/HTTPS | 1 + Lang/Perl-6/HTTPS-Authenticated | 1 + Lang/Perl-6/Infinity | 1 + Lang/Perl-6/Secure-temporary-file | 1 + Lang/Perl-6/Simple-database | 1 + Lang/Perl-6/Table-creation-Postal-addresses | 1 + Lang/Perl-6/Video-display-modes | 1 + Lang/Perl-6/Voronoi-diagram | 1 + Lang/Perl-6/XML-DOM-serialization | 1 + Lang/Perl-6/XML-Output | 1 + Lang/Perl-6/XML-XPath | 1 + Lang/Perl/00DESCRIPTION | 5 +- Lang/Perl/Keyboard-input-Keypress-check | 1 + Lang/Perl/Matrix-arithmetic | 1 + Lang/Perl/Parallel-calculations | 1 + Lang/Perl/Permutations-Rank-of-a-permutation | 1 + Lang/Perl/Simple-database | 1 + Lang/Perl/Terminal-control-Preserve-screen | 1 + Lang/Perl/Write-to-Windows-event-log | 1 + Lang/Phix/Text-processing-1 | 1 + Lang/PicoLisp/00DESCRIPTION | 17 +- Lang/PicoLisp/Extensible-prime-generator | 1 + Lang/PicoLisp/Harshad-or-Niven-series | 1 + Lang/PicoLisp/Josephus-problem | 1 + Lang/PicoLisp/Penneys-game | 1 + Lang/PicoLisp/Stern-Brocot-sequence | 1 + Lang/Pony/Synchronous-concurrency | 1 + Lang/PowerBASIC/Binary-digits | 1 + Lang/PowerBASIC/Rot-13 | 1 + Lang/PowerShell/Calendar | 1 + Lang/PowerShell/Natural-sorting | 1 + Lang/Processing/00DESCRIPTION | 9 +- Lang/Processing/Ackermann-function | 1 + Lang/Processing/Classes | 1 + Lang/Processing/Factorial | 1 + Lang/Processing/Mandelbrot-set | 1 + Lang/Processing/Palindrome-detection | 1 + Lang/Prolog/Arithmetic-geometric-mean | 1 + Lang/Prolog/Closest-pair-problem | 1 + Lang/Prolog/Execute-Brain---- | 1 + Lang/Prolog/Spiral-matrix | 1 + Lang/PureBasic/00DESCRIPTION | 31 +- Lang/PureBasic/Almost-prime | 1 + Lang/PureBasic/Modular-inverse | 1 + Lang/PureBasic/The-Twelve-Days-of-Christmas | 1 + Lang/Python/00DESCRIPTION | 5 +- Lang/Python/Colour-pinstripe-Display | 1 + Lang/Python/Events | 1 + .../Python/Terminal-control-Hiding-the-cursor | 1 + Lang/Python/Terminal-control-Positional-read | 1 + Lang/Python/Variables | 1 + Lang/Q/Look-and-say-sequence | 1 + Lang/R/AKS-test-for-primes | 1 + Lang/R/Amicable-pairs | 1 + Lang/R/Catamorphism | 1 + Lang/R/Dinesmans-multiple-dwelling-problem | 1 + Lang/R/Knapsack-problem-Bounded | 1 + Lang/R/Lucas-Lehmer-test | 1 + Lang/R/Non-decimal-radices-Convert | 1 + Lang/R/Reverse-words-in-a-string | 1 + Lang/R/Statistics-Basic | 1 + Lang/REXX/00DESCRIPTION | 7 +- Lang/REXX/Bitmap-Read-a-PPM-file | 1 + Lang/REXX/Color-of-a-screen-pixel | 1 + Lang/REXX/Deconvolution-1D | 1 + Lang/REXX/Extreme-floating-point-values | 1 + Lang/REXX/Munching-squares | 1 + Lang/REXX/Pattern-matching | 1 + Lang/REXX/Polynomial-long-division | 1 + Lang/Racket/00DESCRIPTION | 8 +- Lang/Red/ABC-Problem | 1 + Lang/Red/Anagrams | 1 + Lang/Red/Array-concatenation | 1 + Lang/Red/Arrays | 1 + Lang/Red/Balanced-brackets | 1 + Lang/Red/Binary-digits | 1 + Lang/Red/Binary-strings | 1 + Lang/Red/CSV-data-manipulation | 1 + Lang/Red/CSV-to-HTML-translation | 1 + Lang/Red/Character-codes | 1 + Lang/Red/Check-that-file-exists | 1 + Lang/Red/Closures-Value-capture | 1 + Lang/Red/Conditional-structures | 1 + Lang/Red/Count-occurrences-of-a-substring | 1 + Lang/Red/Date-manipulation | 1 + Lang/Red/Day-of-the-week | 1 + Lang/Red/Empty-string | 1 + Lang/Red/Execute-a-system-command | 1 + Lang/Red/File-input-output | 1 + Lang/Red/File-size | 1 + Lang/Red/Filter | 1 + .../Globally-replace-text-in-several-files | 1 + Lang/Red/Greatest-element-of-a-list | 1 + Lang/Red/Hello-world-Graphical | 1 + Lang/Red/Huffman-coding | 1 + .../Loop-over-multiple-arrays-simultaneously | 1 + Lang/Red/Loops-Continue | 1 + Lang/Red/Loops-Do-while | 1 + Lang/Red/Loops-Foreach | 1 + Lang/Red/Loops-Infinite | 1 + Lang/Red/Morse-code | 1 + Lang/Red/Ordered-words | 1 + Lang/Red/Pick-random-element | 1 + Lang/Red/Read-a-specific-line-from-a-file | 1 + Lang/Red/Remove-duplicate-elements | 1 + Lang/Red/Repeat-a-string | 1 + Lang/Red/Reverse-a-string | 1 + Lang/Red/Reverse-words-in-a-string | 1 + Lang/Red/Self-describing-numbers | 1 + Lang/Red/Sleep | 1 + Lang/Red/Sort-an-integer-array | 1 + Lang/Red/String-case | 1 + Lang/Red/String-concatenation | 1 + Lang/Red/String-prepend | 1 + .../Strip-a-set-of-characters-from-a-string | 1 + Lang/Red/Strip-comments-from-a-string | 1 + ...trip-whitespace-from-a-string-Top-and-tail | 1 + Lang/Red/Sum-of-a-series | 1 + Lang/Red/Tokenize-a-string | 1 + Lang/Red/User-input-Text | 1 + Lang/Red/Vigen-re-cipher | 1 + Lang/Red/Window-creation | 1 + Lang/Ring/24-game | 1 + Lang/Ring/Aliquot-sequence-classifications | 1 + Lang/Ring/Anagrams | 1 + Lang/Ring/Anagrams-Deranged-anagrams | 1 + Lang/Ring/Animate-a-pendulum | 1 + Lang/Ring/Animation | 1 + Lang/Ring/Anonymous-recursion | 1 + Lang/Ring/Associative-array-Creation | 1 + Lang/Ring/Associative-array-Iteration | 1 + Lang/Ring/Atomic-updates | 1 + Lang/Ring/Averages-Mean-angle | 1 + Lang/Ring/Averages-Mode | 1 + Lang/Ring/Benfords-law | 1 + Lang/Ring/Best-shuffle | 1 + Lang/Ring/Box-the-compass | 1 + Lang/Ring/Brownian-tree | 1 + Lang/Ring/Bulls-and-cows | 1 + Lang/Ring/Bulls-and-cows-Player | 1 + Lang/Ring/Caesar-cipher | 1 + Lang/Ring/Calendar | 1 + Lang/Ring/Carmichael-3-strong-pseudoprimes | 1 + Lang/Ring/Casting-out-nines | 1 + Lang/Ring/Cholesky-decomposition | 1 + ...Circles-of-given-radius-through-two-points | 1 + Lang/Ring/Colour-pinstripe-Display | 1 + Lang/Ring/Combinations | 1 + Lang/Ring/Combinations-with-repetitions | 1 + Lang/Ring/Comma-quibbling | 1 + Lang/Ring/Continued-fraction | 1 + Lang/Ring/Create-a-file-on-magnetic-tape | 1 + Lang/Ring/Date-manipulation | 1 + .../Digital-root-Multiplicative-digital-root | 1 + Lang/Ring/Doubly-linked-list-Definition | 1 + Lang/Ring/Doubly-linked-list-Traversal | 1 + Lang/Ring/Draw-a-cuboid | 1 + Lang/Ring/Dutch-national-flag-problem | 1 + Lang/Ring/Enforced-immutability | 1 + Lang/Ring/Evolutionary-algorithm | 1 + Lang/Ring/Extend-your-language | 1 + Lang/Ring/Factors-of-a-Mersenne-number | 1 + Lang/Ring/Fibonacci-n-step-number-sequences | 1 + Lang/Ring/Fibonacci-word | 1 + Lang/Ring/Forest-fire | 1 + Lang/Ring/Forward-difference | 1 + Lang/Ring/Four-bit-adder | 1 + Lang/Ring/Gray-code | 1 + Lang/Ring/Greatest-subsequential-sum | 1 + Lang/Ring/Greyscale-bars-Display | 1 + Lang/Ring/Hash-from-two-arrays | 1 + Lang/Ring/Heronian-triangles | 1 + Lang/Ring/Higher-order-functions | 1 + Lang/Ring/Hofstadter-Figure-Figure-sequences | 1 + Lang/Ring/Horizontal-sundial-calculations | 1 + Lang/Ring/I-before-E-except-after-C | 1 + Lang/Ring/IBAN | 1 + Lang/Ring/Jensens-Device | 1 + Lang/Ring/Knapsack-problem-0-1 | 1 + Lang/Ring/LZW-compression | 1 + Lang/Ring/Last-letter-first-letter | 1 + Lang/Ring/Levenshtein-distance | 1 + Lang/Ring/Longest-increasing-subsequence | 1 + Lang/Ring/Longest-string-challenge | 1 + Lang/Ring/Ludic-numbers | 1 + Lang/Ring/Maximum-triangle-path-sum | 1 + Lang/Ring/Morse-code | 1 + Lang/Ring/Move-to-front-algorithm | 1 + Lang/Ring/Multisplit | 1 + Lang/Ring/Munching-squares | 1 + Lang/Ring/Nautical-bell | 1 + Lang/Ring/Non-continuous-subsequences | 1 + Lang/Ring/Non-decimal-radices-Convert | 1 + Lang/Ring/Number-reversal-game | 1 + Lang/Ring/Numerical-integration | 1 + Lang/Ring/Odd-word-problem | 1 + Lang/Ring/One-dimensional-cellular-automata | 1 + Lang/Ring/OpenGL | 1 + Lang/Ring/Permutations-Rank-of-a-permutation | 1 + Lang/Ring/Pernicious-numbers | 1 + Lang/Ring/Pig-the-dice-game | 1 + Lang/Ring/Pinstripe-Display | 1 + Lang/Ring/Plot-coordinate-pairs | 1 + Lang/Ring/Power-set | 1 + Lang/Ring/Probabilistic-choice | 1 + Lang/Ring/Range-expansion | 1 + Lang/Ring/Range-extraction | 1 + Lang/Ring/Reduced-row-echelon-form | 1 + Lang/Ring/Regular-expressions | 1 + Lang/Ring/Rep-string | 1 + Lang/Ring/Rock-paper-scissors | 1 + Lang/Ring/Run-length-encoding | 1 + Lang/Ring/SHA-1 | 1 + Lang/Ring/SHA-256 | 1 + Lang/Ring/Scope-Function-names-and-labels | 1 + Lang/Ring/Self-describing-numbers | 1 + Lang/Ring/Set | 1 + Lang/Ring/Set-consolidation | 1 + .../Seven-sided-dice-from-five-sided-dice | 1 + Lang/Ring/Short-circuit-evaluation | 1 + Lang/Ring/Simulate-input-Mouse | 1 + Lang/Ring/Sorting-algorithms-Bogosort | 1 + Lang/Ring/Sorting-algorithms-Heapsort | 1 + Lang/Ring/Sorting-algorithms-Permutation-sort | 1 + Lang/Ring/Sorting-algorithms-Quicksort | 1 + Lang/Ring/Sorting-algorithms-Strand-sort | 1 + Lang/Ring/Soundex | 1 + Lang/Ring/Spiral-matrix | 1 + Lang/Ring/Statistics-Basic | 1 + Lang/Ring/Stem-and-leaf-plot | 1 + Lang/Ring/Stern-Brocot-sequence | 1 + Lang/Ring/Table-creation-Postal-addresses | 1 + Lang/Ring/Terminal-control-Coloured-text | 1 + Lang/Ring/Terminal-control-Cursor-positioning | 1 + ...inal-control-Display-an-extended-character | 1 + Lang/Ring/The-Twelve-Days-of-Christmas | 1 + Lang/Ring/Top-rank-per-group | 1 + Lang/Ring/Truncatable-primes | 1 + Lang/Ring/Ulam-spiral--for-primes- | 1 + Lang/Ring/Undefined-values | 1 + Lang/Ring/Vampire-number | 1 + Lang/Ring/Variadic-function | 1 + Lang/Ring/Vigen-re-cipher | 1 + Lang/Ring/Voronoi-diagram | 1 + Lang/Ring/Word-wrap | 1 + Lang/Ring/Write-float-arrays-to-a-text-file | 1 + Lang/Ring/Zeckendorf-number-representation | 1 + Lang/Ring/Zig-zag-matrix | 1 + Lang/Ruby/00DESCRIPTION | 5 +- Lang/Run-BASIC/00DESCRIPTION | 5 +- Lang/Rust/Amb | 1 + .../Constrained-random-points-on-a-circle | 1 + Lang/Rust/Convert-decimal-number-to-rational | 1 + Lang/Rust/Day-of-the-week | 1 + Lang/Rust/Detect-division-by-zero | 1 + Lang/Rust/Discordian-date | 1 + Lang/Rust/Empty-directory | 1 + Lang/Rust/Evolutionary-algorithm | 1 + Lang/Rust/Fractal-tree | 1 + Lang/Rust/Harshad-or-Niven-series | 1 + Lang/Rust/Identity-matrix | 1 + Lang/Rust/Knuths-algorithm-S | 1 + Lang/Rust/Linear-congruential-generator | 1 + Lang/Rust/Longest-increasing-subsequence | 1 + Lang/Rust/Lucas-Lehmer-test | 1 + Lang/Rust/Man-or-boy-test | 1 + Lang/Rust/Mandelbrot-set | 1 + Lang/Rust/Menu | 1 + Lang/Rust/Minesweeper-game | 1 + Lang/Rust/Monte-Carlo-methods | 1 + Lang/Rust/Parsing-Shunting-yard-algorithm | 1 + Lang/Rust/Pascals-triangle | 1 + Lang/Rust/Probabilistic-choice | 1 + Lang/Rust/Pythagorean-triples | 1 + Lang/Rust/Quaternion-type | 1 + Lang/Rust/Read-a-configuration-file | 1 + Lang/Rust/Read-a-specific-line-from-a-file | 1 + Lang/Rust/Rock-paper-scissors | 1 + Lang/Rust/Self-describing-numbers | 1 + Lang/Rust/Semiprime | 1 + Lang/Rust/Short-circuit-evaluation | 1 + Lang/Rust/Simulate-input-Keyboard | 1 + Lang/Rust/Simulate-input-Mouse | 1 + Lang/Rust/Sorting-algorithms-Counting-sort | 1 + Lang/Rust/Sorting-algorithms-Pancake-sort | 1 + Lang/Rust/String-prepend | 1 + .../Strip-a-set-of-characters-from-a-string | 1 + Lang/Rust/Substring | 1 + Lang/Rust/Sum-multiples-of-3-and-5 | 1 + Lang/Rust/Take-notes-on-the-command-line | 1 + Lang/Rust/Unbias-a-random-generator | 1 + Lang/Rust/Voronoi-diagram | 1 + Lang/SAS/Sieve-of-Eratosthenes | 1 + Lang/SETL/Roman-numerals-Encode | 1 + Lang/Scala/00DESCRIPTION | 6 +- Lang/Scala/Active-Directory-Connect | 1 + .../Arithmetic-geometric-mean-Calculate-Pi | 1 + Lang/Scala/Bitcoin-address-validation | 1 + Lang/Scala/Call-a-foreign-language-function | 1 + Lang/Scala/Catalan-numbers-Pascals-triangle | 1 + Lang/Scala/Catamorphism | 1 + Lang/Scala/Compile-time-calculation | 1 + Lang/Scala/Draw-a-sphere | 1 + Lang/Scala/Echo-server | 1 + Lang/Scala/GUI-Maximum-window-dimensions | 1 + .../Globally-replace-text-in-several-files | 1 + Lang/Scala/Guess-the-number-With-feedback | 1 + Lang/Scala/HTTPS-Authenticated | 1 + Lang/Scala/HTTPS-Client-authenticated | 1 + .../Scala/Hickerson-series-of-almost-integers | 1 + Lang/Scala/Inverted-syntax | 1 + Lang/Scala/Keyboard-input-Keypress-check | 1 + Lang/Scala/Knapsack-problem-Continuous | 1 + Lang/Scala/Knuths-algorithm-S | 1 + Lang/Scala/MD5-Implementation | 1 + Lang/Scala/Memory-layout-of-a-data-structure | 1 + Lang/Scala/Menu | 1 + Lang/Scala/Metaprogramming | 1 + Lang/Scala/Metered-concurrency | 1 + Lang/Scala/Metronome | 1 + Lang/Scala/Narcissist | 1 + Lang/Scala/Non-decimal-radices-Convert | 1 + Lang/Scala/Non-decimal-radices-Input | 1 + Lang/Scala/Non-decimal-radices-Output | 1 + Lang/Scala/Paraffins | 1 + Lang/Scala/Parse-an-IP-Address | 1 + Lang/Scala/Pascals-triangle-Puzzle | 1 + Lang/Scala/Permutations-by-swapping | 1 + Lang/Scala/Polymorphic-copy | 1 + Lang/Scala/Pragmatic-directives | 1 + Lang/Scala/Random-number-generator--device- | 1 + Lang/Scala/Real-constants-and-functions | 1 + .../Runtime-evaluation-In-an-environment | 1 + Lang/Scala/Safe-addition | 1 + Lang/Scala/Scope-Function-names-and-labels | 1 + Lang/Scala/Self-describing-numbers | 1 + Lang/Scala/Sorting-algorithms-Comb-sort | 1 + Lang/Scala/Sorting-algorithms-Stooge-sort | 1 + Lang/Scala/Terminal-control-Coloured-text | 1 + Lang/Scala/Terminal-control-Cursor-movement | 1 + .../Scala/Terminal-control-Cursor-positioning | 1 + Lang/Scala/Terminal-control-Dimensions | 1 + Lang/Scala/Terminal-control-Hiding-the-cursor | 1 + Lang/Scala/Terminal-control-Inverse-video | 1 + Lang/Scala/Topic-variable | 1 + Lang/Scala/Twelve-statements | 1 + .../Use-another-language-to-call-a-function | 1 + Lang/Scala/Variable-size-Set | 1 + Lang/Scala/Video-display-modes | 1 + Lang/Scala/Write-to-Windows-event-log | 1 + Lang/Scheme/24-game-Solve | 1 + Lang/Scheme/Continued-fraction | 1 + Lang/Scilab/Cholesky-decomposition | 1 + Lang/Scilab/Zig-zag-matrix | 1 + Lang/Scratch/00DESCRIPTION | 3 +- Lang/SheerPower-4GL/100-doors | 1 + Lang/Shen/Averages-Root-mean-square | 1 + Lang/Shen/Enumerations | 1 + Lang/Shen/Sorting-algorithms-Bubble-sort | 1 + Lang/Sidef/00DESCRIPTION | 5 +- Lang/Sidef/Arithmetic-Rational | 1 + Lang/Sidef/Brownian-tree | 1 + Lang/Sidef/Casting-out-nines | 1 + ...Circles-of-given-radius-through-two-points | 1 + Lang/Sidef/Color-quantization | 1 + Lang/Sidef/Colour-pinstripe-Display | 1 + Lang/Sidef/Delegates | 1 + Lang/Sidef/Element-wise-operations | 1 + Lang/Sidef/Matrix-arithmetic | 1 + Lang/Sidef/Matrix-exponentiation-operator | 1 + Lang/Sidef/Multiplicative-order | 1 + Lang/Sidef/N-queens-problem | 1 + Lang/Sidef/Vampire-number | 1 + Lang/Sidef/Vogels-approximation-method | 1 + Lang/Simula/Ackermann-function | 1 + Lang/Simula/Greatest-common-divisor | 1 + Lang/Simula/Program-termination | 1 + Lang/Simula/String-case | 1 + Lang/Simula/String-concatenation | 1 + Lang/Simula/Sum-multiples-of-3-and-5 | 1 + Lang/Sinclair-ZX81-BASIC/00DESCRIPTION | 6 +- .../Create-a-two-dimensional-array-at-runtime | 1 + Lang/Sinclair-ZX81-BASIC/Pinstripe-Display | 1 + Lang/Standard-ML/Left-factorials | 1 + Lang/Standard-ML/Unix-ls | 1 + Lang/Stata/00DESCRIPTION | 2 +- Lang/Stata/9-billion-names-of-God-the-integer | 1 + Lang/Stata/Address-of-a-variable | 1 + Lang/Stata/Anagrams | 1 + Lang/Stata/Apply-a-callback-to-an-array | 1 + Lang/Stata/Averages-Root-mean-square | 1 + Lang/Stata/Balanced-brackets | 1 + Lang/Stata/Caesar-cipher | 1 + Lang/Stata/Catalan-numbers | 1 + Lang/Stata/Character-codes | 1 + ...Circles-of-given-radius-through-two-points | 1 + Lang/Stata/Combinations-and-permutations | 1 + Lang/Stata/Combinations-with-repetitions | 1 + Lang/Stata/Conditional-structures | 1 + Lang/Stata/Count-occurrences-of-a-substring | 1 + Lang/Stata/Documentation | 1 + Lang/Stata/Element-wise-operations | 1 + Lang/Stata/Even-or-odd | 1 + Lang/Stata/Exponentiation-operator | 1 + Lang/Stata/Find-the-last-Sunday-of-each-month | 1 + Lang/Stata/Five-weekends | 1 + Lang/Stata/FizzBuzz | 1 + Lang/Stata/Function-definition | 1 + Lang/Stata/Gamma-function | 1 + Lang/Stata/Gaussian-elimination | 1 + Lang/Stata/Greatest-common-divisor | 1 + Lang/Stata/Greatest-element-of-a-list | 1 + Lang/Stata/Identity-matrix | 1 + Lang/Stata/Knuth-shuffle | 1 + Lang/Stata/Last-Friday-of-each-month | 1 + Lang/Stata/Linear-congruential-generator | 1 + Lang/Stata/List-comprehensions | 1 + Lang/Stata/Literals-Floating-point | 1 + Lang/Stata/Map-range | 1 + Lang/Stata/Matrix-arithmetic | 1 + Lang/Stata/Matrix-exponentiation-operator | 1 + Lang/Stata/Matrix-multiplication | 1 + Lang/Stata/Matrix-transposition | 1 + Lang/Stata/Maximum-triangle-path-sum | 1 + Lang/Stata/Multiple-regression | 1 + Lang/Stata/Nth | 1 + Lang/Stata/Numerical-integration | 1 + Lang/Stata/Pascals-triangle | 1 + Lang/Stata/Prime-decomposition | 1 + Lang/Stata/Probabilistic-choice | 1 + Lang/Stata/Roots-of-unity | 1 + Lang/Stata/Rot-13 | 1 + Lang/Stata/Runge-Kutta-method | 1 + Lang/Stata/Semordnilap | 1 + Lang/Stata/Short-circuit-evaluation | 1 + Lang/Stata/Show-the-epoch | 1 + .../Singly-linked-list-Element-definition | 1 + Lang/Stata/Sorting-algorithms-Insertion-sort | 1 + Lang/Stata/Sorting-algorithms-Selection-sort | 1 + Lang/Stata/Spiral-matrix | 1 + Lang/Stata/String-append | 1 + Lang/Stata/String-concatenation | 1 + Lang/Stata/String-interpolation--included- | 1 + Lang/Stata/String-prepend | 1 + ...trip-whitespace-from-a-string-Top-and-tail | 1 + Lang/Stata/Substring | 1 + Lang/Stata/Sudoku | 1 + Lang/Stata/Sum-and-product-of-an-array | 1 + Lang/Stata/Sum-digits-of-an-integer | 1 + Lang/Stata/Sum-of-a-series | 1 + Lang/Stata/Sum-of-squares | 1 + Lang/Stata/System-time | 1 + Lang/Stata/Table-creation-Postal-addresses | 1 + Lang/Stata/Towers-of-Hanoi | 1 + Lang/Stata/Unicode-variable-names | 1 + Lang/Stata/Zig-zag-matrix | 1 + Lang/Swift/Catamorphism | 1 + Lang/Swift/Find-limit-of-recursion | 1 + Lang/Swift/Power-set | 1 + Lang/SystemVerilog/Fast-Fourier-transform | 1 + Lang/Tcl/00DESCRIPTION | 5 +- Lang/TechBASIC/00DESCRIPTION | 101 +-- Lang/TypeScript/Sorting-algorithms-Quicksort | 1 + .../Calendar---for-REAL-programmers | 1 + Lang/UNIX-Shell/Digital-root | 1 + Lang/UNIX-Shell/Dynamic-variable-names | 1 + Lang/UNIX-Shell/Even-or-odd | 1 + Lang/UNIX-Shell/Palindrome-detection | 1 + .../Parsing-RPN-calculator-algorithm | 1 + .../Parsing-Shunting-yard-algorithm | 1 + Lang/UNIX-Shell/Temperature-conversion | 1 + Lang/Ursa/Sockets | 1 + Lang/Ursala/00DESCRIPTION | 1 - Lang/VBA/ABC-Problem | 1 + ...ficient-and-perfect-number-classifications | 1 + Lang/VBA/Amicable-pairs | 1 + Lang/VBA/Anagrams | 1 + Lang/VBA/Anonymous-recursion | 1 + Lang/VBA/Apply-a-callback-to-an-array | 1 + Lang/VBA/Array-concatenation | 1 + Lang/VBA/Best-shuffle | 1 + Lang/VBA/Binary-digits | 1 + Lang/VBA/Binary-strings | 1 + Lang/VBA/Bulls-and-cows | 1 + Lang/VBA/Bulls-and-cows-Player | 1 + Lang/VBA/Caesar-cipher | 1 + Lang/VBA/Call-an-object-method | 1 + Lang/VBA/Check-that-file-exists | 1 + Lang/VBA/Closest-pair-problem | 1 + Lang/VBA/Color-of-a-screen-pixel | 1 + Lang/VBA/Combinations | 1 + Lang/VBA/Comma-quibbling | 1 + Lang/VBA/Conditional-structures | 1 + .../Create-a-two-dimensional-array-at-runtime | 1 + Lang/VBA/Day-of-the-week | 1 + Lang/VBA/Delete-a-file | 1 + Lang/VBA/Detect-division-by-zero | 1 + Lang/VBA/Determine-if-a-string-is-numeric | 1 + Lang/VBA/Empty-directory | 1 + Lang/VBA/Empty-program | 1 + Lang/VBA/Ethiopian-multiplication | 1 + Lang/VBA/Even-or-odd | 1 + Lang/VBA/Exceptions | 1 + Lang/VBA/Extensible-prime-generator | 1 + Lang/VBA/Factorial | 1 + Lang/VBA/Fibonacci-n-step-number-sequences | 1 + Lang/VBA/File-input-output | 1 + Lang/VBA/Filter | 1 + Lang/VBA/Find-limit-of-recursion | 1 + Lang/VBA/Five-weekends | 1 + Lang/VBA/FizzBuzz | 1 + Lang/VBA/Function-definition | 1 + Lang/VBA/Generate-lower-case-ASCII-alphabet | 1 + Lang/VBA/Guess-the-number | 1 + Lang/VBA/Happy-numbers | 1 + Lang/VBA/Langtons-ant | 1 + Lang/VBA/Luhn-test-of-credit-card-numbers | 1 + Lang/VBA/Middle-three-digits | 1 + Lang/VBA/Minesweeper-game | 1 + Lang/VBA/Morse-code | 1 + Lang/VBA/Multiplication-tables | 1 + Lang/VBA/Odd-word-problem | 1 + Lang/VBA/Penneys-game | 1 + Lang/VBA/Phrase-reversals | 1 + Lang/VBA/Pick-random-element | 1 + Lang/VBA/Pig-the-dice-game | 1 + Lang/VBA/Price-fraction | 1 + Lang/VBA/Primality-by-trial-division | 1 + Lang/VBA/Remove-duplicate-elements | 1 + Lang/VBA/Remove-lines-from-a-file | 1 + Lang/VBA/Return-multiple-values | 1 + Lang/VBA/Reverse-words-in-a-string | 1 + Lang/VBA/Roman-numerals-Decode | 1 + Lang/VBA/Run-length-encoding | 1 + Lang/VBA/Sequence-of-non-squares | 1 + Lang/VBA/String-concatenation | 1 + Lang/VBA/Sum-multiples-of-3-and-5 | 1 + Lang/VBA/Temperature-conversion | 1 + Lang/VBA/Test-a-function | 1 + Lang/VBA/The-Twelve-Days-of-Christmas | 1 + Lang/VBA/Tic-tac-toe | 1 + Lang/VBA/Tokenize-a-string | 1 + Lang/VBA/Vigen-re-cipher | 1 + Lang/VBA/Web-scraping | 1 + Lang/VBA/Window-creation | 1 + Lang/VBA/XML-Input | 1 + Lang/VBScript/Guess-the-number-With-feedback | 1 + Lang/Visual-Basic-.NET/Balanced-brackets | 1 + Lang/Visual-Basic-.NET/Hello-world-Text | 1 + Lang/Visual-Basic-.NET/Ray-casting-algorithm | 1 + .../String-interpolation--included- | 1 + Lang/Visual-Basic-.NET/Variables | 1 + Lang/Visual-Basic/100-doors | 1 + Lang/Visual-Basic/Binary-digits | 1 + Lang/Visual-Basic/Check-that-file-exists | 1 + Lang/Visual-Basic/Conditional-structures | 1 + Lang/Visual-Basic/Formatted-numeric-output | 1 + Lang/Visual-Basic/Leap-year | 1 + Lang/Visual-Basic/Null-object | 1 + Lang/Visual-Basic/Rot-13 | 1 + Lang/Wart/00DESCRIPTION | 2 +- Lang/Wart/N-queens-problem | 1 + Lang/X86-Assembly/Balanced-brackets | 1 + Lang/X86-Assembly/Echo-server | 1 + Lang/X86-Assembly/Loops-While | 1 + Lang/XLISP/Accumulator-factory | 1 + Lang/XLISP/Address-of-a-variable | 1 + Lang/XLISP/Greatest-common-divisor | 1 + Lang/XLISP/Priority-queue | 1 + Lang/ZX-Spectrum-Basic/Execute-Brain---- | 1 + Lang/ZX-Spectrum-Basic/Infinity | 1 + Lang/ZX-Spectrum-Basic/Joystick-position | 1 + Lang/ZX-Spectrum-Basic/Pascals-triangle | 1 + Lang/Zkl/00DESCRIPTION | 16 +- Task/100-doors/Astro/100-doors.astro | 9 +- Task/100-doors/BASIC/100-doors-1.basic | 33 +- Task/100-doors/BASIC/100-doors-2.basic | 50 +- Task/100-doors/BASIC/100-doors-3.basic | 21 +- Task/100-doors/BASIC/100-doors-4.basic | 32 +- Task/100-doors/BASIC/100-doors-5.basic | 25 +- Task/100-doors/BASIC/100-doors-6.basic | 46 +- Task/100-doors/BASIC/100-doors-7.basic | 19 +- Task/100-doors/BASIC/100-doors-8.basic | 9 + Task/100-doors/C-sharp/100-doors-2.cs | 12 +- Task/100-doors/Common-Lisp/100-doors-3.lisp | 6 +- Task/100-doors/Common-Lisp/100-doors-4.lisp | 16 +- Task/100-doors/Common-Lisp/100-doors-5.lisp | 29 +- Task/100-doors/Common-Lisp/100-doors-6.lisp | 28 +- Task/100-doors/Common-Lisp/100-doors-7.lisp | 5 + Task/100-doors/Elena/100-doors.elena | 2 +- Task/100-doors/Excel/100-doors-1.excel | 1 + Task/100-doors/Excel/100-doors-2.excel | 1 + Task/100-doors/Excel/100-doors-3.excel | 1 + Task/100-doors/HolyC/100-doors.holyc | 14 + Task/100-doors/Julia/100-doors-1.julia | 2 +- Task/100-doors/Julia/100-doors-2.julia | 2 +- Task/100-doors/Klong/100-doors-1.klong | 2 + Task/100-doors/Klong/100-doors-2.klong | 1 + Task/100-doors/Nial/100-doors-1.nial | 4 + Task/100-doors/Nial/100-doors-2.nial | 2 + Task/100-doors/Nial/100-doors-3.nial | 2 + Task/100-doors/Oforth/100-doors.oforth | 4 +- Task/100-doors/R/100-doors-4.r | 3 + Task/100-doors/Rust/100-doors-1.rust | 5 +- Task/100-doors/Rust/100-doors-2.rust | 4 +- Task/100-doors/Rust/100-doors-3.rust | 6 +- Task/100-doors/Rust/100-doors-4.rust | 4 +- Task/100-doors/SheerPower-4GL/100-doors.4gl | 43 + Task/100-doors/Simula/100-doors.simula | 24 +- Task/100-doors/Stata/100-doors.stata | 32 +- Task/100-doors/Visual-Basic/100-doors.vb | 17 + .../24-game-Solve/Factor/24-game-solve.factor | 18 + .../Mathematica/24-game-solve-3.math | 35 + .../{24-game-solve.py => 24-game-solve-1.py} | 0 Task/24-game-Solve/Python/24-game-solve-2.py | 39 + Task/24-game-Solve/Python/24-game-solve-3.py | 44 + Task/24-game-Solve/Scheme/24-game-solve-1.ss | 46 + Task/24-game-Solve/Scheme/24-game-solve-2.ss | 13 + Task/24-game/Befunge/24-game.bf | 25 + Task/24-game/Elena/24-game.elena | 48 +- Task/24-game/Oforth/24-game.oforth | 19 +- Task/24-game/Ring/24-game.ring | 63 ++ .../Go/9-billion-names-of-god-the-integer.go | 45 + .../9-billion-names-of-god-the-integer.stata | 10 + Task/99-Bottles-of-Beer/00DESCRIPTION | 19 +- .../Astro/99-bottles-of-beer.astro | 8 +- .../Crystal/99-bottles-of-beer.crystal | 7 + .../Elena/99-bottles-of-beer.elena | 17 +- .../Kitten/99-bottles-of-beer.kitten | 32 + .../Limbo/99-bottles-of-beer.limbo | 26 + .../Lingo/99-bottles-of-beer.lingo | 18 + .../Lua/99-bottles-of-beer-3.lua | 11 + .../N-t-roff/99-bottles-of-beer-1.n | 18 + .../N-t-roff/99-bottles-of-beer-2.n | 15 + .../Oforth/99-bottles-of-beer.oforth | 2 +- .../REXX/99-bottles-of-beer.rexx | 38 +- .../Xojo/99-bottles-of-beer.xojo | 2 +- Task/A+B/BASIC/a+b-11.basic | 14 +- Task/A+B/Ceylon/a+b.ceylon | 44 +- Task/A+B/Elena/a+b-1.elena | 2 +- Task/A+B/Elena/a+b-2.elena | 2 +- Task/A+B/Oforth/a+b.oforth | 4 +- Task/ABC-Problem/Astro/abc-problem.astro | 18 +- Task/ABC-Problem/Elena/abc-problem.elena | 6 +- Task/ABC-Problem/Julia/abc-problem.julia | 24 +- Task/ABC-Problem/Maple/abc-problem.maple | 13 +- Task/ABC-Problem/Oforth/abc-problem.oforth | 14 +- Task/ABC-Problem/Red/abc-problem.red | 16 + Task/ABC-Problem/VBA/abc-problem.vba | 34 + .../8th/aks-test-for-primes.8th | 56 ++ .../Elena/aks-test-for-primes.elena | 82 ++ .../Oforth/aks-test-for-primes.oforth | 25 +- .../Perl-6/aks-test-for-primes.pl6 | 31 + .../R/aks-test-for-primes.r | 9 + .../REXX/aks-test-for-primes-2.rexx | 81 +- .../Abstract-type/Julia/abstract-type-1.julia | 4 +- .../Abstract-type/Julia/abstract-type-2.julia | 12 +- .../Oforth/abstract-type-1.oforth | 4 +- .../Oforth/abstract-type-2.oforth | 3 +- ...t-and-perfect-number-classifications.elena | 41 + ...-and-perfect-number-classifications-1.erl} | 0 ...t-and-perfect-number-classifications-2.erl | 29 + ...-and-perfect-number-classifications.factor | 8 + ...nt-and-perfect-number-classifications.mod2 | 47 + ...-and-perfect-number-classifications.oforth | 14 +- ...ient-and-perfect-number-classifications.rb | 2 +- ...ent-and-perfect-number-classifications.vba | 32 + .../Astro/accumulator-factory.astro | 8 +- .../Elena/accumulator-factory.elena | 23 +- .../Factor/accumulator-factory.factor | 1 + .../Java/accumulator-factory-1.java | 33 +- .../Java/accumulator-factory-2.java | 31 +- .../Julia/accumulator-factory.julia | 7 +- .../Oforth/accumulator-factory-1.oforth | 6 +- .../Oforth/accumulator-factory-2.oforth | 13 +- .../Perl-6/accumulator-factory.pl6 | 12 + .../Ruby/accumulator-factory-1.rb | 9 + .../Ruby/accumulator-factory-2.rb | 15 + .../Ruby/accumulator-factory-3.rb | 9 + .../Ruby/accumulator-factory.rb | 30 - .../XLISP/accumulator-factory.xlisp | 4 + .../C-sharp/ackermann-function-1.cs | 32 + ...nn-function.cs => ackermann-function-2.cs} | 0 .../Elena/ackermann-function.elena | 8 +- .../Gambas/ackermann-function.gambas | 21 + .../Julia/ackermann-function-2.julia | 2 +- .../Julia/ackermann-function-3.julia | 5 +- .../Klong/ackermann-function.klong | 2 + .../Nim/ackermann-function.nim | 2 +- .../Oforth/ackermann-function.oforth | 6 +- .../Perl-6/ackermann-function-3.pl6 | 4 + .../Processing/ackermann-function | 9 + .../Simula/ackermann-function.simula | 15 + .../D/active-directory-connect.d | 18 + .../Haskell/active-directory-connect.hs | 15 + .../Scala/active-directory-connect.scala | 18 + .../D/active-directory-search-for-a-user.d | 28 + .../active-directory-search-for-a-user.hs | 15 + Task/Active-object/D/active-object.d | 73 ++ Task/Active-object/Julia/active-object.julia | 40 + .../Active-object/Kotlin/active-object.kotlin | 69 ++ .../Active-object/Lingo/active-object-1.lingo | 41 + .../Active-object/Lingo/active-object-2.lingo | 19 + ...iable-to-a-class-instance-at-runtime.elena | 2 +- ...ble-to-a-class-instance-at-runtime-1.julia | 13 + ...ble-to-a-class-instance-at-runtime-2.julia | 7 + ...iable-to-a-class-instance-at-runtime.lingo | 9 + .../ARM-Assembly/address-of-a-variable.arm | 69 ++ .../Astro/address-of-a-variable.astro | 9 +- .../C/address-of-a-variable-2.c | 4 +- .../C/address-of-a-variable-3.c | 6 +- .../C/address-of-a-variable-4.c | 5 +- .../C/address-of-a-variable-5.c | 5 + .../C/address-of-a-variable-6.c | 2 + .../C/address-of-a-variable-7.c | 4 + .../Kotlin/address-of-a-variable.kotlin | 2 +- .../Oforth/address-of-a-variable.oforth | 14 + .../Stata/address-of-a-variable.stata | 8 + .../XLISP/address-of-a-variable.xlisp | 1 + Task/Align-columns/Aime/align-columns.aime | 52 +- Task/Align-columns/BaCon/align-columns.bacon | 34 + .../Align-columns/Oforth/align-columns.oforth | 28 +- Task/Align-columns/Perl-6/align-columns-1.pl6 | 59 +- Task/Align-columns/Perl-6/align-columns-2.pl6 | 20 +- .../00DESCRIPTION | 8 +- .../aliquot-sequence-classifications.alg | 106 +++ .../C/aliquot-sequence-classifications-1.c | 73 ++ .../C/aliquot-sequence-classifications-2.c | 103 +++ .../Go/aliquot-sequence-classifications.go | 109 +++ .../aliquot-sequence-classifications.oforth | 34 +- .../aliquot-sequence-classifications.rexx | 36 +- .../aliquot-sequence-classifications.ring | 81 ++ Task/Almost-prime/Factor/almost-prime.factor | 12 + .../GW-BASIC/almost-prime.gw-basic | 25 + Task/Almost-prime/Julia/almost-prime.julia | 15 +- Task/Almost-prime/Kotlin/almost-prime.kotlin | 4 +- Task/Almost-prime/Modula-2/almost-prime.mod2 | 46 + Task/Almost-prime/Oforth/almost-prime.oforth | 17 +- .../PureBasic/almost-prime.purebasic | 43 + Task/Amb/C-sharp/amb-3.cs | 101 +++ Task/Amb/C-sharp/amb-4.cs | 36 + Task/Amb/Elena/amb.elena | 28 +- Task/Amb/Julia/amb.julia | 92 +- Task/Amb/Kotlin/amb.kotlin | 131 ++- Task/Amb/Rust/amb.rust | 44 + Task/Amicable-pairs/Ada/amicable-pairs.ada | 32 + .../AppleScript/amicable-pairs-1.applescript | 76 +- .../Amicable-pairs/Elena/amicable-pairs.elena | 32 + .../Factor/amicable-pairs.factor | 16 + .../Julia/amicable-pairs-2.julia | 2 + .../Oforth/amicable-pairs.oforth | 14 +- Task/Amicable-pairs/R/amicable-pairs.r | 11 + Task/Amicable-pairs/VBA/amicable-pairs.vba | 38 + .../BaCon/anagrams-deranged-anagrams.bacon | 29 + .../Julia/anagrams-deranged-anagrams.julia | 62 +- .../REXX/anagrams-deranged-anagrams.rexx | 71 +- .../Ring/anagrams-deranged-anagrams.ring | 82 ++ Task/Anagrams/APL/anagrams-1.apl | 7 + Task/Anagrams/APL/anagrams-2.apl | 2 + Task/Anagrams/BaCon/anagrams.bacon | 20 + Task/Anagrams/Clojure/anagrams-2.clj | 3 +- Task/Anagrams/Elena/anagrams.elena | 11 +- Task/Anagrams/Julia/anagrams.julia | 21 +- Task/Anagrams/Oforth/anagrams.oforth | 12 +- Task/Anagrams/REXX/anagrams-1.rexx | 34 +- Task/Anagrams/REXX/anagrams-2.rexx | 49 +- Task/Anagrams/REXX/anagrams-3.rexx | 50 +- Task/Anagrams/REXX/anagrams-4.rexx | 17 +- Task/Anagrams/REXX/anagrams-5.rexx | 79 +- Task/Anagrams/Red/anagrams.red | 16 + Task/Anagrams/Ring/anagrams.ring | 83 ++ Task/Anagrams/Stata/anagrams.stata | 16 + Task/Anagrams/VBA/anagrams.vba | 162 ++++ .../BASIC/animate-a-pendulum-1.basic | 29 + .../BASIC/animate-a-pendulum-2.basic | 24 + .../BASIC/animate-a-pendulum-3.basic | 22 + .../JavaScript/animate-a-pendulum-2.js | 10 +- .../Julia/animate-a-pendulum.julia | 46 + .../Lingo/animate-a-pendulum.lingo | 43 + .../Ring/animate-a-pendulum.ring | 82 ++ Task/Animation/FreeBASIC/animation.freebasic | 17 +- Task/Animation/J/animation-1.j | 26 + .../J/{animation.j => animation-2.j} | 0 Task/Animation/Julia/animation-1.julia | 35 + Task/Animation/Julia/animation-2.julia | 35 + Task/Animation/Maple/animation-1.maple | 1 + Task/Animation/Maple/animation-2.maple | 1 + Task/Animation/Maple/animation-3.maple | 18 + Task/Animation/Python/animation-1.py | 81 +- Task/Animation/Python/animation-2.py | 68 +- Task/Animation/Python/animation-3.py | 23 + Task/Animation/Ring/animation.ring | 43 + .../AutoIt/anonymous-recursion.autoit | 15 + .../Elena/anonymous-recursion.elena | 7 +- .../Haskell/anonymous-recursion-4.hs | 23 + .../Klong/anonymous-recursion.klong | 1 + .../Ring/anonymous-recursion.ring | 40 + .../VBA/anonymous-recursion.vba | 14 + ...ppend-a-record-to-the-end-of-a-text-file.d | 93 ++ ...d-a-record-to-the-end-of-a-text-file.julia | 46 + ...-a-record-to-the-end-of-a-text-file.kotlin | 56 ++ ...end-a-record-to-the-end-of-a-text-file.pl6 | 66 ++ .../APL/apply-a-callback-to-an-array.apl | 10 + .../Aime/apply-a-callback-to-an-array.aime | 6 +- .../apply-a-callback-to-an-array.bracmat | 8 +- .../Elena/apply-a-callback-to-an-array.elena | 2 +- .../Julia/apply-a-callback-to-an-array.julia | 26 +- .../Stata/apply-a-callback-to-an-array.stata | 23 + .../VBA/apply-a-callback-to-an-array.vba | 21 + ...rbitrary-precision-integers--included-.cpp | 23 + ...trary-precision-integers--included-.ceylon | 25 + ...trary-precision-integers--included-.oforth | 4 +- ...trary-precision-integers--included--1.rexx | 6 +- ...trary-precision-integers--included--2.rexx | 10 +- ...arbitrary-precision-integers--included-.rb | 4 +- ...bitrary-precision-integers--included-.rust | 9 +- .../Julia/arena-storage-pool.julia | 3 + .../Kotlin/arena-storage-pool.kotlin | 2 +- .../Oforth/arithmetic-complex-1.oforth | 39 +- .../Oforth/arithmetic-complex-2.oforth | 8 +- .../APL/arithmetic-integer.apl | 4 + .../ARM-Assembly/arithmetic-integer.arm | 287 +++++++ .../Elena/arithmetic-integer.elena | 2 +- .../HolyC/arithmetic-integer.holyc | 14 + .../Java/arithmetic-integer.java | 16 +- ...tic-integer.js => arithmetic-integer-1.js} | 0 .../JavaScript/arithmetic-integer-2.js | 15 + .../Lingo/arithmetic-integer.lingo | 10 + .../Oforth/arithmetic-integer.oforth | 5 +- .../Factor/arithmetic-rational.factor | 21 + .../Groovy/arithmetic-rational-1.groovy | 37 +- .../Sidef/arithmetic-rational.sidef | 13 + .../Elena/arithmetic-evaluation.elena | 132 +-- .../Kotlin/arithmetic-evaluation.kotlin | 86 ++ .../Perl-6/arithmetic-evaluation.pl6 | 44 + ...rithmetic-geometric-mean-calculate-pi.java | 36 + ...ithmetic-geometric-mean-calculate-pi.julia | 42 +- ...ithmetic-geometric-mean-calculate-pi.scala | 36 + .../8th/arithmetic-geometric-mean.8th | 14 + .../arithmetic-geometric-mean.applescript | 26 +- .../BASIC/arithmetic-geometric-mean.basic | 10 + .../C/arithmetic-geometric-mean-1.c | 32 + ...c-mean.c => arithmetic-geometric-mean-2.c} | 0 .../Factor/arithmetic-geometric-mean.factor | 6 + .../Julia/arithmetic-geometric-mean.julia | 36 +- .../Oforth/arithmetic-geometric-mean-1.oforth | 3 +- .../Prolog/arithmetic-geometric-mean.pro | 5 + .../REXX/arithmetic-geometric-mean.rexx | 21 +- .../Aime/array-concatenation.aime | 12 +- ...nation.lisp => array-concatenation-1.lisp} | 0 .../Common-Lisp/array-concatenation-2.lisp | 13 + .../Elena/array-concatenation.elena | 2 +- .../Fortran/array-concatenation.f | 21 + .../Klong/array-concatenation.klong | 8 + .../Limbo/array-concatenation.limbo | 23 + .../Oforth/array-concatenation.oforth | 2 + .../Red/array-concatenation.red | 12 + ...catenation.ss => array-concatenation-1.ss} | 0 .../Scheme/array-concatenation-2.ss | 25 + .../Simula/array-concatenation.simula | 119 ++- .../VBA/array-concatenation.vba | 25 + Task/Arrays/Delphi/arrays.delphi | 30 +- Task/Arrays/Elena/arrays-3.elena | 2 +- Task/Arrays/Elena/arrays-4.elena | 6 +- Task/Arrays/HolyC/arrays-1.holyc | 8 + Task/Arrays/HolyC/arrays-2.holyc | 98 +++ Task/Arrays/HolyC/arrays-3.holyc | 3 + Task/Arrays/Oforth/arrays.oforth | 4 +- Task/Arrays/Pony/arrays.pony | 4 + Task/Arrays/Red/arrays-1.red | 14 + Task/Arrays/Red/arrays-2.red | 16 + Task/Assertions/Julia/assertions.julia | 23 +- .../AutoIt/associative-array-creation.autoit | 127 +++ .../Elena/associative-array-creation.elena | 2 +- .../Julia/associative-array-creation.julia | 43 +- .../Perl-6/associative-array-creation.pl6 | 28 + .../Ring/associative-array-creation.ring | 10 + .../associative-array-iteration-6.lisp | 14 + .../Elena/associative-array-iteration.elena | 4 +- .../Julia/associative-array-iteration.julia | 16 +- .../Perl-6/associative-array-iteration.pl6 | 5 + .../Ring/associative-array-iteration.ring | 9 + .../Common-Lisp/atomic-updates-1.lisp | 37 + .../Common-Lisp/atomic-updates-2.lisp | 10 + .../Atomic-updates/Julia/atomic-updates.julia | 60 ++ .../Kotlin/atomic-updates.kotlin | 84 ++ Task/Atomic-updates/PicoLisp/atomic-updates.l | 88 +- Task/Atomic-updates/Ring/atomic-updates.ring | 45 + .../C++/average-loop-length.cpp | 62 ++ .../Oberon-2/average-loop-length.oberon-2 | 71 ++ .../REXX/average-loop-length.rexx | 2 +- .../Aime/averages-arithmetic-mean.aime | 9 +- .../Astro/averages-arithmetic-mean.astro | 2 +- .../Elena/averages-arithmetic-mean.elena | 2 +- .../Limbo/averages-arithmetic-mean.limbo | 24 + .../Lingo/averages-arithmetic-mean-1.lingo | 14 + .../Lingo/averages-arithmetic-mean-2.lingo | 6 + .../Oforth/averages-arithmetic-mean.oforth | 6 +- .../Python/averages-arithmetic-mean-7.py | 10 + .../Ruby/averages-arithmetic-mean.rb | 2 +- .../JavaScript/averages-mean-angle.js | 13 +- .../Ring/averages-mean-angle.ring | 37 + .../Stata/averages-mean-angle.stata | 4 +- .../Java/averages-mean-time-of-day.java | 48 ++ .../Julia/averages-mean-time-of-day.julia | 18 + .../Lua/averages-mean-time-of-day.lua | 34 + .../BaCon/averages-median.bacon | 12 + .../Elena/averages-median.elena | 2 +- ...verages-median.go => averages-median-1.go} | 0 Task/Averages-Median/Go/averages-median-2.go | 31 + Task/Averages-Median/Go/averages-median-3.go | 52 ++ .../Lingo/averages-median.lingo | 9 + .../Averages-Median/REXX/averages-median.rexx | 25 +- Task/Averages-Mode/Elena/averages-mode.elena | 8 +- Task/Averages-Mode/Perl-6/averages-mode-1.pl6 | 4 + Task/Averages-Mode/Perl-6/averages-mode-2.pl6 | 9 + Task/Averages-Mode/Ring/averages-mode.ring | 45 + .../Modula-2/averages-pythagorean-means.mod2 | 79 ++ .../Oforth/averages-pythagorean-means.oforth | 20 +- .../Astro/averages-root-mean-square.astro | 2 +- .../Elena/averages-root-mean-square.elena | 16 + .../Shen/averages-root-mean-square.shen | 26 + ...idef => averages-root-mean-square-1.sidef} | 0 .../Sidef/averages-root-mean-square-2.sidef | 1 + .../Stata/averages-root-mean-square-1.stata | 7 + .../Stata/averages-root-mean-square-2.stata | 11 + .../averages-simple-moving-average.elena | 6 +- .../averages-simple-moving-average.julia | 22 + .../Perl-6/averages-simple-moving-average.pl6 | 14 + Task/Balanced-brackets/00DESCRIPTION | 11 +- .../ARM-Assembly/balanced-brackets.arm | 58 ++ ...ackets.basic => balanced-brackets-1.basic} | 0 .../BASIC/balanced-brackets-2.basic | 21 + .../Elena/balanced-brackets.elena | 11 +- .../Julia/balanced-brackets-1.julia | 20 +- .../Julia/balanced-brackets-2.julia | 2 +- .../Perl-6/balanced-brackets-2.pl6 | 2 +- ...ced-brackets.py => balanced-brackets-1.py} | 0 .../Python/balanced-brackets-2.py | 24 + .../Python/balanced-brackets-3.py | 25 + .../Balanced-brackets/R/balanced-brackets-3.r | 2 +- .../Red/balanced-brackets.red | 22 + .../Stata/balanced-brackets.stata | 12 + .../balanced-brackets.visual | 44 + .../X86-Assembly/balanced-brackets.x86 | 66 ++ Task/Balanced-ternary/00DESCRIPTION | 15 +- .../Julia/balanced-ternary.julia | 85 ++ .../REXX/balanced-ternary.rexx | 100 ++- Task/Benfords-law/8th/benfords-law.8th | 4 +- Task/Benfords-law/Aime/benfords-law.aime | 25 +- Task/Benfords-law/Factor/benfords-law.factor | 29 + Task/Benfords-law/REXX/benfords-law.rexx | 56 +- Task/Benfords-law/Ring/benfords-law.ring | 36 + Task/Bernoulli-numbers/00DESCRIPTION | 2 +- .../C++/bernoulli-numbers.cpp | 39 + .../Crystal/bernoulli-numbers.crystal | 73 +- .../Perl-6/bernoulli-numbers-3.pl6 | 7 + .../REXX/bernoulli-numbers.rexx | 9 +- .../bernoulli-numbers.visual | 2 +- .../Common-Lisp/best-shuffle-3.lisp | 6 + Task/Best-shuffle/Elena/best-shuffle.elena | 11 +- Task/Best-shuffle/REXX/best-shuffle.rexx | 30 + Task/Best-shuffle/Ring/best-shuffle-1.ring | 36 + Task/Best-shuffle/Ring/best-shuffle-2.ring | 36 + Task/Best-shuffle/Ring/best-shuffle-3.ring | 25 + Task/Best-shuffle/Ring/best-shuffle-4.ring | 135 +++ Task/Best-shuffle/VBA/best-shuffle.vba | 94 ++ .../Binary-digits/Ceylon/binary-digits.ceylon | 9 + Task/Binary-digits/Elena/binary-digits.elena | 4 +- Task/Binary-digits/Julia/binary-digits.julia | 10 +- .../PowerBASIC/binary-digits.powerbasic | 12 + Task/Binary-digits/Red/binary-digits.red | 7 + Task/Binary-digits/VBA/binary-digits.vba | 38 + .../Visual-Basic/binary-digits.vb | 34 + Task/Binary-search/C++/binary-search-1.cpp | 28 +- .../Binary-search/Julia/binary-search-1.julia | 20 +- .../Binary-search/Julia/binary-search-2.julia | 26 +- Task/Binary-search/N-t-roff/binary-search.n | 38 + ...inary-search.pari => binary-search-1.pari} | 0 .../PARI-GP/binary-search-2.pari | 24 + Task/Binary-search/Rust/binary-search-1.rust | 3 + Task/Binary-search/Rust/binary-search-2.rust | 18 + Task/Binary-search/Rust/binary-search.rust | 17 - .../Binary-strings/Java/binary-strings-1.java | 118 +++ .../Binary-strings/Java/binary-strings-2.java | 60 ++ .../Binary-strings/Lingo/binary-strings.lingo | 60 ++ Task/Binary-strings/Perl-6/binary-strings.pl6 | 2 +- Task/Binary-strings/Red/binary-strings.red | 18 + Task/Binary-strings/Rust/binary-strings.rust | 73 +- Task/Binary-strings/VBA/binary-strings-1.vba | 4 + Task/Binary-strings/VBA/binary-strings-10.vba | 9 + Task/Binary-strings/VBA/binary-strings-2.vba | 5 + Task/Binary-strings/VBA/binary-strings-3.vba | 9 + Task/Binary-strings/VBA/binary-strings-4.vba | 28 + Task/Binary-strings/VBA/binary-strings-5.vba | 6 + Task/Binary-strings/VBA/binary-strings-6.vba | 23 + Task/Binary-strings/VBA/binary-strings-7.vba | 5 + Task/Binary-strings/VBA/binary-strings-8.vba | 6 + Task/Binary-strings/VBA/binary-strings-9.vba | 7 + Task/Bitcoin-address-validation/00DESCRIPTION | 22 +- .../Delphi/bitcoin-address-validation.delphi | 64 ++ .../Haskell/bitcoin-address-validation.hs | 71 +- .../Java/bitcoin-address-validation.java | 20 +- .../Julia/bitcoin-address-validation.julia | 38 + .../Python/bitcoin-address-validation-1.py | 7 +- .../Scala/bitcoin-address-validation.scala | 67 ++ .../bitcoin-public-point-to-address-1.julia | 28 + .../bitcoin-public-point-to-address-2.julia | 3 + .../bitcoin-public-point-to-address.pl6 | 3 +- .../Julia/bitmap-b-zier-curves-cubic.julia | 20 + .../Kotlin/bitmap-b-zier-curves-cubic.kotlin | 77 ++ .../Perl-6/bitmap-b-zier-curves-cubic.pl6 | 99 +++ .../bitmap-b-zier-curves-quadratic.kotlin | 75 ++ .../Perl-6/bitmap-b-zier-curves-quadratic.pl6 | 99 +++ .../00DESCRIPTION | 2 +- .../bitmap-bresenhams-line-algorithm.java | 118 +-- .../bitmap-bresenhams-line-algorithm.julia | 44 +- .../bitmap-bresenhams-line-algorithm.pl6 | 22 + .../Julia/bitmap-flood-fill.julia | 46 + .../Java/bitmap-histogram.java | 206 ++--- .../Julia/bitmap-histogram.julia | 20 +- .../Kotlin/bitmap-histogram.kotlin | 61 ++ .../Perl-6/bitmap-histogram.pl6 | 52 ++ .../bitmap-midpoint-circle-algorithm.julia | 31 + .../bitmap-midpoint-circle-algorithm-1.pl6 | 25 +- ...bitmap-ppm-conversion-through-a-pipe.julia | 4 + ...itmap-ppm-conversion-through-a-pipe.kotlin | 56 ++ .../Erlang/bitmap-read-a-ppm-file-1.erl | 102 +++ .../Erlang/bitmap-read-a-ppm-file-2.erl | 3 + .../Julia/bitmap-read-a-ppm-file.julia | 16 +- .../Kotlin/bitmap-read-a-ppm-file.kotlin | 130 +++ .../Perl-6/bitmap-read-a-ppm-file.pl6 | 36 + .../REXX/bitmap-read-a-ppm-file.rexx | 36 + .../bitmap-read-an-image-through-a-pipe.julia | 4 + ...bitmap-read-an-image-through-a-pipe.kotlin | 135 +++ .../bitmap-read-an-image-through-a-pipe.pl6 | 33 + .../Erlang/bitmap-write-a-ppm-file.erl | 45 + .../Julia/bitmap-write-a-ppm-file.julia | 11 + .../Kotlin/bitmap-write-a-ppm-file.kotlin | 52 ++ .../REXX/bitmap-write-a-ppm-file.rexx | 38 +- Task/Bitmap/Java/bitmap-1.java | 45 +- Task/Bitmap/Java/bitmap-2.java | 31 +- Task/Bitmap/Julia/bitmap.julia | 24 + Task/Bitmap/Maple/bitmap.maple | 23 + Task/Bitmap/Perl-6/bitmap.pl6 | 2 +- Task/Bitmap/REXX/bitmap-1.rexx | 58 +- Task/Bitwise-IO/Kotlin/bitwise-io.kotlin | 84 ++ Task/Bitwise-IO/Python/bitwise-io-1.py | 40 +- Task/Bitwise-IO/Python/bitwise-io-2.py | 1 + .../Befunge/bitwise-operations.bf | 21 + .../Elena/bitwise-operations.elena | 2 +- Task/Boolean-values/APL/boolean-values.apl | 4 + .../Befunge/box-the-compass.bf | 15 + .../Julia/box-the-compass.julia | 13 +- .../Modula-2/box-the-compass.mod2 | 82 ++ .../Box-the-compass/Ring/box-the-compass.ring | 32 + .../OCaml/break-oo-privacy.ocaml | 33 + Task/Brownian-tree/Julia/brownian-tree.julia | 71 +- Task/Brownian-tree/Perl-6/brownian-tree.pl6 | 5 - Task/Brownian-tree/Ring/brownian-tree.ring | 102 +++ Task/Brownian-tree/Sidef/brownian-tree.sidef | 78 ++ .../Julia/bulls-and-cows-player-1.julia | 28 + .../Julia/bulls-and-cows-player-2.julia | 15 + .../Perl-6/bulls-and-cows-player.pl6 | 2 +- .../REXX/bulls-and-cows-player.rexx | 94 +- .../Ring/bulls-and-cows-player.ring | 75 ++ .../VBA/bulls-and-cows-player.vba | 105 +++ .../Ceylon/bulls-and-cows.ceylon | 128 +-- .../Bulls-and-cows/Elena/bulls-and-cows.elena | 14 +- .../Bulls-and-cows/REXX/bulls-and-cows-1.rexx | 33 +- Task/Bulls-and-cows/Ring/bulls-and-cows.ring | 42 + Task/Bulls-and-cows/VBA/bulls-and-cows.vba | 73 ++ Task/CRC-32/Julia/crc-32.julia | 29 +- .../Factor/csv-data-manipulation.factor | 10 + .../Perl-6/csv-data-manipulation-1.pl6 | 2 +- .../Perl-6/csv-data-manipulation-2.pl6 | 4 +- .../Red/csv-data-manipulation-1.red | 4 + .../Red/csv-data-manipulation-2.red | 6 + .../Red/csv-data-manipulation-3.red | 8 + .../Stata/csv-data-manipulation.stata | 4 +- .../Factor/csv-to-html-translation-1.factor | 31 + .../Factor/csv-to-html-translation-2.factor | 8 + .../Forth/csv-to-html-translation-1.fth | 22 + .../Forth/csv-to-html-translation-2.fth | 8 + .../Go/csv-to-html-translation-1.go | 3 +- .../Go/csv-to-html-translation-2.go | 3 +- .../Maple/csv-to-html-translation.maple | 28 + .../Red/csv-to-html-translation.red | 39 + .../Applesoft-BASIC/caesar-cipher.applesoft | 42 + Task/Caesar-cipher/Astro/caesar-cipher.astro | 4 +- .../Caesar-cipher/COBOL/caesar-cipher-1.cobol | 37 + ...sar-cipher.cobol => caesar-cipher-2.cobol} | 0 ...{caesar-cipher.clj => caesar-cipher-1.clj} | 0 .../Caesar-cipher/Clojure/caesar-cipher-2.clj | 7 + .../Crystal/caesar-cipher.crystal | 11 + Task/Caesar-cipher/Elena/caesar-cipher.elena | 13 +- .../Caesar-cipher/Factor/caesar-cipher.factor | 18 + .../JavaScript/caesar-cipher-1.js | 2 +- .../JavaScript/caesar-cipher-2.js | 2 +- Task/Caesar-cipher/Julia/caesar-cipher.julia | 23 +- .../Caesar-cipher/Modula-2/caesar-cipher.mod2 | 77 ++ Task/Caesar-cipher/Ring/caesar-cipher.ring | 60 ++ Task/Caesar-cipher/Stata/caesar-cipher.stata | 11 + Task/Caesar-cipher/VBA/caesar-cipher.vba | 34 + .../calendar---for-real-programmers.bacon | 33 + .../calendar---for-real-programmers.elena | 51 +- .../calendar---for-real-programmers-1.icon | 19 +- .../calendar---for-real-programmers-2.icon | 2 + .../Python/calendar---for-real-programmers.py | 2 +- .../calendar---for-real-programmers.sh | 1 + Task/Calendar/BaCon/calendar.bacon | 33 + Task/Calendar/Go/calendar.go | 71 ++ Task/Calendar/Icon/calendar.icon | 21 +- Task/Calendar/PowerShell/calendar.psh | 36 + Task/Calendar/Ring/calendar.ring | 159 ++++ .../call-a-foreign-language-function-1.julia | 3 + .../call-a-foreign-language-function-2.julia | 3 + .../call-a-foreign-language-function.julia | 7 - .../call-a-foreign-language-function.scala | 7 + ...ll-a-function-in-a-shared-library-1.kotlin | 8 + ...ll-a-function-in-a-shared-library-2.kotlin | 34 + .../call-a-function-in-a-shared-library.pl6 | 4 +- ... call-a-function-in-a-shared-library-1.py} | 0 .../call-a-function-in-a-shared-library-2.py | 7 + .../call-a-function-in-a-shared-library-3.py | 10 + .../ARM-Assembly/call-a-function.arm | 171 ++++ .../Elena/call-a-function-1.elena | 2 + .../Elena/call-a-function-2.elena | 1 + .../Elena/call-a-function-3.elena | 1 + .../Elena/call-a-function-4.elena | 3 + .../Factor/call-a-function-1.factor | 1 + .../Factor/call-a-function-2.factor | 1 + .../Factor/call-a-function-3.factor | 2 + .../Factor/call-a-function-4.factor | 6 + .../Factor/call-a-function-5.factor | 1 + .../Factor/call-a-function-6.factor | 1 + .../Factor/call-a-function-7.factor | 1 + .../Factor/call-a-function-8.factor | 1 + .../Factor/call-a-function-9.factor | 2 + .../Fortress/call-a-function.fortress | 38 + .../Julia/call-a-function.julia | 90 ++ .../C++/call-an-object-method.cpp | 3 + .../Elena/call-an-object-method.elena | 1 + .../VBA/call-an-object-method-1.vba | 13 + .../VBA/call-an-object-method-2.vba | 9 + .../Julia/canny-edge-detector.julia | 3 + .../Go/carmichael-3-strong-pseudoprimes.go | 48 ++ .../J/carmichael-3-strong-pseudoprimes.j | 6 + .../carmichael-3-strong-pseudoprimes-1.julia | 24 +- .../carmichael-3-strong-pseudoprimes-2.julia | 13 +- .../carmichael-3-strong-pseudoprimes.rexx | 39 + .../carmichael-3-strong-pseudoprimes.ring | 46 + .../case-sensitivity-of-identifiers.elena | 2 +- .../case-sensitivity-of-identifiers.factor | 8 + .../case-sensitivity-of-identifiers.julia | 6 +- .../Ring/casting-out-nines.ring | 40 + .../Sidef/casting-out-nines.sidef | 23 + .../00DESCRIPTION | 5 +- .../catalan-numbers-pascals-triangle.factor | 14 + .../Go/catalan-numbers-pascals-triangle.go | 18 + .../catalan-numbers-pascals-triangle.ocaml | 12 + .../catalan-numbers-pascals-triangle.oforth | 9 +- .../catalan-numbers-pascals-triangle.scala | 5 + .../360-Assembly/catalan-numbers.360 | 2 +- .../BBC-BASIC/catalan-numbers.bbc | 15 +- .../Julia/catalan-numbers.julia | 5 +- .../Catalan-numbers/Logo/catalan-numbers.logo | 11 + .../MATLAB/catalan-numbers-1.m | 2 +- .../MATLAB/catalan-numbers-2.m | 2 +- .../MATLAB/catalan-numbers-3.m | 4 +- .../Modula-2/catalan-numbers.mod2 | 65 ++ .../OCaml/catalan-numbers.ocaml | 66 +- .../Oforth/catalan-numbers.oforth | 3 +- .../Perl-6/catalan-numbers-2.pl6 | 4 + Task/Catalan-numbers/R/catalan-numbers.r | 6 +- .../Scala/catalan-numbers.scala | 2 +- .../Stata/catalan-numbers.stata | 5 + Task/Catamorphism/Elena/catamorphism.elena | 4 +- Task/Catamorphism/Factor/catamorphism.factor | 1 + Task/Catamorphism/Fortran/catamorphism-1.f | 9 + Task/Catamorphism/Fortran/catamorphism-2.f | 53 ++ Task/Catamorphism/J/catamorphism-3.j | 4 + Task/Catamorphism/Perl-6/catamorphism-2.pl6 | 1 + Task/Catamorphism/Python/catamorphism-1.py | 1 + Task/Catamorphism/Python/catamorphism-2.py | 2 + Task/Catamorphism/R/catamorphism-1.r | 2 + Task/Catamorphism/R/catamorphism-2.r | 2 + Task/Catamorphism/R/catamorphism-3.r | 2 + Task/Catamorphism/R/catamorphism-4.r | 3 + Task/Catamorphism/REXX/catamorphism.rexx | 46 +- Task/Catamorphism/Scala/catamorphism.scala | 9 + Task/Catamorphism/Swift/catamorphism.swift | 5 + .../catmull-clark-subdivision-surface.hs | 311 +++++++ .../BASIC/character-codes-5.basic | 4 + .../BASIC/character-codes-6.basic | 4 + .../Elena/character-codes.elena | 2 +- .../HolyC/character-codes.holyc | 2 + .../Julia/character-codes.julia | 4 +- Task/Character-codes/Red/character-codes.red | 5 + .../Stata/character-codes-1.stata | 5 + .../Stata/character-codes-2.stata | 5 + .../Stata/character-codes-3.stata | 2 + Task/Chat-server/Julia/chat-server.julia | 82 ++ Task/Chat-server/Perl-6/chat-server.pl6 | 6 + .../Perl-6/check-machin-like-formulas.pl6 | 42 + .../Elena/check-that-file-exists.elena | 2 +- .../HolyC/check-that-file-exists.holyc | 20 + .../Julia/check-that-file-exists.julia | 10 +- .../PicoLisp/check-that-file-exists.l | 17 + .../Red/check-that-file-exists.red | 9 + .../Stata/check-that-file-exists-3.stata | 2 +- .../VBA/check-that-file-exists.vba | 18 + .../VBScript/check-that-file-exists.vb | 51 +- .../Visual-Basic/check-that-file-exists.vb | 16 + .../Go/checkpoint-synchronization-1.go | 34 + .../Go/checkpoint-synchronization-2.go | 40 + .../Go/checkpoint-synchronization-3.go | 64 ++ ...ion.go => checkpoint-synchronization-4.go} | 0 .../Kotlin/checkpoint-synchronization.kotlin | 60 ++ .../Factor/chinese-remainder-theorem.factor | 2 + .../Julia/chinese-remainder-theorem.julia | 26 + .../Sidef/chinese-remainder-theorem.sidef | 18 +- .../Go/cholesky-decomposition-3.go | 8 +- ...ion.math => cholesky-decomposition-1.math} | 0 .../Mathematica/cholesky-decomposition-2.math | 6 + .../REXX/cholesky-decomposition.rexx | 68 +- .../Ring/cholesky-decomposition.ring | 45 + .../Scilab/cholesky-decomposition.scilab | 19 + .../00DESCRIPTION | 9 +- ...es-of-given-radius-through-two-points-1.f} | 17 +- ...les-of-given-radius-through-two-points-2.f | 63 ++ ...es-of-given-radius-through-two-points.java | 86 ++ ...-of-given-radius-through-two-points.kotlin | 64 ++ ...es-of-given-radius-through-two-points.mod2 | 118 +++ ...es-of-given-radius-through-two-points.rexx | 15 +- ...es-of-given-radius-through-two-points.ring | 70 ++ ...s-of-given-radius-through-two-points.sidef | 35 + ...of-given-radius-through-two-points-1.stata | 19 + ...of-given-radius-through-two-points-2.stata | 38 + Task/Classes/Elena/classes.elena | 2 +- Task/Classes/Julia/classes.julia | 20 + Task/Classes/Processing/classes-1 | 17 + Task/Classes/Processing/classes-2 | 5 + .../C++/closest-pair-problem.cpp | 2 +- .../Maple/closest-pair-problem-1.maple | 70 ++ .../Maple/closest-pair-problem-2.maple | 3 + .../Prolog/closest-pair-problem-1.pro | 30 + .../Prolog/closest-pair-problem-2.pro | 12 + .../REXX/closest-pair-problem.rexx | 48 +- .../Racket/closest-pair-problem-2.rkt | 99 ++- .../Racket/closest-pair-problem-3.rkt | 4 + .../VBA/closest-pair-problem.vba | 53 ++ .../Elena/closures-value-capture.elena | 6 +- .../R/closures-value-capture-4.r | 1 + .../R/closures-value-capture-5.r | 1 + .../REXX/closures-value-capture.rexx | 32 +- .../Red/closures-value-capture.red | 4 + Task/Collections/Elena/collections-1.elena | 8 +- Task/Collections/Elena/collections-2.elena | 4 +- Task/Collections/Elena/collections-3.elena | 2 +- Task/Collections/Gambas/collections.gambas | 10 + Task/Collections/Julia/collections.julia | 9 + Task/Collections/Perl-6/collections-4.pl6 | 1 + .../BaCon/color-of-a-screen-pixel.bacon | 4 + .../REXX/color-of-a-screen-pixel.rexx | 21 + .../VBA/color-of-a-screen-pixel.vba | 23 + .../Kotlin/color-quantization.kotlin | 41 + .../Sidef/color-quantization.sidef | 10 + .../Julia/colour-bars-display.julia | 11 + .../Python/colour-pinstripe-display.py | 34 + .../Ring/colour-pinstripe-display.ring | 66 ++ .../Sidef/colour-pinstripe-display.sidef | 30 + .../combinations-and-permutations.lisp | 21 +- .../Go/combinations-and-permutations.go | 64 ++ .../Stata/combinations-and-permutations.stata | 7 + .../combinations-with-repetitions.lisp | 8 + .../Julia/combinations-with-repetitions.julia | 11 +- .../REXX/combinations-with-repetitions-1.rexx | 25 +- .../Ring/combinations-with-repetitions.ring | 66 ++ .../Stata/combinations-with-repetitions.stata | 19 + .../Common-Lisp/combinations-1.lisp | 2 +- Task/Combinations/Elena/combinations.elena | 8 +- Task/Combinations/Glee/combinations-1.glee | 5 + Task/Combinations/Glee/combinations-2.glee | 11 + ...ombinations.julia => combinations-1.julia} | 0 Task/Combinations/Julia/combinations-2.julia | 27 + Task/Combinations/Modula-2/combinations.mod2 | 36 + Task/Combinations/PHP/combinations-1.php | 3 +- Task/Combinations/Ring/combinations.ring | 75 ++ Task/Combinations/Scala/combinations-4.scala | 4 +- Task/Combinations/Stata/combinations-3.stata | 14 + Task/Combinations/VBA/combinations.vba | 64 ++ .../Astro/comma-quibbling.astro | 15 +- .../Factor/comma-quibbling.factor | 20 + .../Julia/comma-quibbling.julia | 14 +- .../OCaml/comma-quibbling-1.ocaml | 17 + .../OCaml/comma-quibbling-2.ocaml | 15 + .../Comma-quibbling/Ring/comma-quibbling.ring | 44 + Task/Comma-quibbling/VBA/comma-quibbling.vba | 16 + .../Elena/command-line-arguments.elena | 6 +- .../JavaScript/command-line-arguments-1.js | 6 +- .../JavaScript/command-line-arguments-2.js | 7 +- .../JavaScript/command-line-arguments-3.js | 6 +- .../JavaScript/command-line-arguments-4.js | 2 + .../Klong/command-line-arguments.klong | 1 + Task/Comments/ARM-Assembly/comments.arm | 8 + Task/Comments/Nim/comments.nim | 19 +- Task/Comments/Simula/comments-3.simula | 1 + ...pare-sorting-algorithms-performance.kotlin | 142 ++++ .../Scala/compile-time-calculation.scala | 7 + .../Elena/compound-data-type.elena | 12 + .../Julia/compound-data-type-1.julia | 2 +- .../Julia/compound-data-type-2.julia | 8 +- .../Julia/compound-data-type-3.julia | 22 +- .../Scala/compound-data-type.scala | 4 +- .../Astro/concurrent-computing.astro | 17 +- .../Go/concurrent-computing-1.go | 13 +- .../Julia/concurrent-computing.julia | 10 + .../Astro/conditional-structures.astro | 22 +- .../BASIC256/conditional-structures.basic256 | 19 + .../JCL/conditional-structures-1.jcl | 2 + .../JCL/conditional-structures-2.jcl | 1 + .../JCL/conditional-structures-3.jcl | 1 + .../JCL/conditional-structures-4.jcl | 1 + .../JCL/conditional-structures-5.jcl | 1 + .../JCL/conditional-structures-6.jcl | 1 + .../Julia/conditional-structures-1.julia | 18 + .../Julia/conditional-structures-2.julia | 1 + .../Perl-6/conditional-structures-2.pl6 | 2 +- .../Red/conditional-structures-1.red | 2 + .../Red/conditional-structures-2.red | 2 + .../Red/conditional-structures-3.red | 22 + .../Red/conditional-structures-4.red | 17 + .../Rust/conditional-structures-3.rust | 14 +- .../Rust/conditional-structures-4.rust | 2 +- .../Rust/conditional-structures-5.rust | 4 +- .../Stata/conditional-structures-1.stata | 11 + .../Stata/conditional-structures-2.stata | 34 + .../Stata/conditional-structures-3.stata | 6 + .../Stata/conditional-structures-4.stata | 13 + .../Stata/conditional-structures-5.stata | 6 + .../VBA/conditional-structures-1.vba | 25 + .../VBA/conditional-structures-2.vba | 16 + .../VBA/conditional-structures-3.vba | 52 ++ .../VBA/conditional-structures-4.vba | 6 + .../VBA/conditional-structures-5.vba | 6 + .../Visual-Basic/conditional-structures-1.vb | 20 + .../Visual-Basic/conditional-structures-2.vb | 3 + .../Visual-Basic/conditional-structures-3.vb | 19 + .../Visual-Basic/conditional-structures-4.vb | 1 + .../Visual-Basic/conditional-structures-5.vb | 3 + .../Visual-Basic/conditional-structures-6.vb | 1 + .../Visual-Basic/conditional-structures-7.vb | 3 + .../Julia/constrained-genericity.julia | 19 + .../Nim/constrained-genericity.nim | 2 +- ...onstrained-random-points-on-a-circle.cobol | 113 +++ ...onstrained-random-points-on-a-circle.julia | 33 +- ...constrained-random-points-on-a-circle.rust | 73 ++ ...rithmetic-construct-from-rational-number.d | 72 ++ ...hmetic-construct-from-rational-number.java | 77 ++ ...metic-construct-from-rational-number.julia | 98 +-- ...hmetic-construct-from-rational-number.mod2 | 76 ++ ...etic-g-matrix-ng,-contined-fraction-n-.pl6 | 75 ++ ...-fraction-n1,-contined-fraction-n2-.kotlin | 216 +++++ ...ned-fraction-n1,-contined-fraction-n2-.pl6 | 114 +++ .../Julia/continued-fraction.julia | 36 + .../Ring/continued-fraction.ring | 21 + .../Scheme/continued-fraction-1.ss | 50 ++ .../Scheme/continued-fraction-2.ss | 6 + .../convert-decimal-number-to-rational.factor | 2 + .../convert-decimal-number-to-rational.rust | 58 ++ .../Elena/conways-game-of-life.elena | 26 +- .../Fortran/conways-game-of-life.f | 32 +- .../Kotlin/conways-game-of-life.kotlin | 111 +++ .../Nim/conways-game-of-life.nim | 18 +- .../Python/conways-game-of-life-3.py | 62 ++ ...opy-a-string.abap => copy-a-string-1.abap} | 0 Task/Copy-a-string/ABAP/copy-a-string-2.abap | 2 + .../Crystal/copy-a-string.crystal | 2 + .../NewLISP/copy-a-string.newlisp | 12 + Task/Copy-a-string/Nim/copy-a-string.nim | 2 +- Task/Copy-a-string/Perl-6/copy-a-string-3.pl6 | 18 +- .../Factor/count-in-factors.factor | 2 + .../Julia/count-in-factors.julia | 27 +- .../Factor/count-in-octal.factor | 2 + .../count-occurrences-of-a-substring.pl6 | 8 +- .../Red/count-occurrences-of-a-substring.red | 25 + .../count-occurrences-of-a-substring.stata | 14 + .../Perl-6/count-the-coins.pl6 | 30 + .../Count-the-coins/Rust/count-the-coins.rust | 2 +- .../00DESCRIPTION | 1 - .../C/create-a-file-on-magnetic-tape.c | 21 + .../D/create-a-file-on-magnetic-tape.d | 10 + .../Haskell/create-a-file-on-magnetic-tape.hs | 4 + .../Ring/create-a-file-on-magnetic-tape.ring | 10 + .../Create-a-file/Gambas/create-a-file.gambas | 13 +- ...e-a-two-dimensional-array-at-runtime-1.cpp | 2 - ...e-a-two-dimensional-array-at-runtime-2.cpp | 2 - ...e-a-two-dimensional-array-at-runtime-3.cpp | 2 +- ...e-a-two-dimensional-array-at-runtime.julia | 50 +- ...te-a-two-dimensional-array-at-runtime.rust | 21 +- ...-two-dimensional-array-at-runtime.sinclair | 14 + ...a-two-dimensional-array-at-runtime-2.stata | 6 +- ...ate-a-two-dimensional-array-at-runtime.vba | 19 + .../Julia/create-an-html-table-1.julia | 13 + .../Julia/create-an-html-table-2.julia | 11 + .../Rust/create-an-html-table-1.rust | 17 +- .../create-an-object-at-a-given-address.julia | 13 + Task/Currying/00DESCRIPTION | 6 +- Task/Currying/C/currying.c | 32 + Task/Currying/Ceylon/currying.ceylon | 10 + Task/Currying/Factor/currying-1.factor | 8 + Task/Currying/Factor/currying-2.factor | 9 + Task/Currying/Factor/currying-3.factor | 4 + Task/Currying/Factor/currying-4.factor | 5 + Task/Currying/Factor/currying-5.factor | 4 + Task/Currying/Python/currying-3.py | 10 + Task/Currying/Python/currying-4.py | 13 + Task/Currying/Rust/currying.rust | 1 - .../Perl-6/cut-a-rectangle.pl6 | 2 +- Task/DNS-query/Crystal/dns-query.crystal | 9 + Task/DNS-query/Objeck/dns-query.objeck | 10 + Task/Date-format/Julia/date-format.julia | 6 +- Task/Date-manipulation/D/date-manipulation.d | 30 + .../Julia/date-manipulation.julia | 12 + .../Maple/date-manipulation-1.maple | 15 + .../Maple/date-manipulation-2.maple | 3 + .../Red/date-manipulation.red | 6 + .../Ring/date-manipulation.ring | 29 + Task/Day-of-the-week/00DESCRIPTION | 2 + .../Julia/day-of-the-week.julia | 19 +- .../Maple/day-of-the-week.maple | 11 + Task/Day-of-the-week/Red/day-of-the-week.red | 15 + .../Day-of-the-week/Rust/day-of-the-week.rust | 8 + .../Stata/day-of-the-week.stata | 49 +- Task/Day-of-the-week/VBA/day-of-the-week.vba | 13 + .../Groovy/deal-cards-for-freecell.groovy | 41 + .../Objeck/deal-cards-for-freecell.objeck | 70 ++ .../REXX/deal-cards-for-freecell.rexx | 19 +- .../Rust/deal-cards-for-freecell.rust | 79 +- Task/Death-Star/00DESCRIPTION | 2 + Task/Death-Star/Perl-6/death-star.pl6 | 2 +- .../Deconvolution-1D/Go/deconvolution-1d-3.go | 36 + .../Haskell/deconvolution-1d.hs | 43 + .../Julia/deconvolution-1d.julia | 9 + .../Perl-6/deconvolution-1d.pl6 | 16 +- .../REXX/deconvolution-1d.rexx | 37 + .../Perl-6/deconvolution-2d+.pl6 | 141 +++ Task/Deepcopy/C/deepcopy-1.c | 49 ++ Task/Deepcopy/C/deepcopy-2.c | 92 ++ Task/Deepcopy/Kotlin/deepcopy.kotlin | 71 ++ Task/Deepcopy/Rust/deepcopy.rust | 17 +- .../Elena/define-a-primitive-data-type.elena | 11 +- .../Go/define-a-primitive-data-type.go | 56 ++ .../Julia/define-a-primitive-data-type.julia | 24 + .../Nim/define-a-primitive-data-type.nim | 9 +- Task/Delegates/Clojure/delegates.clj | 13 + Task/Delegates/Julia/delegates-1.julia | 15 + Task/Delegates/Julia/delegates-2.julia | 11 + Task/Delegates/Kotlin/delegates.kotlin | 25 + Task/Delegates/Sidef/delegates.sidef | 25 + Task/Delete-a-file/VBA/delete-a-file.vba | 10 + .../HolyC/detect-division-by-zero.holyc | 5 + .../Julia/detect-division-by-zero.julia | 15 +- .../Rust/detect-division-by-zero.rust | 11 + .../VBA/detect-division-by-zero.vba | 14 + .../determine-if-a-string-is-numeric.bf | 10 + .../determine-if-a-string-is-numeric.julia | 22 +- .../determine-if-a-string-is-numeric.pl6 | 17 +- .../VBA/determine-if-a-string-is-numeric.vba | 16 + ...ermine-if-only-one-instance-is-running.pl6 | 2 +- ...al-root-multiplicative-digital-root.factor | 31 + ...ital-root-multiplicative-digital-root.ring | 63 ++ Task/Digital-root/Elena/digital-root.elena | 30 + Task/Digital-root/Factor/digital-root.factor | 13 + Task/Digital-root/Julia/digital-root.julia | 15 +- Task/Digital-root/Modula-2/digital-root.mod2 | 51 ++ Task/Digital-root/UNIX-Shell/digital-root.sh | 15 + ...inesmans-multiple-dwelling-problem.bracmat | 2 +- ... dinesmans-multiple-dwelling-problem-1.cs} | 0 .../dinesmans-multiple-dwelling-problem-2.cs | 39 + .../dinesmans-multiple-dwelling-problem.julia | 23 + .../K/dinesmans-multiple-dwelling-problem.k | 12 + .../dinesmans-multiple-dwelling-problem.lua | 63 ++ .../R/dinesmans-multiple-dwelling-problem-1.r | 16 + .../R/dinesmans-multiple-dwelling-problem-2.r | 7 + .../dinesmans-multiple-dwelling-problem-4.rb | 11 + ...ophers.lisp => dining-philosophers-1.lisp} | 0 .../Common-Lisp/dining-philosophers-2.lisp | 49 ++ .../Common-Lisp/dining-philosophers-3.lisp | 44 + .../Julia/dining-philosophers.julia | 83 ++ .../Kotlin/dining-philosophers.kotlin | 58 ++ .../REXX/dining-philosophers.rexx | 96 +-- .../Julia/discordian-date.julia | 37 +- .../Discordian-date/Rust/discordian-date.rust | 71 ++ .../Perl-6/distributed-programming-1.pl6 | 36 + .../Perl-6/distributed-programming-2.pl6 | 29 + Task/Documentation/Forth/documentation-1.fth | 1 + Task/Documentation/Forth/documentation-2.fth | 1 + .../Documentation/Kotlin/documentation.kotlin | 19 + Task/Documentation/Stata/documentation.stata | 3 + Task/Dot-product/Aime/dot-product.aime | 8 +- Task/Dot-product/BASIC/dot-product-1.basic | 20 + Task/Dot-product/BASIC/dot-product-2.basic | 7 + Task/Dot-product/Elena/dot-product.elena | 13 + Task/Dot-product/Fortran/dot-product.f | 2 +- Task/Dot-product/Modula-2/dot-product.mod2 | 25 + .../Ring/doubly-linked-list-definition.ring | 19 + ...oubly-linked-list-element-definition.julia | 8 + .../doubly-linked-list-element-definition.l | 12 +- .../doubly-linked-list-element-insertion.pl6 | 47 + .../Ring/doubly-linked-list-traversal.ring | 14 + Task/Dragon-curve/Julia/dragon-curve.julia | 18 + Task/Dragon-curve/Perl-6/dragon-curve.pl6 | 11 +- Task/Dragon-curve/REXX/dragon-curve.rexx | 2 +- Task/Draw-a-clock/BASIC/draw-a-clock.basic | 32 + .../Draw-a-clock/JavaScript/draw-a-clock-2.js | 84 +- Task/Draw-a-clock/Rust/draw-a-clock.rust | 10 +- Task/Draw-a-cuboid/C/draw-a-cuboid.c | 1 + .../Draw-a-cuboid/JavaScript/draw-a-cuboid.js | 9 +- Task/Draw-a-cuboid/Julia/draw-a-cuboid.julia | 18 + Task/Draw-a-cuboid/Ring/draw-a-cuboid.ring | 61 ++ Task/Draw-a-sphere/MATLAB/draw-a-sphere.m | 1 + Task/Draw-a-sphere/REXX/draw-a-sphere.rexx | 1 - Task/Draw-a-sphere/Scala/draw-a-sphere.scala | 34 + .../Dutch-national-flag-problem/00DESCRIPTION | 2 +- .../AWK/dutch-national-flag-problem-1.awk | 47 + .../AWK/dutch-national-flag-problem-2.awk | 5 + .../Java/dutch-national-flag-problem.java | 40 +- .../Ring/dutch-national-flag-problem.ring | 25 + .../Ruby/dutch-national-flag-problem.rb | 25 + .../C-sharp/dynamic-variable-names.cs | 17 + .../Factor/dynamic-variable-names.factor | 1 + .../Julia/dynamic-variable-names.julia | 15 + .../Perl-6/dynamic-variable-names.pl6 | 6 +- .../UNIX-Shell/dynamic-variable-names.sh | 3 + Task/Echo-server/Aime/echo-server.aime | 10 +- .../{echo-server.pl6 => echo-server-1.pl6} | 6 +- Task/Echo-server/Perl-6/echo-server-2.pl6 | 7 + Task/Echo-server/Scala/echo-server.scala | 30 + Task/Echo-server/X86-Assembly/echo-server.x86 | 178 ++++ .../C-sharp/element-wise-operations.cs | 85 ++ .../Fortran/element-wise-operations.f | 61 ++ .../Kotlin/element-wise-operations.kotlin | 48 ++ .../Maple/element-wise-operations.maple | 16 + .../Perl-6/element-wise-operations.pl6 | 33 + .../Sidef/element-wise-operations.sidef | 25 + .../Stata/element-wise-operations.stata | 17 + .../Factor/empty-directory.factor | 2 + .../Empty-directory/Rust/empty-directory.rust | 20 + Task/Empty-directory/VBA/empty-directory.vba | 11 + Task/Empty-program/ALGOL-W/empty-program.alg | 3 +- Task/Empty-program/N-t-roff/empty-program-1.n | 0 Task/Empty-program/N-t-roff/empty-program-2.n | 1 + .../Empty-program/Stata/empty-program-2.stata | 3 +- Task/Empty-program/VBA/empty-program.vba | 2 + .../Empty-string/Factor/empty-string-1.factor | 1 + .../Empty-string/Factor/empty-string-2.factor | 6 + Task/Empty-string/HolyC/empty-string.holyc | 12 + Task/Empty-string/Red/empty-string.red | 6 + .../Factor/enforced-immutability.factor | 2 + .../Julia/enforced-immutability.julia | 2 + .../Ring/enforced-immutability.ring | 8 + ...tability.sh => enforced-immutability-1.sh} | 0 .../UNIX-Shell/enforced-immutability-2.sh | 1 + Task/Entropy/ALGOL-68/entropy.alg | 24 +- Task/Entropy/Aime/entropy.aime | 29 +- Task/Entropy/BASIC/entropy-1.basic | 23 + Task/Entropy/BASIC/entropy-2.basic | 22 + Task/Entropy/BBC-BASIC/entropy.bbc | 24 + Task/Entropy/C++/entropy.cpp | 6 +- .../{entropy.lisp => entropy-1.lisp} | 4 +- Task/Entropy/Common-Lisp/entropy-2.lisp | 8 + Task/Entropy/Factor/entropy.factor | 11 + Task/Entropy/Julia/entropy.julia | 4 +- Task/Entropy/Objeck/entropy.objeck | 48 ++ .../Enumerations/Factor/enumerations-1.factor | 9 + .../Enumerations/Factor/enumerations-2.factor | 11 + Task/Enumerations/Shen/enumerations.shen | 7 + .../Julia/environment-variables.julia | 4 +- .../Stata/environment-variables.stata | 6 +- .../ABAP/equilibrium-index.abap | 14 + .../Aime/equilibrium-index.aime | 25 + .../Elena/equilibrium-index.elena | 66 ++ .../JavaScript/equilibrium-index-2.js | 94 +- .../JavaScript/equilibrium-index-3.js | 17 +- .../JavaScript/equilibrium-index-4.js | 1 + .../Julia/equilibrium-index.julia | 6 +- .../Objeck/equilibrium-index.objeck | 24 + .../BASIC/ethiopian-multiplication-10.basic | 29 + .../BASIC/ethiopian-multiplication-6.basic | 51 +- .../BASIC/ethiopian-multiplication-7.basic | 11 +- .../BASIC/ethiopian-multiplication-8.basic | 76 +- .../BASIC/ethiopian-multiplication-9.basic | 67 +- .../Julia/ethiopian-multiplication-1.julia | 11 +- .../Julia/ethiopian-multiplication-2.julia | 10 +- .../Julia/ethiopian-multiplication-3.julia | 6 +- .../Limbo/ethiopian-multiplication.limbo | 54 ++ .../Modula-2/ethiopian-multiplication.mod2 | 44 + .../VBA/ethiopian-multiplication-1.vba | 11 + .../VBA/ethiopian-multiplication-2.vba | 30 + .../VBA/ethiopian-multiplication-3.vba | 7 + .../VBA/ethiopian-multiplication-4.vba | 7 + Task/Euler-method/Julia/euler-method.julia | 22 +- .../C++/evaluate-binomial-coefficients-1.cpp | 10 +- .../C++/evaluate-binomial-coefficients-2.cpp | 2 +- .../Erlang/evaluate-binomial-coefficients.erl | 1 + .../evaluate-binomial-coefficients-1.julia | 1 + .../evaluate-binomial-coefficients-2.julia | 8 + .../evaluate-binomial-coefficients.julia | 10 - .../{even-or-odd.lisp => even-or-odd-1.lisp} | 0 .../Common-Lisp/even-or-odd-2.lisp | 13 + Task/Even-or-odd/Modula-2/even-or-odd.mod2 | 15 + Task/Even-or-odd/Stata/even-or-odd.stata | 9 + Task/Even-or-odd/UNIX-Shell/even-or-odd.sh | 4 + Task/Even-or-odd/VBA/even-or-odd.vba | 38 + Task/Events/Julia/events.julia | 20 + Task/Events/Python/events.py | 20 + Task/Evolutionary-algorithm/00DESCRIPTION | 4 +- .../Aime/evolutionary-algorithm.aime | 41 +- .../Factor/evolutionary-algorithm.factor | 37 + .../Julia/evolutionary-algorithm.julia | 24 + .../Pony/evolutionary-algorithm-2.pony | 4 +- ...algorithm.r => evolutionary-algorithm-1.r} | 0 .../R/evolutionary-algorithm-2.r | 34 + .../Ring/evolutionary-algorithm.ring | 60 ++ .../Rust/evolutionary-algorithm.rust | 101 +++ .../Smalltalk/evolutionary-algorithm-1.st | 47 + .../Smalltalk/evolutionary-algorithm-2.st | 21 + .../Smalltalk/evolutionary-algorithm.st | 116 --- .../00DESCRIPTION | 1 - ...an-exception-thrown-in-a-nested-call.elena | 46 + ...an-exception-thrown-in-a-nested-call.julia | 28 + ...-an-exception-thrown-in-a-nested-call-1.st | 45 +- ...-an-exception-thrown-in-a-nested-call-2.st | 54 +- Task/Exceptions/HolyC/exceptions-1.holyc | 8 + Task/Exceptions/HolyC/exceptions-2.holyc | 17 + Task/Exceptions/Julia/exceptions.julia | 14 + Task/Exceptions/VBA/exceptions-1.vba | 7 + Task/Exceptions/VBA/exceptions-2.vba | 46 + Task/Executable-library/00DESCRIPTION | 9 +- .../Clojure/executable-library-1.clj | 28 + .../Clojure/executable-library-2.clj | 13 + .../Julia/executable-library.julia | 53 ++ .../Julia/execute-brain----.julia | 38 + .../Prolog/execute-brain----.pro | 97 +++ .../ZX-Spectrum-Basic/execute-brain----.zx | 34 + Task/Execute-HQ9+/Julia/execute-hq9+.julia | 31 + Task/Execute-HQ9+/OCaml/execute-hq9+.ocaml | 9 + .../Julia/execute-a-markov-algorithm-1.julia | 48 ++ .../Julia/execute-a-markov-algorithm-2.julia | 11 + .../Kotlin/execute-a-markov-algorithm.kotlin | 44 + .../REXX/execute-a-markov-algorithm.rexx | 81 +- .../Aime/execute-a-system-command.aime | 6 +- .../HolyC/execute-a-system-command.holyc | 1 + .../Red/execute-a-system-command.red | 3 + .../Stata/execute-a-system-command.stata | 2 +- .../Perl-6/exponentiation-operator.pl6 | 12 + .../Stata/exponentiation-operator.stata | 10 + .../ABAP/extend-your-language.abap | 4 + .../DUP/extend-your-language-1.dup | 4 + .../DUP/extend-your-language-2.dup | 1 + .../Fortran/extend-your-language-1.f | 51 ++ .../Fortran/extend-your-language-2.f | 6 + .../Fortran/extend-your-language-3.f | 6 + .../Go/extend-your-language.go | 58 ++ .../Idris/extend-your-language.idris | 5 + .../Ring/extend-your-language.ring | 26 + .../Julia/extensible-prime-generator.julia | 21 + .../Lingo/extensible-prime-generator-1.lingo | 105 +++ .../Lingo/extensible-prime-generator-2.lingo | 5 + .../PicoLisp/extensible-prime-generator.l | 37 + .../VBA/extensible-prime-generator.vba | 74 ++ .../extreme-floating-point-values.factor | 12 + .../Perl-6/extreme-floating-point-values.pl6 | 8 +- .../REXX/extreme-floating-point-values.rexx | 31 + .../Ruby/extreme-floating-point-values.rb | 4 +- .../Sidef/extreme-floating-point-values.sidef | 26 +- Task/Factorial/00DESCRIPTION | 4 + Task/Factorial/C/factorial-2.c | 9 +- Task/Factorial/C/factorial-3.c | 6 +- Task/Factorial/C/factorial-4.c | 3 + Task/Factorial/C/factorial-5.c | 13 + Task/Factorial/C/factorial-6.c | 41 + Task/Factorial/Common-Lisp/factorial-4.lisp | 10 + .../Elm/{factorial.elm => factorial-1.elm} | 0 Task/Factorial/Elm/factorial-2.elm | 7 + Task/Factorial/Elm/factorial-3.elm | 5 + Task/Factorial/Go/factorial-3.go | 17 + Task/Factorial/Go/factorial-4.go | 26 + Task/Factorial/HolyC/factorial-1.holyc | 9 + Task/Factorial/HolyC/factorial-2.holyc | 11 + Task/Factorial/JavaScript/factorial-7.js | 32 +- Task/Factorial/Julia/factorial-1.julia | 19 +- Task/Factorial/Julia/factorial-2.julia | 12 +- Task/Factorial/Modula-2/factorial.mod2 | 26 + Task/Factorial/Nim/factorial-1.nim | 5 +- Task/Factorial/Nim/factorial-2.nim | 5 +- Task/Factorial/Nim/factorial-3.nim | 4 + Task/Factorial/OCaml/factorial-4.ocaml | 12 + Task/Factorial/Processing/factorial | 7 + Task/Factorial/Simula/factorial.simula | 13 +- Task/Factorial/VBA/factorial.vba | 28 + Task/Factorial/VHDL/factorial.vhdl | 98 ++- .../00DESCRIPTION | 3 + .../factors-of-a-mersenne-number-1.lingo | 23 + .../factors-of-a-mersenne-number-2.lingo | 6 + .../REXX/factors-of-a-mersenne-number.rexx | 84 +- .../Ring/factors-of-a-mersenne-number.ring | 44 + .../Ruby/factors-of-an-integer-3.rb | 12 + .../APL/fast-fourier-transform-1.apl | 10 + .../APL/fast-fourier-transform-2.apl | 1 + .../Perl/fast-fourier-transform.pl | 2 +- ...m.stata => fast-fourier-transform-1.stata} | 0 .../Stata/fast-fourier-transform-2.stata | 8 + .../SystemVerilog/fast-fourier-transform-1.v | 90 ++ .../SystemVerilog/fast-fourier-transform-2.v | 23 + .../SystemVerilog/fast-fourier-transform-3.v | 52 ++ .../SystemVerilog/fast-fourier-transform-4.v | 14 + .../fibonacci-n-step-number-sequences.ring | 64 ++ .../VBA/fibonacci-n-step-number-sequences.vba | 62 ++ .../CoffeeScript/fibonacci-sequence-1.coffee | 2 +- .../Common-Lisp/fibonacci-sequence-7.lisp | 16 + .../Elena/fibonacci-sequence.elena | 26 + .../Erlang/fibonacci-sequence-4.erl | 4 + .../Haskell/fibonacci-sequence-10.hs | 45 +- .../Haskell/fibonacci-sequence-11.hs | 36 +- .../Haskell/fibonacci-sequence-12.hs | 3 +- .../Haskell/fibonacci-sequence-13.hs | 10 +- .../Haskell/fibonacci-sequence-14.hs | 45 +- .../Haskell/fibonacci-sequence-15.hs | 35 + .../Haskell/fibonacci-sequence-16.hs | 2 + .../Haskell/fibonacci-sequence-17.hs | 1 + .../Haskell/fibonacci-sequence-18.hs | 1 + .../Haskell/fibonacci-sequence-4.hs | 11 +- .../Haskell/fibonacci-sequence-5.hs | 7 +- .../Haskell/fibonacci-sequence-6.hs | 8 +- .../Haskell/fibonacci-sequence-7.hs | 9 +- .../Haskell/fibonacci-sequence-8.hs | 6 +- .../Haskell/fibonacci-sequence-9.hs | 10 +- .../MATLAB/fibonacci-sequence-4.m | 12 + .../Mathematica/fibonacci-sequence-7.math | 2 + .../Mathematica/fibonacci-sequence-8.math | 1 + .../Mathematica/fibonacci-sequence-9.math | 1 + .../Modula-2/fibonacci-sequence.mod2 | 37 + .../PARI-GP/fibonacci-sequence-14.pari | 8 +- .../PARI-GP/fibonacci-sequence-15.pari | 8 +- .../PARI-GP/fibonacci-sequence-16.pari | 8 +- .../PARI-GP/fibonacci-sequence-17.pari | 7 + .../PARI-GP/fibonacci-sequence-18.pari | 1 + .../Perl-6/fibonacci-sequence-5.pl6 | 3 +- .../Perl/fibonacci-sequence-3.pl | 12 +- .../PicoLisp/fibonacci-sequence-4.l | 9 +- .../PicoLisp/fibonacci-sequence-5.l | 11 + .../Python/fibonacci-sequence-11.py | 18 +- .../Python/fibonacci-sequence-12.py | 15 +- .../Python/fibonacci-sequence-13.py | 11 + .../REALbasic/fibonacci-sequence.realbasic | 2 +- .../Racket/fibonacci-sequence-2.rkt | 15 +- .../Racket/fibonacci-sequence-3.rkt | 11 + .../Scala/fibonacci-sequence-3.scala | 3 +- .../Stata/fibonacci-sequence-1.stata | 7 + .../Stata/fibonacci-sequence-2.stata | 12 + ...uence.stata => fibonacci-sequence-3.stata} | 0 .../Julia/fibonacci-word-fractal.julia | 23 + Task/Fibonacci-word/Aime/fibonacci-word.aime | 14 +- Task/Fibonacci-word/C-sharp/fibonacci-word.cs | 71 ++ .../Factor/fibonacci-word.factor | 36 + .../Fibonacci-word/Julia/fibonacci-word.julia | 45 +- .../Objeck/fibonacci-word.objeck | 58 ++ Task/Fibonacci-word/Ring/fibonacci-word.ring | 54 ++ .../Aime/file-input-output.aime | 10 +- .../COBOL/file-input-output-1.cobol | 82 +- .../COBOL/file-input-output-2.cobol | 50 +- .../COBOL/file-input-output-3.cobol | 4 +- .../COBOL/file-input-output-4.cobol | 2 + .../Elena/file-input-output.elena | 8 + ...put-output.fth => file-input-output-1.fth} | 0 .../Forth/file-input-output-2.fth | 10 + .../Red/file-input-output.red | 2 + .../VBA/file-input-output.vba | 27 + .../Julia/file-modification-time.julia | 11 +- .../Perl-6/file-modification-time.pl6 | 2 +- Task/File-size/AWK/file-size-2.awk | 14 +- Task/File-size/Fortran/file-size-1.f | 9 + .../Fortran/{file-size.f => file-size-2.f} | 0 Task/File-size/Red/file-size.red | 4 + Task/Filter/Elena/filter.elena | 13 + .../Java/{filter.java => filter-1.java} | 0 Task/Filter/Java/filter-2.java | 5 + Task/Filter/Java/filter-3.java | 2 + Task/Filter/Julia/filter.julia | 9 +- Task/Filter/Perl-6/filter-2.pl6 | 1 + Task/Filter/Perl-6/filter-3.pl6 | 1 + Task/Filter/Red/filter.red | 9 + Task/Filter/VBA/filter.vba | 47 + .../Julia/find-common-directory-path.julia | 37 +- .../Kotlin/find-common-directory-path.kotlin | 28 + ...-left-truncatable-prime-in-a-given-base.go | 57 ++ ...ft-truncatable-prime-in-a-given-base.julia | 22 +- ...ft-truncatable-prime-in-a-given-base.maple | 35 + .../HolyC/find-limit-of-recursion.holyc | 6 + .../Swift/find-limit-of-recursion.swift | 9 + .../VBA/find-limit-of-recursion.vba | 13 + .../C/find-the-last-sunday-of-each-month.c | 3 +- .../find-the-last-sunday-of-each-month.erl | 25 +- .../find-the-last-sunday-of-each-month.factor | 11 + .../find-the-last-sunday-of-each-month.maple | 18 + .../find-the-last-sunday-of-each-month.pl6 | 4 +- .../find-the-last-sunday-of-each-month.stata | 27 + .../Aime/find-the-missing-permutation.aime | 24 +- .../find-the-missing-permutation.applescript | 315 +++---- .../find-the-missing-permutation.factor | 3 + .../find-the-missing-permutation-1.julia | 24 +- .../find-the-missing-permutation-2.julia | 37 +- .../Maple/find-the-missing-permutation.maple | 11 + .../Perl-6/find-the-missing-permutation-2.pl6 | 3 +- ...ss-functions-use-numbers-analogously.elena | 2 +- ...ss-functions-use-numbers-analogously.julia | 10 + .../Elena/first-class-functions.elena | 4 +- .../Five-weekends/Factor/five-weekends.factor | 17 + Task/Five-weekends/Julia/five-weekends.julia | 35 +- Task/Five-weekends/Maple/five-weekends.maple | 17 + Task/Five-weekends/Stata/five-weekends.stata | 30 + Task/Five-weekends/VBA/five-weekends.vba | 22 + Task/FizzBuzz/ARM-Assembly/fizzbuzz.arm | 119 +++ Task/FizzBuzz/ATS/fizzbuzz.ats | 18 + Task/FizzBuzz/BASIC/fizzbuzz.basic | 16 + Task/FizzBuzz/Clojure/fizzbuzz-1.clj | 10 +- Task/FizzBuzz/Clojure/fizzbuzz-10.clj | 6 +- Task/FizzBuzz/Clojure/fizzbuzz-11.clj | 23 +- Task/FizzBuzz/Clojure/fizzbuzz-12.clj | 25 +- Task/FizzBuzz/Clojure/fizzbuzz-13.clj | 22 +- Task/FizzBuzz/Clojure/fizzbuzz-14.clj | 18 + Task/FizzBuzz/Clojure/fizzbuzz-2.clj | 14 +- Task/FizzBuzz/Clojure/fizzbuzz-3.clj | 6 +- Task/FizzBuzz/Clojure/fizzbuzz-4.clj | 7 +- Task/FizzBuzz/Clojure/fizzbuzz-5.clj | 19 +- Task/FizzBuzz/Clojure/fizzbuzz-6.clj | 19 +- Task/FizzBuzz/Clojure/fizzbuzz-7.clj | 10 +- Task/FizzBuzz/Clojure/fizzbuzz-8.clj | 5 +- Task/FizzBuzz/Clojure/fizzbuzz-9.clj | 3 +- Task/FizzBuzz/Common-Lisp/fizzbuzz-8.lisp | 23 + Task/FizzBuzz/Factor/fizzbuzz.factor | 2 +- Task/FizzBuzz/Groovy/fizzbuzz.groovy | 2 +- Task/FizzBuzz/Julia/fizzbuzz-1.julia | 2 +- Task/FizzBuzz/Julia/fizzbuzz-2.julia | 5 +- Task/FizzBuzz/Julia/fizzbuzz-3.julia | 6 +- Task/FizzBuzz/Julia/fizzbuzz-4.julia | 2 +- Task/FizzBuzz/Julia/fizzbuzz-5.julia | 11 +- Task/FizzBuzz/Modula-2/fizzbuzz.mod2 | 46 + Task/FizzBuzz/PicoLisp/fizzbuzz-1.l | 3 + Task/FizzBuzz/REBOL/fizzbuzz-1.rebol | 21 +- Task/FizzBuzz/REBOL/fizzbuzz-2.rebol | 23 +- Task/FizzBuzz/REBOL/fizzbuzz-3.rebol | 12 +- Task/FizzBuzz/Rust/fizzbuzz-1.rust | 16 +- Task/FizzBuzz/Rust/fizzbuzz-2.rust | 14 +- Task/FizzBuzz/Simula/fizzbuzz.simula | 16 +- Task/FizzBuzz/Stata/fizzbuzz.stata | 17 + .../{fizzbuzz.swift => fizzbuzz-1.swift} | 0 Task/FizzBuzz/Swift/fizzbuzz-2.swift | 6 + Task/FizzBuzz/VBA/fizzbuzz.vba | 17 + Task/Flatten-a-list/Aime/flatten-a-list.aime | 43 +- .../JavaScript/flatten-a-list-5.js | 5 +- .../Julia/flatten-a-list-1.julia | 2 +- .../Julia/flatten-a-list-2.julia | 19 +- Task/Flatten-a-list/Perl-6/flatten-a-list.pl6 | 7 + Task/Flatten-a-list/Red/flatten-a-list.red | 8 + Task/Flatten-a-list/Ring/flatten-a-list.ring | 19 +- .../Julia/flipping-bits-game.julia | 97 +++ .../OCaml/flipping-bits-game.ocaml | 72 ++ .../REXX/flipping-bits-game.rexx | 101 +-- .../flow-control-structures-1.360 | 2 + .../flow-control-structures-2.360 | 7 + .../flow-control-structures-3.360 | 8 + .../flow-control-structures-4.360 | 4 + .../flow-control-structures-5.360 | 7 + .../flow-control-structures-6.360 | 7 + .../Julia/flow-control-structures.julia | 7 + .../360-Assembly/floyds-triangle.360 | 39 + .../BASIC/floyds-triangle-1.basic | 11 + .../BASIC/floyds-triangle-2.basic | 12 + .../Befunge/floyds-triangle.bf | 8 +- .../Julia/floyds-triangle.julia | 0 .../Modula-2/floyds-triangle.mod2 | 37 + .../Perl-6/floyds-triangle-2.pl6 | 13 + .../REXX/floyds-triangle-2.rexx | 6 +- .../REXX/floyds-triangle-3.rexx | 4 +- .../REXX/floyds-triangle-4.rexx | 8 +- Task/Forest-fire/BASIC/forest-fire-10.basic | 160 ++-- Task/Forest-fire/BASIC/forest-fire-11.basic | 56 ++ Task/Forest-fire/BASIC/forest-fire-9.basic | 176 ++-- Task/Forest-fire/Forth/forest-fire.fth | 64 ++ Task/Forest-fire/Ring/forest-fire.ring | 88 ++ Task/Fork/D/fork.d | 9 + Task/Fork/Kotlin/fork.kotlin | 26 + .../Julia/formal-power-series-1.julia | 166 ++++ .../Julia/formal-power-series-2.julia | 15 + .../Kotlin/formal-power-series.kotlin | 208 +++++ .../Mathematica/formal-power-series.math | 3 + .../Factor/formatted-numeric-output.factor | 2 + .../formatted-numeric-output-1.vb | 1 + .../formatted-numeric-output-2.vb | 1 + .../Julia/forward-difference.julia | 5 +- .../Ring/forward-difference.ring | 28 + .../Kotlin/four-bit-adder.kotlin | 52 ++ Task/Four-bit-adder/Ring/four-bit-adder.ring | 69 ++ Task/Fractal-tree/BASIC/fractal-tree-1.basic | 45 + Task/Fractal-tree/BASIC/fractal-tree-2.basic | 60 ++ Task/Fractal-tree/BASIC/fractal-tree-3.basic | 5 + Task/Fractal-tree/BASIC/fractal-tree-4.basic | 16 + Task/Fractal-tree/Rust/fractal-tree.rust | 57 ++ Task/Fractran/Fortran/fractran-4.f | 7 +- Task/Fractran/Julia/fractran.julia | 32 + Task/Fractran/Perl-6/fractran-2.pl6 | 3 + Task/Fractran/Ruby/fractran.rb | 4 +- .../Elena/function-composition.elena | 4 +- .../Fortress/function-composition-1.fortress | 5 + .../Fortress/function-composition-2.fortress | 5 + .../Fortress/function-composition-3.fortress | 1 + .../Julia/function-composition-1.julia | 1 + .../Julia/function-composition-2.julia | 2 + .../Julia/function-composition.julia | 1 - .../Perl-6/function-composition.pl6 | 4 +- ...tion.basic => function-definition-1.basic} | 0 .../BASIC/function-definition-2.basic | 3 + .../HolyC/function-definition.holyc | 7 + .../Julia/function-definition-1.julia | 4 +- .../Julia/function-definition-2.julia | 2 +- .../Julia/function-definition-3.julia | 2 +- .../Perl-6/function-definition-4.pl6 | 1 - .../Stata/function-definition-1.stata | 7 + .../Stata/function-definition-2.stata | 7 + .../VBA/function-definition-1.vba | 3 + .../VBA/function-definition-2.vba | 4 + .../Julia/function-frequency.julia | 33 + .../C/gui-maximum-window-dimensions.c | 10 + .../Scala/gui-maximum-window-dimensions.scala | 20 + Task/GUI-component-interaction/00DESCRIPTION | 4 +- .../Maple/gui-component-interaction-1.maple | 1 + .../Maple/gui-component-interaction-2.maple | 1 + .../Maple/gui-component-interaction-3.maple | 14 + .../Perl-6/gui-component-interaction.pl6 | 11 +- .../00DESCRIPTION | 3 +- .../gui-enabling-disabling-of-controls-2.java | 2 +- .../gui-enabling-disabling-of-controls.kotlin | 70 ++ ...gui-enabling-disabling-of-controls-1.maple | 1 + ...gui-enabling-disabling-of-controls-2.maple | 1 + ...gui-enabling-disabling-of-controls-3.maple | 29 + .../gui-enabling-disabling-of-controls.pl6 | 11 +- .../Kotlin/galton-box-animation.kotlin | 102 +++ .../Julia/gamma-function-1.julia | 2 +- .../Julia/gamma-function-2.julia | 7 +- .../Gamma-function/Maple/gamma-function.maple | 4 + .../Gamma-function/Stata/gamma-function.stata | 42 + Task/Gaussian-elimination/00DESCRIPTION | 10 +- .../FreeBASIC/gaussian-elimination.freebasic | 61 ++ ...imination.go => gaussian-elimination-1.go} | 0 .../Go/gaussian-elimination-2.go | 94 ++ .../Klong/gaussian-elimination-1.klong | 5 + .../Klong/gaussian-elimination-2.klong | 12 + .../Kotlin/gaussian-elimination.kotlin | 81 ++ .../Perl-6/gaussian-elimination.pl6 | 99 +-- .../REXX/gaussian-elimination-2.rexx | 73 +- .../REXX/gaussian-elimination-3.rexx | 48 ++ .../Sidef/gaussian-elimination.sidef | 27 +- .../Stata/gaussian-elimination-1.stata | 29 + .../Stata/gaussian-elimination-2.stata | 43 + .../Stata/gaussian-elimination-3.stata | 21 + .../00DESCRIPTION | 4 +- .../C/generate-chess960-starting-position.c | 104 +++ .../generate-chess960-starting-position.julia | 48 +- .../generate-chess960-starting-position-3.pl6 | 6 +- .../generate-chess960-starting-position-4.pl6 | 2 +- .../generate-chess960-starting-position.rust | 4 +- ...enerate-chess960-starting-position-1.scala | 25 + ...nerate-chess960-starting-position-2.scala} | 0 .../generate-lower-case-ascii-alphabet-1.abap | 3 + .../generate-lower-case-ascii-alphabet-2.abap | 10 + .../generate-lower-case-ascii-alphabet.abap | 1 - ...te-lower-case-ascii-alphabet-1.applescript | 66 +- .../generate-lower-case-ascii-alphabet-1.bf | 26 + .../generate-lower-case-ascii-alphabet-2.bf | 3 + .../generate-lower-case-ascii-alphabet-1.cs | 10 + ...> generate-lower-case-ascii-alphabet-2.cs} | 0 .../generate-lower-case-ascii-alphabet.dup | 2 + .../generate-lower-case-ascii-alphabet.elena | 34 + .../generate-lower-case-ascii-alphabet.julia | 7 +- .../generate-lower-case-ascii-alphabet.ocaml | 4 + .../generate-lower-case-ascii-alphabet.pl6 | 2 +- .../generate-lower-case-ascii-alphabet.vba | 19 + Task/Generator-Exponential/00DESCRIPTION | 23 +- .../Julia/generator-exponential.julia | 32 +- .../Lingo/generator-exponential-1.lingo | 11 + .../Lingo/generator-exponential-2.lingo | 23 + .../Lingo/generator-exponential-3.lingo | 43 + .../Generic-swap/Crystal/generic-swap.crystal | 1 + .../{generic-swap.hs => generic-swap-1.hs} | 0 Task/Generic-swap/Haskell/generic-swap-2.hs | 7 + ...bally-replace-text-in-several-files.kotlin | 15 + ...bally-replace-text-in-several-files-2.rexx | 2 +- ...globally-replace-text-in-several-files.red | 4 + ...obally-replace-text-in-several-files.scala | 13 + Task/Gray-code/Aime/gray-code-1.aime | 4 +- Task/Gray-code/Julia/gray-code.julia | 11 +- Task/Gray-code/Perl-6/gray-code.pl6 | 16 + Task/Gray-code/Ring/gray-code.ring | 39 + .../JavaScript/grayscale-image.js | 59 +- .../Kotlin/grayscale-image.kotlin | 27 + .../Maple/grayscale-image.maple | 16 + .../REXX/grayscale-image-1.rexx | 7 +- .../REXX/grayscale-image-2.rexx | 2 +- .../AWK/greatest-common-divisor.awk | 2 +- .../Elena/greatest-common-divisor.elena | 34 + .../Klong/greatest-common-divisor.klong | 1 + .../Ruby/greatest-common-divisor-1.rb | 3 +- .../Simula/greatest-common-divisor.simula | 23 + .../Stata/greatest-common-divisor.stata | 9 + .../XLISP/greatest-common-divisor.xlisp | 4 + .../Aime/greatest-element-of-a-list-1.aime | 15 + .../Aime/greatest-element-of-a-list-2.aime | 10 + .../Aime/greatest-element-of-a-list.aime | 19 - .../greatest-element-of-a-list-2.applescript | 88 +- .../Befunge/greatest-element-of-a-list.bf | 6 +- .../Dart/greatest-element-of-a-list.dart | 5 + .../Emacs-Lisp/greatest-element-of-a-list-3.l | 1 + .../greatest-element-of-a-list.futhark | 1 + .../greatest-element-of-a-list-5.js | 63 +- ...p => greatest-element-of-a-list-1.newlisp} | 0 .../greatest-element-of-a-list-2.newlisp | 2 + .../Red/greatest-element-of-a-list.red | 3 + .../Stata/greatest-element-of-a-list-1.stata | 2 + .../Stata/greatest-element-of-a-list-2.stata | 2 + .../Julia/greatest-subsequential-sum.julia | 25 +- .../Ring/greatest-subsequential-sum.ring | 51 ++ .../Perl-6/greyscale-bars-display.pl6 | 6 +- .../Ring/greyscale-bars-display.ring | 61 ++ .../00DESCRIPTION | 2 +- .../guess-the-number-with-feedback.elena | 25 + .../guess-the-number-with-feedback.holyc | 20 + .../guess-the-number-with-feedback.julia | 24 +- .../guess-the-number-with-feedback.scala | 17 + .../guess-the-number-with-feedback.vb | 26 + .../Aime/guess-the-number.aime | 2 +- .../Batch-File/guess-the-number.bat | 21 +- .../Elena/guess-the-number.elena | 21 + .../HolyC/guess-the-number.holyc | 17 + .../Julia/guess-the-number.julia | 14 +- .../Python/guess-the-number.py | 7 +- .../Ring/guess-the-number.ring | 38 +- .../Guess-the-number/VBA/guess-the-number.vba | 9 + Task/HTTP/Haskell/http-1.hs | 13 +- Task/HTTP/JavaScript/http-2.js | 8 +- Task/HTTP/JavaScript/http-3.js | 65 ++ Task/HTTP/JavaScript/http-4.js | 3 + Task/HTTP/JavaScript/http-5.js | 19 + Task/HTTP/Nim/http.nim | 3 +- Task/HTTP/Pascal/http-1.pascal | 16 + .../Pascal/{http.pascal => http-2.pascal} | 0 .../Haskell/https-authenticated.hs | 27 + .../Kotlin/https-authenticated.kotlin | 28 + .../Perl-6/https-authenticated.pl6 | 10 + .../Scala/https-authenticated.scala | 24 + .../Go/https-client-authenticated.go | 38 + .../Kotlin/https-client-authenticated.kotlin | 37 + .../Scala/https-client-authenticated.scala | 29 + Task/HTTPS/Haskell/https-1.hs | 2 +- Task/HTTPS/NewLISP/https.newlisp | 1 + Task/HTTPS/Nim/https.nim | 3 +- Task/HTTPS/Pascal/https.pascal | 16 + Task/HTTPS/Perl-6/https-1.pl6 | 2 + Task/HTTPS/Perl-6/https-2.pl6 | 2 + .../Aime/hailstone-sequence.aime | 14 +- .../Elena/hailstone-sequence.elena | 48 ++ .../Haskell/hailstone-sequence-1.hs | 15 +- .../JavaScript/hailstone-sequence-9.js | 138 ++- .../Julia/hailstone-sequence-1.julia | 11 + .../Julia/hailstone-sequence-2.julia | 40 + .../Julia/hailstone-sequence-3.julia | 40 + .../Julia/hailstone-sequence.julia | 8 - Task/Hamming-numbers/AWK/hamming-numbers.awk | 3 +- Task/Hamming-numbers/Ada/hamming-numbers.ada | 113 +++ .../Julia/hamming-numbers.julia | 30 +- .../PicoLisp/hamming-numbers.l | 4 +- .../Python/hamming-numbers-3.py | 37 +- .../Python/hamming-numbers-4.py | 30 +- .../Python/hamming-numbers-5.py | 45 +- .../Python/hamming-numbers-6.py | 38 + ...{hamming-numbers.r => hamming-numbers-1.r} | 0 Task/Hamming-numbers/R/hamming-numbers-2.r | 8 + Task/Handle-a-signal/D/handle-a-signal.d | 29 + Task/Happy-numbers/Elena/happy-numbers.elena | 44 + Task/Happy-numbers/VBA/happy-numbers.vba | 29 + .../Factor/harshad-or-niven-series.factor | 9 + .../Julia/harshad-or-niven-series.julia | 18 +- .../PicoLisp/harshad-or-niven-series.l | 23 + .../Rust/harshad-or-niven-series.rust | 16 + .../C++/hash-from-two-arrays-1.cpp | 18 +- .../C++/hash-from-two-arrays-2.cpp | 16 +- .../Julia/hash-from-two-arrays-1.julia | 8 +- .../Julia/hash-from-two-arrays-2.julia | 3 +- .../Julia/hash-from-two-arrays-3.julia | 3 +- .../Perl-6/hash-from-two-arrays.pl6 | 19 + .../Ring/hash-from-two-arrays.ring | 17 + .../Ruby/hash-from-two-arrays-2.rb | 10 +- Task/Hash-join/C++/hash-join.cpp | 64 ++ Task/Hash-join/Perl-6/hash-join.pl6 | 27 + Task/Hash-join/Rust/hash-join.rust | 53 +- .../C++/haversine-formula.cpp | 56 ++ .../Elena/haversine-formula.elena | 23 + .../JavaScript/haversine-formula-2.js | 9 +- .../Julia/haversine-formula.julia | 8 +- .../REXX/haversine-formula.rexx | 40 +- .../Elena/hello-world-graphical.elena | 2 +- .../hello-world-graphical-1.freebasic | 4 + .../hello-world-graphical-2.freebasic | 2 + .../FreeBASIC/hello-world-graphical.freebasic | 16 - .../HolyC/hello-world-graphical-1.holyc | 1 + .../HolyC/hello-world-graphical-2.holyc | 6 + .../HolyC/hello-world-graphical-3.holyc | 21 + .../N-t-roff/hello-world-graphical.n | 1 + .../PARI-GP/hello-world-graphical.pari | 3 + .../Perl-6/hello-world-graphical.pl6 | 7 + .../Python/hello-world-graphical-7.py | 20 + .../Python/hello-world-graphical-8.py | 29 + .../Red/hello-world-graphical.red | 1 + .../hello-world-graphical.visual | 2 + Task/Hello-world-Line-printer/00DESCRIPTION | 1 + .../Clojure/hello-world-line-printer.clj | 6 + .../N-t-roff/hello-world-line-printer.n | 1 + .../ARM-Assembly/hello-world-newbie.arm | 19 + ...ada => hello-world-newline-omission-1.ada} | 2 +- .../Ada/hello-world-newline-omission-2.ada | 8 + .../Befunge/hello-world-newline-omission.bf | 1 + .../Elena/hello-world-newline-omission.elena | 7 + .../hello-world-newline-omission.gambas | 6 + .../hello-world-newline-omission-1.holyc | 1 + .../hello-world-newline-omission-2.holyc | 1 + .../Icon/hello-world-newline-omission.icon | 3 + .../hello-world-newline-omission.mod2 | 7 + .../N-t-roff/hello-world-newline-omission.n | 1 + Task/Hello-world-Standard-error/00DESCRIPTION | 1 + .../hello-world-standard-error.arm | 19 + .../N-t-roff/hello-world-standard-error.n | 1 + .../6502-Assembly/hello-world-text.6502 | 4 +- Task/Hello-world-Text/C/hello-world-text-4.c | 6 + .../Common-Lisp/hello-world-text-3.lisp | 6 + .../FreeBASIC/hello-world-text.freebasic | 16 +- .../Haskell/hello-world-text.hs | 4 +- .../HolyC/hello-world-text.holyc | 1 + .../N-t-roff/hello-world-text.n | 1 + .../PL-M/hello-world-text.plm | 8 + .../Rust/hello-world-text-1.rust | 3 + ...orld-text.rust => hello-world-text-2.rust} | 0 .../VBScript/hello-world-text.vb | 2 +- .../Visual-Basic-.NET/hello-world-text.visual | 7 + Task/Hello-world-Web-server/00DESCRIPTION | 1 + .../Aime/hello-world-web-server-1.aime | 6 +- .../Crystal/hello-world-web-server.crystal | 7 + .../Perl-6/hello-world-web-server-1.pl6 | 7 + .../Perl-6/hello-world-web-server-2.pl6 | 8 + .../Perl-6/hello-world-web-server.pl6 | 6 - Task/Here-document/C/here-document.c | 16 + .../Here-document/JavaScript/here-document.js | 6 + Task/Here-document/Perl-6/here-document-1.pl6 | 3 +- Task/Here-document/Perl-6/here-document-3.pl6 | 5 +- .../UNIX-Shell/here-document-5.sh | 17 +- .../UNIX-Shell/here-document-6.sh | 9 + .../heronian-triangles.applescript | 247 +++--- .../Heronian-triangles/C/heronian-triangles.c | 122 +++ .../REXX/heronian-triangles-1.rexx | 6 +- .../REXX/heronian-triangles-2.rexx | 31 +- .../Ring/heronian-triangles.ring | 43 + .../hickerson-series-of-almost-integers.scala | 26 + .../Elena/higher-order-functions.elena | 8 + .../Lingo/higher-order-functions-1.lingo | 10 +- .../Ring/higher-order-functions.ring | 21 + .../Elena/history-variables.elena | 51 ++ .../Java/history-variables-1.java | 73 ++ .../Java/history-variables-2.java | 25 + .../Java/history-variables-3.java | 0 .../Java/history-variables-4.java | 76 ++ .../Perl-6/history-variables.pl6 | 14 +- .../hofstadter-figure-figure-sequences.pl6 | 14 +- .../hofstadter-figure-figure-sequences.ring | 33 + .../Julia/hofstadter-q-sequence-1.julia | 20 +- .../Julia/hofstadter-q-sequence-2.julia | 18 +- .../Perl-6/hofstadter-q-sequence-1.pl6 | 11 + .../Perl-6/hofstadter-q-sequence-2.pl6 | 16 +- .../horizontal-sundial-calculations.gw-basic | 23 + .../horizontal-sundial-calculations.mod2 | 49 ++ .../REXX/horizontal-sundial-calculations.rexx | 9 +- .../Ring/horizontal-sundial-calculations.ring | 27 + ...orners-rule-for-polynomial-evaluation.aime | 17 +- ...rners-rule-for-polynomial-evaluation.elena | 12 + ...ers-rule-for-polynomial-evaluation-1.julia | 16 +- ...ers-rule-for-polynomial-evaluation-2.julia | 5 +- ...orners-rule-for-polynomial-evaluation.mod2 | 29 + ...horners-rule-for-polynomial-evaluation.nim | 5 +- .../Perl-6/host-introspection.pl6 | 1 + Task/Huffman-coding/Lua/huffman-coding.lua | 73 ++ .../Perl-6/huffman-coding-2.pl6 | 20 + Task/Huffman-coding/REXX/huffman-coding.rexx | 11 +- Task/Huffman-coding/Red/huffman-coding.red | 91 ++ Task/Huffman-coding/Tcl/huffman-coding.tcl | 7 +- .../D/i-before-e-except-after-c.d | 124 +++ .../Factor/i-before-e-except-after-c.factor | 23 + .../Ring/i-before-e-except-after-c.ring | 42 + Task/IBAN/AWK/iban-1.awk | 50 ++ Task/IBAN/AWK/iban-2.awk | 9 + Task/IBAN/AWK/iban-3.awk | 6 + Task/IBAN/Fortran/iban.f | 124 +++ Task/IBAN/Julia/iban.julia | 34 +- Task/IBAN/REXX/iban-1.rexx | 84 +- Task/IBAN/REXX/iban-2.rexx | 88 +- Task/IBAN/Ring/iban.ring | 55 ++ Task/Identity-matrix/Go/identity-matrix-1.go | 8 +- .../Identity-matrix/Rust/identity-matrix.rust | 41 + .../Stata/identity-matrix-1.stata | 8 + .../Stata/identity-matrix-2.stata | 8 + .../Julia/image-convolution.julia | 9 + .../Kotlin/image-convolution.kotlin | 116 +++ Task/Image-noise/C++/image-noise.cpp | 1 + Task/Image-noise/Kotlin/image-noise.kotlin | 117 +++ Task/Image-noise/Perl-6/image-noise.pl6 | 96 ++- .../VBScript/include-a-file-3.vb | 7 + .../Elena/increment-a-numerical-string.elena | 9 + .../HolyC/increment-a-numerical-string.holyc | 9 + .../Julia/increment-a-numerical-string.julia | 6 +- .../increment-a-numerical-string.math | 2 +- Task/Infinity/Perl-6/infinity.pl6 | 2 + Task/Infinity/ZX-Spectrum-Basic/infinity-1.zx | 1 + Task/Infinity/ZX-Spectrum-Basic/infinity-2.zx | 4 + ...ce-multiple.d => inheritance-multiple-1.d} | 0 .../D/inheritance-multiple-2.d | 12 + .../D/inheritance-multiple-3.d | 38 + .../D/inheritance-multiple-4.d | 19 + .../Julia/inheritance-single.julia | 10 +- Task/Input-loop/Java/input-loop-1.java | 30 +- Task/Input-loop/Java/input-loop-2.java | 39 +- Task/Input-loop/Julia/input-loop.julia | 7 +- .../Astro/integer-comparison.astro | 4 +- .../Haskell/integer-comparison-1.hs | 7 +- .../HolyC/integer-comparison.holyc | 12 + Task/Integer-overflow/00DESCRIPTION | 2 +- .../Julia/integer-overflow-1.julia | 12 +- .../Julia/integer-overflow-2.julia | 8 +- .../Elena/integer-sequence.elena | 12 + .../Modula-2/integer-sequence.mod2 | 16 + .../Forth/interactive-programming.fth | 15 +- .../Java/interactive-programming.java | 9 + .../Ruby/interactive-programming.rb | 2 +- Task/Introspection/Icon/introspection.icon | 4 +- Task/Introspection/Julia/introspection.julia | 14 +- Task/Introspection/Perl-6/introspection.pl6 | 2 +- .../Kotlin/inverted-index.kotlin | 58 ++ Task/Inverted-syntax/D/inverted-syntax.d | 14 + .../Factor/inverted-syntax-1.factor | 4 + .../Factor/inverted-syntax-2.factor | 4 + .../Julia/inverted-syntax.julia | 7 + .../Scala/inverted-syntax.scala | 6 + Task/Iterated-digits-squaring/00DESCRIPTION | 11 +- .../C-sharp/iterated-digits-squaring.cs | 34 + .../Factor/iterated-digits-squaring.factor | 17 + .../Julia/iterated-digits-squaring-1.julia | 12 +- .../Julia/iterated-digits-squaring-2.julia | 31 +- .../Julia/iterated-digits-squaring-3.julia | 3 + .../Perl-6/iterated-digits-squaring-3.pl6 | 1 + .../REXX/iterated-digits-squaring-1.rexx | 23 +- .../REXX/iterated-digits-squaring-2.rexx | 55 +- Task/JSON/00DESCRIPTION | 4 +- Task/JSON/Julia/json.julia | 16 +- Task/JSON/Kotlin/json.kotlin | 15 + .../Jensens-Device/Julia/jensens-device.julia | 23 +- Task/Jensens-Device/Ring/jensens-device.ring | 16 + .../BASIC/josephus-problem-1.basic | 7 + .../BASIC/josephus-problem-2.basic | 5 + .../BBC-BASIC/josephus-problem.bbc | 10 + .../Julia/josephus-problem-1.julia | 6 +- .../Julia/josephus-problem-2.julia | 18 +- .../MATLAB/josephus-problem.m | 38 + .../Modula-2/josephus-problem.mod2 | 26 + .../Perl-6/josephus-problem.pl6 | 16 + .../PicoLisp/josephus-problem.l | 23 + .../Python/josephus-problem-4.py | 33 + .../Haskell/joystick-position.hs | 22 + .../ZX-Spectrum-Basic/joystick-position.zx | 17 + Task/Jump-anywhere/Go/jump-anywhere.go | 21 + Task/Jump-anywhere/Julia/jump-anywhere.julia | 7 + Task/K-d-tree/D/k-d-tree-2.d | 73 +- Task/K-d-tree/Kotlin/k-d-tree.kotlin | 126 +++ Task/K-means++-clustering/00META.yaml | 2 + .../JavaScript/k-means++-clustering.js | 745 ++++++++++++++++ .../Kotlin/k-means++-clustering.kotlin | 162 ++++ .../Erlang/kaprekar-numbers.erl | 27 + .../Factor/kaprekar-numbers.factor | 27 + .../Julia/kaprekar-numbers.julia | 15 +- .../Modula-2/kaprekar-numbers.mod2 | 63 ++ .../REXX/kaprekar-numbers.rexx | 2 +- .../Sidef/kaprekar-numbers.sidef | 15 +- ...oard-input-flush-the-keyboard-buffer.julia | 9 + .../Elena/keyboard-input-keypress-check.elena | 10 + .../Perl/keyboard-input-keypress-check-1.pl | 12 + .../Perl/keyboard-input-keypress-check-2.pl | 50 ++ .../Scala/keyboard-input-keypress-check.scala | 33 + .../keyboard-input-obtain-a-y-or-n-response.c | 2 +- ...board-input-obtain-a-y-or-n-response.julia | 18 + .../Keyboard-macros/Java/keyboard-macros.java | 1 + .../Kotlin/keyboard-macros.kotlin | 25 + .../Julia/knapsack-problem-0-1-1.julia | 25 +- .../Julia/knapsack-problem-0-1-2.julia | 11 +- .../Racket/knapsack-problem-0-1-3.rkt | 33 + .../Racket/knapsack-problem-0-1-4.rkt | 17 + .../Racket/knapsack-problem-0-1-5.rkt | 24 + .../Racket/knapsack-problem-0-1-6.rkt | 1 + .../Ring/knapsack-problem-0-1.ring | 88 ++ .../Julia/knapsack-problem-bounded-1.julia | 31 +- .../Julia/knapsack-problem-bounded-2.julia | 11 +- .../R/knapsack-problem-bounded-1.r | 11 + .../R/knapsack-problem-bounded-2.r | 21 + .../Knapsack-problem-Continuous/00DESCRIPTION | 1 - .../Julia/knapsack-problem-continuous-1.julia | 33 +- .../Julia/knapsack-problem-continuous-2.julia | 42 +- .../Scala/knapsack-problem-continuous.scala | 57 ++ .../Julia/knapsack-problem-unbounded.julia | 23 + .../Scala/knapsack-problem-unbounded.scala | 66 +- .../Knuth-shuffle/BASIC/knuth-shuffle-2.basic | 27 +- .../Knuth-shuffle/BASIC/knuth-shuffle-3.basic | 14 + .../JavaScript/knuth-shuffle-2.js | 60 +- .../JavaScript/knuth-shuffle-4.js | 97 ++- Task/Knuth-shuffle/Julia/knuth-shuffle.julia | 11 + Task/Knuth-shuffle/PicoLisp/knuth-shuffle.l | 18 +- Task/Knuth-shuffle/Ring/knuth-shuffle.ring | 45 +- Task/Knuth-shuffle/Stata/knuth-shuffle.stata | 15 + Task/Knuths-algorithm-S/00DESCRIPTION | 24 +- .../Julia/knuths-algorithm-s.julia | 27 +- .../REXX/knuths-algorithm-s.rexx | 75 +- .../Rust/knuths-algorithm-s.rust | 46 + .../Scala/knuths-algorithm-s.scala | 21 + .../LU-decomposition/Go/lu-decomposition-3.go | 21 +- .../Kotlin/lu-decomposition.kotlin | 102 +++ .../REXX/lu-decomposition.rexx | 115 ++- ...osition.stata => lu-decomposition-1.stata} | 0 .../Stata/lu-decomposition-2.stata | 23 + .../Stata/lu-decomposition-3.stata | 33 + .../BaCon/lzw-compression.bacon | 76 ++ Task/LZW-compression/Go/lzw-compression.go | 135 +-- .../Julia/lzw-compression.julia | 50 ++ .../REXX/lzw-compression-2.rexx | 22 +- .../LZW-compression/Ring/lzw-compression.ring | 81 ++ Task/Langtons-ant/00DESCRIPTION | 10 +- Task/Langtons-ant/Aime/langtons-ant.aime | 40 +- Task/Langtons-ant/Kotlin/langtons-ant.kotlin | 34 + Task/Langtons-ant/REXX/langtons-ant-1.rexx | 37 + Task/Langtons-ant/REXX/langtons-ant-2.rexx | 1 + Task/Langtons-ant/REXX/langtons-ant-3.rexx | 1 + Task/Langtons-ant/REXX/langtons-ant.rexx | 36 - Task/Langtons-ant/Sidef/langtons-ant.sidef | 6 +- Task/Langtons-ant/VBA/langtons-ant.vba | 59 ++ .../largest-int-from-concatenated-ints.aime | 6 +- .../largest-int-from-concatenated-ints-1.lisp | 8 + ...largest-int-from-concatenated-ints-2.lisp} | 0 .../largest-int-from-concatenated-ints.factor | 15 + .../largest-int-from-concatenated-ints.julia | 22 +- .../largest-int-from-concatenated-ints-1.rexx | 23 + .../largest-int-from-concatenated-ints-2.rexx | 29 + .../largest-int-from-concatenated-ints-3.rexx | 56 ++ .../largest-int-from-concatenated-ints-4.rexx | 81 ++ .../largest-int-from-concatenated-ints.rexx | 29 - .../Factor/last-friday-of-each-month.factor | 6 + .../Maple/last-friday-of-each-month.maple | 18 + .../Stata/last-friday-of-each-month.stata | 27 + .../BaCon/last-letter-first-letter-1.bacon | 31 + .../BaCon/last-letter-first-letter-2.bacon | 53 ++ .../Clojure/last-letter-first-letter-1.clj | 38 + .../Clojure/last-letter-first-letter-2.clj | 25 + .../Julia/last-letter-first-letter.julia | 37 + .../REXX/last-letter-first-letter-1.rexx | 2 +- .../REXX/last-letter-first-letter-2.rexx | 9 +- .../Ring/last-letter-first-letter.ring | 70 ++ Task/Leap-year/GW-BASIC/leap-year.gw-basic | 11 + .../Java/{leap-year.java => leap-year-1.java} | 0 Task/Leap-year/Java/leap-year-2.java | 8 + Task/Leap-year/Julia/leap-year.julia | 7 +- .../MATLAB/{leap-year.m => leap-year-1.m} | 0 Task/Leap-year/MATLAB/leap-year-2.m | 1 + Task/Leap-year/Modula-2/leap-year.mod2 | 30 + Task/Leap-year/R/leap-year.r | 2 +- Task/Leap-year/Rust/leap-year.rust | 1 - Task/Leap-year/Visual-Basic/leap-year-1.vb | 9 + Task/Leap-year/Visual-Basic/leap-year-2.vb | 7 + Task/Least-common-multiple/00DESCRIPTION | 6 +- .../C++/least-common-multiple-2.cpp | 10 +- .../Elena/least-common-multiple.elena | 11 + .../GW-BASIC/least-common-multiple.gw-basic | 22 + .../Modula-2/least-common-multiple.mod2 | 29 + .../Perl/least-common-multiple-1.pl | 10 +- .../Perl/least-common-multiple-2.pl | 12 +- .../REXX/least-common-multiple-1.rexx | 2 +- .../Rust/least-common-multiple.rust | 27 +- Task/Left-factorials/00DESCRIPTION | 2 + .../Factor/left-factorials.factor | 26 + .../Left-factorials/Forth/left-factorials.fth | 48 ++ .../Julia/left-factorials.julia | 6 +- .../Left-factorials/Ruby/left-factorials-1.rb | 5 +- .../Left-factorials/Ruby/left-factorials-2.rb | 16 +- .../Standard-ML/left-factorials.ml | 29 + .../Aime/letter-frequency-1.aime | 15 + .../Aime/letter-frequency-2.aime | 13 + .../BaCon/letter-frequency.bacon | 5 + .../Julia/letter-frequency.julia | 10 +- .../Perl-6/letter-frequency.pl6 | 10 +- .../Aime/levenshtein-distance.aime | 38 +- .../Factor/levenshtein-distance.factor | 2 + .../Julia/levenshtein-distance-1.julia | 16 + .../Julia/levenshtein-distance-2.julia | 21 + .../Julia/levenshtein-distance-3.julia | 13 + .../Julia/levenshtein-distance.julia | 20 - ...e.kotlin => levenshtein-distance-1.kotlin} | 0 .../Kotlin/levenshtein-distance-2.kotlin | 19 + .../Ring/levenshtein-distance.ring | 42 + .../Rust/levenshtein-distance.rust | 1 + .../Julia/linear-congruential-generator.julia | 31 +- .../Rust/linear-congruential-generator.rust | 71 ++ .../Stata/linear-congruential-generator.stata | 25 + Task/List-comprehensions/00DESCRIPTION | 2 - .../list-comprehensions-1.applescript | 51 +- .../C/list-comprehensions-1.c | 1 + .../C/list-comprehensions-2.c | 2 + ...mprehensions.c => list-comprehensions-3.c} | 0 .../Haskell/list-comprehensions-5.hs | 1 + .../Haskell/list-comprehensions-6.hs | 1 + .../Java/list-comprehensions.java | 33 + .../JavaScript/list-comprehensions-4.js | 42 +- .../JavaScript/list-comprehensions-5.js | 1 + .../OCaml/list-comprehensions-4.ocaml | 7 + .../Python/list-comprehensions-3.py | 1 + .../Python/list-comprehensions-4.py | 1 + .../Python/list-comprehensions-5.py | 5 + .../Python/list-comprehensions-6.py | 1 + .../Python/list-comprehensions-7.py | 1 + .../REXX/list-comprehensions-1.rexx | 22 +- .../REXX/list-comprehensions-2.rexx | 18 +- .../Stata/list-comprehensions.stata | 8 + .../Elena/literals-floating-point.elena | 3 + .../Julia/literals-floating-point.julia | 7 + .../Stata/literals-floating-point.stata | 4 + .../Factor/literals-integer-1.factor | 4 + .../Factor/literals-integer-2.factor | 2 + .../HolyC/literals-integer-1.holyc | 4 + .../HolyC/literals-integer-2.holyc | 2 + .../Limbo/literals-integer.limbo | 18 + .../REXX/literals-integer.rexx | 39 +- .../Rust/literals-integer.rust | 1 + .../Elena/logical-operations.elena | 12 + ...-operations.hs => logical-operations-1.hs} | 3 + .../Haskell/logical-operations-2.hs | 8 + .../Haskell/logical-operations-3.hs | 8 + .../HolyC/logical-operations.holyc | 7 + .../Modula-2/logical-operations.mod2 | 24 + .../REXX/logical-operations-1.rexx | 26 + .../REXX/logical-operations-2.rexx | 29 + .../REXX/logical-operations.rexx | 27 - .../COBOL/long-multiplication.cobol | 88 ++ .../Ceylon/long-multiplication.ceylon | 58 ++ .../Common-Lisp/long-multiplication.lisp | 6 +- .../JavaScript/long-multiplication-1.js | 2 +- .../Julia/long-multiplication-1.julia | 45 + .../Julia/long-multiplication-2.julia | 2 + .../Maple/long-multiplication.maple | 14 +- .../Perl-6/long-multiplication.pl6 | 6 +- .../Ruby/long-multiplication.rb | 14 +- .../Sidef/long-multiplication-2.sidef | 54 +- .../longest-increasing-subsequence.julia | 20 + .../Ring/longest-increasing-subsequence.ring | 61 ++ .../Rust/longest-increasing-subsequence.rust | 40 + .../longest-increasing-subsequence-1.scala | 51 +- Task/Longest-string-challenge/00DESCRIPTION | 4 +- .../Haskell/longest-string-challenge.hs | 25 + .../Julia/longest-string-challenge.julia | 24 + .../Python/longest-string-challenge.py | 18 +- .../REXX/longest-string-challenge-1.rexx | 36 +- .../REXX/longest-string-challenge-2.rexx | 62 +- .../Ring/longest-string-challenge.ring | 26 + .../BASIC256/look-and-say-sequence.basic256 | 25 + .../C++/look-and-say-sequence.cpp | 48 +- .../Ceylon/look-and-say-sequence.ceylon | 28 + .../Perl-6/look-and-say-sequence.pl6 | 2 +- .../Q/look-and-say-sequence.q | 2 + .../Scala/look-and-say-sequence-1.scala | 36 +- .../Scala/look-and-say-sequence-2.scala | 24 +- .../Scala/look-and-say-sequence-3.scala | 17 + .../00DESCRIPTION | 16 + ...tiple-arrays-simultaneously-1.applescript} | 0 ...ltiple-arrays-simultaneously-2.applescript | 75 ++ ...p-over-multiple-arrays-simultaneously-5.js | 10 +- ...p-over-multiple-arrays-simultaneously-7.js | 33 + ...ver-multiple-arrays-simultaneously-1.julia | 6 +- ...ver-multiple-arrays-simultaneously-2.julia | 10 +- ...op-over-multiple-arrays-simultaneously.red | 7 + ...-over-multiple-arrays-simultaneously.sidef | 4 +- Task/Loops-Break/00DESCRIPTION | 22 +- Task/Loops-Break/ALGOL-60/loops-break.alg | 25 + Task/Loops-Break/Arc/loops-break.arc | 2 +- Task/Loops-Break/BASIC/loops-break-1.basic | 2 +- Task/Loops-Break/C++/loops-break.cpp | 24 +- Task/Loops-Break/C/loops-break.c | 28 +- Task/Loops-Break/HolyC/loops-break.holyc | 2 +- Task/Loops-Break/REXX/loops-break.rexx | 6 +- ...{loops-break.stata => loops-break-1.stata} | 0 Task/Loops-Break/Stata/loops-break-2.stata | 5 + Task/Loops-Continue/00DESCRIPTION | 16 + .../{loops-continue.d => loops-continue-1.d} | 0 Task/Loops-Continue/D/loops-continue-2.d | 6 + Task/Loops-Continue/Red/loops-continue.red | 7 + Task/Loops-Do-while/00DESCRIPTION | 18 + .../Fortress/loops-do-while.fortress | 15 + .../GW-BASIC/loops-do-while-1.gw-basic | 8 + .../GW-BASIC/loops-do-while-2.gw-basic | 4 + .../Haskell/loops-do-while-4.hs | 10 + .../JavaScript/loops-do-while-8.js | 20 + .../JavaScript/loops-do-while-9.js | 6 + Task/Loops-Do-while/Nim/loops-do-while.nim | 2 +- Task/Loops-Do-while/Red/loops-do-while.red | 7 + Task/Loops-Downward-for/00DESCRIPTION | 16 + .../GW-BASIC/loops-downward-for.gw-basic | 3 + .../00DESCRIPTION | 16 + .../loops-for-with-a-specified-step.simula | 6 +- Task/Loops-For/00DESCRIPTION | 17 + Task/Loops-For/BASIC/loops-for-10.basic | 17 +- Task/Loops-For/BASIC/loops-for-11.basic | 17 +- Task/Loops-For/BASIC/loops-for-12.basic | 12 +- Task/Loops-For/BASIC/loops-for-13.basic | 13 +- Task/Loops-For/BASIC/loops-for-14.basic | 13 +- Task/Loops-For/BASIC/loops-for-15.basic | 12 +- Task/Loops-For/BASIC/loops-for-16.basic | 8 +- Task/Loops-For/BASIC/loops-for-17.basic | 6 + Task/Loops-For/C++/loops-for.cpp | 9 +- Task/Loops-For/Klong/loops-for.klong | 10 + Task/Loops-For/PHP/loops-for-3.php | 2 + Task/Loops-For/Perl/loops-for-1.pl | 4 +- Task/Loops-For/Perl/loops-for-3.pl | 2 +- Task/Loops-For/Perl/loops-for-4.pl | 1 + Task/Loops-For/Python/loops-for-3.py | 1 + Task/Loops-For/Rust/loops-for.rust | 12 +- .../{loops-for.stata => loops-for-1.stata} | 0 Task/Loops-For/Stata/loops-for-2.stata | 4 + Task/Loops-Foreach/00DESCRIPTION | 16 + Task/Loops-Foreach/Aime/loops-foreach.aime | 5 + Task/Loops-Foreach/Red/loops-foreach.red | 25 + Task/Loops-Infinite/00DESCRIPTION | 16 + Task/Loops-Infinite/C/loops-infinite-5.c | 3 + .../Emacs-Lisp/loops-infinite.l | 3 + .../Fortress/loops-infinite.fortress | 6 + Task/Loops-Infinite/Perl/loops-infinite-1.pl | 3 + ...{loops-infinite.pl => loops-infinite-2.pl} | 0 Task/Loops-Infinite/Red/loops-infinite.red | 3 + Task/Loops-N-plus-one-half/00DESCRIPTION | 16 +- .../ALGOL-60/loops-n-plus-one-half.alg | 8 + .../Ada/loops-n-plus-one-half.ada | 21 +- .../Fortran/loops-n-plus-one-half-1.f | 52 +- .../Fortran/loops-n-plus-one-half-2.f | 57 +- .../Fortran/loops-n-plus-one-half-3.f | 8 + ...one-half.hs => loops-n-plus-one-half-1.hs} | 5 +- .../Haskell/loops-n-plus-one-half-2.hs | 1 + ...one-half.pl => loops-n-plus-one-half-1.pl} | 2 +- .../Perl/loops-n-plus-one-half-2.pl | 1 + Task/Loops-Nested/00DESCRIPTION | 16 + Task/Loops-Nested/ALGOL-60/loops-nested.alg | 22 + Task/Loops-Nested/Factor/loops-nested.factor | 10 + Task/Loops-Nested/Haskell/loops-nested-1.hs | 4 +- Task/Loops-Nested/Haskell/loops-nested-2.hs | 6 +- Task/Loops-While/00DESCRIPTION | 16 + Task/Loops-While/BASIC/loops-while-3.basic | 6 + Task/Loops-While/C++/loops-while-1.cpp | 2 +- Task/Loops-While/C++/loops-while-2.cpp | 2 +- Task/Loops-While/C++/loops-while-3.cpp | 3 +- Task/Loops-While/C++/loops-while-4.cpp | 3 +- .../Loops-While/Fortress/loops-while.fortress | 9 + Task/Loops-While/Haskell/loops-while-1.hs | 1 + Task/Loops-While/Haskell/loops-while-2.hs | 13 +- Task/Loops-While/Haskell/loops-while-3.hs | 14 +- Task/Loops-While/PL-SQL/loops-while.sql | 10 + Task/Loops-While/Perl/loops-while-1.pl | 2 +- Task/Loops-While/Perl/loops-while-2.pl | 4 +- Task/Loops-While/Perl/loops-while-3.pl | 5 + Task/Loops-While/X86-Assembly/loops-while.x86 | 40 + Task/Lucas-Lehmer-test/00DESCRIPTION | 2 +- .../Forth/lucas-lehmer-test.fth | 8 + .../Julia/lucas-lehmer-test.julia | 16 + Task/Lucas-Lehmer-test/R/lucas-lehmer-test.r | 33 + .../REXX/lucas-lehmer-test.rexx | 112 ++- .../Rust/lucas-lehmer-test.rust | 53 ++ Task/Ludic-numbers/Ring/ludic-numbers.ring | 75 ++ .../8th/luhn-test-of-credit-card-numbers.8th | 25 + .../AWK/luhn-test-of-credit-card-numbers.awk | 8 +- .../luhn-test-of-credit-card-numbers.bf | 9 + .../luhn-test-of-credit-card-numbers-3.js | 20 +- .../luhn-test-of-credit-card-numbers-1.julia | 1 + .../luhn-test-of-credit-card-numbers-2.julia | 10 + .../luhn-test-of-credit-card-numbers.julia | 5 - .../luhn-test-of-credit-card-numbers.pl6 | 23 + .../luhn-test-of-credit-card-numbers.ring | 69 +- .../luhn-test-of-credit-card-numbers.rust | 35 +- .../luhn-test-of-credit-card-numbers-1.scala | 51 +- .../VBA/luhn-test-of-credit-card-numbers.vba | 27 + .../Lingo/md5-implementation-1.lingo | 275 ++++++ .../Lingo/md5-implementation-2.lingo | 12 + .../Perl-6/md5-implementation.pl6 | 12 +- .../Scala/md5-implementation.scala | 20 + Task/MD5/Julia/md5.julia | 35 +- Task/MD5/Lingo/md5-2.lingo | 8 +- Task/Mad-Libs/00DESCRIPTION | 5 + Task/Mad-Libs/Aime/mad-libs.aime | 38 +- .../Mad-Libs/AppleScript/mad-libs.applescript | 7 + Task/Mad-Libs/Julia/mad-libs.julia | 18 + .../BASIC/magic-squares-of-odd-order.basic | 13 + Task/Main-step-of-GOST-28147-89/00DESCRIPTION | 13 +- .../Julia/main-step-of-gost-28147-89.julia | 41 + .../Kotlin/main-step-of-gost-28147-89.kotlin | 77 ++ .../REXX/main-step-of-gost-28147-89.rexx | 52 +- .../Aime/make-directory-path.aime | 21 + .../make-directory-path.applescript | 58 ++ .../D/make-directory-path.d | 29 + .../Julia/make-directory-path.julia | 1 + .../Lua/make-directory-path.lua | 11 + .../Objeck/make-directory-path.objeck | 5 + Task/Man-or-boy-test/00DESCRIPTION | 11 +- .../Man-or-boy-test/Aime/man-or-boy-test.aime | 12 +- .../Man-or-boy-test/Rust/man-or-boy-test.rust | 39 + .../Swift/man-or-boy-test-1.swift | 11 +- .../Swift/man-or-boy-test-2.swift | 24 +- .../Swift/man-or-boy-test-3.swift | 14 + .../BASIC/mandelbrot-set-10.basic | 15 + .../BASIC/mandelbrot-set-11.basic | 20 + .../BASIC/mandelbrot-set-2.basic | 34 +- .../BASIC/mandelbrot-set-6.basic | 129 +-- .../BASIC/mandelbrot-set-7.basic | 103 ++- .../BASIC/mandelbrot-set-8.basic | 44 +- .../BASIC/mandelbrot-set-9.basic | 44 +- Task/Mandelbrot-set/C/mandelbrot-set-3.c | 3 + Task/Mandelbrot-set/J/mandelbrot-set-2.j | 2 +- .../Mandelbrot-set/Maple/mandelbrot-set.maple | 1 + .../Metapost/mandelbrot-set-1.metapost | 44 + .../Metapost/mandelbrot-set-2.metapost | 1 + Task/Mandelbrot-set/Processing/mandelbrot-set | 64 ++ Task/Mandelbrot-set/Ring/mandelbrot-set.ring | 2 +- Task/Mandelbrot-set/Rust/mandelbrot-set.rust | 43 + Task/Map-range/Julia/map-range.julia | 9 +- Task/Map-range/Maple/map-range.maple | 8 + Task/Map-range/REXX/map-range-1.rexx | 12 +- Task/Map-range/REXX/map-range-2.rexx | 14 +- Task/Map-range/REXX/map-range-3.rexx | 21 +- Task/Map-range/REXX/map-range-4.rexx | 2 +- Task/Map-range/Ring/map-range.ring | 5 +- Task/Map-range/Stata/map-range-1.stata | 22 + Task/Map-range/Stata/map-range-2.stata | 6 + Task/Matrix-arithmetic/00DESCRIPTION | 3 +- .../Go/matrix-arithmetic-4.go | 6 +- .../Perl/matrix-arithmetic.pl | 27 + .../Sidef/matrix-arithmetic.sidef | 31 + .../Simula/matrix-arithmetic.simula | 33 +- .../Stata/matrix-arithmetic-1.stata | 28 + .../Stata/matrix-arithmetic-2.stata | 19 + .../matrix-exponentiation-operator.sidef | 22 + .../matrix-exponentiation-operator-1.stata | 13 + .../matrix-exponentiation-operator-2.stata | 7 + .../Fortran/matrix-multiplication-1.f | 4 +- .../Go/matrix-multiplication-1.go | 10 +- .../Klong/matrix-multiplication.klong | 4 + .../Stata/matrix-multiplication-1.stata | 9 + .../Stata/matrix-multiplication-2.stata | 8 + .../Go/matrix-transposition-1.go | 8 +- .../JavaScript/matrix-transposition-3.js | 4 +- .../Perl-6/matrix-transposition.pl6 | 23 +- .../REXX/matrix-transposition.rexx | 25 + .../Stata/matrix-transposition-1.stata | 16 + .../Stata/matrix-transposition-2.stata | 21 + .../Astro/maximum-triangle-path-sum.astro | 16 +- .../C++/maximum-triangle-path-sum.cpp | 3 +- .../Elena/maximum-triangle-path-sum.elena | 52 ++ .../Julia/maximum-triangle-path-sum.julia | 31 + .../Perl-6/maximum-triangle-path-sum.pl6 | 36 + .../Ring/maximum-triangle-path-sum.ring | 57 ++ .../Stata/maximum-triangle-path-sum.stata | 11 + .../BASIC/maze-generation.basic | 68 ++ .../Batch-File/maze-generation.bat | 94 ++ .../Julia/maze-generation-1.julia | 19 + .../Julia/maze-generation-2.julia | 13 + .../Julia/maze-generation.julia | 27 - .../OCaml/maze-generation.ocaml | 13 +- .../Swift/maze-generation.swift | 16 +- Task/Maze-solving/Julia/maze-solving.julia | 80 ++ Task/Maze-solving/Kotlin/maze-solving.kotlin | 117 +++ Task/Median-filter/Julia/median-filter.julia | 7 + .../Median-filter/Kotlin/median-filter.kotlin | 57 ++ .../Julia/memory-allocation.julia | 2 + .../memory-layout-of-a-data-structure.julia | 23 + .../memory-layout-of-a-data-structure.scala | 40 + Task/Menu/00DESCRIPTION | 1 - Task/Menu/Julia/menu.julia | 28 + Task/Menu/Rust/menu.rust | 47 + Task/Menu/Scala/menu.scala | 28 + .../Metaprogramming/Nim/metaprogramming-1.nim | 2 +- .../Metaprogramming/Nim/metaprogramming-7.nim | 4 +- .../Scala/metaprogramming.scala | 11 + .../Kotlin/metered-concurrency.kotlin | 20 + .../Scala/metered-concurrency.scala | 30 + Task/Metronome/Julia/metronome.julia | 13 + Task/Metronome/Scala/metronome.scala | 14 + .../Aime/middle-three-digits.aime | 11 +- .../Elena/middle-three-digits.elena | 29 + .../Factor/middle-three-digits.factor | 26 + .../Julia/middle-three-digits.julia | 21 +- .../Kotlin/middle-three-digits.kotlin | 20 +- .../VBA/middle-three-digits.vba | 21 + .../Ceylon/minesweeper-game.ceylon | 134 +++ .../Rust/minesweeper-game.rust | 316 +++++++ .../VBA/minesweeper-game-1.vba | 12 + .../VBA/minesweeper-game-2.vba | 241 ++++++ .../Julia/modular-exponentiation.julia | 9 +- .../C-sharp/modular-inverse.cs | 24 + .../Factor/modular-inverse.factor | 2 + .../GW-BASIC/modular-inverse.gw-basic | 27 + .../Modula-2/modular-inverse.mod2 | 43 + .../PureBasic/modular-inverse.purebasic | 37 + ...lo-methods.go => monte-carlo-methods-1.go} | 0 .../Go/monte-carlo-methods-2.go | 34 + .../Julia/monte-carlo-methods.julia | 14 +- .../Ruby/monte-carlo-methods.rb | 3 +- .../Rust/monte-carlo-methods.rust | 33 + Task/Morse-code/ABAP/morse-code.abap | 72 ++ Task/Morse-code/Modula-2/morse-code.mod2 | 62 ++ Task/Morse-code/Red/morse-code-1.red | 60 ++ Task/Morse-code/Red/morse-code-2.red | 25 + Task/Morse-code/Ring/morse-code.ring | 55 ++ Task/Morse-code/VBA/morse-code.vba | 60 ++ Task/Mouse-position/00DESCRIPTION | 1 + .../Aime/move-to-front-algorithm.aime | 48 ++ .../Bracmat/move-to-front-algorithm.bracmat | 46 + .../Go/move-to-front-algorithm.go | 9 +- .../Julia/move-to-front-algorithm.julia | 33 + .../REXX/move-to-front-algorithm-2.rexx | 12 +- .../Ring/move-to-front-algorithm.ring | 42 + Task/Multifactorial/Aime/multifactorial.aime | 30 + .../BBC-BASIC/multifactorial.bbc | 17 + .../Factor/multifactorial.factor | 15 + .../Multifactorial/Julia/multifactorial.julia | 24 +- .../Multifactorial/Maple/multifactorial.maple | 16 + .../multiple-distinct-objects-1.applescript | 46 +- .../Julia/multiple-distinct-objects-1.julia | 2 + .../Julia/multiple-distinct-objects-2.julia | 1 + Task/Multiple-regression/00META.yaml | 2 +- .../Fortran/multiple-regression.f | 22 +- .../Kotlin/multiple-regression.kotlin | 121 +++ .../Stata/multiple-regression-1.stata | 7 + .../Stata/multiple-regression-2.stata | 1 + .../Stata/multiple-regression-3.stata | 11 + .../Stata/multiple-regression-4.stata | 25 + .../GW-BASIC/multiplication-tables.gw-basic | 17 + .../HolyC/multiplication-tables.holyc | 21 + .../JavaScript/multiplication-tables-4.js | 92 ++ .../Modula-2/multiplication-tables.mod2 | 39 + .../VBA/multiplication-tables.vba | 29 + .../Clojure/multiplicative-order.clj | 26 + .../Java/multiplicative-order.java | 106 +++ .../Kotlin/multiplicative-order.kotlin | 94 ++ .../Perl-6/multiplicative-order.pl6 | 5 +- .../Sidef/multiplicative-order.sidef | 26 + .../{multisplit.hs => multisplit-1.hs} | 0 Task/Multisplit/Haskell/multisplit-2.hs | 25 + .../{multisplit.js => multisplit-1.js} | 0 Task/Multisplit/JavaScript/multisplit-2.js | 119 +++ Task/Multisplit/Ring/multisplit.ring | 12 + .../Munching-squares/AWK/munching-squares.awk | 17 + .../Factor/munching-squares.factor | 21 + .../Kotlin/munching-squares.kotlin | 47 + .../Perl-6/munching-squares-1.pl6 | 2 +- .../Perl-6/munching-squares-2.pl6 | 2 +- .../REXX/munching-squares.rexx | 20 + .../Ring/munching-squares.ring | 57 ++ .../Elena/mutual-recursion.elena | 20 + .../Maple/mutual-recursion.maple | 17 + ...ens-problem.clj => n-queens-problem-1.clj} | 0 .../Clojure/n-queens-problem-2.clj | 6 + .../Prolog/n-queens-problem-6.pro | 5 + .../REXX/n-queens-problem.rexx | 10 +- .../Sidef/n-queens-problem.sidef | 31 + .../Stata/n-queens-problem-1.stata | 38 +- .../Stata/n-queens-problem-3.stata | 41 +- .../Stata/n-queens-problem-4.stata | 2 + .../Wart/n-queens-problem.wart | 24 + Task/Named-parameters/Go/named-parameters.go | 20 + .../Perl-6/named-parameters-2.pl6 | 6 + Task/Narcissist/D/narcissist.d | 1 + Task/Narcissist/Julia/narcissist.julia | 3 + Task/Narcissist/Scala/narcissist.scala | 11 + .../Narcissistic-decimal-number/00DESCRIPTION | 8 + .../COBOL/narcissistic-decimal-number.cobol | 57 ++ .../Factor/narcissistic-decimal-number.factor | 15 + .../Maple/narcissistic-decimal-number.maple | 22 + .../Perl-6/narcissistic-decimal-number-2.pl6 | 16 +- .../REXX/narcissistic-decimal-number-1.rexx | 16 +- .../REXX/narcissistic-decimal-number-2.rexx | 20 +- .../REXX/narcissistic-decimal-number-3.rexx | 29 +- .../REXX/narcissistic-decimal-number-4.rexx | 40 + .../Ruby/narcissistic-decimal-number.rb | 28 +- .../Haskell/natural-sorting.hs | 89 ++ .../Natural-sorting/Phix/natural-sorting.phix | 2 +- .../PowerShell/natural-sorting.psh | 62 ++ Task/Nautical-bell/C/nautical-bell.c | 46 +- .../Mathematica/nautical-bell.math | 1 + Task/Nautical-bell/REXX/nautical-bell.rexx | 29 +- Task/Nautical-bell/Ring/nautical-bell.ring | 23 + .../Julia/non-continuous-subsequences.julia | 56 ++ .../Ring/non-continuous-subsequences.ring | 61 ++ .../non-decimal-radices-convert-1.applescript | 55 +- .../Maple/non-decimal-radices-convert.maple | 31 + .../R/non-decimal-radices-convert.r | 26 + .../Ring/non-decimal-radices-convert.ring | 32 + .../Scala/non-decimal-radices-convert.scala | 3 + .../Scala/non-decimal-radices-input.scala | 5 + .../Julia/non-decimal-radices-output.julia | 10 +- .../Ring/non-decimal-radices-output.ring | 2 +- .../Scala/non-decimal-radices-output.scala | 9 + .../Go/{nth-root.go => nth-root-1.go} | 0 Task/Nth-root/Go/nth-root-2.go | 65 ++ Task/Nth-root/Julia/nth-root.julia | 22 +- Task/Nth-root/Sidef/nth-root-1.sidef | 12 +- Task/Nth-root/Sidef/nth-root-2.sidef | 6 +- Task/Nth/AppleScript/nth.applescript | 68 +- Task/Nth/Elena/nth.elena | 29 + Task/Nth/Fortran/nth.f | 2 + Task/Nth/GW-BASIC/nth.gw-basic | 28 + Task/Nth/Julia/nth-1.julia | 18 +- Task/Nth/Julia/nth-2.julia | 25 +- Task/Nth/Modula-2/nth.mod2 | 45 + Task/Nth/Rust/nth.rust | 24 +- Task/Nth/Stata/nth.stata | 18 + Task/Null-object/AutoIt/null-object.autoit | 2 + Task/Null-object/Haskell/null-object-4.hs | 4 + Task/Null-object/Haskell/null-object-5.hs | 4 + .../Null-object/Visual-Basic/null-object-1.vb | 15 + .../Null-object/Visual-Basic/null-object-2.vb | 17 + Task/Number-names/AWK/number-names.awk | 1 + Task/Number-names/Go/number-names.go | 92 +- Task/Number-names/Java/number-names-1.java | 78 +- Task/Number-names/JavaScript/number-names.js | 44 + .../Astro/number-reversal-game.astro | 22 +- .../REXX/number-reversal-game.rexx | 52 +- .../Ring/number-reversal-game.ring | 53 ++ .../Perl-6/numeric-error-propagation.pl6 | 2 +- ...al-integration-gauss-legendre-quadrature.m | 74 ++ .../Julia/numerical-integration.julia | 18 +- .../Ring/numerical-integration.ring | 88 ++ .../Stata/numerical-integration.stata | 41 + .../Haskell/object-serialization.hs | 25 + .../Julia/object-serialization.julia | 37 + .../Kotlin/object-serialization.kotlin | 57 ++ .../Ceylon/odd-word-problem.ceylon | 33 + .../Julia/odd-word-problem.julia | 33 + .../Ring/odd-word-problem.ring | 46 + .../VBA/odd-word-problem-1.vba | 35 + .../VBA/odd-word-problem-2.vba | 39 + .../VBA/odd-word-problem-3.vba | 11 + Task/Old-lady-swallowed-a-fly/00DESCRIPTION | 3 +- .../Fortran/old-lady-swallowed-a-fly.f | 38 + .../Haskell/old-lady-swallowed-a-fly.hs | 58 +- .../Julia/old-lady-swallowed-a-fly-1.julia | 10 + .../Julia/old-lady-swallowed-a-fly-2.julia | 22 + .../Modula-2/old-lady-swallowed-a-fly.mod2 | 52 ++ .../Rust/old-lady-swallowed-a-fly.rust | 5 + ...> one-dimensional-cellular-automata-1.fth} | 0 .../one-dimensional-cellular-automata-2.fth | 10 + .../one-dimensional-cellular-automata.julia | 8 +- .../one-dimensional-cellular-automata.kotlin | 27 + .../one-dimensional-cellular-automata-1.nim | 96 +-- ... one-dimensional-cellular-automata-1.pari} | 0 .../one-dimensional-cellular-automata-2.pari | 1 + .../one-dimensional-cellular-automata-3.pari | 10 + .../one-dimensional-cellular-automata.pl6 | 36 + .../one-dimensional-cellular-automata.ring | 27 + Task/One-of-n-lines-in-a-file/00DESCRIPTION | 23 +- .../Kotlin/one-of-n-lines-in-a-file.kotlin | 24 + .../Rust/one-of-n-lines-in-a-file.rust | 27 +- Task/OpenGL/BaCon/opengl.bacon | 34 + Task/OpenGL/Lingo/opengl.lingo | 58 ++ Task/OpenGL/Racket/opengl.rkt | 2 +- Task/OpenGL/Ring/opengl.ring | 25 + .../Kotlin/optional-parameters.kotlin | 46 + .../Aime/order-disjoint-list-items.aime | 37 +- .../C++/order-disjoint-list-items.cpp | 71 ++ .../Perl-6/order-disjoint-list-items.pl6 | 19 + .../Aime/order-two-numerical-lists.aime | 30 + .../J/order-two-numerical-lists-2.j | 50 +- .../J/order-two-numerical-lists-3.j | 29 + .../Julia/order-two-numerical-lists.julia | 13 + Task/Ordered-Partitions/00DESCRIPTION | 15 +- .../C++/ordered-partitions.cpp | 57 ++ .../Julia/ordered-partitions.julia | 24 + .../Perl-6/ordered-partitions.pl6 | 13 +- .../REXX/ordered-partitions.rexx | 56 +- Task/Ordered-words/Aime/ordered-words.aime | 50 +- .../Ordered-words/Julia/ordered-words-1.julia | 9 +- .../Ordered-words/Julia/ordered-words-2.julia | 24 +- Task/Ordered-words/Maple/ordered-words.maple | 19 + Task/Ordered-words/Red/ordered-words.red | 15 + ...ction.lisp => palindrome-detection-1.lisp} | 0 .../Common-Lisp/palindrome-detection-2.lisp | 16 + .../Falcon/palindrome-detection-1.falcon | 11 + .../Falcon/palindrome-detection-2.falcon | 5 + .../Forth/palindrome-detection-2.fth | 2 +- .../Modula-2/palindrome-detection.mod2 | 39 + .../OCaml/palindrome-detection-2.ocaml | 10 +- .../Processing/palindrome-detection | 21 + .../Rust/palindrome-detection-1.rust | 2 +- .../UNIX-Shell/palindrome-detection.sh | 5 + ...gram-checker.ats => pangram-checker-1.ats} | 0 .../Pangram-checker/ATS/pangram-checker-2.ats | 19 + .../AppleScript/pangram-checker-1.applescript | 48 +- .../Julia/pangram-checker.julia | 31 +- .../Maple/pangram-checker-1.maple | 7 + .../Maple/pangram-checker-2.maple | 3 + .../Pangram-checker/REXX/pangram-checker.rexx | 14 +- Task/Paraffins/Scala/paraffins.scala | 34 + .../Julia/parallel-calculations.julia | 21 + .../Kotlin/parallel-calculations.kotlin | 52 ++ .../Perl-6/parallel-calculations.pl6 | 35 +- .../Perl/parallel-calculations.pl | 19 + Task/Parametric-polymorphism/00DESCRIPTION | 8 +- .../Julia/parametric-polymorphism.julia | 12 + .../REXX/parametric-polymorphism.rexx | 35 +- .../Haskell/parametrized-sql-statement.hs | 20 + .../Julia/parametrized-sql-statement.julia | 19 + .../Kotlin/parametrized-sql-statement.kotlin | 24 + .../Julia/parse-an-ip-address.julia | 34 + .../Scala/parse-an-ip-address.scala | 296 +++++++ .../parsing-rpn-calculator-algorithm-1.factor | 4 + .../parsing-rpn-calculator-algorithm-2.factor | 2 + .../parsing-rpn-calculator-algorithm-1.maxima | 39 + .../parsing-rpn-calculator-algorithm-2.maxima | 15 + .../parsing-rpn-calculator-algorithm-1.n | 118 +++ .../parsing-rpn-calculator-algorithm-2.n | 14 + .../parsing-rpn-calculator-algorithm-3.n | 89 ++ .../parsing-rpn-calculator-algorithm-4.n | 14 + .../parsing-rpn-calculator-algorithm-1.pari | 39 + .../parsing-rpn-calculator-algorithm-2.pari | 13 + .../parsing-rpn-calculator-algorithm-1.sh | 65 ++ .../parsing-rpn-calculator-algorithm-2.sh | 14 + .../C++/parsing-rpn-to-infix-conversion.cpp | 5 +- .../C/parsing-rpn-to-infix-conversion.c | 127 +++ .../parsing-rpn-to-infix-conversion.julia | 20 + .../parsing-rpn-to-infix-conversion.kotlin | 52 ++ .../8th/parsing-shunting-yard-algorithm.8th | 130 +++ .../D/parsing-shunting-yard-algorithm.d | 90 ++ .../parsing-shunting-yard-algorithm.js | 4 +- .../parsing-shunting-yard-algorithm.julia | 41 + .../parsing-shunting-yard-algorithm.kotlin | 61 ++ .../Rust/parsing-shunting-yard-algorithm.rust | 159 ++++ .../parsing-shunting-yard-algorithm-1.sh | 103 +++ .../parsing-shunting-yard-algorithm-2.sh | 48 ++ .../Elena/partial-function-application.elena | 10 +- .../partial-function-application.factor | 11 + .../Julia/partial-function-application.julia | 12 + .../Julia/pascals-triangle-puzzle.julia | 14 + .../REXX/pascals-triangle-puzzle.rexx | 64 +- .../Scala/pascals-triangle-puzzle.scala | 12 + Task/Pascals-triangle/00DESCRIPTION | 2 +- .../pascals-triangle-1.commodore | 24 + .../pascals-triangle-2.commodore | 12 + .../Modula-2/pascals-triangle.mod2 | 33 + .../Perl/pascals-triangle-4.pl | 34 + .../Ruby/pascals-triangle-1.rb | 2 +- .../Rust/pascals-triangle.rust | 15 + .../Scala/pascals-triangle-1.scala | 10 +- .../Scala/pascals-triangle-2.scala | 5 +- .../Scala/pascals-triangle-3.scala | 10 + .../Stata/pascals-triangle-1.stata | 26 + .../Stata/pascals-triangle-2.stata | 16 + .../ZX-Spectrum-Basic/pascals-triangle-1.zx | 24 + .../ZX-Spectrum-Basic/pascals-triangle-2.zx | 1 + Task/Pattern-matching/00DESCRIPTION | 7 +- .../C++/pattern-matching-1.cpp | 45 + .../C++/pattern-matching-2.cpp | 103 +++ .../Kotlin/pattern-matching.kotlin | 84 ++ .../REXX/pattern-matching.rexx | 38 + Task/Penneys-game/Factor/penneys-game.factor | 88 ++ Task/Penneys-game/Kotlin/penneys-game.kotlin | 69 ++ Task/Penneys-game/Perl-6/penneys-game.pl6 | 6 +- Task/Penneys-game/PicoLisp/penneys-game.l | 45 + Task/Penneys-game/VBA/penneys-game.vba | 81 ++ .../percentage-difference-between-images-1.go | 74 +- .../percentage-difference-between-images.java | 74 +- ...percentage-difference-between-images.julia | 17 + ...ercentage-difference-between-images.kotlin | 43 + .../percentage-difference-between-images-1.py | 16 + ...percentage-difference-between-images-2.py} | 0 .../Go/percolation-bond-percolation.go | 4 +- .../Julia/percolation-bond-percolation.julia | 93 ++ .../percolation-bond-percolation.kotlin | 91 ++ .../percolation-mean-cluster-density.julia | 51 ++ .../percolation-mean-cluster-density.kotlin | 80 ++ .../Julia/percolation-mean-run-density.julia | 20 + .../percolation-mean-run-density.kotlin | 40 + .../Julia/percolation-site-percolation.julia | 75 ++ .../percolation-site-percolation.kotlin | 67 ++ .../Julia/perfect-numbers.julia | 7 +- .../Modula-2/perfect-numbers.mod2 | 43 + .../Perl-6/perfect-numbers.pl6 | 5 +- .../Java/permutation-test.java | 30 + .../Julia/permutation-test-1.julia | 35 +- .../Julia/permutation-test-2.julia | 18 +- .../Perl-6/permutations-derangements.pl6 | 27 +- ...ents.pl => permutations-derangements-1.pl} | 0 .../Perl/permutations-derangements-2.pl | 25 + .../REXX/permutations-derangements.rexx | 73 +- .../permutations-rank-of-a-permutation.pl | 20 + .../permutations-rank-of-a-permutation.rexx | 49 +- .../permutations-rank-of-a-permutation.ring | 44 + Task/Permutations-by-swapping/00DESCRIPTION | 2 +- .../C/permutations-by-swapping.c | 69 ++ .../Clojure/permutations-by-swapping-1.clj | 42 +- .../Julia/permutations-by-swapping-1.julia | 58 ++ .../Julia/permutations-by-swapping-2.julia | 23 + ...ing.lua => permutations-by-swapping-1.lua} | 0 .../Lua/permutations-by-swapping-2.lua | 21 + .../REXX/permutations-by-swapping.rexx | 78 +- .../Scala/permutations-by-swapping.scala | 36 + Task/Permutations/Fortran/permutations-3.f | 398 ++++++++- Task/Permutations/Fortran/permutations-4.f | 41 + Task/Permutations/Julia/permutations.julia | 2 + Task/Permutations/Rust/permutations-1.rust | 52 +- Task/Permutations/Rust/permutations-2.rust | 13 +- .../{permutations.st => permutations-1.st} | 0 Task/Permutations/Smalltalk/permutations-2.st | 27 + Task/Permutations/Smalltalk/permutations-3.st | 2 + Task/Permutations/Stata/permutations-2.stata | 10 +- Task/Pernicious-numbers/00DESCRIPTION | 6 +- .../AWK/pernicious-numbers.awk | 54 ++ .../Factor/pernicious-numbers.factor | 6 + ...ous-numbers.hs => pernicious-numbers-1.hs} | 0 .../Haskell/pernicious-numbers-2.hs | 26 + .../Julia/pernicious-numbers.julia | 29 +- .../Modula-2/pernicious-numbers.mod2 | 50 ++ .../Ring/pernicious-numbers.ring | 42 + .../Elena/phrase-reversals.elena | 17 + .../Factor/phrase-reversals.factor | 9 + .../Perl-6/phrase-reversals.pl6 | 8 +- .../Phrase-reversals/VBA/phrase-reversals.vba | 32 + Task/Pi/Fortran/pi-1.f | 35 +- Task/Pi/JavaScript/pi-1.js | 25 + Task/Pi/JavaScript/pi-2.js | 44 + Task/Pi/JavaScript/{pi.js => pi-3.js} | 0 ...ment.basic => pick-random-element-1.basic} | 0 .../BASIC/pick-random-element-2.basic | 8 + .../Haskell/pick-random-element-1.hs | 2 +- .../Haskell/pick-random-element-2.hs | 5 +- .../Haskell/pick-random-element-3.hs | 6 +- .../Kotlin/pick-random-element.kotlin | 35 +- .../Nim/pick-random-element.nim | 12 +- .../Perl-6/pick-random-element-2.pl6 | 6 +- .../Perl-6/pick-random-element-3.pl6 | 6 +- .../Red/pick-random-element.red | 1 + .../Ring/pick-random-element.ring | 2 +- .../Ruby/pick-random-element.rb | 6 +- .../Rust/pick-random-element.rust | 6 +- .../VBA/pick-random-element.vba | 10 + .../Ring/pig-the-dice-game.ring | 31 + .../VBA/pig-the-dice-game.vba | 50 ++ .../Julia/pinstripe-display.julia | 20 + .../Ring/pinstripe-display.ring | 64 ++ .../pinstripe-display.sinclair | 9 + .../Playing-cards/Factor/playing-cards.factor | 19 + .../{playing-cards.st => playing-cards-1.st} | 0 .../Smalltalk/playing-cards-2.st | 37 + .../Smalltalk/playing-cards-3.st | 14 + .../Julia/plot-coordinate-pairs.julia | 8 +- .../Kotlin/plot-coordinate-pairs.kotlin | 39 + .../Perl-6/plot-coordinate-pairs.pl6 | 9 +- .../Ring/plot-coordinate-pairs.ring | 78 ++ .../Elena/polymorphic-copy.elena | 24 + .../Scala/polymorphic-copy.scala | 21 + Task/Polymorphism/Elena/polymorphism.elena | 46 + Task/Polymorphism/Julia/polymorphism.julia | 20 +- .../APL/polynomial-long-division.apl | 8 + .../Clojure/polynomial-long-division.clj | 95 +++ .../Java/polynomial-long-division.java | 118 +++ .../Kotlin/polynomial-long-division.kotlin | 90 ++ .../REXX/polynomial-long-division.rexx | 44 + .../D/polynomial-regression.d | 47 + .../Java/polynomial-regression.java | 50 ++ .../Julia/polynomial-regression.julia | 9 +- .../Kotlin/polynomial-regression.kotlin | 38 + .../Modula-2/polynomial-regression.mod2 | 87 ++ .../Ruby/polynomial-regression-1.rb | 4 +- .../Ruby/polynomial-regression-2.rb | 8 +- Task/Power-set/Clojure/power-set-2.clj | 5 +- Task/Power-set/Go/power-set.go | 6 +- .../{power-set.pari => power-set-1.pari} | 0 Task/Power-set/PARI-GP/power-set-2.pari | 2 + Task/Power-set/Perl/power-set-10.pl | 25 +- Task/Power-set/Perl/power-set-11.pl | 21 + Task/Power-set/Perl/power-set-2.pl | 8 +- Task/Power-set/Perl/power-set-3.pl | 2 +- Task/Power-set/Perl/power-set-4.pl | 18 +- Task/Power-set/Perl/power-set-5.pl | 18 +- Task/Power-set/Perl/power-set-6.pl | 15 +- Task/Power-set/Perl/power-set-7.pl | 10 +- Task/Power-set/Perl/power-set-8.pl | 4 +- Task/Power-set/Perl/power-set-9.pl | 9 +- Task/Power-set/Ring/power-set.ring | 23 + Task/Power-set/Swift/power-set-1.swift | 15 + Task/Power-set/Swift/power-set-2.swift | 2 + .../C/pragmatic-directives.c | 41 + .../Scala/pragmatic-directives.scala | 2 + .../Gambas/price-fraction.gambas | 14 + Task/Price-fraction/VBA/price-fraction.vba | 18 + .../Clojure/primality-by-trial-division-2.clj | 2 +- .../Clojure/primality-by-trial-division-3.clj | 2 +- ...isp => primality-by-trial-division-1.lisp} | 0 .../primality-by-trial-division-2.lisp | 15 + .../Lingo/primality-by-trial-division-1.lingo | 8 + .../Lingo/primality-by-trial-division-2.lingo | 5 + ...ef => primality-by-trial-division-1.sidef} | 0 .../Sidef/primality-by-trial-division-2.sidef | 8 + .../VBA/primality-by-trial-division.vba | 27 + .../Erlang/prime-decomposition.erl | 1 + .../Ring/prime-decomposition.ring | 2 +- .../Sidef/prime-decomposition-1.sidef | 5 +- .../Sidef/prime-decomposition-2.sidef | 28 +- .../Sidef/prime-decomposition-3.sidef | 2 +- .../Stata/prime-decomposition.stata | 26 + Task/Priority-queue/C/priority-queue.c | 11 +- Task/Priority-queue/Nim/priority-queue-2.nim | 24 +- Task/Priority-queue/Nim/priority-queue-3.nim | 18 + .../Priority-queue/REXX/priority-queue-1.rexx | 16 +- .../XLISP/priority-queue-1.xlisp | 35 + .../XLISP/priority-queue-10.xlisp | 3 + .../XLISP/priority-queue-2.xlisp | 7 + .../XLISP/priority-queue-3.xlisp | 6 + .../XLISP/priority-queue-4.xlisp | 3 + .../XLISP/priority-queue-5.xlisp | 3 + .../XLISP/priority-queue-6.xlisp | 3 + .../XLISP/priority-queue-7.xlisp | 3 + .../XLISP/priority-queue-8.xlisp | 8 + .../XLISP/priority-queue-9.xlisp | 15 + .../REXX/probabilistic-choice.rexx | 39 +- .../Ring/probabilistic-choice.ring | 25 + .../Rust/probabilistic-choice.rust | 127 +++ .../Stata/probabilistic-choice.stata | 8 + .../Julia/problem-of-apollonius-1.julia | 51 ++ .../Julia/problem-of-apollonius-2.julia | 8 + .../Julia/problem-of-apollonius.julia | 55 -- .../ARM-Assembly/program-name.arm | 54 ++ .../Common-Lisp/program-termination.lisp | 15 +- .../Julia/program-termination.julia | 1 + .../Simula/program-termination.simula | 1 + Task/Pythagorean-triples/00DESCRIPTION | 9 +- .../360-Assembly/pythagorean-triples.360 | 127 +++ .../JavaScript/pythagorean-triples-1.js | 62 +- .../Rust/pythagorean-triples.rust | 46 + Task/QR-decomposition/C/qr-decomposition.c | 2 +- .../Elena/quaternion-type.elena | 87 ++ .../Quaternion-type/Rust/quaternion-type.rust | 173 ++++ .../Elena/queue-definition.elena | 62 ++ .../Perl-6/queue-definition.pl6 | 31 + Task/Queue-Usage/Astro/queue-usage.astro | 8 +- Task/Queue-Usage/Julia/queue-usage.julia | 7 + .../Julia/quickselect-algorithm.julia | 2 + .../Maple/quickselect-algorithm.maple | 36 + .../Ring/quickselect-algorithm.ring | 32 +- Task/Quine/JavaScript/quine-4.js | 2 +- Task/Quine/JavaScript/quine-5.js | 6 +- Task/Quine/JavaScript/quine-7.js | 2 +- Task/Quine/JavaScript/quine-8.js | 5 + Task/Quine/MATLAB/quine-1.m | 8 +- Task/Quine/MATLAB/quine-2.m | 6 +- Task/Quine/MATLAB/quine-3.m | 4 +- Task/Quine/MATLAB/quine-4.m | 1 + Task/Quine/Python/quine-1.py | 4 +- Task/Quine/Python/quine-10.py | 6 +- Task/Quine/Python/quine-11.py | 10 +- Task/Quine/Python/quine-12.py | 12 +- Task/Quine/Python/quine-13.py | 5 + Task/Quine/Python/quine-2.py | 3 +- Task/Quine/Python/quine-3.py | 2 +- Task/Quine/Python/quine-4.py | 2 +- Task/Quine/Python/quine-5.py | 2 +- Task/Quine/Python/quine-6.py | 1 - Task/Quine/Python/quine-7.py | 6 +- Task/Quine/Python/quine-8.py | 15 +- Task/Quine/Python/quine-9.py | 14 +- Task/Quine/REXX/quine-1.rexx | 2 +- Task/Quine/REXX/quine-2.rexx | 9 +- Task/Quine/Rust/quine-3.rust | 42 + Task/RIPEMD-160/Julia/ripemd-160.julia | 71 +- Task/RSA-code/Java/rsa-code.java | 27 + Task/RSA-code/Julia/rsa-code.julia | 18 + .../D/random-number-generator--device-.d | 10 + .../random-number-generator--device-.rust | 7 +- .../random-number-generator--device-.scala | 9 + .../random-number-generator--included-.elena | 7 + .../Random-numbers/Elena/random-numbers.elena | 32 + .../Factor/random-numbers.factor | 1 + Task/Random-numbers/Go/random-numbers.go | 31 +- ...{random-numbers.hs => random-numbers-1.hs} | 0 .../Haskell/random-numbers-2.hs | 1 + .../Haskell/random-numbers-3.hs | 9 + .../Lingo/random-numbers-1.lingo | 5 + .../Lingo/random-numbers-2.lingo | 4 + ...m-numbers.scala => random-numbers-1.scala} | 0 .../Scala/random-numbers-2.scala | 25 + .../Standard-ML/random-numbers-3.ml | 36 + ...m-numbers.stata => random-numbers-1.stata} | 0 .../Stata/random-numbers-2.stata | 1 + .../Range-expansion/Ring/range-expansion.ring | 44 + .../Clojure/range-extraction.clj | 16 + .../Factor/range-extraction.factor | 18 + .../Ring/range-extraction.ring | 46 + .../Rust/range-extraction-1.rust | 12 +- .../Rust/range-extraction-3.rust | 2 +- Task/Ranking-methods/C/ranking-methods.c | 119 +++ Task/Ranking-methods/D/ranking-methods.d | 167 ++++ Task/Rate-counter/D/rate-counter.d | 20 + Task/Ray-casting-algorithm/00DESCRIPTION | 2 +- .../Java/ray-casting-algorithm.java | 2 +- .../Julia/ray-casting-algorithm-1.julia | 45 + .../Julia/ray-casting-algorithm-2.julia | 31 + .../REXX/ray-casting-algorithm.rexx | 61 +- .../Racket/ray-casting-algorithm.rkt | 28 +- .../Rust/ray-casting-algorithm.rust | 90 +- .../ray-casting-algorithm.visual | 47 + Task/Read-a-configuration-file/00DESCRIPTION | 2 +- .../Aime/read-a-configuration-file.aime | 55 +- .../C/read-a-configuration-file.c | 171 ++++ .../Clojure/read-a-configuration-file.clj | 50 +- .../read-a-configuration-file-1.lisp | 50 +- .../read-a-configuration-file-2.lisp | 21 +- .../Julia/read-a-configuration-file.julia | 24 + .../Perl-6/read-a-configuration-file.pl6 | 2 +- .../read-a-configuration-file-4.psh | 88 ++ .../read-a-configuration-file-5.psh | 1 + .../read-a-configuration-file-6.psh | 1 + .../read-a-configuration-file-7.psh | 8 + .../read-a-configuration-file-8.psh | 45 + .../Rust/read-a-configuration-file.rust | 80 ++ .../Aime/read-a-file-line-by-line.aime | 4 +- .../Astro/read-a-file-line-by-line.astro | 5 +- .../C/read-a-file-line-by-line-1.c | 2 +- .../Maple/read-a-file-line-by-line.maple | 6 + .../read-a-specific-line-from-a-file.aime | 20 +- .../Red/read-a-specific-line-from-a-file.red | 7 + .../read-a-specific-line-from-a-file-1.rust | 19 + .../read-a-specific-line-from-a-file-2.rust | 32 + .../Julia/read-entire-file-1.julia | 4 +- .../Julia/read-entire-file-2.julia | 3 +- .../Perl/real-constants-and-functions.pl | 6 + .../Scala/real-constants-and-functions.scala | 12 + Task/Record-sound/Julia/record-sound.julia | 5 + Task/Reduced-row-echelon-form/00DESCRIPTION | 20 +- .../Aime/reduced-row-echelon-form.aime | 20 +- .../J/reduced-row-echelon-form-1.j | 44 +- .../J/reduced-row-echelon-form-2.j | 26 +- .../J/reduced-row-echelon-form-3.j | 53 +- .../J/reduced-row-echelon-form-4.j | 37 + .../Kotlin/reduced-row-echelon-form.kotlin | 80 ++ .../Perl-6/reduced-row-echelon-form-1.pl6 | 16 +- .../REXX/reduced-row-echelon-form.rexx | 49 +- .../Ring/reduced-row-echelon-form.ring | 60 ++ .../Sidef/reduced-row-echelon-form.sidef | 35 +- Task/Regular-expressions/00DESCRIPTION | 8 +- .../Factor/regular-expressions.factor | 8 + .../Maple/regular-expressions.maple | 5 + .../Ring/regular-expressions.ring | 12 + .../Aime/remove-duplicate-elements-1.aime | 5 + .../Aime/remove-duplicate-elements-2.aime | 12 + .../Elena/remove-duplicate-elements.elena | 13 + ...ements.f => remove-duplicate-elements-1.f} | 0 .../Fortran/remove-duplicate-elements-2.f | 21 + .../remove-duplicate-elements.gw-basic | 27 + .../Gambas/remove-duplicate-elements.gambas | 14 + .../Julia/remove-duplicate-elements.julia | 4 +- .../Modula-2/remove-duplicate-elements.mod2 | 49 ++ .../Red/remove-duplicate-elements.red | 3 + .../Rust/remove-duplicate-elements.rust | 25 +- .../VBA/remove-duplicate-elements.vba | 29 + .../VBA/remove-lines-from-a-file-1.vba | 34 + .../VBA/remove-lines-from-a-file-2.vba | 36 + .../VBScript/remove-lines-from-a-file.vb | 2 +- Task/Rename-a-file/BaCon/rename-a-file.bacon | 4 + .../Rename-a-file/JavaScript/rename-a-file.js | 10 +- Task/Rename-a-file/OCaml/rename-a-file.ocaml | 9 +- .../Rename-a-file/Octave/rename-a-file.octave | 2 +- Task/Rep-string/BaCon/rep-string.bacon | 17 + Task/Rep-string/Julia/rep-string.julia | 35 +- Task/Rep-string/Ring/rep-string.ring | 34 + .../BaCon/repeat-a-string-1.bacon | 4 + .../BaCon/repeat-a-string-2.bacon | 1 + .../Julia/repeat-a-string.julia | 8 +- .../Perl-6/repeat-a-string.pl6 | 2 +- Task/Repeat-a-string/Red/repeat-a-string.red | 5 + Task/Resistor-mesh/Java/resistor-mesh.java | 107 +++ .../Resistor-mesh/Modula-2/resistor-mesh.mod2 | 111 +++ .../respond-to-an-unknown-method-call.julia | 13 + .../respond-to-an-unknown-method-call.kotlin | 22 +- .../Objeck/return-multiple-values.objeck | 11 + .../VBA/return-multiple-values-1.vba | 19 + .../VBA/return-multiple-values-2.vba | 21 + .../VBA/return-multiple-values-3.vba | 34 + .../VBA/return-multiple-values-4.vba | 18 + .../Aime/reverse-a-string.aime | 2 +- .../Fortran/reverse-a-string-3.f | 13 + .../Modula-2/reverse-a-string.mod2 | 40 + ...se-a-string.nim => reverse-a-string-1.nim} | 0 .../Nim/reverse-a-string-2.nim | 4 + .../Reverse-a-string/Red/reverse-a-string.red | 2 + .../Aime/reverse-words-in-a-string.aime | 43 +- .../Factor/reverse-words-in-a-string.factor | 15 + .../Lua/reverse-words-in-a-string-1.lua | 9 + ...ng.lua => reverse-words-in-a-string-2.lua} | 0 .../Modula-2/reverse-words-in-a-string.mod2 | 58 ++ .../Nial/reverse-words-in-a-string.nial | 18 + .../R/reverse-words-in-a-string-1.r | 18 + .../R/reverse-words-in-a-string-2.r | 3 + .../Red/reverse-words-in-a-string.red | 15 + .../VBA/reverse-words-in-a-string.vba | 38 + .../ALGOL-68/rock-paper-scissors.alg | 230 ++--- .../Aime/rock-paper-scissors.aime | 43 +- .../C/rock-paper-scissors-1.c | 31 +- .../Kotlin/rock-paper-scissors.kotlin | 79 ++ .../Lua/rock-paper-scissors.lua | 106 ++- .../PHP/rock-paper-scissors.php | 28 + .../Perl-6/rock-paper-scissors-1.pl6 | 2 +- .../REXX/rock-paper-scissors-1.rexx | 25 +- .../REXX/rock-paper-scissors-2.rexx | 33 +- .../Ring/rock-paper-scissors.ring | 40 + .../Rust/rock-paper-scissors.rust | 83 ++ .../Elena/roman-numerals-decode.elena | 43 + .../Elixir/roman-numerals-decode.elixir | 3 +- .../Forth/roman-numerals-decode-2.fth | 66 +- .../Julia/roman-numerals-decode-1.julia | 28 +- .../Julia/roman-numerals-decode-2.julia | 18 +- .../UNIX-Shell/roman-numerals-decode.sh | 35 + .../VBA/roman-numerals-decode.vba | 34 + .../Clojure/roman-numerals-encode-5.clj | 20 + .../Clojure/roman-numerals-encode-6.clj | 5 + .../Elena/roman-numerals-encode.elena | 31 + .../Julia/roman-numerals-encode.julia | 31 +- ....kotlin => roman-numerals-encode-1.kotlin} | 0 .../Kotlin/roman-numerals-encode-2.kotlin | 19 + .../Modula-2/roman-numerals-encode.mod2 | 46 + .../Perl-6/roman-numerals-encode.pl6 | 22 + .../Python/roman-numerals-encode-5.py | 22 + .../SETL/roman-numerals-encode.setl | 17 + .../Julia/roots-of-a-quadratic-function.julia | 38 +- .../Roots-of-unity/Stata/roots-of-unity.stata | 12 + Task/Rot-13/00DESCRIPTION | 2 +- Task/Rot-13/6502-Assembly/rot-13.6502 | 65 +- Task/Rot-13/Applesoft-BASIC/rot-13.applesoft | 2 + Task/Rot-13/Elena/rot-13.elena | 30 + Task/Rot-13/Julia/rot-13.julia | 7 +- Task/Rot-13/Perl-6/rot-13.pl6 | 2 +- Task/Rot-13/PowerBASIC/rot-13.powerbasic | 40 + Task/Rot-13/PowerShell/rot-13.psh | 16 +- Task/Rot-13/Python/rot-13-3.py | 33 +- Task/Rot-13/Python/rot-13-4.py | 20 +- Task/Rot-13/Ring/rot-13.ring | 2 +- Task/Rot-13/Stata/rot-13.stata | 11 + Task/Rot-13/Visual-Basic/rot-13-1.vb | 24 + Task/Rot-13/Visual-Basic/rot-13-2.vb | 4 + .../BaCon/run-length-encoding.bacon | 42 + .../Ceylon/run-length-encoding.ceylon | 31 + .../Elena/run-length-encoding.elena | 63 ++ .../Factor/run-length-encoding.factor | 18 + .../Julia/run-length-encoding.julia | 10 + .../Python/run-length-encoding-1.py | 17 +- .../Ring/run-length-encoding.ring | 30 + .../VBA/run-length-encoding.vba | 37 + .../Runge-Kutta-method/C/runge-kutta-method.c | 2 +- .../Julia/runge-kutta-method-1.julia | 23 + .../Julia/runge-kutta-method-2.julia | 21 + .../Julia/runge-kutta-method.julia | 33 - .../Nim/runge-kutta-method.nim | 26 + .../Octave/runge-kutta-method.octave | 31 +- .../REXX/runge-kutta-method.rexx | 44 +- .../Rust/runge-kutta-method.rust | 20 +- .../Stata/runge-kutta-method.stata | 41 + ...runtime-evaluation-in-an-environment.elena | 9 + ...ntime-evaluation-in-an-environment-1.julia | 10 + ...ntime-evaluation-in-an-environment-2.julia | 9 + ...runtime-evaluation-in-an-environment.scala | 8 + .../Elena/runtime-evaluation.elena | 6 + .../Java/runtime-evaluation.java | 86 ++ .../Julia/runtime-evaluation-1.julia | 1 + .../Julia/runtime-evaluation-2.julia | 6 + Task/S-Expressions/Julia/s-expressions.julia | 74 ++ .../S-Expressions/Kotlin/s-expressions.kotlin | 98 +++ Task/SEDOLs/C++/sedols.cpp | 59 +- Task/SEDOLs/Gambas/sedols.gambas | 29 + Task/SEDOLs/Julia/sedols.julia | 21 + Task/SHA-1/Astro/sha-1.astro | 5 +- Task/SHA-1/J/sha-1-2.j | 39 +- Task/SHA-1/J/sha-1-3.j | 39 +- Task/SHA-1/J/sha-1-4.j | 5 + Task/SHA-1/Julia/sha-1.julia | 45 +- Task/SHA-1/Lingo/sha-1.lingo | 2 + Task/SHA-1/Ring/sha-1.ring | 10 + Task/SHA-256/J/sha-256-3.j | 1 + Task/SHA-256/J/sha-256-4.j | 2 + Task/SHA-256/Julia/sha-256.julia | 17 +- Task/SHA-256/Ring/sha-256.ring | 10 + Task/SHA-256/Rust/sha-256.rust | 14 +- Task/SOAP/C/soap-1.c | 56 ++ Task/SOAP/C/soap-2.c | 10 + Task/SOAP/C/soap-3.c | 10 + Task/SOAP/Clojure/soap.clj | 5 + Task/SOAP/Kotlin/soap.kotlin | 59 ++ .../Julia/sql-based-authentication.julia | 48 ++ .../Kotlin/sql-based-authentication.kotlin | 101 +++ Task/Safe-addition/D/safe-addition.d | 16 + Task/Safe-addition/Java/safe-addition.java | 20 + Task/Safe-addition/Julia/safe-addition.julia | 19 + Task/Safe-addition/Scala/safe-addition.scala | 13 + Task/Same-Fringe/Julia/same-fringe.julia | 50 ++ Task/Same-Fringe/Perl-6/same-fringe.pl6 | 26 + Task/Same-Fringe/REXX/same-fringe-3.rexx | 132 ++- .../00DESCRIPTION | 3 +- .../Ring/scope-function-names-and-labels.ring | 11 + .../scope-function-names-and-labels.scala | 55 ++ .../C-sharp/scope-modifiers-1.cs | 19 +- Task/Search-a-list/Aime/search-a-list.aime | 4 +- Task/Search-a-list/Julia/search-a-list.julia | 17 +- Task/Search-a-list/Maple/search-a-list.maple | 10 + .../Perl-6/secure-temporary-file.pl6 | 20 + .../PicoLisp/secure-temporary-file.l | 5 +- .../Factor/self-describing-numbers.factor | 11 + .../Haskell/self-describing-numbers-1.hs | 17 +- .../Haskell/self-describing-numbers-2.hs | 11 +- .../Julia/self-describing-numbers.julia | 17 +- .../Modula-2/self-describing-numbers.mod2 | 51 ++ .../Red/self-describing-numbers.red | 30 + .../Ring/self-describing-numbers.ring | 27 + .../Rust/self-describing-numbers.rust | 22 + .../Scala/self-describing-numbers.scala | 14 + .../Aime/self-referential-sequence.aime | 55 +- .../Perl-6/self-referential-sequence.pl6 | 11 +- Task/Semiprime/Factor/semiprime-1.factor | 4 + Task/Semiprime/Factor/semiprime-2.factor | 1 + Task/Semiprime/Julia/semiprime.julia | 4 +- Task/Semiprime/Lingo/semiprime-1.lingo | 13 + Task/Semiprime/Lingo/semiprime-2.lingo | 5 + Task/Semiprime/Perl-6/semiprime-1.pl6 | 5 +- Task/Semiprime/Perl-6/semiprime-2.pl6 | 4 +- Task/Semiprime/Ring/semiprime.ring | 2 +- Task/Semiprime/Ruby/semiprime.rb | 2 +- Task/Semiprime/Rust/semiprime.rust | 56 ++ Task/Semordnilap/00DESCRIPTION | 2 +- Task/Semordnilap/Aime/semordnilap.aime | 25 +- Task/Semordnilap/Haskell/semordnilap.hs | 21 +- Task/Semordnilap/Kotlin/semordnilap.kotlin | 4 +- Task/Semordnilap/OCaml/semordnilap.ocaml | 6 +- Task/Semordnilap/Octave/semordnilap.octave | 5 + Task/Semordnilap/Ring/semordnilap.ring | 42 +- Task/Semordnilap/Stata/semordnilap.stata | 18 + .../Julia/send-an-unknown-method-call.julia | 6 + Task/Send-email/C/send-email.c | 99 +++ Task/Send-email/Groovy/send-email.groovy | 47 + Task/Send-email/Haskell/send-email-1.hs | 24 + Task/Send-email/Haskell/send-email-2.hs | 7 + Task/Send-email/Julia/send-email.julia | 18 + Task/Send-email/Ring/send-email.ring | 1 + .../Factor/sequence-of-non-squares.factor | 12 + .../Julia/sequence-of-non-squares.julia | 6 +- .../REXX/sequence-of-non-squares.rexx | 32 +- .../VBA/sequence-of-non-squares.vba | 19 + .../Aime/set-consolidation.aime | 52 +- .../Ring/set-consolidation.ring | 41 + .../Elena/set-of-real-numbers.elena | 18 +- .../Julia/set-of-real-numbers.julia | 76 ++ .../Perl-6/set-of-real-numbers.pl6 | 45 +- Task/Set/Lua/{set.lua => set-1.lua} | 0 Task/Set/Lua/set-2.lua | 111 +++ Task/Set/Perl-6/set.pl6 | 4 +- Task/Set/Ring/set.ring | 116 +++ .../seven-sided-dice-from-five-sided-dice.pl6 | 20 + ...seven-sided-dice-from-five-sided-dice.ring | 22 + Task/Shell-one-liner/Go/shell-one-liner.go | 1 + .../Elena/short-circuit-evaluation.elena | 4 +- .../Factor/short-circuit-evaluation.factor | 14 + .../short-circuit-evaluation.livecode | 17 +- .../Modula-2/short-circuit-evaluation.mod2 | 42 + .../Ring/short-circuit-evaluation.ring | 31 + .../Rust/short-circuit-evaluation.rust | 19 + .../Stata/short-circuit-evaluation-1.stata | 24 + .../Stata/short-circuit-evaluation-2.stata | 15 + ...w-the-epoch.abap => show-the-epoch-1.abap} | 0 .../Show-the-epoch/ABAP/show-the-epoch-2.abap | 1 + .../Show-the-epoch/Julia/show-the-epoch.julia | 3 +- .../Show-the-epoch/Lingo/show-the-epoch.lingo | 9 + Task/Show-the-epoch/REXX/show-the-epoch.rexx | 16 +- .../Show-the-epoch/Stata/show-the-epoch.stata | 4 + .../Julia/sierpinski-carpet.julia | 26 +- .../Perl-6/sierpinski-carpet.pl6 | 27 + .../ATS/sierpinski-triangle-graphical.ats | 103 +++ .../Erlang/sierpinski-triangle-graphical.erl | 29 + .../Julia/sierpinski-triangle-graphical.julia | 21 + .../Python/sierpinski-triangle-graphical-1.py | 29 +- .../Python/sierpinski-triangle-graphical-2.py | 75 +- .../Python/sierpinski-triangle-graphical-3.py | 60 ++ .../Julia/sierpinski-triangle.julia | 29 +- .../MATLAB/sierpinski-triangle-3.m | 1 + .../C++/sieve-of-eratosthenes-1.cpp | 61 +- .../C++/sieve-of-eratosthenes-2.cpp | 50 +- .../C++/sieve-of-eratosthenes-3.cpp | 41 + .../C/sieve-of-eratosthenes-2.c | 2 +- .../Common-Lisp/sieve-of-eratosthenes-2.lisp | 24 +- .../Go/sieve-of-eratosthenes-6.go | 58 ++ .../Limbo/sieve-of-eratosthenes.limbo | 40 + .../Lingo/sieve-of-eratosthenes-1.lingo | 41 + .../Lingo/sieve-of-eratosthenes-2.lingo | 2 + .../MATLAB/sieve-of-eratosthenes-1.m | 11 +- .../MATLAB/sieve-of-eratosthenes-2.m | 15 +- .../Nim/sieve-of-eratosthenes-1.nim | 27 +- .../SAS/sieve-of-eratosthenes.sas | 17 + .../Scheme/sieve-of-eratosthenes-8.ss | 2 +- .../Scheme/sieve-of-eratosthenes-9.ss | 9 +- .../Stata/sieve-of-eratosthenes-1.stata | 20 +- .../Kotlin/simple-database.kotlin | 110 +++ .../Perl-6/simple-database-1.pl6 | 104 +++ .../Perl-6/simple-database-2.pl6 | 50 ++ Task/Simple-database/Perl/simple-database.pl | 118 +++ .../Factor/simple-windowed-application.factor | 27 + .../Java/simple-windowed-application.java | 37 +- .../Julia/simple-windowed-application.julia | 23 + ...n => simple-windowed-application-1.kotlin} | 0 .../simple-windowed-application-2.kotlin | 13 + .../Perl-6/simple-windowed-application.pl6 | 7 +- .../Phix/simple-windowed-application-1.phix | 20 + ...hix => simple-windowed-application-2.phix} | 5 +- .../Python/simulate-input-keyboard-1.py | 6 + ...yboard.py => simulate-input-keyboard-2.py} | 0 .../Rust/simulate-input-keyboard.rust | 4 + Task/Simulate-input-Mouse/00DESCRIPTION | 1 - .../C/simulate-input-mouse.c | 38 + .../Python/simulate-input-mouse-2.py | 32 +- .../Python/simulate-input-mouse-3.py | 19 + .../Ring/simulate-input-mouse.ring | 45 + .../Rust/simulate-input-mouse.rust | 25 + Task/Singleton/Julia/singleton.julia | 6 + ...ingly-linked-list-element-definition.elena | 11 + ...ingly-linked-list-element-definition.julia | 59 ++ ...gly-linked-list-element-definition-1.scala | 10 +- ...gly-linked-list-element-definition-2.scala | 14 +- ...gly-linked-list-element-definition-1.stata | 8 + ...ly-linked-list-element-definition-10.stata | 2 + ...ly-linked-list-element-definition-11.stata | 1 + ...ly-linked-list-element-definition-12.stata | 5 + ...ly-linked-list-element-definition-13.stata | 7 + ...ly-linked-list-element-definition-14.stata | 7 + ...gly-linked-list-element-definition-2.stata | 3 + ...gly-linked-list-element-definition-3.stata | 36 + ...gly-linked-list-element-definition-4.stata | 22 + ...gly-linked-list-element-definition-5.stata | 12 + ...gly-linked-list-element-definition-6.stata | 13 + ...gly-linked-list-element-definition-7.stata | 37 + ...gly-linked-list-element-definition-8.stata | 6 + ...gly-linked-list-element-definition-9.stata | 6 + ...singly-linked-list-element-insertion.elena | 7 + ...singly-linked-list-element-insertion.julia | 21 + ...singly-linked-list-element-insertion.scala | 15 +- .../Elena/singly-linked-list-traversal.elena | 4 + .../Julia/singly-linked-list-traversal.julia | 12 + .../Limbo/singly-linked-list-traversal.limbo | 20 + .../Perl-6/singly-linked-list-traversal-2.pl6 | 2 +- .../Scala/singly-linked-list-traversal.scala | 15 + Task/Sleep/Elena/sleep.elena | 9 + Task/Sleep/Red/sleep.red | 4 + Task/Sockets/Elena/sockets.elena | 12 + Task/Sockets/Kotlin/sockets.kotlin | 10 + Task/Sockets/Ursa/sockets.ursa | 4 + Task/Sokoban/Kotlin/sokoban.kotlin | 116 +++ .../Kotlin/solve-a-hidato-puzzle.kotlin | 75 ++ .../Perl-6/solve-a-hidato-puzzle.pl6 | 2 +- .../Go/solve-a-holy-knights-tour.go | 94 ++ .../Haskell/solve-a-holy-knights-tour-3.hs | 203 +++-- .../Haskell/solve-a-holy-knights-tour-4.hs | 98 +++ .../Perl-6/solve-a-holy-knights-tour.pl6 | 86 ++ .../Kotlin/solve-a-hopido-puzzle.kotlin | 96 +++ .../Perl-6/solve-a-hopido-puzzle.pl6 | 84 ++ .../Kotlin/solve-a-numbrix-puzzle.kotlin | 90 ++ .../Perl-6/solve-a-numbrix-puzzle.pl6 | 116 +++ .../solve-the-no-connection-puzzle.kotlin | 84 ++ .../Perl-6/solve-the-no-connection-puzzle.pl6 | 84 ++ ...ort-an-array-of-composite-structures.julia | 53 +- .../Red/sort-an-integer-array.red | 4 + .../Stata/sort-an-integer-array-1.stata | 20 + .../Stata/sort-an-integer-array-2.stata | 3 + ...ay.stata => sort-an-integer-array-3.stata} | 0 .../Elena/sort-disjoint-sublist.elena | 29 + .../Julia/sort-disjoint-sublist.julia | 9 +- ...nt-sublist.k => sort-disjoint-sublist-1.k} | 0 .../K/sort-disjoint-sublist-2.k | 6 + .../Kotlin/sort-disjoint-sublist.kotlin | 17 + .../Nial/sort-disjoint-sublist.nial | 4 + .../Perl-6/sort-disjoint-sublist-2.pl6 | 2 +- .../Kotlin/sort-stability.kotlin | 10 + Task/Sort-stability/Rust/sort-stability.rust | 8 +- .../sort-using-a-custom-comparator.elena | 16 + .../sort-using-a-custom-comparator.julia | 22 +- .../Perl-6/sort-using-a-custom-comparator.pl6 | 7 + .../Julia/sorting-algorithms-bead-sort.julia | 38 +- .../REXX/sorting-algorithms-bead-sort.rexx | 23 +- .../Elena/sorting-algorithms-bogosort.elena | 25 + .../Gambas/sorting-algorithms-bogosort.gambas | 19 + .../Julia/sorting-algorithms-bogosort.julia | 28 +- .../Maple/sorting-algorithms-bogosort.maple | 16 + .../Ring/sorting-algorithms-bogosort.ring | 43 + .../C/sorting-algorithms-bubble-sort.c | 5 +- .../sorting-algorithms-bubble-sort-1.cobol | 145 ++++ ...=> sorting-algorithms-bubble-sort-2.cobol} | 0 .../D/sorting-algorithms-bubble-sort.d | 30 +- .../sorting-algorithms-bubble-sort.elixir | 18 +- .../sorting-algorithms-bubble-sort.gambas | 32 + .../sorting-algorithms-bubble-sort.julia | 27 +- .../sorting-algorithms-bubble-sort.maple | 16 + .../N-t-roff/sorting-algorithms-bubble-sort.n | 70 ++ .../sorting-algorithms-bubble-sort-2.rexx | 4 +- .../sorting-algorithms-bubble-sort-1.shen | 27 + .../sorting-algorithms-bubble-sort-2.shen | 12 + .../sorting-algorithms-bubble-sort-3.shen | 11 + .../sorting-algorithms-bubble-sort-4.shen | 1 + .../sorting-algorithms-cocktail-sort.elena | 50 ++ .../sorting-algorithms-cocktail-sort.gambas | 47 + .../sorting-algorithms-cocktail-sort.julia | 25 +- .../sorting-algorithms-cocktail-sort.maple | 26 + .../Elena/sorting-algorithms-comb-sort.elena | 42 + .../sorting-algorithms-comb-sort.gambas | 43 + .../Maple/sorting-algorithms-comb-sort.maple | 32 + ... => sorting-algorithms-comb-sort-1.pascal} | 3 + .../sorting-algorithms-comb-sort-2.pascal | 53 ++ .../REXX/sorting-algorithms-comb-sort.rexx | 17 +- .../Scala/sorting-algorithms-comb-sort.scala | 29 + .../00DESCRIPTION | 5 + .../sorting-algorithms-counting-sort.basic256 | 37 + .../sorting-algorithms-counting-sort.elena | 37 + .../sorting-algorithms-counting-sort-1.f | 12 +- .../sorting-algorithms-counting-sort.julia | 37 +- .../sorting-algorithms-counting-sort.pl6 | 13 + .../sorting-algorithms-counting-sort-1.rexx | 36 +- .../sorting-algorithms-counting-sort.rust | 34 + .../00DESCRIPTION | 7 +- .../Elena/sorting-algorithms-gnome-sort.elena | 40 + .../sorting-algorithms-gnome-sort.gambas | 39 + .../Julia/sorting-algorithms-gnome-sort.julia | 18 +- .../Maple/sorting-algorithms-gnome-sort.maple | 14 + .../Maple/sorting-algorithms-heapsort.maple | 36 + .../REXX/sorting-algorithms-heapsort-1.rexx | 19 +- .../REXX/sorting-algorithms-heapsort-2.rexx | 18 +- .../Ring/sorting-algorithms-heapsort.ring | 53 ++ .../Rust/sorting-algorithms-heapsort-1.rust | 28 +- .../Rust/sorting-algorithms-heapsort-2.rust | 4 +- .../sorting-algorithms-insertion-sort-1.alg | 13 + .../sorting-algorithms-insertion-sort-2.alg | 16 + .../sorting-algorithms-insertion-sort.elena | 33 + .../sorting-algorithms-insertion-sort-1.f | 29 +- .../sorting-algorithms-insertion-sort-2.f | 23 +- .../sorting-algorithms-insertion-sort.maple | 12 + .../sorting-algorithms-insertion-sort-1.n | 55 ++ .../sorting-algorithms-insertion-sort-2.n | 45 + .../sorting-algorithms-insertion-sort.stata | 15 + .../sorting-algorithms-merge-sort-1.astro | 18 +- .../Julia/sorting-algorithms-merge-sort.julia | 57 +- .../Maple/sorting-algorithms-merge-sort.maple | 39 + .../REXX/sorting-algorithms-merge-sort.rexx | 27 +- .../sorting-algorithms-pancake-sort.clj | 10 + .../sorting-algorithms-pancake-sort.elena | 66 ++ .../sorting-algorithms-pancake-sort.julia | 27 +- .../Rust/sorting-algorithms-pancake-sort.rust | 42 + ...sorting-algorithms-permutation-sort.factor | 8 + .../sorting-algorithms-permutation-sort.maple | 10 + .../sorting-algorithms-permutation-sort.ring | 38 + .../Elena/sorting-algorithms-quicksort.elena | 48 ++ .../sorting-algorithms-quicksort.elixir | 13 +- .../Java/sorting-algorithms-quicksort-1.java | 30 + .../Java/sorting-algorithms-quicksort-2.java | 11 + .../Java/sorting-algorithms-quicksort.java | 31 - .../sorting-algorithms-quicksort-1.js | 2 +- .../sorting-algorithms-quicksort-2.kotlin | 5 +- .../Maple/sorting-algorithms-quicksort.maple | 29 + .../PHP/sorting-algorithms-quicksort-1.php | 8 +- .../Ring/sorting-algorithms-quicksort.ring | 49 ++ .../sorting-algorithms-quicksort-1.ml | 7 + ...t.ml => sorting-algorithms-quicksort-2.ml} | 14 - .../sorting-algorithms-quicksort.type | 64 ++ .../Fortran/sorting-algorithms-radix-sort.f | 14 +- .../Perl-6/sorting-algorithms-radix-sort.pl6 | 3 +- .../Racket/sorting-algorithms-radix-sort.rkt | 20 +- .../sorting-algorithms-selection-sort.elena | 33 + .../sorting-algorithms-selection-sort.gambas | 49 ++ .../sorting-algorithms-selection-sort.julia | 26 +- .../sorting-algorithms-selection-sort.maple | 16 + .../sorting-algorithms-selection-sort-1.n | 43 + .../sorting-algorithms-selection-sort-2.n | 19 + .../sorting-algorithms-selection-sort.stata | 13 + .../Maple/sorting-algorithms-shell-sort.maple | 20 + .../Elena/sorting-algorithms-sleep-sort.elena | 27 + .../Julia/sorting-algorithms-sleep-sort.julia | 20 +- .../sorting-algorithms-sleep-sort.kotlin | 23 + .../sorting-algorithms-stooge-sort.clj | 13 + .../sorting-algorithms-stooge-sort.elena | 31 + .../sorting-algorithms-stooge-sort.scala | 20 + .../Perl-6/sorting-algorithms-strand-sort.pl6 | 41 +- .../Ring/sorting-algorithms-strand-sort.ring | 47 + Task/Soundex/00DESCRIPTION | 4 +- Task/Soundex/C++/soundex.cpp | 77 ++ Task/Soundex/Julia/soundex.julia | 50 ++ Task/Soundex/Lua/soundex.lua | 42 + Task/Soundex/NetRexx/soundex.netrexx | 103 +++ Task/Soundex/PowerShell/soundex-3.psh | 18 + Task/Soundex/PowerShell/soundex-4.psh | 15 + Task/Soundex/Ring/soundex.ring | 23 + .../Stata/{soundex.stata => soundex-1.stata} | 0 Task/Soundex/Stata/soundex-2.stata | 2 + .../C/sparkline-in-unicode.c | 49 ++ .../Julia/sparkline-in-unicode.julia | 30 +- .../Java/special-variables.java | 30 + .../AutoIt/speech-synthesis.autoit | 2 + .../Kotlin/speech-synthesis.kotlin | 26 + .../Spiral-matrix/Octave/spiral-matrix.octave | 40 +- Task/Spiral-matrix/Perl-6/spiral-matrix-1.pl6 | 19 + Task/Spiral-matrix/Perl-6/spiral-matrix-2.pl6 | 19 +- Task/Spiral-matrix/Perl-6/spiral-matrix-3.pl6 | 28 +- Task/Spiral-matrix/Prolog/spiral-matrix.pro | 51 ++ Task/Spiral-matrix/Ring/spiral-matrix.ring | 46 + .../Spiral-matrix/Scilab/spiral-matrix.scilab | 47 +- Task/Spiral-matrix/Stata/spiral-matrix.stata | 21 + .../Batch-File/stable-marriage-problem.bat | 243 +++--- .../Ceylon/stable-marriage-problem.ceylon | 138 +++ .../Julia/stable-marriage-problem.julia | 125 +++ .../Kotlin/stable-marriage-problem.kotlin | 198 ++--- Task/Stack-traces/Julia/stack-traces.julia | 4 + Task/Stack/Julia/stack.julia | 16 +- .../Julia/stair-climbing-puzzle-1.julia | 1 + .../Julia/stair-climbing-puzzle-2.julia | 2 + .../Kotlin/stair-climbing-puzzle.kotlin | 23 + .../Julia/state-name-puzzle-1.julia | 55 ++ .../Julia/state-name-puzzle-2.julia | 6 + .../Kotlin/state-name-puzzle.kotlin | 71 ++ .../Perl-6/state-name-puzzle.pl6 | 6 +- .../Factor/statistics-basic.factor | 37 + .../Julia/statistics-basic.julia | 18 + .../Klong/statistics-basic.klong | 9 + .../Perl-6/statistics-basic.pl6 | 2 +- .../PicoLisp/statistics-basic.l | 28 + Task/Statistics-Basic/R/statistics-basic.r | 28 + .../REXX/statistics-basic.rexx | 25 +- .../Ring/statistics-basic.ring | 41 + Task/Stem-and-leaf-plot/00DESCRIPTION | 2 +- ...d-leaf-plot.hs => stem-and-leaf-plot-1.hs} | 0 .../Haskell/stem-and-leaf-plot-2.hs | 72 ++ ...d-leaf-plot.js => stem-and-leaf-plot-1.js} | 0 .../JavaScript/stem-and-leaf-plot-2.js | 211 +++++ .../Ring/stem-and-leaf-plot.ring | 34 + .../PicoLisp/stern-brocot-sequence.l | 17 + .../REXX/stern-brocot-sequence.rexx | 51 +- .../Ring/stern-brocot-sequence.ring | 56 ++ .../Sidef/stern-brocot-sequence.sidef | 2 +- Task/String-append/Ada/string-append.ada | 9 + .../String-append/Factor/string-append.factor | 1 + .../String-append/Falcon/string-append.falcon | 6 + Task/String-append/Stata/string-append.stata | 5 + Task/String-case/BASIC/string-case-5.basic | 8 +- Task/String-case/BASIC/string-case-6.basic | 8 +- Task/String-case/BASIC/string-case-7.basic | 11 +- Task/String-case/BASIC/string-case-8.basic | 26 +- Task/String-case/Fortran/string-case-4.f | 76 ++ Task/String-case/Red/string-case.red | 7 + Task/String-case/Simula/string-case.simula | 6 + .../Astro/string-comparison.astro | 30 +- .../Factor/string-comparison.factor | 18 + .../Falcon/string-comparison.falcon | 35 + Task/String-concatenation/00DESCRIPTION | 1 + ...ation.abap => string-concatenation-1.abap} | 0 .../ABAP/string-concatenation-2.abap | 13 + .../Falcon/string-concatenation.falcon | 7 + .../Perl-6/string-concatenation.pl6 | 9 + .../Red/string-concatenation.red | 6 + .../Simula/string-concatenation.simula | 14 + .../Stata/string-concatenation-1.stata | 5 + .../Stata/string-concatenation-2.stata | 5 + .../VBA/string-concatenation.vba | 11 + .../string-interpolation--included-.falcon | 8 + ... => string-interpolation--included--1.nim} | 0 .../Nim/string-interpolation--included--2.nim | 5 + .../string-interpolation--included--5.py | 4 + .../string-interpolation--included-.stata | 2 + .../string-interpolation--included-.visual | 4 + ...tring-length.aime => string-length-1.aime} | 0 Task/String-length/Aime/string-length-2.aime | 1 + Task/String-length/BaCon/string-length.bacon | 8 + Task/String-length/HolyC/string-length.holyc | 2 + .../JavaScript/string-length-3.js | 21 + Task/String-length/Rust/string-length-1.rust | 4 + Task/String-length/Rust/string-length-2.rust | 4 + Task/String-length/Rust/string-length.rust | 4 - .../Falcon/string-matching.falcon | 14 + .../Falcon/string-prepend.falcon | 7 + Task/String-prepend/Perl/string-prepend.pl | 24 +- Task/String-prepend/Red/string-prepend.red | 4 + Task/String-prepend/Rust/string-prepend.rust | 3 + .../String-prepend/Stata/string-prepend.stata | 5 + ...rip-a-set-of-characters-from-a-string.aime | 23 +- ...ip-a-set-of-characters-from-a-string.elena | 10 + ...p-a-set-of-characters-from-a-string.factor | 6 + ...ip-a-set-of-characters-from-a-string.julia | 12 +- ...p-a-set-of-characters-from-a-string-1.rexx | 16 +- ...trip-a-set-of-characters-from-a-string.red | 2 + ...strip-a-set-of-characters-from-a-string.rb | 3 +- ...p-a-set-of-characters-from-a-string-1.rust | 9 + ...p-a-set-of-characters-from-a-string-2.rust | 3 + ...p-a-set-of-characters-from-a-string-3.rust | 3 + .../ALGOL-W/strip-comments-from-a-string.alg | 43 + .../strip-comments-from-a-string.objeck | 29 + .../Python/strip-comments-from-a-string-1.py | 17 +- .../Python/strip-comments-from-a-string-2.py | 11 +- .../Red/strip-comments-from-a-string-1.red | 4 + .../Red/strip-comments-from-a-string-2.red | 10 + ...d-extended-characters-from-a-string.factor | 6 + ...-and-extended-characters-from-a-string.pl6 | 4 +- ...hitespace-from-a-string-top-and-tail.elena | 9 + ...itespace-from-a-string-top-and-tail-1.rexx | 2 +- ...-whitespace-from-a-string-top-and-tail.red | 6 + ...hitespace-from-a-string-top-and-tail.stata | 12 + .../Elena/substring-top-and-tail.elena | 10 + .../Factor/substring-top-and-tail.factor | 1 + Task/Substring/Falcon/substring.falcon | 13 + Task/Substring/R/substring.r | 4 +- Task/Substring/Rust/substring.rust | 20 + Task/Substring/Stata/substring.stata | 13 + .../Kotlin/subtractive-generator.kotlin | 40 + .../Perl-6/subtractive-generator.pl6 | 4 +- .../REXX/subtractive-generator.rexx | 4 +- Task/Sudoku/Ada/sudoku.ada | 108 +++ Task/Sudoku/Kotlin/sudoku.kotlin | 84 ++ Task/Sudoku/Stata/sudoku-1.stata | 101 +++ Task/Sudoku/Stata/sudoku-2.stata | 53 ++ .../Aime/sum-and-product-of-an-array.aime | 12 +- .../Fortran/sum-and-product-of-an-array.f | 4 +- .../Nim/sum-and-product-of-an-array-3.nim | 8 + .../Stata/sum-and-product-of-an-array.stata | 5 + .../BASIC/sum-digits-of-an-integer-1.basic | 2 +- .../Befunge/sum-digits-of-an-integer.bf | 5 + .../Crystal/sum-digits-of-an-integer.crystal | 13 + .../Modula-2/sum-digits-of-an-integer.mod2 | 49 ++ .../Stata/sum-digits-of-an-integer.stata | 19 + .../Swift/sum-digits-of-an-integer.swift | 21 + .../360-Assembly/sum-multiples-of-3-and-5.360 | 46 + .../Factor/sum-multiples-of-3-and-5.factor | 22 + .../Go/sum-multiples-of-3-and-5-1.go | 15 +- .../Objeck/sum-multiples-of-3-and-5.objeck | 16 + .../Rust/sum-multiples-of-3-and-5.rust | 36 + .../Simula/sum-multiples-of-3-and-5.simula | 54 ++ .../VBA/sum-multiples-of-3-and-5-1.vba | 8 + .../VBA/sum-multiples-of-3-and-5-2.vba | 9 + .../VBA/sum-multiples-of-3-and-5-3.vba | 12 + .../VBA/sum-multiples-of-3-and-5-4.vba | 13 + .../Sum-of-a-series/Aime/sum-of-a-series.aime | 4 +- .../Maple/sum-of-a-series.maple | 1 + .../Perl-6/sum-of-a-series-8.pl6 | 1 + Task/Sum-of-a-series/Red/sum-of-a-series.red | 4 + .../Stata/sum-of-a-series.stata | 6 + Task/Sum-of-squares/Aime/sum-of-squares.aime | 12 +- .../Sum-of-squares/Astro/sum-of-squares.astro | 1 + .../Sum-of-squares/REXX/sum-of-squares-1.rexx | 1 + .../Sum-of-squares/Stata/sum-of-squares.stata | 9 + .../sutherland-hodgman-polygon-clipping.math | 6 + .../sutherland-hodgman-polygon-clipping.rust | 48 +- .../Aime/symmetric-difference.aime | 34 +- .../JavaScript/symmetric-difference-5.js | 12 + .../JavaScript/symmetric-difference-6.js | 2 + .../Julia/symmetric-difference.julia | 10 +- .../REXX/symmetric-difference-1.rexx | 76 +- .../Forth/synchronous-concurrency.fth | 30 + .../Julia/synchronous-concurrency.julia | 20 + .../Kotlin/synchronous-concurrency.kotlin | 30 + .../Pony/synchronous-concurrency.pony | 31 + Task/System-time/ABAP/system-time.abap | 3 + Task/System-time/Elena/system-time.elena | 6 + Task/System-time/Falcon/system-time.falcon | 4 + Task/System-time/HolyC/system-time.holyc | 4 + Task/System-time/Modula-2/system-time.mod2 | 21 + Task/System-time/Stata/system-time.stata | 2 + .../table-creation-postal-addresses.julia | 11 + .../table-creation-postal-addresses.kotlin | 89 ++ .../Lua/table-creation-postal-addresses.lua | 18 + .../table-creation-postal-addresses.pl6 | 14 + .../table-creation-postal-addresses-1.rexx | 63 +- .../Ring/table-creation-postal-addresses.ring | 18 + .../table-creation-postal-addresses.stata | 7 + .../Aime/take-notes-on-the-command-line.aime | 30 +- .../take-notes-on-the-command-line.kotlin | 20 + .../Rust/take-notes-on-the-command-line.rust | 44 + .../temperature-conversion.applescript | 51 +- .../AutoIt/temperature-conversion.autoit | 20 + .../Elena/temperature-conversion.elena | 27 + .../Factor/temperature-conversion.factor | 12 + .../UNIX-Shell/temperature-conversion-1.sh | 12 + .../UNIX-Shell/temperature-conversion-2.sh | 12 + .../VBA/temperature-conversion.vba | 24 + .../terminal-control-clear-the-screen.elena | 4 + .../Ring/terminal-control-coloured-text.ring | 14 + .../terminal-control-coloured-text.scala | 24 + .../terminal-control-cursor-movement.scala | 19 + .../D/terminal-control-cursor-positioning.d | 6 + .../terminal-control-cursor-positioning.elena | 4 + .../terminal-control-cursor-positioning.ring | 9 + .../terminal-control-cursor-positioning.scala | 4 + .../Scala/terminal-control-dimensions.scala | 7 + ...control-display-an-extended-character.ring | 6 + .../terminal-control-hiding-the-cursor.pl6 | 1 + .../terminal-control-hiding-the-cursor.py | 11 + .../terminal-control-hiding-the-cursor.scala | 6 + .../terminal-control-inverse-video.scala | 3 + .../terminal-control-positional-read.py | 21 + .../terminal-control-preserve-screen.bf | 1 + .../Perl/terminal-control-preserve-screen.pl | 9 + .../terminal-control-preserve-screen.rexx | 35 +- .../Go/terminal-control-unicode-output.go | 16 + Task/Ternary-logic/Elena/ternary-logic.elena | 64 ++ Task/Ternary-logic/Julia/ternary-logic.julia | 27 + Task/Ternary-logic/Perl-6/ternary-logic.pl6 | 47 + .../Julia/test-a-function.julia | 20 + .../Perl-6/test-a-function.pl6 | 2 + Task/Test-a-function/VBA/test-a-function.vba | 15 + Task/Text-processing-1/00DESCRIPTION | 2 + .../Aime/text-processing-1.aime | 55 +- .../Julia/text-processing-1.julia | 54 ++ .../Kotlin/text-processing-1.kotlin | 51 ++ .../Phix/text-processing-1.phix | 78 ++ Task/Text-processing-2/00DESCRIPTION | 4 +- .../Aime/text-processing-2.aime | 49 +- .../Julia/text-processing-2.julia | 5 + .../Kotlin/text-processing-2.kotlin | 42 + .../Perl-6/text-processing-2.pl6 | 19 + .../00DESCRIPTION | 2 + .../text-processing-max-licenses-in-use.julia | 18 + ...text-processing-max-licenses-in-use.kotlin | 30 + Task/Textonyms/Clojure/textonyms.clj | 24 + Task/Textonyms/REXX/textonyms.rexx | 48 +- .../Julia/the-isaac-cipher.julia | 180 ++++ .../Modula-2/the-isaac-cipher.mod2 | 250 ++++++ .../00DESCRIPTION | 10 +- .../Elena/the-twelve-days-of-christmas.elena | 42 + .../the-twelve-days-of-christmas.factor | 34 + .../the-twelve-days-of-christmas.purebasic | 16 + .../REXX/the-twelve-days-of-christmas.rexx | 30 +- .../Ring/the-twelve-days-of-christmas.ring | 20 + .../VBA/the-twelve-days-of-christmas.vba | 16 + .../Perl-6/thieles-interpolation-formula.pl6 | 10 +- Task/Tic-tac-toe/00DESCRIPTION | 7 +- Task/Tic-tac-toe/Fortran/tic-tac-toe.f | 99 +++ Task/Tic-tac-toe/Kotlin/tic-tac-toe.kotlin | 107 +++ Task/Tic-tac-toe/Lingo/tic-tac-toe.lingo | 237 ++++++ Task/Tic-tac-toe/Perl-6/tic-tac-toe.pl6 | 19 +- Task/Tic-tac-toe/REXX/tic-tac-toe.rexx | 192 +++-- Task/Tic-tac-toe/Scala/tic-tac-toe.scala | 2 +- Task/Tic-tac-toe/VBA/tic-tac-toe.vba | 126 +++ .../Elena/time-a-function.elena | 23 + .../360-Assembly/tokenize-a-string.360 | 83 ++ .../Ada/tokenize-a-string.ada | 31 +- .../Astro/tokenize-a-string.astro | 4 +- .../Falcon/tokenize-a-string.falcon | 13 + .../Gambas/tokenize-a-string.gambas | 6 + .../Maple/tokenize-a-string.maple | 1 + .../Nial/tokenize-a-string-1.nial | 4 + .../Nial/tokenize-a-string-2.nial | 6 + .../Nial/tokenize-a-string-3.nial | 4 + .../Nial/tokenize-a-string-4.nial | 8 + .../Red/tokenize-a-string.red | 8 + .../VBA/tokenize-a-string.vba | 13 + .../Aime/top-rank-per-group.aime | 12 +- .../Ceylon/top-rank-per-group.ceylon | 42 + .../Perl-6/top-rank-per-group.pl6 | 2 +- .../R/top-rank-per-group-5.r | 6 + .../Ring/top-rank-per-group.ring | 62 ++ .../AppleScript/topic-variable-1.applescript | 10 +- .../Topic-variable/Scala/topic-variable.scala | 13 + .../C-sharp/topological-sort-1.cs | 139 +++ .../C-sharp/topological-sort-2.cs | 10 + .../C-sharp/topological-sort-3.cs | 2 + Task/Topological-sort/D/topological-sort.d | 2 +- .../Java/topological-sort.java | 2 +- .../Julia/topological-sort.julia | 37 + .../Kotlin/topological-sort.kotlin | 69 ++ .../REXX/topological-sort.rexx | 98 +-- Task/Topswops/C++/topswops.cpp | 29 + Task/Topswops/REXX/topswops.rexx | 22 +- Task/Total-circles-area/00DESCRIPTION | 4 + .../Julia/total-circles-area.julia | 73 +- ...ers-of-hanoi.alg => towers-of-hanoi-1.alg} | 0 .../ALGOL-68/towers-of-hanoi-2.alg | 9 + .../Befunge/towers-of-hanoi.bf | 4 + ...of-hanoi.cobol => towers-of-hanoi-1.cobol} | 0 .../COBOL/towers-of-hanoi-2.cobol | 29 + .../Elena/towers-of-hanoi.elena | 12 + .../Haskell/towers-of-hanoi-4.hs | 25 +- .../HolyC/towers-of-hanoi.holyc | 9 + .../MIPS-Assembly/towers-of-hanoi.mips | 101 +++ .../Maple/towers-of-hanoi.maple | 12 + .../Modula-2/towers-of-hanoi.mod2 | 20 + .../REXX/towers-of-hanoi-2.rexx | 2 +- .../Stata/towers-of-hanoi.stata | 17 + .../Elena/trabb-pardo-knuth-algorithm.elena | 32 + .../Factor/trabb-pardo-knuth-algorithm.factor | 24 + .../Maple/trabb-pardo-knuth-algorithm.maple | 10 + .../PL-M/trabb-pardo-knuth-algorithm.plm | 28 + .../REXX/trabb-pardo-knuth-algorithm.rexx | 62 +- .../Ring/trabb-pardo-knuth-algorithm.ring | 37 +- .../Tree-traversal/Elena/tree-traversal.elena | 103 +++ .../Modula-2/trigonometric-functions.mod2 | 46 + .../Factor/truncatable-primes.factor | 36 + .../Maple/truncatable-primes.maple | 50 ++ .../Ring/truncatable-primes.ring | 56 ++ .../Clojure/truncate-a-file.clj | 5 + .../Clojure/twelve-statements.clj | 20 + .../Elena/twelve-statements.elena | 2 +- .../Pascal/twelve-statements.pascal | 132 +++ .../Scala/twelve-statements.scala | 81 ++ .../Sidef/twelve-statements.sidef | 16 +- Task/URL-decoding/BaCon/url-decoding.bacon | 14 + Task/URL-decoding/Factor/url-decoding.factor | 6 + Task/URL-decoding/Lingo/url-decoding-1.lingo | 24 + Task/URL-decoding/Lingo/url-decoding-2.lingo | 2 + Task/URL-decoding/Perl-6/url-decoding.pl6 | 9 + .../URL-decoding/UNIX-Shell/url-decoding-1.sh | 1 + .../URL-decoding/UNIX-Shell/url-decoding-2.sh | 5 + .../{url-decoding.sh => url-decoding-3.sh} | 0 Task/Ulam-spiral--for-primes-/00DESCRIPTION | 5 +- .../C/ulam-spiral--for-primes--1.c | 2 +- .../JavaScript/ulam-spiral--for-primes-.js | 107 +++ .../Julia/ulam-spiral--for-primes-.julia | 31 + .../Racket/ulam-spiral--for-primes-.rkt | 8 +- .../Ring/ulam-spiral--for-primes-.ring | 104 +++ .../Aime/unbias-a-random-generator.aime | 16 +- .../Elena/unbias-a-random-generator.elena | 45 + ....java => unbias-a-random-generator-1.java} | 0 .../Java/unbias-a-random-generator-2.java | 28 + .../Julia/unbias-a-random-generator.julia | 20 + .../REXX/unbias-a-random-generator.rexx | 2 +- .../Rust/unbias-a-random-generator.rust | 39 + .../Perl-6/undefined-values-4.pl6 | 1 - .../Ring/undefined-values.ring | 11 + Task/Unicode-strings/D/unicode-strings.d | 22 + Task/Unicode-variable-names/00DESCRIPTION | 3 +- .../BaCon/unicode-variable-names.bacon | 9 + .../C/unicode-variable-names.c | 13 + .../Stata/unicode-variable-names.stata | 13 + .../Kotlin/universal-turing-machine.kotlin | 172 ++++ .../Perl-6/universal-turing-machine.pl6 | 117 +-- Task/Unix-ls/D/unix-ls.d | 4 +- Task/Unix-ls/Erlang/unix-ls.erl | 14 + Task/Unix-ls/Kotlin/unix-ls.kotlin | 18 + Task/Unix-ls/Standard-ML/unix-ls-1.ml | 1 + Task/Unix-ls/Standard-ML/unix-ls-2.ml | 15 + .../Kotlin/update-a-configuration-file.kotlin | 100 +++ .../Perl-6/update-a-configuration-file.pl6 | 17 +- ...other-language-to-call-a-function-1.kotlin | 14 + ...other-language-to-call-a-function-2.kotlin | 35 + ...other-language-to-call-a-function-3.kotlin | 25 + ...nother-language-to-call-a-function-1.scala | 12 + ...nother-language-to-call-a-function-2.scala | 105 +++ ...nother-language-to-call-a-function-3.scala | 22 + .../Perl-6/user-input-graphical.pl6 | 5 +- .../HolyC/user-input-text.holyc | 10 + .../Julia/user-input-text.julia | 6 +- .../User-input-Text/REXX/user-input-text.rexx | 20 +- Task/User-input-Text/Red/user-input-text.red | 1 + .../Factor/vampire-number.factor | 44 + ...{vampire-number.pl => vampire-number-1.pl} | 0 Task/Vampire-number/Perl/vampire-number-2.pl | 45 + Task/Vampire-number/REXX/vampire-number.rexx | 52 +- Task/Vampire-number/Ring/vampire-number.ring | 82 ++ .../Vampire-number/Sidef/vampire-number.sidef | 39 + .../Julia/van-der-corput-sequence.julia | 14 +- .../Modula-2/van-der-corput-sequence.mod2 | 50 ++ .../REXX/van-der-corput-sequence-2.rexx | 53 +- .../Stata/van-der-corput-sequence-2.stata | 4 +- Task/Variable-length-quantity/00DESCRIPTION | 5 +- .../Julia/variable-length-quantity.julia | 41 +- .../Scala/variable-size-set.scala | 7 + Task/Variables/Falcon/variables.falcon | 26 + Task/Variables/HicEst/variables.hicest | 33 + Task/Variables/HolyC/variables-1.holyc | 1 + Task/Variables/HolyC/variables-2.holyc | 2 + Task/Variables/HolyC/variables-3.holyc | 1 + Task/Variables/HolyC/variables-4.holyc | 1 + Task/Variables/HolyC/variables-5.holyc | 13 + Task/Variables/Perl-6/variables-2.pl6 | 2 +- Task/Variables/Python/variables.py | 8 + Task/Variables/REXX/variables-1.rexx | 2 +- .../Visual-Basic-.NET/variables.visual | 4 + .../Aime/variadic-function-2.aime | 38 +- .../Batch-File/variadic-function.bat | 13 + .../Elena/variadic-function.elena | 2 +- .../Factor/variadic-function-1.factor | 1 + .../Factor/variadic-function-2.factor | 13 + .../Ring/variadic-function.ring | 26 + .../Factor/vector-products.factor | 31 + .../Julia/vector-products.julia | 30 +- .../Modula-2/vector-products.mod2 | 83 ++ ...ibution-uniformity-chi-squared-test.kotlin | 77 ++ ...verify-distribution-uniformity-naive.julia | 15 + .../Kotlin/video-display-modes.kotlin | 25 + .../Perl-6/video-display-modes.pl6 | 16 + .../Scala/video-display-modes.scala | 27 + .../Go/vigen-re-cipher-cryptanalysis.go | 119 +++ .../Haskell/vigen-re-cipher-cryptanalysis.hs | 98 +++ .../Java/vigen-re-cipher-cryptanalysis.java | 108 +++ .../Applesoft-BASIC/vigen-re-cipher.applesoft | 28 + .../Elena/vigen-re-cipher.elena | 48 ++ .../Factor/vigen-re-cipher.factor | 30 + .../Julia/vigen-re-cipher.julia | 47 +- .../REXX/vigen-re-cipher-1.rexx | 14 +- .../REXX/vigen-re-cipher-2.rexx | 18 +- Task/Vigen-re-cipher/Red/vigen-re-cipher.red | 77 ++ .../Vigen-re-cipher/Ring/vigen-re-cipher.ring | 48 ++ .../Scala/vigen-re-cipher.scala | 34 + Task/Vigen-re-cipher/VBA/vigen-re-cipher.vba | 65 ++ ...igen-re-cipher.vb => vigen-re-cipher-1.vb} | 0 .../VBScript/vigen-re-cipher-2.vb | 34 + .../Kotlin/visualize-a-tree.kotlin | 45 + .../C/vogels-approximation-method.c | 108 +++ .../Go/vogels-approximation-method.go | 139 +++ .../Sidef/vogels-approximation-method.sidef | 72 ++ .../Julia/voronoi-diagram-1.julia | 13 + .../Julia/voronoi-diagram-2.julia | 21 + .../Perl-6/voronoi-diagram.pl6 | 46 + .../Voronoi-diagram/Ring/voronoi-diagram.ring | 124 +++ .../Voronoi-diagram/Rust/voronoi-diagram.rust | 180 ++++ .../walk-a-directory-non-recursively.julia | 5 + .../Forth/walk-a-directory-recursively.fth | 47 +- .../Julia/walk-a-directory-recursively.julia | 8 + .../walk-a-directory-recursively.kotlin | 14 + Task/Web-scraping/00DESCRIPTION | 14 +- Task/Web-scraping/8th/web-scraping.8th | 2 +- .../App-Inventor/web-scraping.app | 12 +- .../Cache-ObjectScript/web-scraping.cos | 102 +-- Task/Web-scraping/Ceylon/web-scraping.ceylon | 31 + .../Web-scraping/Delphi/web-scraping-1.delphi | 2 +- Task/Web-scraping/Erlang/web-scraping.erl | 8 +- Task/Web-scraping/Java/web-scraping.java | 30 +- Task/Web-scraping/Julia/web-scraping-1.julia | 4 +- Task/Web-scraping/Lasso/web-scraping.lasso | 18 +- Task/Web-scraping/MATLAB/web-scraping.m | 2 +- Task/Web-scraping/Maple/web-scraping.maple | 2 + Task/Web-scraping/PHP/web-scraping-2.php | 6 +- Task/Web-scraping/REBOL/web-scraping.rebol | 8 +- Task/Web-scraping/Scala/web-scraping.scala | 12 +- Task/Web-scraping/VBA/web-scraping.vba | 38 + Task/Web-scraping/VBScript/web-scraping.vb | 45 +- .../C/window-creation-x11-1.c | 2 +- .../Julia/window-creation-x11.julia | 40 + .../Perl-6/window-creation-x11.pl6 | 54 +- Task/Window-creation/J/window-creation-1.j | 4 +- Task/Window-creation/J/window-creation-2.j | 1 - .../Perl-6/window-creation.pl6 | 7 +- Task/Window-creation/Red/window-creation.red | 1 + Task/Window-creation/VBA/window-creation.vba | 8 + Task/Window-management/00DESCRIPTION | 1 + .../Gambas/window-management.gambas | 87 ++ Task/Wireworld/Elena/wireworld.elena | 137 +++ Task/Wireworld/Perl-6/wireworld.pl6 | 81 +- Task/Word-wrap/Factor/word-wrap.factor | 12 + Task/Word-wrap/Julia/word-wrap.julia | 12 + Task/Word-wrap/Ring/word-wrap.ring | 33 + .../Elena/world-cup-group-stage.elena | 50 ++ .../write-float-arrays-to-a-text-file.cobol | 42 + .../write-float-arrays-to-a-text-file.ring | 24 + .../write-language-name-in-3d-ascii.mod2 | 38 + .../write-language-name-in-3d-ascii.pl6 | 4 +- .../C/write-to-windows-event-log.c | 18 + .../D/write-to-windows-event-log.d | 12 + .../Lingo/write-to-windows-event-log.lingo | 5 + .../Perl/write-to-windows-event-log.pl | 16 + ...g.psh => write-to-windows-event-log-1.psh} | 0 .../write-to-windows-event-log-2.psh | 5 + .../write-to-windows-event-log-3.psh | 7 + .../Scala/write-to-windows-event-log.scala | 11 + .../MATLAB/xml-dom-serialization.m | 5 + .../Perl-6/xml-dom-serialization-1.pl6 | 6 + .../Perl-6/xml-dom-serialization-2.pl6 | 1 + Task/XML-Input/Julia/xml-input.julia | 18 + Task/XML-Input/Perl-6/xml-input.pl6 | 3 +- Task/XML-Input/REXX/xml-input-1.rexx | 27 +- Task/XML-Input/REXX/xml-input-2.rexx | 160 ++-- Task/XML-Input/VBA/xml-input.vba | 28 + Task/XML-Output/Go/xml-output-3.go | 6 +- Task/XML-Output/Perl-6/xml-output-1.pl6 | 11 + Task/XML-Output/Perl-6/xml-output-2.pl6 | 3 + Task/XML-Output/REXX/xml-output.rexx | 187 ++-- Task/XML-XPath/C/xml-xpath.c | 57 ++ Task/XML-XPath/Perl-6/xml-xpath.pl6 | 37 + .../C/xiaolin-wus-line-algorithm-2.c | 8 +- .../Julia/xiaolin-wus-line-algorithm.julia | 75 ++ .../REXX/xiaolin-wus-line-algorithm.rexx | 32 +- Task/Y-combinator/Elena/y-combinator.elena | 10 +- Task/Y-combinator/Elm/y-combinator.elm | 18 + Task/Y-combinator/Kitten/y-combinator.kitten | 18 + Task/Y-combinator/Python/y-combinator-3.py | 1 + Task/Y-combinator/Rust/y-combinator.rust | 66 +- Task/Y-combinator/Scheme/y-combinator-1.ss | 11 + .../SuperCollider/y-combinator.supercollider | 14 +- .../Kotlin/yahoo--search-interface.kotlin | 45 + Task/Yin-and-yang/Julia/yin-and-yang.julia | 20 + Task/Yin-and-yang/Perl-6/yin-and-yang-1.pl6 | 7 +- Task/Yin-and-yang/Perl-6/yin-and-yang-2.pl6 | 6 +- Task/Yin-and-yang/REXX/yin-and-yang.rexx | 2 +- Task/Zebra-puzzle/ALGOL-68/zebra-puzzle.alg | 140 +++ Task/Zebra-puzzle/Julia/zebra-puzzle.julia | 51 ++ Task/Zebra-puzzle/Nial/zebra-puzzle.nial | 55 ++ Task/Zebra-puzzle/REXX/zebra-puzzle.rexx | 9 +- .../{zebra-puzzle.rb => zebra-puzzle-1.rb} | 0 Task/Zebra-puzzle/Ruby/zebra-puzzle-2.rb | 24 + Task/Zebra-puzzle/Scala/zebra-puzzle-1.scala | 76 +- Task/Zebra-puzzle/Scala/zebra-puzzle-2.scala | 5 +- .../D/zeckendorf-arithmetic.d | 172 ++++ .../Java/zeckendorf-arithmetic.java | 186 ++++ .../Kotlin/zeckendorf-arithmetic.kotlin | 156 ++++ ...ckendorf-number-representation.applescript | 181 ++-- .../zeckendorf-number-representation-1.lingo | 29 + .../zeckendorf-number-representation-2.lingo | 3 + .../zeckendorf-number-representation.ring | 30 + .../Dc/zero-to-the-zero-power.dc | 1 + .../Falcon/zero-to-the-zero-power.falcon | 7 + .../HolyC/zero-to-the-zero-power.holyc | 2 + ...o-power.js => zero-to-the-zero-power-1.js} | 0 .../JavaScript/zero-to-the-zero-power-2.js | 2 + .../Julia/zero-to-the-zero-power.julia | 12 +- .../Python/zero-to-the-zero-power-1.py | 11 + ...o-power.py => zero-to-the-zero-power-2.py} | 0 .../C/zhang-suen-thinning-algorithm.c | 162 ++++ .../Julia/zhang-suen-thinning-algorithm.julia | 77 ++ .../Octave/zig-zag-matrix-1.octave | 28 + .../Octave/zig-zag-matrix-2.octave | 18 + Task/Zig-zag-matrix/Perl-6/zig-zag-matrix.pl6 | 43 +- Task/Zig-zag-matrix/Ring/zig-zag-matrix.ring | 56 ++ .../Scilab/zig-zag-matrix.scilab | 19 + .../Stata/zig-zag-matrix-1.stata | 22 + .../Stata/zig-zag-matrix-2.stata | 18 + .../Stata/zig-zag-matrix-3.stata | 10 + 5278 files changed, 84726 insertions(+), 14379 deletions(-) create mode 120000 Lang/360-Assembly/Flow-control-structures create mode 120000 Lang/360-Assembly/Floyds-triangle create mode 120000 Lang/360-Assembly/Pythagorean-triples create mode 120000 Lang/360-Assembly/Sum-multiples-of-3-and-5 create mode 120000 Lang/360-Assembly/Tokenize-a-string create mode 120000 Lang/8th/AKS-test-for-primes create mode 120000 Lang/8th/Arithmetic-geometric-mean create mode 120000 Lang/8th/Luhn-test-of-credit-card-numbers create mode 120000 Lang/8th/Parsing-Shunting-yard-algorithm create mode 120000 Lang/ABAP/Equilibrium-index create mode 120000 Lang/ABAP/Extend-your-language create mode 120000 Lang/ABAP/Morse-code create mode 120000 Lang/ABAP/System-time create mode 120000 Lang/ALGOL-60/Loops-Break create mode 120000 Lang/ALGOL-60/Loops-N-plus-one-half create mode 120000 Lang/ALGOL-60/Loops-Nested create mode 120000 Lang/ALGOL-68/Aliquot-sequence-classifications create mode 120000 Lang/ALGOL-68/Zebra-puzzle create mode 120000 Lang/ALGOL-W/Sorting-algorithms-Insertion-sort create mode 120000 Lang/ALGOL-W/Strip-comments-from-a-string create mode 120000 Lang/APL/Anagrams create mode 120000 Lang/APL/Apply-a-callback-to-an-array create mode 120000 Lang/APL/Arithmetic-Integer create mode 120000 Lang/APL/Boolean-values create mode 120000 Lang/APL/Fast-Fourier-transform create mode 120000 Lang/APL/Polynomial-long-division create mode 120000 Lang/ARM-Assembly/Address-of-a-variable create mode 120000 Lang/ARM-Assembly/Arithmetic-Integer create mode 120000 Lang/ARM-Assembly/Balanced-brackets create mode 120000 Lang/ARM-Assembly/Call-a-function create mode 120000 Lang/ARM-Assembly/Comments create mode 120000 Lang/ARM-Assembly/FizzBuzz create mode 120000 Lang/ARM-Assembly/Hello-world-Newbie create mode 120000 Lang/ARM-Assembly/Hello-world-Standard-error create mode 120000 Lang/ARM-Assembly/Program-name create mode 120000 Lang/ATS/FizzBuzz create mode 120000 Lang/ATS/Sierpinski-triangle-Graphical create mode 120000 Lang/AWK/Dutch-national-flag-problem create mode 120000 Lang/AWK/IBAN create mode 120000 Lang/AWK/Munching-squares create mode 120000 Lang/AWK/Pernicious-numbers create mode 120000 Lang/Ada/Amicable-pairs create mode 120000 Lang/Ada/String-append create mode 120000 Lang/Ada/Sudoku create mode 120000 Lang/Aime/Equilibrium-index create mode 120000 Lang/Aime/Letter-frequency create mode 120000 Lang/Aime/Loops-Foreach create mode 120000 Lang/Aime/Make-directory-path create mode 120000 Lang/Aime/Move-to-front-algorithm create mode 120000 Lang/Aime/Multifactorial create mode 120000 Lang/Aime/Order-two-numerical-lists create mode 120000 Lang/Aime/Remove-duplicate-elements create mode 120000 Lang/AppleScript/Mad-Libs create mode 120000 Lang/AppleScript/Make-directory-path create mode 120000 Lang/Applesoft-BASIC/Caesar-cipher create mode 120000 Lang/Applesoft-BASIC/Rot-13 create mode 120000 Lang/Applesoft-BASIC/Vigen-re-cipher create mode 120000 Lang/Astro/Sum-of-squares create mode 120000 Lang/AutoIt/Anonymous-recursion create mode 120000 Lang/AutoIt/Associative-array-Creation create mode 120000 Lang/AutoIt/Null-object create mode 120000 Lang/AutoIt/Speech-synthesis create mode 120000 Lang/AutoIt/Temperature-conversion create mode 120000 Lang/BASIC/Animate-a-pendulum create mode 120000 Lang/BASIC/Arithmetic-geometric-mean create mode 120000 Lang/BASIC/Dot-product create mode 120000 Lang/BASIC/Draw-a-clock create mode 120000 Lang/BASIC/Entropy create mode 120000 Lang/BASIC/FizzBuzz create mode 120000 Lang/BASIC/Floyds-triangle create mode 120000 Lang/BASIC/Fractal-tree create mode 120000 Lang/BASIC/Josephus-problem create mode 120000 Lang/BASIC/Magic-squares-of-odd-order create mode 120000 Lang/BASIC/Maze-generation create mode 120000 Lang/BASIC256/Conditional-structures create mode 120000 Lang/BASIC256/Look-and-say-sequence create mode 120000 Lang/BASIC256/Sorting-algorithms-Counting-sort create mode 120000 Lang/BBC-BASIC/Entropy create mode 120000 Lang/BBC-BASIC/Josephus-problem create mode 120000 Lang/BBC-BASIC/Multifactorial create mode 120000 Lang/BaCon/Align-columns create mode 120000 Lang/BaCon/Anagrams create mode 120000 Lang/BaCon/Anagrams-Deranged-anagrams create mode 120000 Lang/BaCon/Averages-Median create mode 120000 Lang/BaCon/Calendar create mode 120000 Lang/BaCon/Calendar---for-REAL-programmers create mode 120000 Lang/BaCon/Color-of-a-screen-pixel create mode 120000 Lang/BaCon/LZW-compression create mode 120000 Lang/BaCon/Last-letter-first-letter create mode 120000 Lang/BaCon/Letter-frequency create mode 120000 Lang/BaCon/OpenGL create mode 120000 Lang/BaCon/Rename-a-file create mode 120000 Lang/BaCon/Rep-string create mode 120000 Lang/BaCon/Repeat-a-string create mode 120000 Lang/BaCon/Run-length-encoding create mode 120000 Lang/BaCon/String-length create mode 120000 Lang/BaCon/URL-decoding create mode 120000 Lang/BaCon/Unicode-variable-names create mode 120000 Lang/Batch-File/Maze-generation create mode 120000 Lang/Batch-File/Variadic-function create mode 120000 Lang/Befunge/24-game create mode 120000 Lang/Befunge/Bitwise-operations create mode 120000 Lang/Befunge/Box-the-compass create mode 120000 Lang/Befunge/Determine-if-a-string-is-numeric create mode 120000 Lang/Befunge/Hello-world-Newline-omission create mode 120000 Lang/Befunge/Luhn-test-of-credit-card-numbers create mode 120000 Lang/Befunge/Sum-digits-of-an-integer create mode 120000 Lang/Befunge/Terminal-control-Preserve-screen create mode 120000 Lang/Befunge/Towers-of-Hanoi create mode 120000 Lang/Bracmat/Move-to-front-algorithm create mode 120000 Lang/Brainf---/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/C++/Arbitrary-precision-integers--included- create mode 120000 Lang/C++/Average-loop-length create mode 120000 Lang/C++/Bernoulli-numbers create mode 120000 Lang/C++/Hash-join create mode 120000 Lang/C++/Haversine-formula create mode 120000 Lang/C++/Order-disjoint-list-items create mode 120000 Lang/C++/Ordered-Partitions create mode 120000 Lang/C++/Pattern-matching create mode 120000 Lang/C++/Soundex create mode 120000 Lang/C++/Topswops create mode 120000 Lang/C-sharp/Dynamic-variable-names create mode 120000 Lang/C-sharp/Element-wise-operations create mode 120000 Lang/C-sharp/Fibonacci-word create mode 120000 Lang/C-sharp/Iterated-digits-squaring create mode 120000 Lang/C-sharp/Modular-inverse create mode 120000 Lang/C-sharp/Topological-sort create mode 120000 Lang/C/Aliquot-sequence-classifications create mode 120000 Lang/C/Create-a-file-on-magnetic-tape create mode 120000 Lang/C/Currying create mode 120000 Lang/C/Deepcopy create mode 120000 Lang/C/GUI-Maximum-window-dimensions create mode 120000 Lang/C/Generate-Chess960-starting-position create mode 120000 Lang/C/Here-document create mode 120000 Lang/C/Heronian-triangles create mode 120000 Lang/C/Parsing-RPN-to-infix-conversion create mode 120000 Lang/C/Permutations-by-swapping create mode 120000 Lang/C/Pragmatic-directives create mode 120000 Lang/C/Ranking-methods create mode 120000 Lang/C/Read-a-configuration-file create mode 120000 Lang/C/SOAP create mode 120000 Lang/C/Send-email create mode 120000 Lang/C/Simulate-input-Mouse create mode 120000 Lang/C/Sparkline-in-unicode create mode 120000 Lang/C/Unicode-variable-names create mode 120000 Lang/C/Vogels-approximation-method create mode 120000 Lang/C/Write-to-Windows-event-log create mode 120000 Lang/C/XML-XPath create mode 120000 Lang/C/Zhang-Suen-thinning-algorithm create mode 120000 Lang/COBOL/Constrained-random-points-on-a-circle create mode 120000 Lang/COBOL/Long-multiplication create mode 120000 Lang/COBOL/Narcissistic-decimal-number create mode 120000 Lang/COBOL/Write-float-arrays-to-a-text-file create mode 120000 Lang/Ceylon/Arbitrary-precision-integers--included- create mode 120000 Lang/Ceylon/Binary-digits create mode 120000 Lang/Ceylon/Currying create mode 120000 Lang/Ceylon/Long-multiplication create mode 120000 Lang/Ceylon/Look-and-say-sequence create mode 120000 Lang/Ceylon/Minesweeper-game create mode 120000 Lang/Ceylon/Odd-word-problem create mode 120000 Lang/Ceylon/Run-length-encoding create mode 120000 Lang/Ceylon/Stable-marriage-problem create mode 120000 Lang/Ceylon/Top-rank-per-group create mode 120000 Lang/Ceylon/Web-scraping create mode 120000 Lang/Clojure/Delegates create mode 120000 Lang/Clojure/Executable-library create mode 120000 Lang/Clojure/Hello-world-Line-printer create mode 120000 Lang/Clojure/Last-letter-first-letter create mode 120000 Lang/Clojure/Multiplicative-order create mode 120000 Lang/Clojure/Polynomial-long-division create mode 120000 Lang/Clojure/Range-extraction create mode 120000 Lang/Clojure/SOAP create mode 120000 Lang/Clojure/Sorting-algorithms-Pancake-sort create mode 120000 Lang/Clojure/Sorting-algorithms-Stooge-sort create mode 120000 Lang/Clojure/Textonyms create mode 120000 Lang/Clojure/Truncate-a-file create mode 120000 Lang/Clojure/Twelve-statements create mode 120000 Lang/Commodore-BASIC/Pascals-triangle create mode 120000 Lang/Common-Lisp/Atomic-updates create mode 120000 Lang/Common-Lisp/Combinations-with-repetitions create mode 120000 Lang/Crystal/99-Bottles-of-Beer create mode 120000 Lang/Crystal/Caesar-cipher create mode 120000 Lang/Crystal/Copy-a-string create mode 120000 Lang/Crystal/DNS-query create mode 120000 Lang/Crystal/Generic-swap create mode 120000 Lang/Crystal/Hello-world-Web-server create mode 120000 Lang/Crystal/Sum-digits-of-an-integer create mode 120000 Lang/D/Active-Directory-Connect create mode 120000 Lang/D/Active-Directory-Search-for-a-user create mode 120000 Lang/D/Active-object create mode 120000 Lang/D/Append-a-record-to-the-end-of-a-text-file create mode 120000 Lang/D/Continued-fraction-Arithmetic-Construct-from-rational-number create mode 120000 Lang/D/Create-a-file-on-magnetic-tape create mode 120000 Lang/D/Date-manipulation create mode 120000 Lang/D/Fork create mode 120000 Lang/D/Handle-a-signal create mode 120000 Lang/D/I-before-E-except-after-C create mode 120000 Lang/D/Inverted-syntax create mode 120000 Lang/D/Make-directory-path create mode 120000 Lang/D/Narcissist create mode 120000 Lang/D/Parsing-Shunting-yard-algorithm create mode 120000 Lang/D/Polynomial-regression create mode 120000 Lang/D/Random-number-generator--device- create mode 120000 Lang/D/Ranking-methods create mode 120000 Lang/D/Rate-counter create mode 120000 Lang/D/Safe-addition create mode 120000 Lang/D/Terminal-control-Cursor-positioning create mode 120000 Lang/D/Unicode-strings create mode 120000 Lang/D/Write-to-Windows-event-log create mode 120000 Lang/D/Zeckendorf-arithmetic create mode 120000 Lang/DUP/Extend-your-language create mode 120000 Lang/DUP/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Dc/Zero-to-the-zero-power create mode 120000 Lang/Delphi/Bitcoin-address-validation create mode 120000 Lang/Elena/AKS-test-for-primes create mode 120000 Lang/Elena/Abundant,-deficient-and-perfect-number-classifications create mode 120000 Lang/Elena/Amicable-pairs create mode 120000 Lang/Elena/Averages-Root-mean-square create mode 120000 Lang/Elena/Call-a-function create mode 120000 Lang/Elena/Compound-data-type create mode 120000 Lang/Elena/Digital-root create mode 120000 Lang/Elena/Dot-product create mode 120000 Lang/Elena/Equilibrium-index create mode 120000 Lang/Elena/Exceptions-Catch-an-exception-thrown-in-a-nested-call create mode 120000 Lang/Elena/Fibonacci-sequence create mode 120000 Lang/Elena/File-input-output create mode 120000 Lang/Elena/Filter create mode 120000 Lang/Elena/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Elena/Greatest-common-divisor create mode 120000 Lang/Elena/Guess-the-number create mode 120000 Lang/Elena/Guess-the-number-With-feedback create mode 120000 Lang/Elena/Hailstone-sequence create mode 120000 Lang/Elena/Happy-numbers create mode 120000 Lang/Elena/Haversine-formula create mode 120000 Lang/Elena/Hello-world-Newline-omission create mode 120000 Lang/Elena/Higher-order-functions create mode 120000 Lang/Elena/History-variables create mode 120000 Lang/Elena/Horners-rule-for-polynomial-evaluation create mode 120000 Lang/Elena/Increment-a-numerical-string create mode 120000 Lang/Elena/Integer-sequence create mode 120000 Lang/Elena/Keyboard-input-Keypress-check create mode 120000 Lang/Elena/Least-common-multiple create mode 120000 Lang/Elena/Literals-Floating-point create mode 120000 Lang/Elena/Logical-operations create mode 120000 Lang/Elena/Maximum-triangle-path-sum create mode 120000 Lang/Elena/Middle-three-digits create mode 120000 Lang/Elena/Mutual-recursion create mode 120000 Lang/Elena/Nth create mode 120000 Lang/Elena/Phrase-reversals create mode 120000 Lang/Elena/Polymorphic-copy create mode 120000 Lang/Elena/Polymorphism create mode 120000 Lang/Elena/Quaternion-type create mode 120000 Lang/Elena/Queue-Definition create mode 120000 Lang/Elena/Random-number-generator--included- create mode 120000 Lang/Elena/Random-numbers create mode 120000 Lang/Elena/Remove-duplicate-elements create mode 120000 Lang/Elena/Roman-numerals-Decode create mode 120000 Lang/Elena/Roman-numerals-Encode create mode 120000 Lang/Elena/Rot-13 create mode 120000 Lang/Elena/Run-length-encoding create mode 120000 Lang/Elena/Runtime-evaluation create mode 120000 Lang/Elena/Runtime-evaluation-In-an-environment create mode 120000 Lang/Elena/Singly-linked-list-Element-definition create mode 120000 Lang/Elena/Singly-linked-list-Element-insertion create mode 120000 Lang/Elena/Singly-linked-list-Traversal create mode 120000 Lang/Elena/Sleep create mode 120000 Lang/Elena/Sockets create mode 120000 Lang/Elena/Sort-disjoint-sublist create mode 120000 Lang/Elena/Sort-using-a-custom-comparator create mode 120000 Lang/Elena/Sorting-algorithms-Bogosort create mode 120000 Lang/Elena/Sorting-algorithms-Cocktail-sort create mode 120000 Lang/Elena/Sorting-algorithms-Comb-sort create mode 120000 Lang/Elena/Sorting-algorithms-Counting-sort create mode 120000 Lang/Elena/Sorting-algorithms-Gnome-sort create mode 120000 Lang/Elena/Sorting-algorithms-Insertion-sort create mode 120000 Lang/Elena/Sorting-algorithms-Pancake-sort create mode 120000 Lang/Elena/Sorting-algorithms-Quicksort create mode 120000 Lang/Elena/Sorting-algorithms-Selection-sort create mode 120000 Lang/Elena/Sorting-algorithms-Sleep-sort create mode 120000 Lang/Elena/Sorting-algorithms-Stooge-sort create mode 120000 Lang/Elena/Strip-a-set-of-characters-from-a-string create mode 120000 Lang/Elena/Strip-whitespace-from-a-string-Top-and-tail create mode 120000 Lang/Elena/Substring-Top-and-tail create mode 120000 Lang/Elena/System-time create mode 120000 Lang/Elena/Temperature-conversion create mode 120000 Lang/Elena/Terminal-control-Clear-the-screen create mode 120000 Lang/Elena/Terminal-control-Cursor-positioning create mode 120000 Lang/Elena/Ternary-logic create mode 120000 Lang/Elena/The-Twelve-Days-of-Christmas create mode 120000 Lang/Elena/Time-a-function create mode 120000 Lang/Elena/Towers-of-Hanoi create mode 120000 Lang/Elena/Trabb-Pardo-Knuth-algorithm create mode 120000 Lang/Elena/Tree-traversal create mode 120000 Lang/Elena/Unbias-a-random-generator create mode 120000 Lang/Elena/Vigen-re-cipher create mode 120000 Lang/Elena/Wireworld create mode 120000 Lang/Elena/World-Cup-group-stage create mode 120000 Lang/Elm/Y-combinator create mode 120000 Lang/Emacs-Lisp/Loops-Infinite create mode 120000 Lang/Erlang/Bitmap-Read-a-PPM-file create mode 120000 Lang/Erlang/Bitmap-Write-a-PPM-file create mode 120000 Lang/Erlang/Kaprekar-numbers create mode 120000 Lang/Erlang/Sierpinski-triangle-Graphical create mode 120000 Lang/Erlang/Unix-ls create mode 120000 Lang/Excel/100-doors create mode 120000 Lang/Factor/24-game-Solve create mode 120000 Lang/Factor/Abundant,-deficient-and-perfect-number-classifications create mode 120000 Lang/Factor/Almost-prime create mode 120000 Lang/Factor/Amicable-pairs create mode 120000 Lang/Factor/Arithmetic-Rational create mode 120000 Lang/Factor/Arithmetic-geometric-mean create mode 120000 Lang/Factor/Benfords-law create mode 120000 Lang/Factor/CSV-data-manipulation create mode 120000 Lang/Factor/CSV-to-HTML-translation create mode 120000 Lang/Factor/Caesar-cipher create mode 120000 Lang/Factor/Call-a-function create mode 120000 Lang/Factor/Case-sensitivity-of-identifiers create mode 120000 Lang/Factor/Catalan-numbers-Pascals-triangle create mode 120000 Lang/Factor/Catamorphism create mode 120000 Lang/Factor/Chinese-remainder-theorem create mode 120000 Lang/Factor/Comma-quibbling create mode 120000 Lang/Factor/Convert-decimal-number-to-rational create mode 120000 Lang/Factor/Count-in-factors create mode 120000 Lang/Factor/Count-in-octal create mode 120000 Lang/Factor/Currying create mode 120000 Lang/Factor/Digital-root create mode 120000 Lang/Factor/Digital-root-Multiplicative-digital-root create mode 120000 Lang/Factor/Dynamic-variable-names create mode 120000 Lang/Factor/Empty-directory create mode 120000 Lang/Factor/Empty-string create mode 120000 Lang/Factor/Enforced-immutability create mode 120000 Lang/Factor/Entropy create mode 120000 Lang/Factor/Enumerations create mode 120000 Lang/Factor/Evolutionary-algorithm create mode 120000 Lang/Factor/Extreme-floating-point-values create mode 120000 Lang/Factor/Fibonacci-word create mode 120000 Lang/Factor/Find-the-last-Sunday-of-each-month create mode 120000 Lang/Factor/Find-the-missing-permutation create mode 120000 Lang/Factor/Five-weekends create mode 120000 Lang/Factor/Formatted-numeric-output create mode 120000 Lang/Factor/Harshad-or-Niven-series create mode 120000 Lang/Factor/I-before-E-except-after-C create mode 120000 Lang/Factor/Inverted-syntax create mode 120000 Lang/Factor/Iterated-digits-squaring create mode 120000 Lang/Factor/Kaprekar-numbers create mode 120000 Lang/Factor/Largest-int-from-concatenated-ints create mode 120000 Lang/Factor/Last-Friday-of-each-month create mode 120000 Lang/Factor/Left-factorials create mode 120000 Lang/Factor/Levenshtein-distance create mode 120000 Lang/Factor/Literals-Integer create mode 120000 Lang/Factor/Loops-Nested create mode 120000 Lang/Factor/Middle-three-digits create mode 120000 Lang/Factor/Modular-inverse create mode 120000 Lang/Factor/Multifactorial create mode 120000 Lang/Factor/Munching-squares create mode 120000 Lang/Factor/Narcissistic-decimal-number create mode 120000 Lang/Factor/Parsing-RPN-calculator-algorithm create mode 120000 Lang/Factor/Partial-function-application create mode 120000 Lang/Factor/Penneys-game create mode 120000 Lang/Factor/Pernicious-numbers create mode 120000 Lang/Factor/Phrase-reversals create mode 120000 Lang/Factor/Playing-cards create mode 120000 Lang/Factor/Range-extraction create mode 120000 Lang/Factor/Regular-expressions create mode 120000 Lang/Factor/Reverse-words-in-a-string create mode 120000 Lang/Factor/Run-length-encoding create mode 120000 Lang/Factor/Self-describing-numbers create mode 120000 Lang/Factor/Semiprime create mode 120000 Lang/Factor/Sequence-of-non-squares create mode 120000 Lang/Factor/Short-circuit-evaluation create mode 120000 Lang/Factor/Simple-windowed-application create mode 120000 Lang/Factor/Sorting-algorithms-Permutation-sort create mode 120000 Lang/Factor/Statistics-Basic create mode 120000 Lang/Factor/String-append create mode 120000 Lang/Factor/String-comparison create mode 120000 Lang/Factor/Strip-a-set-of-characters-from-a-string create mode 120000 Lang/Factor/Strip-control-codes-and-extended-characters-from-a-string create mode 120000 Lang/Factor/Substring-Top-and-tail create mode 120000 Lang/Factor/Sum-multiples-of-3-and-5 create mode 120000 Lang/Factor/Temperature-conversion create mode 120000 Lang/Factor/The-Twelve-Days-of-Christmas create mode 120000 Lang/Factor/Trabb-Pardo-Knuth-algorithm create mode 120000 Lang/Factor/Truncatable-primes create mode 120000 Lang/Factor/URL-decoding create mode 120000 Lang/Factor/Vampire-number create mode 120000 Lang/Factor/Variadic-function create mode 120000 Lang/Factor/Vector-products create mode 120000 Lang/Factor/Vigen-re-cipher create mode 120000 Lang/Factor/Word-wrap create mode 120000 Lang/Falcon/Palindrome-detection create mode 120000 Lang/Falcon/String-append create mode 120000 Lang/Falcon/String-comparison create mode 120000 Lang/Falcon/String-concatenation create mode 120000 Lang/Falcon/String-interpolation--included- create mode 120000 Lang/Falcon/String-matching create mode 120000 Lang/Falcon/String-prepend create mode 120000 Lang/Falcon/Substring create mode 120000 Lang/Falcon/System-time create mode 120000 Lang/Falcon/Tokenize-a-string create mode 120000 Lang/Falcon/Variables create mode 120000 Lang/Falcon/Zero-to-the-zero-power create mode 120000 Lang/Forth/CSV-to-HTML-translation create mode 120000 Lang/Forth/Documentation create mode 120000 Lang/Forth/Forest-fire create mode 120000 Lang/Forth/Left-factorials create mode 120000 Lang/Forth/Lucas-Lehmer-test create mode 120000 Lang/Forth/Synchronous-concurrency create mode 120000 Lang/Fortran/Catamorphism create mode 120000 Lang/Fortran/Element-wise-operations create mode 120000 Lang/Fortran/Extend-your-language create mode 120000 Lang/Fortran/IBAN create mode 120000 Lang/Fortran/Old-lady-swallowed-a-fly create mode 120000 Lang/Fortran/Tic-tac-toe create mode 120000 Lang/Fortress/Call-a-function create mode 120000 Lang/Fortress/Function-composition create mode 120000 Lang/Fortress/Loops-Do-while create mode 120000 Lang/Fortress/Loops-Infinite create mode 120000 Lang/Fortress/Loops-While create mode 120000 Lang/FreeBASIC/Gaussian-elimination create mode 120000 Lang/Futhark/Greatest-element-of-a-list create mode 120000 Lang/GW-BASIC/Almost-prime create mode 120000 Lang/GW-BASIC/Horizontal-sundial-calculations create mode 120000 Lang/GW-BASIC/Leap-year create mode 120000 Lang/GW-BASIC/Least-common-multiple create mode 120000 Lang/GW-BASIC/Loops-Do-while create mode 120000 Lang/GW-BASIC/Loops-Downward-for create mode 120000 Lang/GW-BASIC/Modular-inverse create mode 120000 Lang/GW-BASIC/Multiplication-tables create mode 120000 Lang/GW-BASIC/Nth create mode 120000 Lang/GW-BASIC/Remove-duplicate-elements create mode 120000 Lang/Gambas/Ackermann-function create mode 120000 Lang/Gambas/Collections create mode 120000 Lang/Gambas/Hello-world-Newline-omission create mode 120000 Lang/Gambas/Price-fraction create mode 120000 Lang/Gambas/Remove-duplicate-elements create mode 120000 Lang/Gambas/SEDOLs create mode 120000 Lang/Gambas/Sorting-algorithms-Bogosort create mode 120000 Lang/Gambas/Sorting-algorithms-Bubble-sort create mode 120000 Lang/Gambas/Sorting-algorithms-Cocktail-sort create mode 120000 Lang/Gambas/Sorting-algorithms-Comb-sort create mode 120000 Lang/Gambas/Sorting-algorithms-Gnome-sort create mode 120000 Lang/Gambas/Sorting-algorithms-Selection-sort create mode 120000 Lang/Gambas/Tokenize-a-string create mode 120000 Lang/Gambas/Window-management create mode 120000 Lang/Glee/Combinations create mode 120000 Lang/Go/9-billion-names-of-God-the-integer create mode 120000 Lang/Go/Aliquot-sequence-classifications create mode 120000 Lang/Go/Calendar create mode 120000 Lang/Go/Carmichael-3-strong-pseudoprimes create mode 120000 Lang/Go/Catalan-numbers-Pascals-triangle create mode 120000 Lang/Go/Combinations-and-permutations create mode 120000 Lang/Go/Define-a-primitive-data-type create mode 120000 Lang/Go/Extend-your-language create mode 120000 Lang/Go/Find-largest-left-truncatable-prime-in-a-given-base create mode 120000 Lang/Go/HTTPS-Client-authenticated create mode 120000 Lang/Go/Jump-anywhere create mode 120000 Lang/Go/Named-parameters create mode 120000 Lang/Go/Solve-a-Holy-Knights-tour create mode 120000 Lang/Go/Terminal-control-Unicode-output create mode 120000 Lang/Go/Vigen-re-cipher-Cryptanalysis create mode 120000 Lang/Go/Vogels-approximation-method create mode 120000 Lang/Groovy/Deal-cards-for-FreeCell create mode 120000 Lang/Haskell/Active-Directory-Connect create mode 120000 Lang/Haskell/Active-Directory-Search-for-a-user create mode 120000 Lang/Haskell/Catmull-Clark-subdivision-surface create mode 120000 Lang/Haskell/Create-a-file-on-magnetic-tape create mode 120000 Lang/Haskell/HTTPS-Authenticated create mode 120000 Lang/Haskell/Joystick-position create mode 120000 Lang/Haskell/Longest-string-challenge create mode 120000 Lang/Haskell/Natural-sorting create mode 120000 Lang/Haskell/Object-serialization create mode 120000 Lang/Haskell/Parametrized-SQL-statement create mode 120000 Lang/Haskell/Send-email create mode 120000 Lang/HolyC/100-doors create mode 120000 Lang/HolyC/Arithmetic-Integer create mode 120000 Lang/HolyC/Arrays create mode 120000 Lang/HolyC/Character-codes create mode 120000 Lang/HolyC/Check-that-file-exists create mode 120000 Lang/HolyC/Detect-division-by-zero create mode 120000 Lang/HolyC/Empty-string create mode 120000 Lang/HolyC/Exceptions create mode 120000 Lang/HolyC/Execute-a-system-command create mode 120000 Lang/HolyC/Factorial create mode 120000 Lang/HolyC/Find-limit-of-recursion create mode 120000 Lang/HolyC/Function-definition create mode 120000 Lang/HolyC/Guess-the-number create mode 120000 Lang/HolyC/Guess-the-number-With-feedback create mode 120000 Lang/HolyC/Hello-world-Graphical create mode 120000 Lang/HolyC/Hello-world-Newline-omission create mode 120000 Lang/HolyC/Hello-world-Text create mode 120000 Lang/HolyC/Increment-a-numerical-string create mode 120000 Lang/HolyC/Integer-comparison create mode 120000 Lang/HolyC/Literals-Integer create mode 120000 Lang/HolyC/Logical-operations create mode 120000 Lang/HolyC/Multiplication-tables create mode 120000 Lang/HolyC/String-length create mode 120000 Lang/HolyC/System-time create mode 120000 Lang/HolyC/Towers-of-Hanoi create mode 120000 Lang/HolyC/User-input-Text create mode 120000 Lang/HolyC/Variables create mode 120000 Lang/HolyC/Zero-to-the-zero-power create mode 120000 Lang/Idris/Extend-your-language create mode 120000 Lang/J/Carmichael-3-strong-pseudoprimes create mode 120000 Lang/JCL/Conditional-structures create mode 120000 Lang/Java/Arithmetic-geometric-mean-Calculate-Pi create mode 120000 Lang/Java/Averages-Mean-time-of-day create mode 120000 Lang/Java/Binary-strings create mode 120000 Lang/Java/Circles-of-given-radius-through-two-points create mode 120000 Lang/Java/Continued-fraction-Arithmetic-Construct-from-rational-number create mode 120000 Lang/Java/History-variables create mode 120000 Lang/Java/Interactive-programming create mode 120000 Lang/Java/List-comprehensions create mode 120000 Lang/Java/Multiplicative-order create mode 120000 Lang/Java/Permutation-test create mode 120000 Lang/Java/Polynomial-long-division create mode 120000 Lang/Java/Polynomial-regression create mode 120000 Lang/Java/RSA-code create mode 120000 Lang/Java/Resistor-mesh create mode 120000 Lang/Java/Runtime-evaluation create mode 120000 Lang/Java/Safe-addition create mode 120000 Lang/Java/Special-variables create mode 120000 Lang/Java/Vigen-re-cipher-Cryptanalysis create mode 120000 Lang/Java/Zeckendorf-arithmetic create mode 120000 Lang/JavaScript/Here-document create mode 120000 Lang/JavaScript/K-means++-clustering create mode 120000 Lang/JavaScript/Number-names create mode 120000 Lang/JavaScript/Ulam-spiral--for-primes- create mode 120000 Lang/Julia/Active-object create mode 120000 Lang/Julia/Add-a-variable-to-a-class-instance-at-runtime create mode 120000 Lang/Julia/Animate-a-pendulum create mode 120000 Lang/Julia/Animation create mode 120000 Lang/Julia/Append-a-record-to-the-end-of-a-text-file create mode 120000 Lang/Julia/Arena-storage-pool create mode 120000 Lang/Julia/Atomic-updates create mode 120000 Lang/Julia/Averages-Mean-time-of-day create mode 120000 Lang/Julia/Balanced-ternary create mode 120000 Lang/Julia/Bitcoin-address-validation create mode 120000 Lang/Julia/Bitcoin-public-point-to-address create mode 120000 Lang/Julia/Bitmap-B-zier-curves-Cubic create mode 120000 Lang/Julia/Bitmap-Flood-fill create mode 120000 Lang/Julia/Bitmap-Midpoint-circle-algorithm create mode 120000 Lang/Julia/Bitmap-PPM-conversion-through-a-pipe create mode 120000 Lang/Julia/Bitmap-Read-an-image-through-a-pipe create mode 120000 Lang/Julia/Bulls-and-cows-Player create mode 120000 Lang/Julia/Call-a-function create mode 120000 Lang/Julia/Canny-edge-detector create mode 120000 Lang/Julia/Chat-server create mode 120000 Lang/Julia/Chinese-remainder-theorem create mode 120000 Lang/Julia/Classes create mode 120000 Lang/Julia/Collections create mode 120000 Lang/Julia/Colour-bars-Display create mode 120000 Lang/Julia/Concurrent-computing create mode 120000 Lang/Julia/Conditional-structures create mode 120000 Lang/Julia/Constrained-genericity create mode 120000 Lang/Julia/Create-an-HTML-table create mode 120000 Lang/Julia/Create-an-object-at-a-given-address create mode 120000 Lang/Julia/Date-manipulation create mode 120000 Lang/Julia/Deconvolution-1D create mode 120000 Lang/Julia/Define-a-primitive-data-type create mode 120000 Lang/Julia/Delegates create mode 120000 Lang/Julia/Dinesmans-multiple-dwelling-problem create mode 120000 Lang/Julia/Dining-philosophers create mode 120000 Lang/Julia/Doubly-linked-list-Element-definition create mode 120000 Lang/Julia/Dragon-curve create mode 120000 Lang/Julia/Draw-a-cuboid create mode 120000 Lang/Julia/Dynamic-variable-names create mode 120000 Lang/Julia/Enforced-immutability create mode 120000 Lang/Julia/Events create mode 120000 Lang/Julia/Exceptions create mode 120000 Lang/Julia/Exceptions-Catch-an-exception-thrown-in-a-nested-call create mode 120000 Lang/Julia/Executable-library create mode 120000 Lang/Julia/Execute-Brain---- create mode 120000 Lang/Julia/Execute-HQ9+ create mode 120000 Lang/Julia/Execute-a-Markov-algorithm create mode 120000 Lang/Julia/Extensible-prime-generator create mode 120000 Lang/Julia/Fibonacci-word-fractal create mode 120000 Lang/Julia/First-class-functions-Use-numbers-analogously create mode 120000 Lang/Julia/Flipping-bits-game create mode 120000 Lang/Julia/Flow-control-structures create mode 120000 Lang/Julia/Formal-power-series create mode 120000 Lang/Julia/Fractran create mode 120000 Lang/Julia/Function-frequency create mode 120000 Lang/Julia/Image-convolution create mode 120000 Lang/Julia/Inverted-syntax create mode 120000 Lang/Julia/Jump-anywhere create mode 120000 Lang/Julia/Keyboard-input-Flush-the-keyboard-buffer create mode 120000 Lang/Julia/Keyboard-input-Obtain-a-Y-or-N-response create mode 120000 Lang/Julia/Knapsack-problem-Unbounded create mode 120000 Lang/Julia/LZW-compression create mode 120000 Lang/Julia/Last-letter-first-letter create mode 120000 Lang/Julia/Literals-Floating-point create mode 120000 Lang/Julia/Long-multiplication create mode 120000 Lang/Julia/Longest-increasing-subsequence create mode 120000 Lang/Julia/Longest-string-challenge create mode 120000 Lang/Julia/Lucas-Lehmer-test create mode 120000 Lang/Julia/Mad-Libs create mode 120000 Lang/Julia/Main-step-of-GOST-28147-89 create mode 120000 Lang/Julia/Make-directory-path create mode 120000 Lang/Julia/Maximum-triangle-path-sum create mode 120000 Lang/Julia/Maze-solving create mode 120000 Lang/Julia/Median-filter create mode 120000 Lang/Julia/Memory-allocation create mode 120000 Lang/Julia/Memory-layout-of-a-data-structure create mode 120000 Lang/Julia/Menu create mode 120000 Lang/Julia/Metronome create mode 120000 Lang/Julia/Move-to-front-algorithm create mode 120000 Lang/Julia/Multiple-distinct-objects create mode 120000 Lang/Julia/Narcissist create mode 120000 Lang/Julia/Object-serialization create mode 120000 Lang/Julia/Odd-word-problem create mode 120000 Lang/Julia/Old-lady-swallowed-a-fly create mode 120000 Lang/Julia/Ordered-Partitions create mode 120000 Lang/Julia/Parallel-calculations create mode 120000 Lang/Julia/Parametric-polymorphism create mode 120000 Lang/Julia/Parametrized-SQL-statement create mode 120000 Lang/Julia/Parse-an-IP-Address create mode 120000 Lang/Julia/Parsing-RPN-to-infix-conversion create mode 120000 Lang/Julia/Parsing-Shunting-yard-algorithm create mode 120000 Lang/Julia/Partial-function-application create mode 120000 Lang/Julia/Pascals-triangle-Puzzle create mode 120000 Lang/Julia/Percentage-difference-between-images create mode 120000 Lang/Julia/Percolation-Bond-percolation create mode 120000 Lang/Julia/Percolation-Mean-cluster-density create mode 120000 Lang/Julia/Percolation-Mean-run-density create mode 120000 Lang/Julia/Percolation-Site-percolation create mode 120000 Lang/Julia/Permutations-by-swapping create mode 120000 Lang/Julia/Pinstripe-Display create mode 120000 Lang/Julia/Program-termination create mode 120000 Lang/Julia/Queue-Usage create mode 120000 Lang/Julia/Quickselect-algorithm create mode 120000 Lang/Julia/RSA-code create mode 120000 Lang/Julia/Ray-casting-algorithm create mode 120000 Lang/Julia/Read-a-configuration-file create mode 120000 Lang/Julia/Record-sound create mode 120000 Lang/Julia/Respond-to-an-unknown-method-call create mode 120000 Lang/Julia/Run-length-encoding create mode 120000 Lang/Julia/Runtime-evaluation create mode 120000 Lang/Julia/Runtime-evaluation-In-an-environment create mode 120000 Lang/Julia/S-Expressions create mode 120000 Lang/Julia/SEDOLs create mode 120000 Lang/Julia/SQL-based-authentication create mode 120000 Lang/Julia/Safe-addition create mode 120000 Lang/Julia/Same-Fringe create mode 120000 Lang/Julia/Send-an-unknown-method-call create mode 120000 Lang/Julia/Send-email create mode 120000 Lang/Julia/Set-of-real-numbers create mode 120000 Lang/Julia/Sierpinski-triangle-Graphical create mode 120000 Lang/Julia/Simple-windowed-application create mode 120000 Lang/Julia/Singleton create mode 120000 Lang/Julia/Singly-linked-list-Element-insertion create mode 120000 Lang/Julia/Singly-linked-list-Traversal create mode 120000 Lang/Julia/Soundex create mode 120000 Lang/Julia/Stable-marriage-problem create mode 120000 Lang/Julia/Stack-traces create mode 120000 Lang/Julia/Stair-climbing-puzzle create mode 120000 Lang/Julia/State-name-puzzle create mode 120000 Lang/Julia/Statistics-Basic create mode 120000 Lang/Julia/Synchronous-concurrency create mode 120000 Lang/Julia/Table-creation-Postal-addresses create mode 120000 Lang/Julia/Ternary-logic create mode 120000 Lang/Julia/Test-a-function create mode 120000 Lang/Julia/Text-processing-1 create mode 120000 Lang/Julia/Text-processing-2 create mode 120000 Lang/Julia/Text-processing-Max-licenses-in-use create mode 120000 Lang/Julia/The-ISAAC-Cipher create mode 120000 Lang/Julia/Topological-sort create mode 120000 Lang/Julia/Ulam-spiral--for-primes- create mode 120000 Lang/Julia/Unbias-a-random-generator create mode 120000 Lang/Julia/Verify-distribution-uniformity-Naive create mode 120000 Lang/Julia/Voronoi-diagram create mode 120000 Lang/Julia/Walk-a-directory-Non-recursively create mode 120000 Lang/Julia/Walk-a-directory-Recursively create mode 120000 Lang/Julia/Window-creation-X11 create mode 120000 Lang/Julia/Word-wrap create mode 120000 Lang/Julia/XML-Input create mode 120000 Lang/Julia/Xiaolin-Wus-line-algorithm create mode 120000 Lang/Julia/Yin-and-yang create mode 120000 Lang/Julia/Zebra-puzzle create mode 120000 Lang/Julia/Zhang-Suen-thinning-algorithm create mode 120000 Lang/K/Dinesmans-multiple-dwelling-problem create mode 120000 Lang/Kitten/99-Bottles-of-Beer create mode 120000 Lang/Kitten/Y-combinator create mode 120000 Lang/Klong/100-doors create mode 120000 Lang/Klong/Ackermann-function create mode 120000 Lang/Klong/Anonymous-recursion create mode 120000 Lang/Klong/Array-concatenation create mode 120000 Lang/Klong/Command-line-arguments create mode 120000 Lang/Klong/Gaussian-elimination create mode 120000 Lang/Klong/Greatest-common-divisor create mode 120000 Lang/Klong/Loops-For create mode 120000 Lang/Klong/Matrix-multiplication create mode 120000 Lang/Klong/Statistics-Basic create mode 120000 Lang/Kotlin/Active-object create mode 120000 Lang/Kotlin/Append-a-record-to-the-end-of-a-text-file create mode 120000 Lang/Kotlin/Arithmetic-evaluation create mode 120000 Lang/Kotlin/Atomic-updates create mode 120000 Lang/Kotlin/Bitmap-B-zier-curves-Cubic create mode 120000 Lang/Kotlin/Bitmap-B-zier-curves-Quadratic create mode 120000 Lang/Kotlin/Bitmap-Histogram create mode 120000 Lang/Kotlin/Bitmap-PPM-conversion-through-a-pipe create mode 120000 Lang/Kotlin/Bitmap-Read-a-PPM-file create mode 120000 Lang/Kotlin/Bitmap-Read-an-image-through-a-pipe create mode 120000 Lang/Kotlin/Bitmap-Write-a-PPM-file create mode 120000 Lang/Kotlin/Bitwise-IO create mode 120000 Lang/Kotlin/Call-a-function-in-a-shared-library create mode 120000 Lang/Kotlin/Checkpoint-synchronization create mode 120000 Lang/Kotlin/Circles-of-given-radius-through-two-points create mode 120000 Lang/Kotlin/Color-quantization create mode 120000 Lang/Kotlin/Compare-sorting-algorithms-performance create mode 120000 Lang/Kotlin/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2- create mode 120000 Lang/Kotlin/Conways-Game-of-Life create mode 120000 Lang/Kotlin/Deepcopy create mode 120000 Lang/Kotlin/Delegates create mode 120000 Lang/Kotlin/Dining-philosophers create mode 120000 Lang/Kotlin/Documentation create mode 120000 Lang/Kotlin/Element-wise-operations create mode 120000 Lang/Kotlin/Execute-a-Markov-algorithm create mode 120000 Lang/Kotlin/Find-common-directory-path create mode 120000 Lang/Kotlin/Fork create mode 120000 Lang/Kotlin/Formal-power-series create mode 120000 Lang/Kotlin/Four-bit-adder create mode 120000 Lang/Kotlin/GUI-enabling-disabling-of-controls create mode 120000 Lang/Kotlin/Galton-box-animation create mode 120000 Lang/Kotlin/Gaussian-elimination create mode 120000 Lang/Kotlin/Globally-replace-text-in-several-files create mode 120000 Lang/Kotlin/Grayscale-image create mode 120000 Lang/Kotlin/HTTPS-Authenticated create mode 120000 Lang/Kotlin/HTTPS-Client-authenticated create mode 120000 Lang/Kotlin/Image-convolution create mode 120000 Lang/Kotlin/Image-noise create mode 120000 Lang/Kotlin/Inverted-index create mode 120000 Lang/Kotlin/JSON create mode 120000 Lang/Kotlin/K-d-tree create mode 120000 Lang/Kotlin/K-means++-clustering create mode 120000 Lang/Kotlin/Keyboard-macros create mode 120000 Lang/Kotlin/LU-decomposition create mode 120000 Lang/Kotlin/Langtons-ant create mode 120000 Lang/Kotlin/Main-step-of-GOST-28147-89 create mode 120000 Lang/Kotlin/Maze-solving create mode 120000 Lang/Kotlin/Median-filter create mode 120000 Lang/Kotlin/Metered-concurrency create mode 120000 Lang/Kotlin/Multiple-regression create mode 120000 Lang/Kotlin/Multiplicative-order create mode 120000 Lang/Kotlin/Munching-squares create mode 120000 Lang/Kotlin/Object-serialization create mode 120000 Lang/Kotlin/One-dimensional-cellular-automata create mode 120000 Lang/Kotlin/One-of-n-lines-in-a-file create mode 120000 Lang/Kotlin/Optional-parameters create mode 120000 Lang/Kotlin/Parallel-calculations create mode 120000 Lang/Kotlin/Parametrized-SQL-statement create mode 120000 Lang/Kotlin/Parsing-RPN-to-infix-conversion create mode 120000 Lang/Kotlin/Parsing-Shunting-yard-algorithm create mode 120000 Lang/Kotlin/Pattern-matching create mode 120000 Lang/Kotlin/Penneys-game create mode 120000 Lang/Kotlin/Percentage-difference-between-images create mode 120000 Lang/Kotlin/Percolation-Bond-percolation create mode 120000 Lang/Kotlin/Percolation-Mean-cluster-density create mode 120000 Lang/Kotlin/Percolation-Mean-run-density create mode 120000 Lang/Kotlin/Percolation-Site-percolation create mode 120000 Lang/Kotlin/Plot-coordinate-pairs create mode 120000 Lang/Kotlin/Polynomial-long-division create mode 120000 Lang/Kotlin/Polynomial-regression create mode 120000 Lang/Kotlin/Reduced-row-echelon-form create mode 120000 Lang/Kotlin/Rock-paper-scissors create mode 120000 Lang/Kotlin/S-Expressions create mode 120000 Lang/Kotlin/SOAP create mode 120000 Lang/Kotlin/SQL-based-authentication create mode 120000 Lang/Kotlin/Simple-database create mode 120000 Lang/Kotlin/Sockets create mode 120000 Lang/Kotlin/Sokoban create mode 120000 Lang/Kotlin/Solve-a-Hidato-puzzle create mode 120000 Lang/Kotlin/Solve-a-Hopido-puzzle create mode 120000 Lang/Kotlin/Solve-a-Numbrix-puzzle create mode 120000 Lang/Kotlin/Solve-the-no-connection-puzzle create mode 120000 Lang/Kotlin/Sort-disjoint-sublist create mode 120000 Lang/Kotlin/Sort-stability create mode 120000 Lang/Kotlin/Sorting-algorithms-Sleep-sort create mode 120000 Lang/Kotlin/Speech-synthesis create mode 120000 Lang/Kotlin/Stair-climbing-puzzle create mode 120000 Lang/Kotlin/State-name-puzzle create mode 120000 Lang/Kotlin/Subtractive-generator create mode 120000 Lang/Kotlin/Sudoku create mode 120000 Lang/Kotlin/Synchronous-concurrency create mode 120000 Lang/Kotlin/Table-creation-Postal-addresses create mode 120000 Lang/Kotlin/Take-notes-on-the-command-line create mode 120000 Lang/Kotlin/Text-processing-1 create mode 120000 Lang/Kotlin/Text-processing-2 create mode 120000 Lang/Kotlin/Text-processing-Max-licenses-in-use create mode 120000 Lang/Kotlin/Tic-tac-toe create mode 120000 Lang/Kotlin/Topological-sort create mode 120000 Lang/Kotlin/Universal-Turing-machine create mode 120000 Lang/Kotlin/Unix-ls create mode 120000 Lang/Kotlin/Update-a-configuration-file create mode 120000 Lang/Kotlin/Use-another-language-to-call-a-function create mode 120000 Lang/Kotlin/Verify-distribution-uniformity-Chi-squared-test create mode 120000 Lang/Kotlin/Video-display-modes create mode 120000 Lang/Kotlin/Visualize-a-tree create mode 120000 Lang/Kotlin/Walk-a-directory-Recursively create mode 120000 Lang/Kotlin/Yahoo--search-interface create mode 120000 Lang/Kotlin/Zeckendorf-arithmetic create mode 120000 Lang/Limbo/99-Bottles-of-Beer create mode 120000 Lang/Limbo/Array-concatenation create mode 120000 Lang/Limbo/Averages-Arithmetic-mean create mode 120000 Lang/Limbo/Ethiopian-multiplication create mode 120000 Lang/Limbo/Literals-Integer create mode 120000 Lang/Limbo/Sieve-of-Eratosthenes create mode 120000 Lang/Limbo/Singly-linked-list-Traversal create mode 120000 Lang/Lingo/99-Bottles-of-Beer create mode 120000 Lang/Lingo/Active-object create mode 120000 Lang/Lingo/Add-a-variable-to-a-class-instance-at-runtime create mode 120000 Lang/Lingo/Animate-a-pendulum create mode 120000 Lang/Lingo/Arithmetic-Integer create mode 120000 Lang/Lingo/Averages-Arithmetic-mean create mode 120000 Lang/Lingo/Averages-Median create mode 120000 Lang/Lingo/Binary-strings create mode 120000 Lang/Lingo/Extensible-prime-generator create mode 120000 Lang/Lingo/Factors-of-a-Mersenne-number create mode 120000 Lang/Lingo/Generator-Exponential create mode 120000 Lang/Lingo/MD5-Implementation create mode 120000 Lang/Lingo/OpenGL create mode 120000 Lang/Lingo/Primality-by-trial-division create mode 120000 Lang/Lingo/Random-numbers create mode 120000 Lang/Lingo/SHA-1 create mode 120000 Lang/Lingo/Semiprime create mode 120000 Lang/Lingo/Show-the-epoch create mode 120000 Lang/Lingo/Sieve-of-Eratosthenes create mode 120000 Lang/Lingo/Tic-tac-toe create mode 120000 Lang/Lingo/URL-decoding create mode 120000 Lang/Lingo/Write-to-Windows-event-log create mode 120000 Lang/Lingo/Zeckendorf-number-representation create mode 120000 Lang/Logo/Catalan-numbers create mode 120000 Lang/Lua/Averages-Mean-time-of-day create mode 120000 Lang/Lua/Dinesmans-multiple-dwelling-problem create mode 120000 Lang/Lua/Huffman-coding create mode 120000 Lang/Lua/Make-directory-path create mode 120000 Lang/Lua/Soundex create mode 120000 Lang/Lua/Table-creation-Postal-addresses create mode 120000 Lang/MATLAB/Draw-a-sphere create mode 120000 Lang/MATLAB/Josephus-problem create mode 120000 Lang/MATLAB/Numerical-integration-Gauss-Legendre-Quadrature create mode 120000 Lang/MATLAB/XML-DOM-serialization create mode 120000 Lang/MIPS-Assembly/Towers-of-Hanoi create mode 120000 Lang/Maple/Animation create mode 120000 Lang/Maple/Bitmap create mode 120000 Lang/Maple/CSV-to-HTML-translation create mode 120000 Lang/Maple/Closest-pair-problem create mode 120000 Lang/Maple/Date-manipulation create mode 120000 Lang/Maple/Day-of-the-week create mode 120000 Lang/Maple/Element-wise-operations create mode 120000 Lang/Maple/Find-largest-left-truncatable-prime-in-a-given-base create mode 120000 Lang/Maple/Find-the-last-Sunday-of-each-month create mode 120000 Lang/Maple/Find-the-missing-permutation create mode 120000 Lang/Maple/Five-weekends create mode 120000 Lang/Maple/GUI-component-interaction create mode 120000 Lang/Maple/GUI-enabling-disabling-of-controls create mode 120000 Lang/Maple/Gamma-function create mode 120000 Lang/Maple/Grayscale-image create mode 120000 Lang/Maple/Last-Friday-of-each-month create mode 120000 Lang/Maple/Mandelbrot-set create mode 120000 Lang/Maple/Map-range create mode 120000 Lang/Maple/Multifactorial create mode 120000 Lang/Maple/Mutual-recursion create mode 120000 Lang/Maple/Narcissistic-decimal-number create mode 120000 Lang/Maple/Non-decimal-radices-Convert create mode 120000 Lang/Maple/Ordered-words create mode 120000 Lang/Maple/Pangram-checker create mode 120000 Lang/Maple/Quickselect-algorithm create mode 120000 Lang/Maple/Read-a-file-line-by-line create mode 120000 Lang/Maple/Regular-expressions create mode 120000 Lang/Maple/Search-a-list create mode 120000 Lang/Maple/Sorting-algorithms-Bogosort create mode 120000 Lang/Maple/Sorting-algorithms-Bubble-sort create mode 120000 Lang/Maple/Sorting-algorithms-Cocktail-sort create mode 120000 Lang/Maple/Sorting-algorithms-Comb-sort create mode 120000 Lang/Maple/Sorting-algorithms-Gnome-sort create mode 120000 Lang/Maple/Sorting-algorithms-Heapsort create mode 120000 Lang/Maple/Sorting-algorithms-Insertion-sort create mode 120000 Lang/Maple/Sorting-algorithms-Merge-sort create mode 120000 Lang/Maple/Sorting-algorithms-Permutation-sort create mode 120000 Lang/Maple/Sorting-algorithms-Quicksort create mode 120000 Lang/Maple/Sorting-algorithms-Selection-sort create mode 120000 Lang/Maple/Sorting-algorithms-Shell-sort create mode 120000 Lang/Maple/Sum-of-a-series create mode 120000 Lang/Maple/Tokenize-a-string create mode 120000 Lang/Maple/Towers-of-Hanoi create mode 120000 Lang/Maple/Trabb-Pardo-Knuth-algorithm create mode 120000 Lang/Maple/Truncatable-primes create mode 120000 Lang/Maple/Web-scraping create mode 120000 Lang/Mathematica/Formal-power-series create mode 120000 Lang/Mathematica/Nautical-bell create mode 120000 Lang/Mathematica/Sutherland-Hodgman-polygon-clipping create mode 120000 Lang/Maxima/Parsing-RPN-calculator-algorithm create mode 120000 Lang/Metapost/Mandelbrot-set create mode 120000 Lang/Modula-2/Abundant,-deficient-and-perfect-number-classifications create mode 120000 Lang/Modula-2/Almost-prime create mode 120000 Lang/Modula-2/Averages-Pythagorean-means create mode 120000 Lang/Modula-2/Box-the-compass create mode 120000 Lang/Modula-2/Caesar-cipher create mode 120000 Lang/Modula-2/Catalan-numbers create mode 120000 Lang/Modula-2/Circles-of-given-radius-through-two-points create mode 120000 Lang/Modula-2/Combinations create mode 120000 Lang/Modula-2/Continued-fraction-Arithmetic-Construct-from-rational-number create mode 120000 Lang/Modula-2/Digital-root create mode 120000 Lang/Modula-2/Dot-product create mode 120000 Lang/Modula-2/Ethiopian-multiplication create mode 120000 Lang/Modula-2/Even-or-odd create mode 120000 Lang/Modula-2/Factorial create mode 120000 Lang/Modula-2/Fibonacci-sequence create mode 120000 Lang/Modula-2/FizzBuzz create mode 120000 Lang/Modula-2/Floyds-triangle create mode 120000 Lang/Modula-2/Hello-world-Newline-omission create mode 120000 Lang/Modula-2/Horizontal-sundial-calculations create mode 120000 Lang/Modula-2/Horners-rule-for-polynomial-evaluation create mode 120000 Lang/Modula-2/Integer-sequence create mode 120000 Lang/Modula-2/Josephus-problem create mode 120000 Lang/Modula-2/Kaprekar-numbers create mode 120000 Lang/Modula-2/Leap-year create mode 120000 Lang/Modula-2/Least-common-multiple create mode 120000 Lang/Modula-2/Logical-operations create mode 120000 Lang/Modula-2/Modular-inverse create mode 120000 Lang/Modula-2/Morse-code create mode 120000 Lang/Modula-2/Multiplication-tables create mode 120000 Lang/Modula-2/Nth create mode 120000 Lang/Modula-2/Old-lady-swallowed-a-fly create mode 120000 Lang/Modula-2/Palindrome-detection create mode 120000 Lang/Modula-2/Pascals-triangle create mode 120000 Lang/Modula-2/Perfect-numbers create mode 120000 Lang/Modula-2/Pernicious-numbers create mode 120000 Lang/Modula-2/Polynomial-regression create mode 120000 Lang/Modula-2/Remove-duplicate-elements create mode 120000 Lang/Modula-2/Resistor-mesh create mode 120000 Lang/Modula-2/Reverse-a-string create mode 120000 Lang/Modula-2/Reverse-words-in-a-string create mode 120000 Lang/Modula-2/Roman-numerals-Encode create mode 120000 Lang/Modula-2/Self-describing-numbers create mode 120000 Lang/Modula-2/Short-circuit-evaluation create mode 120000 Lang/Modula-2/Sum-digits-of-an-integer create mode 120000 Lang/Modula-2/System-time create mode 120000 Lang/Modula-2/The-ISAAC-Cipher create mode 120000 Lang/Modula-2/Towers-of-Hanoi create mode 120000 Lang/Modula-2/Trigonometric-functions create mode 120000 Lang/Modula-2/Van-der-Corput-sequence create mode 120000 Lang/Modula-2/Vector-products create mode 120000 Lang/Modula-2/Write-language-name-in-3D-ASCII create mode 120000 Lang/N-t-roff/99-Bottles-of-Beer create mode 120000 Lang/N-t-roff/Binary-search create mode 120000 Lang/N-t-roff/Empty-program create mode 120000 Lang/N-t-roff/Hello-world-Graphical create mode 120000 Lang/N-t-roff/Hello-world-Line-printer create mode 120000 Lang/N-t-roff/Hello-world-Newline-omission create mode 120000 Lang/N-t-roff/Hello-world-Standard-error create mode 120000 Lang/N-t-roff/Hello-world-Text create mode 120000 Lang/N-t-roff/Parsing-RPN-calculator-algorithm create mode 120000 Lang/N-t-roff/Sorting-algorithms-Bubble-sort create mode 120000 Lang/N-t-roff/Sorting-algorithms-Insertion-sort create mode 120000 Lang/N-t-roff/Sorting-algorithms-Selection-sort create mode 120000 Lang/NetRexx/Soundex create mode 120000 Lang/NewLISP/HTTPS create mode 120000 Lang/Nial/100-doors create mode 120000 Lang/Nial/Reverse-words-in-a-string create mode 120000 Lang/Nial/Sort-disjoint-sublist create mode 120000 Lang/Nial/Tokenize-a-string create mode 120000 Lang/Nial/Zebra-puzzle create mode 120000 Lang/Nim/Runge-Kutta-method create mode 120000 Lang/OCaml/Break-OO-privacy create mode 120000 Lang/OCaml/Catalan-numbers-Pascals-triangle create mode 120000 Lang/OCaml/Comma-quibbling create mode 120000 Lang/OCaml/Execute-HQ9+ create mode 120000 Lang/OCaml/Flipping-bits-game create mode 120000 Lang/OCaml/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/Oberon-2/Average-loop-length create mode 120000 Lang/Objeck/DNS-query create mode 120000 Lang/Objeck/Deal-cards-for-FreeCell create mode 120000 Lang/Objeck/Entropy create mode 120000 Lang/Objeck/Equilibrium-index create mode 120000 Lang/Objeck/Fibonacci-word create mode 120000 Lang/Objeck/Make-directory-path create mode 120000 Lang/Objeck/Return-multiple-values create mode 120000 Lang/Objeck/Strip-comments-from-a-string create mode 120000 Lang/Objeck/Sum-multiples-of-3-and-5 create mode 120000 Lang/Octave/Semordnilap create mode 120000 Lang/Octave/Zig-zag-matrix create mode 120000 Lang/Oforth/Address-of-a-variable create mode 120000 Lang/PARI-GP/Hello-world-Graphical create mode 120000 Lang/PARI-GP/Parsing-RPN-calculator-algorithm create mode 120000 Lang/PHP/Rock-paper-scissors create mode 120000 Lang/PL-M/Hello-world-Text create mode 120000 Lang/PL-M/Trabb-Pardo-Knuth-algorithm create mode 120000 Lang/PL-SQL/Loops-While create mode 120000 Lang/Pascal/HTTPS create mode 120000 Lang/Pascal/Twelve-statements create mode 120000 Lang/Perl-6/Append-a-record-to-the-end-of-a-text-file create mode 120000 Lang/Perl-6/Bitmap-B-zier-curves-Cubic create mode 120000 Lang/Perl-6/Bitmap-B-zier-curves-Quadratic create mode 120000 Lang/Perl-6/Bitmap-Histogram create mode 120000 Lang/Perl-6/Bitmap-Read-a-PPM-file create mode 120000 Lang/Perl-6/Bitmap-Read-an-image-through-a-pipe create mode 120000 Lang/Perl-6/Distributed-programming create mode 120000 Lang/Perl-6/HTTPS create mode 120000 Lang/Perl-6/HTTPS-Authenticated create mode 120000 Lang/Perl-6/Infinity create mode 120000 Lang/Perl-6/Secure-temporary-file create mode 120000 Lang/Perl-6/Simple-database create mode 120000 Lang/Perl-6/Table-creation-Postal-addresses create mode 120000 Lang/Perl-6/Video-display-modes create mode 120000 Lang/Perl-6/Voronoi-diagram create mode 120000 Lang/Perl-6/XML-DOM-serialization create mode 120000 Lang/Perl-6/XML-Output create mode 120000 Lang/Perl-6/XML-XPath create mode 120000 Lang/Perl/Keyboard-input-Keypress-check create mode 120000 Lang/Perl/Matrix-arithmetic create mode 120000 Lang/Perl/Parallel-calculations create mode 120000 Lang/Perl/Permutations-Rank-of-a-permutation create mode 120000 Lang/Perl/Simple-database create mode 120000 Lang/Perl/Terminal-control-Preserve-screen create mode 120000 Lang/Perl/Write-to-Windows-event-log create mode 120000 Lang/Phix/Text-processing-1 create mode 120000 Lang/PicoLisp/Extensible-prime-generator create mode 120000 Lang/PicoLisp/Harshad-or-Niven-series create mode 120000 Lang/PicoLisp/Josephus-problem create mode 120000 Lang/PicoLisp/Penneys-game create mode 120000 Lang/PicoLisp/Stern-Brocot-sequence create mode 120000 Lang/Pony/Synchronous-concurrency create mode 120000 Lang/PowerBASIC/Binary-digits create mode 120000 Lang/PowerBASIC/Rot-13 create mode 120000 Lang/PowerShell/Calendar create mode 120000 Lang/PowerShell/Natural-sorting create mode 120000 Lang/Processing/Ackermann-function create mode 120000 Lang/Processing/Classes create mode 120000 Lang/Processing/Factorial create mode 120000 Lang/Processing/Mandelbrot-set create mode 120000 Lang/Processing/Palindrome-detection create mode 120000 Lang/Prolog/Arithmetic-geometric-mean create mode 120000 Lang/Prolog/Closest-pair-problem create mode 120000 Lang/Prolog/Execute-Brain---- create mode 120000 Lang/Prolog/Spiral-matrix create mode 120000 Lang/PureBasic/Almost-prime create mode 120000 Lang/PureBasic/Modular-inverse create mode 120000 Lang/PureBasic/The-Twelve-Days-of-Christmas create mode 120000 Lang/Python/Colour-pinstripe-Display create mode 120000 Lang/Python/Events create mode 120000 Lang/Python/Terminal-control-Hiding-the-cursor create mode 120000 Lang/Python/Terminal-control-Positional-read create mode 120000 Lang/Python/Variables create mode 120000 Lang/Q/Look-and-say-sequence create mode 120000 Lang/R/AKS-test-for-primes create mode 120000 Lang/R/Amicable-pairs create mode 120000 Lang/R/Catamorphism create mode 120000 Lang/R/Dinesmans-multiple-dwelling-problem create mode 120000 Lang/R/Knapsack-problem-Bounded create mode 120000 Lang/R/Lucas-Lehmer-test create mode 120000 Lang/R/Non-decimal-radices-Convert create mode 120000 Lang/R/Reverse-words-in-a-string create mode 120000 Lang/R/Statistics-Basic create mode 120000 Lang/REXX/Bitmap-Read-a-PPM-file create mode 120000 Lang/REXX/Color-of-a-screen-pixel create mode 120000 Lang/REXX/Deconvolution-1D create mode 120000 Lang/REXX/Extreme-floating-point-values create mode 120000 Lang/REXX/Munching-squares create mode 120000 Lang/REXX/Pattern-matching create mode 120000 Lang/REXX/Polynomial-long-division create mode 120000 Lang/Red/ABC-Problem create mode 120000 Lang/Red/Anagrams create mode 120000 Lang/Red/Array-concatenation create mode 120000 Lang/Red/Arrays create mode 120000 Lang/Red/Balanced-brackets create mode 120000 Lang/Red/Binary-digits create mode 120000 Lang/Red/Binary-strings create mode 120000 Lang/Red/CSV-data-manipulation create mode 120000 Lang/Red/CSV-to-HTML-translation create mode 120000 Lang/Red/Character-codes create mode 120000 Lang/Red/Check-that-file-exists create mode 120000 Lang/Red/Closures-Value-capture create mode 120000 Lang/Red/Conditional-structures create mode 120000 Lang/Red/Count-occurrences-of-a-substring create mode 120000 Lang/Red/Date-manipulation create mode 120000 Lang/Red/Day-of-the-week create mode 120000 Lang/Red/Empty-string create mode 120000 Lang/Red/Execute-a-system-command create mode 120000 Lang/Red/File-input-output create mode 120000 Lang/Red/File-size create mode 120000 Lang/Red/Filter create mode 120000 Lang/Red/Globally-replace-text-in-several-files create mode 120000 Lang/Red/Greatest-element-of-a-list create mode 120000 Lang/Red/Hello-world-Graphical create mode 120000 Lang/Red/Huffman-coding create mode 120000 Lang/Red/Loop-over-multiple-arrays-simultaneously create mode 120000 Lang/Red/Loops-Continue create mode 120000 Lang/Red/Loops-Do-while create mode 120000 Lang/Red/Loops-Foreach create mode 120000 Lang/Red/Loops-Infinite create mode 120000 Lang/Red/Morse-code create mode 120000 Lang/Red/Ordered-words create mode 120000 Lang/Red/Pick-random-element create mode 120000 Lang/Red/Read-a-specific-line-from-a-file create mode 120000 Lang/Red/Remove-duplicate-elements create mode 120000 Lang/Red/Repeat-a-string create mode 120000 Lang/Red/Reverse-a-string create mode 120000 Lang/Red/Reverse-words-in-a-string create mode 120000 Lang/Red/Self-describing-numbers create mode 120000 Lang/Red/Sleep create mode 120000 Lang/Red/Sort-an-integer-array create mode 120000 Lang/Red/String-case create mode 120000 Lang/Red/String-concatenation create mode 120000 Lang/Red/String-prepend create mode 120000 Lang/Red/Strip-a-set-of-characters-from-a-string create mode 120000 Lang/Red/Strip-comments-from-a-string create mode 120000 Lang/Red/Strip-whitespace-from-a-string-Top-and-tail create mode 120000 Lang/Red/Sum-of-a-series create mode 120000 Lang/Red/Tokenize-a-string create mode 120000 Lang/Red/User-input-Text create mode 120000 Lang/Red/Vigen-re-cipher create mode 120000 Lang/Red/Window-creation create mode 120000 Lang/Ring/24-game create mode 120000 Lang/Ring/Aliquot-sequence-classifications create mode 120000 Lang/Ring/Anagrams create mode 120000 Lang/Ring/Anagrams-Deranged-anagrams create mode 120000 Lang/Ring/Animate-a-pendulum create mode 120000 Lang/Ring/Animation create mode 120000 Lang/Ring/Anonymous-recursion create mode 120000 Lang/Ring/Associative-array-Creation create mode 120000 Lang/Ring/Associative-array-Iteration create mode 120000 Lang/Ring/Atomic-updates create mode 120000 Lang/Ring/Averages-Mean-angle create mode 120000 Lang/Ring/Averages-Mode create mode 120000 Lang/Ring/Benfords-law create mode 120000 Lang/Ring/Best-shuffle create mode 120000 Lang/Ring/Box-the-compass create mode 120000 Lang/Ring/Brownian-tree create mode 120000 Lang/Ring/Bulls-and-cows create mode 120000 Lang/Ring/Bulls-and-cows-Player create mode 120000 Lang/Ring/Caesar-cipher create mode 120000 Lang/Ring/Calendar create mode 120000 Lang/Ring/Carmichael-3-strong-pseudoprimes create mode 120000 Lang/Ring/Casting-out-nines create mode 120000 Lang/Ring/Cholesky-decomposition create mode 120000 Lang/Ring/Circles-of-given-radius-through-two-points create mode 120000 Lang/Ring/Colour-pinstripe-Display create mode 120000 Lang/Ring/Combinations create mode 120000 Lang/Ring/Combinations-with-repetitions create mode 120000 Lang/Ring/Comma-quibbling create mode 120000 Lang/Ring/Continued-fraction create mode 120000 Lang/Ring/Create-a-file-on-magnetic-tape create mode 120000 Lang/Ring/Date-manipulation create mode 120000 Lang/Ring/Digital-root-Multiplicative-digital-root create mode 120000 Lang/Ring/Doubly-linked-list-Definition create mode 120000 Lang/Ring/Doubly-linked-list-Traversal create mode 120000 Lang/Ring/Draw-a-cuboid create mode 120000 Lang/Ring/Dutch-national-flag-problem create mode 120000 Lang/Ring/Enforced-immutability create mode 120000 Lang/Ring/Evolutionary-algorithm create mode 120000 Lang/Ring/Extend-your-language create mode 120000 Lang/Ring/Factors-of-a-Mersenne-number create mode 120000 Lang/Ring/Fibonacci-n-step-number-sequences create mode 120000 Lang/Ring/Fibonacci-word create mode 120000 Lang/Ring/Forest-fire create mode 120000 Lang/Ring/Forward-difference create mode 120000 Lang/Ring/Four-bit-adder create mode 120000 Lang/Ring/Gray-code create mode 120000 Lang/Ring/Greatest-subsequential-sum create mode 120000 Lang/Ring/Greyscale-bars-Display create mode 120000 Lang/Ring/Hash-from-two-arrays create mode 120000 Lang/Ring/Heronian-triangles create mode 120000 Lang/Ring/Higher-order-functions create mode 120000 Lang/Ring/Hofstadter-Figure-Figure-sequences create mode 120000 Lang/Ring/Horizontal-sundial-calculations create mode 120000 Lang/Ring/I-before-E-except-after-C create mode 120000 Lang/Ring/IBAN create mode 120000 Lang/Ring/Jensens-Device create mode 120000 Lang/Ring/Knapsack-problem-0-1 create mode 120000 Lang/Ring/LZW-compression create mode 120000 Lang/Ring/Last-letter-first-letter create mode 120000 Lang/Ring/Levenshtein-distance create mode 120000 Lang/Ring/Longest-increasing-subsequence create mode 120000 Lang/Ring/Longest-string-challenge create mode 120000 Lang/Ring/Ludic-numbers create mode 120000 Lang/Ring/Maximum-triangle-path-sum create mode 120000 Lang/Ring/Morse-code create mode 120000 Lang/Ring/Move-to-front-algorithm create mode 120000 Lang/Ring/Multisplit create mode 120000 Lang/Ring/Munching-squares create mode 120000 Lang/Ring/Nautical-bell create mode 120000 Lang/Ring/Non-continuous-subsequences create mode 120000 Lang/Ring/Non-decimal-radices-Convert create mode 120000 Lang/Ring/Number-reversal-game create mode 120000 Lang/Ring/Numerical-integration create mode 120000 Lang/Ring/Odd-word-problem create mode 120000 Lang/Ring/One-dimensional-cellular-automata create mode 120000 Lang/Ring/OpenGL create mode 120000 Lang/Ring/Permutations-Rank-of-a-permutation create mode 120000 Lang/Ring/Pernicious-numbers create mode 120000 Lang/Ring/Pig-the-dice-game create mode 120000 Lang/Ring/Pinstripe-Display create mode 120000 Lang/Ring/Plot-coordinate-pairs create mode 120000 Lang/Ring/Power-set create mode 120000 Lang/Ring/Probabilistic-choice create mode 120000 Lang/Ring/Range-expansion create mode 120000 Lang/Ring/Range-extraction create mode 120000 Lang/Ring/Reduced-row-echelon-form create mode 120000 Lang/Ring/Regular-expressions create mode 120000 Lang/Ring/Rep-string create mode 120000 Lang/Ring/Rock-paper-scissors create mode 120000 Lang/Ring/Run-length-encoding create mode 120000 Lang/Ring/SHA-1 create mode 120000 Lang/Ring/SHA-256 create mode 120000 Lang/Ring/Scope-Function-names-and-labels create mode 120000 Lang/Ring/Self-describing-numbers create mode 120000 Lang/Ring/Set create mode 120000 Lang/Ring/Set-consolidation create mode 120000 Lang/Ring/Seven-sided-dice-from-five-sided-dice create mode 120000 Lang/Ring/Short-circuit-evaluation create mode 120000 Lang/Ring/Simulate-input-Mouse create mode 120000 Lang/Ring/Sorting-algorithms-Bogosort create mode 120000 Lang/Ring/Sorting-algorithms-Heapsort create mode 120000 Lang/Ring/Sorting-algorithms-Permutation-sort create mode 120000 Lang/Ring/Sorting-algorithms-Quicksort create mode 120000 Lang/Ring/Sorting-algorithms-Strand-sort create mode 120000 Lang/Ring/Soundex create mode 120000 Lang/Ring/Spiral-matrix create mode 120000 Lang/Ring/Statistics-Basic create mode 120000 Lang/Ring/Stem-and-leaf-plot create mode 120000 Lang/Ring/Stern-Brocot-sequence create mode 120000 Lang/Ring/Table-creation-Postal-addresses create mode 120000 Lang/Ring/Terminal-control-Coloured-text create mode 120000 Lang/Ring/Terminal-control-Cursor-positioning create mode 120000 Lang/Ring/Terminal-control-Display-an-extended-character create mode 120000 Lang/Ring/The-Twelve-Days-of-Christmas create mode 120000 Lang/Ring/Top-rank-per-group create mode 120000 Lang/Ring/Truncatable-primes create mode 120000 Lang/Ring/Ulam-spiral--for-primes- create mode 120000 Lang/Ring/Undefined-values create mode 120000 Lang/Ring/Vampire-number create mode 120000 Lang/Ring/Variadic-function create mode 120000 Lang/Ring/Vigen-re-cipher create mode 120000 Lang/Ring/Voronoi-diagram create mode 120000 Lang/Ring/Word-wrap create mode 120000 Lang/Ring/Write-float-arrays-to-a-text-file create mode 120000 Lang/Ring/Zeckendorf-number-representation create mode 120000 Lang/Ring/Zig-zag-matrix create mode 120000 Lang/Rust/Amb create mode 120000 Lang/Rust/Constrained-random-points-on-a-circle create mode 120000 Lang/Rust/Convert-decimal-number-to-rational create mode 120000 Lang/Rust/Day-of-the-week create mode 120000 Lang/Rust/Detect-division-by-zero create mode 120000 Lang/Rust/Discordian-date create mode 120000 Lang/Rust/Empty-directory create mode 120000 Lang/Rust/Evolutionary-algorithm create mode 120000 Lang/Rust/Fractal-tree create mode 120000 Lang/Rust/Harshad-or-Niven-series create mode 120000 Lang/Rust/Identity-matrix create mode 120000 Lang/Rust/Knuths-algorithm-S create mode 120000 Lang/Rust/Linear-congruential-generator create mode 120000 Lang/Rust/Longest-increasing-subsequence create mode 120000 Lang/Rust/Lucas-Lehmer-test create mode 120000 Lang/Rust/Man-or-boy-test create mode 120000 Lang/Rust/Mandelbrot-set create mode 120000 Lang/Rust/Menu create mode 120000 Lang/Rust/Minesweeper-game create mode 120000 Lang/Rust/Monte-Carlo-methods create mode 120000 Lang/Rust/Parsing-Shunting-yard-algorithm create mode 120000 Lang/Rust/Pascals-triangle create mode 120000 Lang/Rust/Probabilistic-choice create mode 120000 Lang/Rust/Pythagorean-triples create mode 120000 Lang/Rust/Quaternion-type create mode 120000 Lang/Rust/Read-a-configuration-file create mode 120000 Lang/Rust/Read-a-specific-line-from-a-file create mode 120000 Lang/Rust/Rock-paper-scissors create mode 120000 Lang/Rust/Self-describing-numbers create mode 120000 Lang/Rust/Semiprime create mode 120000 Lang/Rust/Short-circuit-evaluation create mode 120000 Lang/Rust/Simulate-input-Keyboard create mode 120000 Lang/Rust/Simulate-input-Mouse create mode 120000 Lang/Rust/Sorting-algorithms-Counting-sort create mode 120000 Lang/Rust/Sorting-algorithms-Pancake-sort create mode 120000 Lang/Rust/String-prepend create mode 120000 Lang/Rust/Strip-a-set-of-characters-from-a-string create mode 120000 Lang/Rust/Substring create mode 120000 Lang/Rust/Sum-multiples-of-3-and-5 create mode 120000 Lang/Rust/Take-notes-on-the-command-line create mode 120000 Lang/Rust/Unbias-a-random-generator create mode 120000 Lang/Rust/Voronoi-diagram create mode 120000 Lang/SAS/Sieve-of-Eratosthenes create mode 120000 Lang/SETL/Roman-numerals-Encode create mode 120000 Lang/Scala/Active-Directory-Connect create mode 120000 Lang/Scala/Arithmetic-geometric-mean-Calculate-Pi create mode 120000 Lang/Scala/Bitcoin-address-validation create mode 120000 Lang/Scala/Call-a-foreign-language-function create mode 120000 Lang/Scala/Catalan-numbers-Pascals-triangle create mode 120000 Lang/Scala/Catamorphism create mode 120000 Lang/Scala/Compile-time-calculation create mode 120000 Lang/Scala/Draw-a-sphere create mode 120000 Lang/Scala/Echo-server create mode 120000 Lang/Scala/GUI-Maximum-window-dimensions create mode 120000 Lang/Scala/Globally-replace-text-in-several-files create mode 120000 Lang/Scala/Guess-the-number-With-feedback create mode 120000 Lang/Scala/HTTPS-Authenticated create mode 120000 Lang/Scala/HTTPS-Client-authenticated create mode 120000 Lang/Scala/Hickerson-series-of-almost-integers create mode 120000 Lang/Scala/Inverted-syntax create mode 120000 Lang/Scala/Keyboard-input-Keypress-check create mode 120000 Lang/Scala/Knapsack-problem-Continuous create mode 120000 Lang/Scala/Knuths-algorithm-S create mode 120000 Lang/Scala/MD5-Implementation create mode 120000 Lang/Scala/Memory-layout-of-a-data-structure create mode 120000 Lang/Scala/Menu create mode 120000 Lang/Scala/Metaprogramming create mode 120000 Lang/Scala/Metered-concurrency create mode 120000 Lang/Scala/Metronome create mode 120000 Lang/Scala/Narcissist create mode 120000 Lang/Scala/Non-decimal-radices-Convert create mode 120000 Lang/Scala/Non-decimal-radices-Input create mode 120000 Lang/Scala/Non-decimal-radices-Output create mode 120000 Lang/Scala/Paraffins create mode 120000 Lang/Scala/Parse-an-IP-Address create mode 120000 Lang/Scala/Pascals-triangle-Puzzle create mode 120000 Lang/Scala/Permutations-by-swapping create mode 120000 Lang/Scala/Polymorphic-copy create mode 120000 Lang/Scala/Pragmatic-directives create mode 120000 Lang/Scala/Random-number-generator--device- create mode 120000 Lang/Scala/Real-constants-and-functions create mode 120000 Lang/Scala/Runtime-evaluation-In-an-environment create mode 120000 Lang/Scala/Safe-addition create mode 120000 Lang/Scala/Scope-Function-names-and-labels create mode 120000 Lang/Scala/Self-describing-numbers create mode 120000 Lang/Scala/Sorting-algorithms-Comb-sort create mode 120000 Lang/Scala/Sorting-algorithms-Stooge-sort create mode 120000 Lang/Scala/Terminal-control-Coloured-text create mode 120000 Lang/Scala/Terminal-control-Cursor-movement create mode 120000 Lang/Scala/Terminal-control-Cursor-positioning create mode 120000 Lang/Scala/Terminal-control-Dimensions create mode 120000 Lang/Scala/Terminal-control-Hiding-the-cursor create mode 120000 Lang/Scala/Terminal-control-Inverse-video create mode 120000 Lang/Scala/Topic-variable create mode 120000 Lang/Scala/Twelve-statements create mode 120000 Lang/Scala/Use-another-language-to-call-a-function create mode 120000 Lang/Scala/Variable-size-Set create mode 120000 Lang/Scala/Video-display-modes create mode 120000 Lang/Scala/Write-to-Windows-event-log create mode 120000 Lang/Scheme/24-game-Solve create mode 120000 Lang/Scheme/Continued-fraction create mode 120000 Lang/Scilab/Cholesky-decomposition create mode 120000 Lang/Scilab/Zig-zag-matrix create mode 120000 Lang/SheerPower-4GL/100-doors create mode 120000 Lang/Shen/Averages-Root-mean-square create mode 120000 Lang/Shen/Enumerations create mode 120000 Lang/Shen/Sorting-algorithms-Bubble-sort create mode 120000 Lang/Sidef/Arithmetic-Rational create mode 120000 Lang/Sidef/Brownian-tree create mode 120000 Lang/Sidef/Casting-out-nines create mode 120000 Lang/Sidef/Circles-of-given-radius-through-two-points create mode 120000 Lang/Sidef/Color-quantization create mode 120000 Lang/Sidef/Colour-pinstripe-Display create mode 120000 Lang/Sidef/Delegates create mode 120000 Lang/Sidef/Element-wise-operations create mode 120000 Lang/Sidef/Matrix-arithmetic create mode 120000 Lang/Sidef/Matrix-exponentiation-operator create mode 120000 Lang/Sidef/Multiplicative-order create mode 120000 Lang/Sidef/N-queens-problem create mode 120000 Lang/Sidef/Vampire-number create mode 120000 Lang/Sidef/Vogels-approximation-method create mode 120000 Lang/Simula/Ackermann-function create mode 120000 Lang/Simula/Greatest-common-divisor create mode 120000 Lang/Simula/Program-termination create mode 120000 Lang/Simula/String-case create mode 120000 Lang/Simula/String-concatenation create mode 120000 Lang/Simula/Sum-multiples-of-3-and-5 create mode 120000 Lang/Sinclair-ZX81-BASIC/Create-a-two-dimensional-array-at-runtime create mode 120000 Lang/Sinclair-ZX81-BASIC/Pinstripe-Display create mode 120000 Lang/Standard-ML/Left-factorials create mode 120000 Lang/Standard-ML/Unix-ls create mode 120000 Lang/Stata/9-billion-names-of-God-the-integer create mode 120000 Lang/Stata/Address-of-a-variable create mode 120000 Lang/Stata/Anagrams create mode 120000 Lang/Stata/Apply-a-callback-to-an-array create mode 120000 Lang/Stata/Averages-Root-mean-square create mode 120000 Lang/Stata/Balanced-brackets create mode 120000 Lang/Stata/Caesar-cipher create mode 120000 Lang/Stata/Catalan-numbers create mode 120000 Lang/Stata/Character-codes create mode 120000 Lang/Stata/Circles-of-given-radius-through-two-points create mode 120000 Lang/Stata/Combinations-and-permutations create mode 120000 Lang/Stata/Combinations-with-repetitions create mode 120000 Lang/Stata/Conditional-structures create mode 120000 Lang/Stata/Count-occurrences-of-a-substring create mode 120000 Lang/Stata/Documentation create mode 120000 Lang/Stata/Element-wise-operations create mode 120000 Lang/Stata/Even-or-odd create mode 120000 Lang/Stata/Exponentiation-operator create mode 120000 Lang/Stata/Find-the-last-Sunday-of-each-month create mode 120000 Lang/Stata/Five-weekends create mode 120000 Lang/Stata/FizzBuzz create mode 120000 Lang/Stata/Function-definition create mode 120000 Lang/Stata/Gamma-function create mode 120000 Lang/Stata/Gaussian-elimination create mode 120000 Lang/Stata/Greatest-common-divisor create mode 120000 Lang/Stata/Greatest-element-of-a-list create mode 120000 Lang/Stata/Identity-matrix create mode 120000 Lang/Stata/Knuth-shuffle create mode 120000 Lang/Stata/Last-Friday-of-each-month create mode 120000 Lang/Stata/Linear-congruential-generator create mode 120000 Lang/Stata/List-comprehensions create mode 120000 Lang/Stata/Literals-Floating-point create mode 120000 Lang/Stata/Map-range create mode 120000 Lang/Stata/Matrix-arithmetic create mode 120000 Lang/Stata/Matrix-exponentiation-operator create mode 120000 Lang/Stata/Matrix-multiplication create mode 120000 Lang/Stata/Matrix-transposition create mode 120000 Lang/Stata/Maximum-triangle-path-sum create mode 120000 Lang/Stata/Multiple-regression create mode 120000 Lang/Stata/Nth create mode 120000 Lang/Stata/Numerical-integration create mode 120000 Lang/Stata/Pascals-triangle create mode 120000 Lang/Stata/Prime-decomposition create mode 120000 Lang/Stata/Probabilistic-choice create mode 120000 Lang/Stata/Roots-of-unity create mode 120000 Lang/Stata/Rot-13 create mode 120000 Lang/Stata/Runge-Kutta-method create mode 120000 Lang/Stata/Semordnilap create mode 120000 Lang/Stata/Short-circuit-evaluation create mode 120000 Lang/Stata/Show-the-epoch create mode 120000 Lang/Stata/Singly-linked-list-Element-definition create mode 120000 Lang/Stata/Sorting-algorithms-Insertion-sort create mode 120000 Lang/Stata/Sorting-algorithms-Selection-sort create mode 120000 Lang/Stata/Spiral-matrix create mode 120000 Lang/Stata/String-append create mode 120000 Lang/Stata/String-concatenation create mode 120000 Lang/Stata/String-interpolation--included- create mode 120000 Lang/Stata/String-prepend create mode 120000 Lang/Stata/Strip-whitespace-from-a-string-Top-and-tail create mode 120000 Lang/Stata/Substring create mode 120000 Lang/Stata/Sudoku create mode 120000 Lang/Stata/Sum-and-product-of-an-array create mode 120000 Lang/Stata/Sum-digits-of-an-integer create mode 120000 Lang/Stata/Sum-of-a-series create mode 120000 Lang/Stata/Sum-of-squares create mode 120000 Lang/Stata/System-time create mode 120000 Lang/Stata/Table-creation-Postal-addresses create mode 120000 Lang/Stata/Towers-of-Hanoi create mode 120000 Lang/Stata/Unicode-variable-names create mode 120000 Lang/Stata/Zig-zag-matrix create mode 120000 Lang/Swift/Catamorphism create mode 120000 Lang/Swift/Find-limit-of-recursion create mode 120000 Lang/Swift/Power-set create mode 120000 Lang/SystemVerilog/Fast-Fourier-transform create mode 120000 Lang/TypeScript/Sorting-algorithms-Quicksort create mode 120000 Lang/UNIX-Shell/Calendar---for-REAL-programmers create mode 120000 Lang/UNIX-Shell/Digital-root create mode 120000 Lang/UNIX-Shell/Dynamic-variable-names create mode 120000 Lang/UNIX-Shell/Even-or-odd create mode 120000 Lang/UNIX-Shell/Palindrome-detection create mode 120000 Lang/UNIX-Shell/Parsing-RPN-calculator-algorithm create mode 120000 Lang/UNIX-Shell/Parsing-Shunting-yard-algorithm create mode 120000 Lang/UNIX-Shell/Temperature-conversion create mode 120000 Lang/Ursa/Sockets create mode 120000 Lang/VBA/ABC-Problem create mode 120000 Lang/VBA/Abundant,-deficient-and-perfect-number-classifications create mode 120000 Lang/VBA/Amicable-pairs create mode 120000 Lang/VBA/Anagrams create mode 120000 Lang/VBA/Anonymous-recursion create mode 120000 Lang/VBA/Apply-a-callback-to-an-array create mode 120000 Lang/VBA/Array-concatenation create mode 120000 Lang/VBA/Best-shuffle create mode 120000 Lang/VBA/Binary-digits create mode 120000 Lang/VBA/Binary-strings create mode 120000 Lang/VBA/Bulls-and-cows create mode 120000 Lang/VBA/Bulls-and-cows-Player create mode 120000 Lang/VBA/Caesar-cipher create mode 120000 Lang/VBA/Call-an-object-method create mode 120000 Lang/VBA/Check-that-file-exists create mode 120000 Lang/VBA/Closest-pair-problem create mode 120000 Lang/VBA/Color-of-a-screen-pixel create mode 120000 Lang/VBA/Combinations create mode 120000 Lang/VBA/Comma-quibbling create mode 120000 Lang/VBA/Conditional-structures create mode 120000 Lang/VBA/Create-a-two-dimensional-array-at-runtime create mode 120000 Lang/VBA/Day-of-the-week create mode 120000 Lang/VBA/Delete-a-file create mode 120000 Lang/VBA/Detect-division-by-zero create mode 120000 Lang/VBA/Determine-if-a-string-is-numeric create mode 120000 Lang/VBA/Empty-directory create mode 120000 Lang/VBA/Empty-program create mode 120000 Lang/VBA/Ethiopian-multiplication create mode 120000 Lang/VBA/Even-or-odd create mode 120000 Lang/VBA/Exceptions create mode 120000 Lang/VBA/Extensible-prime-generator create mode 120000 Lang/VBA/Factorial create mode 120000 Lang/VBA/Fibonacci-n-step-number-sequences create mode 120000 Lang/VBA/File-input-output create mode 120000 Lang/VBA/Filter create mode 120000 Lang/VBA/Find-limit-of-recursion create mode 120000 Lang/VBA/Five-weekends create mode 120000 Lang/VBA/FizzBuzz create mode 120000 Lang/VBA/Function-definition create mode 120000 Lang/VBA/Generate-lower-case-ASCII-alphabet create mode 120000 Lang/VBA/Guess-the-number create mode 120000 Lang/VBA/Happy-numbers create mode 120000 Lang/VBA/Langtons-ant create mode 120000 Lang/VBA/Luhn-test-of-credit-card-numbers create mode 120000 Lang/VBA/Middle-three-digits create mode 120000 Lang/VBA/Minesweeper-game create mode 120000 Lang/VBA/Morse-code create mode 120000 Lang/VBA/Multiplication-tables create mode 120000 Lang/VBA/Odd-word-problem create mode 120000 Lang/VBA/Penneys-game create mode 120000 Lang/VBA/Phrase-reversals create mode 120000 Lang/VBA/Pick-random-element create mode 120000 Lang/VBA/Pig-the-dice-game create mode 120000 Lang/VBA/Price-fraction create mode 120000 Lang/VBA/Primality-by-trial-division create mode 120000 Lang/VBA/Remove-duplicate-elements create mode 120000 Lang/VBA/Remove-lines-from-a-file create mode 120000 Lang/VBA/Return-multiple-values create mode 120000 Lang/VBA/Reverse-words-in-a-string create mode 120000 Lang/VBA/Roman-numerals-Decode create mode 120000 Lang/VBA/Run-length-encoding create mode 120000 Lang/VBA/Sequence-of-non-squares create mode 120000 Lang/VBA/String-concatenation create mode 120000 Lang/VBA/Sum-multiples-of-3-and-5 create mode 120000 Lang/VBA/Temperature-conversion create mode 120000 Lang/VBA/Test-a-function create mode 120000 Lang/VBA/The-Twelve-Days-of-Christmas create mode 120000 Lang/VBA/Tic-tac-toe create mode 120000 Lang/VBA/Tokenize-a-string create mode 120000 Lang/VBA/Vigen-re-cipher create mode 120000 Lang/VBA/Web-scraping create mode 120000 Lang/VBA/Window-creation create mode 120000 Lang/VBA/XML-Input create mode 120000 Lang/VBScript/Guess-the-number-With-feedback create mode 120000 Lang/Visual-Basic-.NET/Balanced-brackets create mode 120000 Lang/Visual-Basic-.NET/Hello-world-Text create mode 120000 Lang/Visual-Basic-.NET/Ray-casting-algorithm create mode 120000 Lang/Visual-Basic-.NET/String-interpolation--included- create mode 120000 Lang/Visual-Basic-.NET/Variables create mode 120000 Lang/Visual-Basic/100-doors create mode 120000 Lang/Visual-Basic/Binary-digits create mode 120000 Lang/Visual-Basic/Check-that-file-exists create mode 120000 Lang/Visual-Basic/Conditional-structures create mode 120000 Lang/Visual-Basic/Formatted-numeric-output create mode 120000 Lang/Visual-Basic/Leap-year create mode 120000 Lang/Visual-Basic/Null-object create mode 120000 Lang/Visual-Basic/Rot-13 create mode 120000 Lang/Wart/N-queens-problem create mode 120000 Lang/X86-Assembly/Balanced-brackets create mode 120000 Lang/X86-Assembly/Echo-server create mode 120000 Lang/X86-Assembly/Loops-While create mode 120000 Lang/XLISP/Accumulator-factory create mode 120000 Lang/XLISP/Address-of-a-variable create mode 120000 Lang/XLISP/Greatest-common-divisor create mode 120000 Lang/XLISP/Priority-queue create mode 120000 Lang/ZX-Spectrum-Basic/Execute-Brain---- create mode 120000 Lang/ZX-Spectrum-Basic/Infinity create mode 120000 Lang/ZX-Spectrum-Basic/Joystick-position create mode 120000 Lang/ZX-Spectrum-Basic/Pascals-triangle create mode 100644 Task/100-doors/BASIC/100-doors-8.basic create mode 100644 Task/100-doors/Common-Lisp/100-doors-7.lisp create mode 100644 Task/100-doors/Excel/100-doors-1.excel create mode 100644 Task/100-doors/Excel/100-doors-2.excel create mode 100644 Task/100-doors/Excel/100-doors-3.excel create mode 100644 Task/100-doors/HolyC/100-doors.holyc create mode 100644 Task/100-doors/Klong/100-doors-1.klong create mode 100644 Task/100-doors/Klong/100-doors-2.klong create mode 100644 Task/100-doors/Nial/100-doors-1.nial create mode 100644 Task/100-doors/Nial/100-doors-2.nial create mode 100644 Task/100-doors/Nial/100-doors-3.nial create mode 100644 Task/100-doors/R/100-doors-4.r create mode 100644 Task/100-doors/SheerPower-4GL/100-doors.4gl create mode 100644 Task/100-doors/Visual-Basic/100-doors.vb create mode 100644 Task/24-game-Solve/Factor/24-game-solve.factor create mode 100644 Task/24-game-Solve/Mathematica/24-game-solve-3.math rename Task/24-game-Solve/Python/{24-game-solve.py => 24-game-solve-1.py} (100%) create mode 100644 Task/24-game-Solve/Python/24-game-solve-2.py create mode 100644 Task/24-game-Solve/Python/24-game-solve-3.py create mode 100644 Task/24-game-Solve/Scheme/24-game-solve-1.ss create mode 100644 Task/24-game-Solve/Scheme/24-game-solve-2.ss create mode 100644 Task/24-game/Befunge/24-game.bf create mode 100644 Task/24-game/Ring/24-game.ring create mode 100644 Task/9-billion-names-of-God-the-integer/Go/9-billion-names-of-god-the-integer.go create mode 100644 Task/9-billion-names-of-God-the-integer/Stata/9-billion-names-of-god-the-integer.stata create mode 100644 Task/99-Bottles-of-Beer/Crystal/99-bottles-of-beer.crystal create mode 100644 Task/99-Bottles-of-Beer/Kitten/99-bottles-of-beer.kitten create mode 100644 Task/99-Bottles-of-Beer/Limbo/99-bottles-of-beer.limbo create mode 100644 Task/99-Bottles-of-Beer/Lingo/99-bottles-of-beer.lingo create mode 100644 Task/99-Bottles-of-Beer/Lua/99-bottles-of-beer-3.lua create mode 100644 Task/99-Bottles-of-Beer/N-t-roff/99-bottles-of-beer-1.n create mode 100644 Task/99-Bottles-of-Beer/N-t-roff/99-bottles-of-beer-2.n create mode 100644 Task/ABC-Problem/Red/abc-problem.red create mode 100644 Task/ABC-Problem/VBA/abc-problem.vba create mode 100644 Task/AKS-test-for-primes/8th/aks-test-for-primes.8th create mode 100644 Task/AKS-test-for-primes/Elena/aks-test-for-primes.elena create mode 100644 Task/AKS-test-for-primes/Perl-6/aks-test-for-primes.pl6 create mode 100644 Task/AKS-test-for-primes/R/aks-test-for-primes.r create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/Elena/abundant,-deficient-and-perfect-number-classifications.elena rename Task/Abundant,-deficient-and-perfect-number-classifications/Erlang/{abundant,-deficient-and-perfect-number-classifications.erl => abundant,-deficient-and-perfect-number-classifications-1.erl} (100%) create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/Erlang/abundant,-deficient-and-perfect-number-classifications-2.erl create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/Factor/abundant,-deficient-and-perfect-number-classifications.factor create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/Modula-2/abundant,-deficient-and-perfect-number-classifications.mod2 create mode 100644 Task/Abundant,-deficient-and-perfect-number-classifications/VBA/abundant,-deficient-and-perfect-number-classifications.vba create mode 100644 Task/Accumulator-factory/Perl-6/accumulator-factory.pl6 create mode 100644 Task/Accumulator-factory/Ruby/accumulator-factory-1.rb create mode 100644 Task/Accumulator-factory/Ruby/accumulator-factory-2.rb create mode 100644 Task/Accumulator-factory/Ruby/accumulator-factory-3.rb delete mode 100644 Task/Accumulator-factory/Ruby/accumulator-factory.rb create mode 100644 Task/Accumulator-factory/XLISP/accumulator-factory.xlisp create mode 100644 Task/Ackermann-function/C-sharp/ackermann-function-1.cs rename Task/Ackermann-function/C-sharp/{ackermann-function.cs => ackermann-function-2.cs} (100%) create mode 100644 Task/Ackermann-function/Gambas/ackermann-function.gambas create mode 100644 Task/Ackermann-function/Klong/ackermann-function.klong create mode 100644 Task/Ackermann-function/Processing/ackermann-function create mode 100644 Task/Ackermann-function/Simula/ackermann-function.simula create mode 100644 Task/Active-Directory-Connect/D/active-directory-connect.d create mode 100644 Task/Active-Directory-Connect/Haskell/active-directory-connect.hs create mode 100644 Task/Active-Directory-Connect/Scala/active-directory-connect.scala create mode 100644 Task/Active-Directory-Search-for-a-user/D/active-directory-search-for-a-user.d create mode 100644 Task/Active-Directory-Search-for-a-user/Haskell/active-directory-search-for-a-user.hs create mode 100644 Task/Active-object/D/active-object.d create mode 100644 Task/Active-object/Julia/active-object.julia create mode 100644 Task/Active-object/Kotlin/active-object.kotlin create mode 100644 Task/Active-object/Lingo/active-object-1.lingo create mode 100644 Task/Active-object/Lingo/active-object-2.lingo create mode 100644 Task/Add-a-variable-to-a-class-instance-at-runtime/Julia/add-a-variable-to-a-class-instance-at-runtime-1.julia create mode 100644 Task/Add-a-variable-to-a-class-instance-at-runtime/Julia/add-a-variable-to-a-class-instance-at-runtime-2.julia create mode 100644 Task/Add-a-variable-to-a-class-instance-at-runtime/Lingo/add-a-variable-to-a-class-instance-at-runtime.lingo create mode 100644 Task/Address-of-a-variable/ARM-Assembly/address-of-a-variable.arm create mode 100644 Task/Address-of-a-variable/C/address-of-a-variable-5.c create mode 100644 Task/Address-of-a-variable/C/address-of-a-variable-6.c create mode 100644 Task/Address-of-a-variable/C/address-of-a-variable-7.c create mode 100644 Task/Address-of-a-variable/Oforth/address-of-a-variable.oforth create mode 100644 Task/Address-of-a-variable/Stata/address-of-a-variable.stata create mode 100644 Task/Address-of-a-variable/XLISP/address-of-a-variable.xlisp create mode 100644 Task/Align-columns/BaCon/align-columns.bacon create mode 100644 Task/Aliquot-sequence-classifications/ALGOL-68/aliquot-sequence-classifications.alg create mode 100644 Task/Aliquot-sequence-classifications/C/aliquot-sequence-classifications-1.c create mode 100644 Task/Aliquot-sequence-classifications/C/aliquot-sequence-classifications-2.c create mode 100644 Task/Aliquot-sequence-classifications/Go/aliquot-sequence-classifications.go create mode 100644 Task/Aliquot-sequence-classifications/Ring/aliquot-sequence-classifications.ring create mode 100644 Task/Almost-prime/Factor/almost-prime.factor create mode 100644 Task/Almost-prime/GW-BASIC/almost-prime.gw-basic create mode 100644 Task/Almost-prime/Modula-2/almost-prime.mod2 create mode 100644 Task/Almost-prime/PureBasic/almost-prime.purebasic create mode 100644 Task/Amb/C-sharp/amb-3.cs create mode 100644 Task/Amb/C-sharp/amb-4.cs create mode 100644 Task/Amb/Rust/amb.rust create mode 100644 Task/Amicable-pairs/Ada/amicable-pairs.ada create mode 100644 Task/Amicable-pairs/Elena/amicable-pairs.elena create mode 100644 Task/Amicable-pairs/Factor/amicable-pairs.factor create mode 100644 Task/Amicable-pairs/R/amicable-pairs.r create mode 100644 Task/Amicable-pairs/VBA/amicable-pairs.vba create mode 100644 Task/Anagrams-Deranged-anagrams/BaCon/anagrams-deranged-anagrams.bacon create mode 100644 Task/Anagrams-Deranged-anagrams/Ring/anagrams-deranged-anagrams.ring create mode 100644 Task/Anagrams/APL/anagrams-1.apl create mode 100644 Task/Anagrams/APL/anagrams-2.apl create mode 100644 Task/Anagrams/BaCon/anagrams.bacon create mode 100644 Task/Anagrams/Red/anagrams.red create mode 100644 Task/Anagrams/Ring/anagrams.ring create mode 100644 Task/Anagrams/Stata/anagrams.stata create mode 100644 Task/Anagrams/VBA/anagrams.vba create mode 100644 Task/Animate-a-pendulum/BASIC/animate-a-pendulum-1.basic create mode 100644 Task/Animate-a-pendulum/BASIC/animate-a-pendulum-2.basic create mode 100644 Task/Animate-a-pendulum/BASIC/animate-a-pendulum-3.basic create mode 100644 Task/Animate-a-pendulum/Julia/animate-a-pendulum.julia create mode 100644 Task/Animate-a-pendulum/Lingo/animate-a-pendulum.lingo create mode 100644 Task/Animate-a-pendulum/Ring/animate-a-pendulum.ring create mode 100644 Task/Animation/J/animation-1.j rename Task/Animation/J/{animation.j => animation-2.j} (100%) create mode 100644 Task/Animation/Julia/animation-1.julia create mode 100644 Task/Animation/Julia/animation-2.julia create mode 100644 Task/Animation/Maple/animation-1.maple create mode 100644 Task/Animation/Maple/animation-2.maple create mode 100644 Task/Animation/Maple/animation-3.maple create mode 100644 Task/Animation/Python/animation-3.py create mode 100644 Task/Animation/Ring/animation.ring create mode 100644 Task/Anonymous-recursion/AutoIt/anonymous-recursion.autoit create mode 100644 Task/Anonymous-recursion/Haskell/anonymous-recursion-4.hs create mode 100644 Task/Anonymous-recursion/Klong/anonymous-recursion.klong create mode 100644 Task/Anonymous-recursion/Ring/anonymous-recursion.ring create mode 100644 Task/Anonymous-recursion/VBA/anonymous-recursion.vba create mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/D/append-a-record-to-the-end-of-a-text-file.d create mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/Julia/append-a-record-to-the-end-of-a-text-file.julia create mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/Kotlin/append-a-record-to-the-end-of-a-text-file.kotlin create mode 100644 Task/Append-a-record-to-the-end-of-a-text-file/Perl-6/append-a-record-to-the-end-of-a-text-file.pl6 create mode 100644 Task/Apply-a-callback-to-an-array/APL/apply-a-callback-to-an-array.apl create mode 100644 Task/Apply-a-callback-to-an-array/Stata/apply-a-callback-to-an-array.stata create mode 100644 Task/Apply-a-callback-to-an-array/VBA/apply-a-callback-to-an-array.vba create mode 100644 Task/Arbitrary-precision-integers--included-/C++/arbitrary-precision-integers--included-.cpp create mode 100644 Task/Arbitrary-precision-integers--included-/Ceylon/arbitrary-precision-integers--included-.ceylon create mode 100644 Task/Arena-storage-pool/Julia/arena-storage-pool.julia create mode 100644 Task/Arithmetic-Integer/APL/arithmetic-integer.apl create mode 100644 Task/Arithmetic-Integer/ARM-Assembly/arithmetic-integer.arm create mode 100644 Task/Arithmetic-Integer/HolyC/arithmetic-integer.holyc rename Task/Arithmetic-Integer/JavaScript/{arithmetic-integer.js => arithmetic-integer-1.js} (100%) create mode 100644 Task/Arithmetic-Integer/JavaScript/arithmetic-integer-2.js create mode 100644 Task/Arithmetic-Integer/Lingo/arithmetic-integer.lingo create mode 100644 Task/Arithmetic-Rational/Factor/arithmetic-rational.factor create mode 100644 Task/Arithmetic-Rational/Sidef/arithmetic-rational.sidef create mode 100644 Task/Arithmetic-evaluation/Kotlin/arithmetic-evaluation.kotlin create mode 100644 Task/Arithmetic-evaluation/Perl-6/arithmetic-evaluation.pl6 create mode 100644 Task/Arithmetic-geometric-mean-Calculate-Pi/Java/arithmetic-geometric-mean-calculate-pi.java create mode 100644 Task/Arithmetic-geometric-mean-Calculate-Pi/Scala/arithmetic-geometric-mean-calculate-pi.scala create mode 100644 Task/Arithmetic-geometric-mean/8th/arithmetic-geometric-mean.8th create mode 100644 Task/Arithmetic-geometric-mean/BASIC/arithmetic-geometric-mean.basic create mode 100644 Task/Arithmetic-geometric-mean/C/arithmetic-geometric-mean-1.c rename Task/Arithmetic-geometric-mean/C/{arithmetic-geometric-mean.c => arithmetic-geometric-mean-2.c} (100%) create mode 100644 Task/Arithmetic-geometric-mean/Factor/arithmetic-geometric-mean.factor create mode 100644 Task/Arithmetic-geometric-mean/Prolog/arithmetic-geometric-mean.pro rename Task/Array-concatenation/Common-Lisp/{array-concatenation.lisp => array-concatenation-1.lisp} (100%) create mode 100644 Task/Array-concatenation/Common-Lisp/array-concatenation-2.lisp create mode 100644 Task/Array-concatenation/Fortran/array-concatenation.f create mode 100644 Task/Array-concatenation/Klong/array-concatenation.klong create mode 100644 Task/Array-concatenation/Limbo/array-concatenation.limbo create mode 100644 Task/Array-concatenation/Red/array-concatenation.red rename Task/Array-concatenation/Scheme/{array-concatenation.ss => array-concatenation-1.ss} (100%) create mode 100644 Task/Array-concatenation/Scheme/array-concatenation-2.ss create mode 100644 Task/Array-concatenation/VBA/array-concatenation.vba create mode 100644 Task/Arrays/HolyC/arrays-1.holyc create mode 100644 Task/Arrays/HolyC/arrays-2.holyc create mode 100644 Task/Arrays/HolyC/arrays-3.holyc create mode 100644 Task/Arrays/Red/arrays-1.red create mode 100644 Task/Arrays/Red/arrays-2.red create mode 100644 Task/Associative-array-Creation/AutoIt/associative-array-creation.autoit create mode 100644 Task/Associative-array-Creation/Perl-6/associative-array-creation.pl6 create mode 100644 Task/Associative-array-Creation/Ring/associative-array-creation.ring create mode 100644 Task/Associative-array-Iteration/Common-Lisp/associative-array-iteration-6.lisp create mode 100644 Task/Associative-array-Iteration/Ring/associative-array-iteration.ring create mode 100644 Task/Atomic-updates/Common-Lisp/atomic-updates-1.lisp create mode 100644 Task/Atomic-updates/Common-Lisp/atomic-updates-2.lisp create mode 100644 Task/Atomic-updates/Julia/atomic-updates.julia create mode 100644 Task/Atomic-updates/Kotlin/atomic-updates.kotlin create mode 100644 Task/Atomic-updates/Ring/atomic-updates.ring create mode 100644 Task/Average-loop-length/C++/average-loop-length.cpp create mode 100644 Task/Average-loop-length/Oberon-2/average-loop-length.oberon-2 create mode 100644 Task/Averages-Arithmetic-mean/Limbo/averages-arithmetic-mean.limbo create mode 100644 Task/Averages-Arithmetic-mean/Lingo/averages-arithmetic-mean-1.lingo create mode 100644 Task/Averages-Arithmetic-mean/Lingo/averages-arithmetic-mean-2.lingo create mode 100644 Task/Averages-Arithmetic-mean/Python/averages-arithmetic-mean-7.py create mode 100644 Task/Averages-Mean-angle/Ring/averages-mean-angle.ring create mode 100644 Task/Averages-Mean-time-of-day/Java/averages-mean-time-of-day.java create mode 100644 Task/Averages-Mean-time-of-day/Julia/averages-mean-time-of-day.julia create mode 100644 Task/Averages-Mean-time-of-day/Lua/averages-mean-time-of-day.lua create mode 100644 Task/Averages-Median/BaCon/averages-median.bacon rename Task/Averages-Median/Go/{averages-median.go => averages-median-1.go} (100%) create mode 100644 Task/Averages-Median/Go/averages-median-2.go create mode 100644 Task/Averages-Median/Go/averages-median-3.go create mode 100644 Task/Averages-Median/Lingo/averages-median.lingo create mode 100644 Task/Averages-Mode/Ring/averages-mode.ring create mode 100644 Task/Averages-Pythagorean-means/Modula-2/averages-pythagorean-means.mod2 create mode 100644 Task/Averages-Root-mean-square/Elena/averages-root-mean-square.elena create mode 100644 Task/Averages-Root-mean-square/Shen/averages-root-mean-square.shen rename Task/Averages-Root-mean-square/Sidef/{averages-root-mean-square.sidef => averages-root-mean-square-1.sidef} (100%) create mode 100644 Task/Averages-Root-mean-square/Sidef/averages-root-mean-square-2.sidef create mode 100644 Task/Averages-Root-mean-square/Stata/averages-root-mean-square-1.stata create mode 100644 Task/Averages-Root-mean-square/Stata/averages-root-mean-square-2.stata create mode 100644 Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average.julia create mode 100644 Task/Averages-Simple-moving-average/Perl-6/averages-simple-moving-average.pl6 create mode 100644 Task/Balanced-brackets/ARM-Assembly/balanced-brackets.arm rename Task/Balanced-brackets/BASIC/{balanced-brackets.basic => balanced-brackets-1.basic} (100%) create mode 100644 Task/Balanced-brackets/BASIC/balanced-brackets-2.basic rename Task/Balanced-brackets/Python/{balanced-brackets.py => balanced-brackets-1.py} (100%) create mode 100644 Task/Balanced-brackets/Python/balanced-brackets-2.py create mode 100644 Task/Balanced-brackets/Python/balanced-brackets-3.py create mode 100644 Task/Balanced-brackets/Red/balanced-brackets.red create mode 100644 Task/Balanced-brackets/Stata/balanced-brackets.stata create mode 100644 Task/Balanced-brackets/Visual-Basic-.NET/balanced-brackets.visual create mode 100644 Task/Balanced-brackets/X86-Assembly/balanced-brackets.x86 create mode 100644 Task/Balanced-ternary/Julia/balanced-ternary.julia create mode 100644 Task/Benfords-law/Factor/benfords-law.factor create mode 100644 Task/Benfords-law/Ring/benfords-law.ring create mode 100644 Task/Bernoulli-numbers/C++/bernoulli-numbers.cpp create mode 100644 Task/Best-shuffle/Common-Lisp/best-shuffle-3.lisp create mode 100644 Task/Best-shuffle/REXX/best-shuffle.rexx create mode 100644 Task/Best-shuffle/Ring/best-shuffle-1.ring create mode 100644 Task/Best-shuffle/Ring/best-shuffle-2.ring create mode 100644 Task/Best-shuffle/Ring/best-shuffle-3.ring create mode 100644 Task/Best-shuffle/Ring/best-shuffle-4.ring create mode 100644 Task/Best-shuffle/VBA/best-shuffle.vba create mode 100644 Task/Binary-digits/Ceylon/binary-digits.ceylon create mode 100644 Task/Binary-digits/PowerBASIC/binary-digits.powerbasic create mode 100644 Task/Binary-digits/Red/binary-digits.red create mode 100644 Task/Binary-digits/VBA/binary-digits.vba create mode 100644 Task/Binary-digits/Visual-Basic/binary-digits.vb create mode 100644 Task/Binary-search/N-t-roff/binary-search.n rename Task/Binary-search/PARI-GP/{binary-search.pari => binary-search-1.pari} (100%) create mode 100644 Task/Binary-search/PARI-GP/binary-search-2.pari create mode 100644 Task/Binary-search/Rust/binary-search-1.rust create mode 100644 Task/Binary-search/Rust/binary-search-2.rust delete mode 100644 Task/Binary-search/Rust/binary-search.rust create mode 100644 Task/Binary-strings/Java/binary-strings-1.java create mode 100644 Task/Binary-strings/Java/binary-strings-2.java create mode 100644 Task/Binary-strings/Lingo/binary-strings.lingo create mode 100644 Task/Binary-strings/Red/binary-strings.red create mode 100644 Task/Binary-strings/VBA/binary-strings-1.vba create mode 100644 Task/Binary-strings/VBA/binary-strings-10.vba create mode 100644 Task/Binary-strings/VBA/binary-strings-2.vba create mode 100644 Task/Binary-strings/VBA/binary-strings-3.vba create mode 100644 Task/Binary-strings/VBA/binary-strings-4.vba create mode 100644 Task/Binary-strings/VBA/binary-strings-5.vba create mode 100644 Task/Binary-strings/VBA/binary-strings-6.vba create mode 100644 Task/Binary-strings/VBA/binary-strings-7.vba create mode 100644 Task/Binary-strings/VBA/binary-strings-8.vba create mode 100644 Task/Binary-strings/VBA/binary-strings-9.vba create mode 100644 Task/Bitcoin-address-validation/Delphi/bitcoin-address-validation.delphi create mode 100644 Task/Bitcoin-address-validation/Julia/bitcoin-address-validation.julia create mode 100644 Task/Bitcoin-address-validation/Scala/bitcoin-address-validation.scala create mode 100644 Task/Bitcoin-public-point-to-address/Julia/bitcoin-public-point-to-address-1.julia create mode 100644 Task/Bitcoin-public-point-to-address/Julia/bitcoin-public-point-to-address-2.julia create mode 100644 Task/Bitmap-B-zier-curves-Cubic/Julia/bitmap-b-zier-curves-cubic.julia create mode 100644 Task/Bitmap-B-zier-curves-Cubic/Kotlin/bitmap-b-zier-curves-cubic.kotlin create mode 100644 Task/Bitmap-B-zier-curves-Cubic/Perl-6/bitmap-b-zier-curves-cubic.pl6 create mode 100644 Task/Bitmap-B-zier-curves-Quadratic/Kotlin/bitmap-b-zier-curves-quadratic.kotlin create mode 100644 Task/Bitmap-B-zier-curves-Quadratic/Perl-6/bitmap-b-zier-curves-quadratic.pl6 create mode 100644 Task/Bitmap-Flood-fill/Julia/bitmap-flood-fill.julia create mode 100644 Task/Bitmap-Histogram/Kotlin/bitmap-histogram.kotlin create mode 100644 Task/Bitmap-Histogram/Perl-6/bitmap-histogram.pl6 create mode 100644 Task/Bitmap-Midpoint-circle-algorithm/Julia/bitmap-midpoint-circle-algorithm.julia create mode 100644 Task/Bitmap-PPM-conversion-through-a-pipe/Julia/bitmap-ppm-conversion-through-a-pipe.julia create mode 100644 Task/Bitmap-PPM-conversion-through-a-pipe/Kotlin/bitmap-ppm-conversion-through-a-pipe.kotlin create mode 100644 Task/Bitmap-Read-a-PPM-file/Erlang/bitmap-read-a-ppm-file-1.erl create mode 100644 Task/Bitmap-Read-a-PPM-file/Erlang/bitmap-read-a-ppm-file-2.erl create mode 100644 Task/Bitmap-Read-a-PPM-file/Kotlin/bitmap-read-a-ppm-file.kotlin create mode 100644 Task/Bitmap-Read-a-PPM-file/Perl-6/bitmap-read-a-ppm-file.pl6 create mode 100644 Task/Bitmap-Read-a-PPM-file/REXX/bitmap-read-a-ppm-file.rexx create mode 100644 Task/Bitmap-Read-an-image-through-a-pipe/Julia/bitmap-read-an-image-through-a-pipe.julia create mode 100644 Task/Bitmap-Read-an-image-through-a-pipe/Kotlin/bitmap-read-an-image-through-a-pipe.kotlin create mode 100644 Task/Bitmap-Read-an-image-through-a-pipe/Perl-6/bitmap-read-an-image-through-a-pipe.pl6 create mode 100644 Task/Bitmap-Write-a-PPM-file/Erlang/bitmap-write-a-ppm-file.erl create mode 100644 Task/Bitmap-Write-a-PPM-file/Julia/bitmap-write-a-ppm-file.julia create mode 100644 Task/Bitmap-Write-a-PPM-file/Kotlin/bitmap-write-a-ppm-file.kotlin create mode 100644 Task/Bitmap/Julia/bitmap.julia create mode 100644 Task/Bitmap/Maple/bitmap.maple create mode 100644 Task/Bitwise-IO/Kotlin/bitwise-io.kotlin create mode 100644 Task/Bitwise-operations/Befunge/bitwise-operations.bf create mode 100644 Task/Boolean-values/APL/boolean-values.apl create mode 100644 Task/Box-the-compass/Befunge/box-the-compass.bf create mode 100644 Task/Box-the-compass/Modula-2/box-the-compass.mod2 create mode 100644 Task/Box-the-compass/Ring/box-the-compass.ring create mode 100644 Task/Break-OO-privacy/OCaml/break-oo-privacy.ocaml create mode 100644 Task/Brownian-tree/Ring/brownian-tree.ring create mode 100644 Task/Brownian-tree/Sidef/brownian-tree.sidef create mode 100644 Task/Bulls-and-cows-Player/Julia/bulls-and-cows-player-1.julia create mode 100644 Task/Bulls-and-cows-Player/Julia/bulls-and-cows-player-2.julia create mode 100644 Task/Bulls-and-cows-Player/Ring/bulls-and-cows-player.ring create mode 100644 Task/Bulls-and-cows-Player/VBA/bulls-and-cows-player.vba create mode 100644 Task/Bulls-and-cows/Ring/bulls-and-cows.ring create mode 100644 Task/Bulls-and-cows/VBA/bulls-and-cows.vba create mode 100644 Task/CSV-data-manipulation/Factor/csv-data-manipulation.factor create mode 100644 Task/CSV-data-manipulation/Red/csv-data-manipulation-1.red create mode 100644 Task/CSV-data-manipulation/Red/csv-data-manipulation-2.red create mode 100644 Task/CSV-data-manipulation/Red/csv-data-manipulation-3.red create mode 100644 Task/CSV-to-HTML-translation/Factor/csv-to-html-translation-1.factor create mode 100644 Task/CSV-to-HTML-translation/Factor/csv-to-html-translation-2.factor create mode 100644 Task/CSV-to-HTML-translation/Forth/csv-to-html-translation-1.fth create mode 100644 Task/CSV-to-HTML-translation/Forth/csv-to-html-translation-2.fth create mode 100644 Task/CSV-to-HTML-translation/Maple/csv-to-html-translation.maple create mode 100644 Task/CSV-to-HTML-translation/Red/csv-to-html-translation.red create mode 100644 Task/Caesar-cipher/Applesoft-BASIC/caesar-cipher.applesoft create mode 100644 Task/Caesar-cipher/COBOL/caesar-cipher-1.cobol rename Task/Caesar-cipher/COBOL/{caesar-cipher.cobol => caesar-cipher-2.cobol} (100%) rename Task/Caesar-cipher/Clojure/{caesar-cipher.clj => caesar-cipher-1.clj} (100%) create mode 100644 Task/Caesar-cipher/Clojure/caesar-cipher-2.clj create mode 100644 Task/Caesar-cipher/Crystal/caesar-cipher.crystal create mode 100644 Task/Caesar-cipher/Factor/caesar-cipher.factor create mode 100644 Task/Caesar-cipher/Modula-2/caesar-cipher.mod2 create mode 100644 Task/Caesar-cipher/Ring/caesar-cipher.ring create mode 100644 Task/Caesar-cipher/Stata/caesar-cipher.stata create mode 100644 Task/Caesar-cipher/VBA/caesar-cipher.vba create mode 100644 Task/Calendar---for-REAL-programmers/BaCon/calendar---for-real-programmers.bacon create mode 100644 Task/Calendar---for-REAL-programmers/UNIX-Shell/calendar---for-real-programmers.sh create mode 100644 Task/Calendar/BaCon/calendar.bacon create mode 100644 Task/Calendar/Go/calendar.go create mode 100644 Task/Calendar/PowerShell/calendar.psh create mode 100644 Task/Calendar/Ring/calendar.ring create mode 100644 Task/Call-a-foreign-language-function/Julia/call-a-foreign-language-function-1.julia create mode 100644 Task/Call-a-foreign-language-function/Julia/call-a-foreign-language-function-2.julia delete mode 100644 Task/Call-a-foreign-language-function/Julia/call-a-foreign-language-function.julia create mode 100644 Task/Call-a-foreign-language-function/Scala/call-a-foreign-language-function.scala create mode 100644 Task/Call-a-function-in-a-shared-library/Kotlin/call-a-function-in-a-shared-library-1.kotlin create mode 100644 Task/Call-a-function-in-a-shared-library/Kotlin/call-a-function-in-a-shared-library-2.kotlin rename Task/Call-a-function-in-a-shared-library/Python/{call-a-function-in-a-shared-library.py => call-a-function-in-a-shared-library-1.py} (100%) create mode 100644 Task/Call-a-function-in-a-shared-library/Python/call-a-function-in-a-shared-library-2.py create mode 100644 Task/Call-a-function-in-a-shared-library/Python/call-a-function-in-a-shared-library-3.py create mode 100644 Task/Call-a-function/ARM-Assembly/call-a-function.arm create mode 100644 Task/Call-a-function/Elena/call-a-function-1.elena create mode 100644 Task/Call-a-function/Elena/call-a-function-2.elena create mode 100644 Task/Call-a-function/Elena/call-a-function-3.elena create mode 100644 Task/Call-a-function/Elena/call-a-function-4.elena create mode 100644 Task/Call-a-function/Factor/call-a-function-1.factor create mode 100644 Task/Call-a-function/Factor/call-a-function-2.factor create mode 100644 Task/Call-a-function/Factor/call-a-function-3.factor create mode 100644 Task/Call-a-function/Factor/call-a-function-4.factor create mode 100644 Task/Call-a-function/Factor/call-a-function-5.factor create mode 100644 Task/Call-a-function/Factor/call-a-function-6.factor create mode 100644 Task/Call-a-function/Factor/call-a-function-7.factor create mode 100644 Task/Call-a-function/Factor/call-a-function-8.factor create mode 100644 Task/Call-a-function/Factor/call-a-function-9.factor create mode 100644 Task/Call-a-function/Fortress/call-a-function.fortress create mode 100644 Task/Call-a-function/Julia/call-a-function.julia create mode 100644 Task/Call-an-object-method/Elena/call-an-object-method.elena create mode 100644 Task/Call-an-object-method/VBA/call-an-object-method-1.vba create mode 100644 Task/Call-an-object-method/VBA/call-an-object-method-2.vba create mode 100644 Task/Canny-edge-detector/Julia/canny-edge-detector.julia create mode 100644 Task/Carmichael-3-strong-pseudoprimes/Go/carmichael-3-strong-pseudoprimes.go create mode 100644 Task/Carmichael-3-strong-pseudoprimes/J/carmichael-3-strong-pseudoprimes.j create mode 100644 Task/Carmichael-3-strong-pseudoprimes/REXX/carmichael-3-strong-pseudoprimes.rexx create mode 100644 Task/Carmichael-3-strong-pseudoprimes/Ring/carmichael-3-strong-pseudoprimes.ring create mode 100644 Task/Case-sensitivity-of-identifiers/Factor/case-sensitivity-of-identifiers.factor create mode 100644 Task/Casting-out-nines/Ring/casting-out-nines.ring create mode 100644 Task/Casting-out-nines/Sidef/casting-out-nines.sidef create mode 100644 Task/Catalan-numbers-Pascals-triangle/Factor/catalan-numbers-pascals-triangle.factor create mode 100644 Task/Catalan-numbers-Pascals-triangle/Go/catalan-numbers-pascals-triangle.go create mode 100644 Task/Catalan-numbers-Pascals-triangle/OCaml/catalan-numbers-pascals-triangle.ocaml create mode 100644 Task/Catalan-numbers-Pascals-triangle/Scala/catalan-numbers-pascals-triangle.scala create mode 100644 Task/Catalan-numbers/Logo/catalan-numbers.logo create mode 100644 Task/Catalan-numbers/Modula-2/catalan-numbers.mod2 create mode 100644 Task/Catalan-numbers/Stata/catalan-numbers.stata create mode 100644 Task/Catamorphism/Factor/catamorphism.factor create mode 100644 Task/Catamorphism/Fortran/catamorphism-1.f create mode 100644 Task/Catamorphism/Fortran/catamorphism-2.f create mode 100644 Task/Catamorphism/J/catamorphism-3.j create mode 100644 Task/Catamorphism/R/catamorphism-1.r create mode 100644 Task/Catamorphism/R/catamorphism-2.r create mode 100644 Task/Catamorphism/R/catamorphism-3.r create mode 100644 Task/Catamorphism/R/catamorphism-4.r create mode 100644 Task/Catamorphism/Scala/catamorphism.scala create mode 100644 Task/Catamorphism/Swift/catamorphism.swift create mode 100644 Task/Catmull-Clark-subdivision-surface/Haskell/catmull-clark-subdivision-surface.hs create mode 100644 Task/Character-codes/BASIC/character-codes-5.basic create mode 100644 Task/Character-codes/BASIC/character-codes-6.basic create mode 100644 Task/Character-codes/HolyC/character-codes.holyc create mode 100644 Task/Character-codes/Red/character-codes.red create mode 100644 Task/Character-codes/Stata/character-codes-1.stata create mode 100644 Task/Character-codes/Stata/character-codes-2.stata create mode 100644 Task/Character-codes/Stata/character-codes-3.stata create mode 100644 Task/Chat-server/Julia/chat-server.julia create mode 100644 Task/Check-Machin-like-formulas/Perl-6/check-machin-like-formulas.pl6 create mode 100644 Task/Check-that-file-exists/HolyC/check-that-file-exists.holyc create mode 100644 Task/Check-that-file-exists/Red/check-that-file-exists.red create mode 100644 Task/Check-that-file-exists/VBA/check-that-file-exists.vba create mode 100644 Task/Check-that-file-exists/Visual-Basic/check-that-file-exists.vb create mode 100644 Task/Checkpoint-synchronization/Go/checkpoint-synchronization-1.go create mode 100644 Task/Checkpoint-synchronization/Go/checkpoint-synchronization-2.go create mode 100644 Task/Checkpoint-synchronization/Go/checkpoint-synchronization-3.go rename Task/Checkpoint-synchronization/Go/{checkpoint-synchronization.go => checkpoint-synchronization-4.go} (100%) create mode 100644 Task/Checkpoint-synchronization/Kotlin/checkpoint-synchronization.kotlin create mode 100644 Task/Chinese-remainder-theorem/Factor/chinese-remainder-theorem.factor create mode 100644 Task/Chinese-remainder-theorem/Julia/chinese-remainder-theorem.julia rename Task/Cholesky-decomposition/Mathematica/{cholesky-decomposition.math => cholesky-decomposition-1.math} (100%) create mode 100644 Task/Cholesky-decomposition/Mathematica/cholesky-decomposition-2.math create mode 100644 Task/Cholesky-decomposition/Ring/cholesky-decomposition.ring create mode 100644 Task/Cholesky-decomposition/Scilab/cholesky-decomposition.scilab rename Task/Circles-of-given-radius-through-two-points/Fortran/{circles-of-given-radius-through-two-points.f => circles-of-given-radius-through-two-points-1.f} (85%) create mode 100644 Task/Circles-of-given-radius-through-two-points/Fortran/circles-of-given-radius-through-two-points-2.f create mode 100644 Task/Circles-of-given-radius-through-two-points/Java/circles-of-given-radius-through-two-points.java create mode 100644 Task/Circles-of-given-radius-through-two-points/Kotlin/circles-of-given-radius-through-two-points.kotlin create mode 100644 Task/Circles-of-given-radius-through-two-points/Modula-2/circles-of-given-radius-through-two-points.mod2 create mode 100644 Task/Circles-of-given-radius-through-two-points/Ring/circles-of-given-radius-through-two-points.ring create mode 100644 Task/Circles-of-given-radius-through-two-points/Sidef/circles-of-given-radius-through-two-points.sidef create mode 100644 Task/Circles-of-given-radius-through-two-points/Stata/circles-of-given-radius-through-two-points-1.stata create mode 100644 Task/Circles-of-given-radius-through-two-points/Stata/circles-of-given-radius-through-two-points-2.stata create mode 100644 Task/Classes/Julia/classes.julia create mode 100644 Task/Classes/Processing/classes-1 create mode 100644 Task/Classes/Processing/classes-2 create mode 100644 Task/Closest-pair-problem/Maple/closest-pair-problem-1.maple create mode 100644 Task/Closest-pair-problem/Maple/closest-pair-problem-2.maple create mode 100644 Task/Closest-pair-problem/Prolog/closest-pair-problem-1.pro create mode 100644 Task/Closest-pair-problem/Prolog/closest-pair-problem-2.pro create mode 100644 Task/Closest-pair-problem/Racket/closest-pair-problem-3.rkt create mode 100644 Task/Closest-pair-problem/VBA/closest-pair-problem.vba create mode 100644 Task/Closures-Value-capture/R/closures-value-capture-4.r create mode 100644 Task/Closures-Value-capture/R/closures-value-capture-5.r create mode 100644 Task/Closures-Value-capture/Red/closures-value-capture.red create mode 100644 Task/Collections/Gambas/collections.gambas create mode 100644 Task/Collections/Julia/collections.julia create mode 100644 Task/Color-of-a-screen-pixel/BaCon/color-of-a-screen-pixel.bacon create mode 100644 Task/Color-of-a-screen-pixel/REXX/color-of-a-screen-pixel.rexx create mode 100644 Task/Color-of-a-screen-pixel/VBA/color-of-a-screen-pixel.vba create mode 100644 Task/Color-quantization/Kotlin/color-quantization.kotlin create mode 100644 Task/Color-quantization/Sidef/color-quantization.sidef create mode 100644 Task/Colour-bars-Display/Julia/colour-bars-display.julia create mode 100644 Task/Colour-pinstripe-Display/Python/colour-pinstripe-display.py create mode 100644 Task/Colour-pinstripe-Display/Ring/colour-pinstripe-display.ring create mode 100644 Task/Colour-pinstripe-Display/Sidef/colour-pinstripe-display.sidef create mode 100644 Task/Combinations-and-permutations/Go/combinations-and-permutations.go create mode 100644 Task/Combinations-and-permutations/Stata/combinations-and-permutations.stata create mode 100644 Task/Combinations-with-repetitions/Common-Lisp/combinations-with-repetitions.lisp create mode 100644 Task/Combinations-with-repetitions/Ring/combinations-with-repetitions.ring create mode 100644 Task/Combinations-with-repetitions/Stata/combinations-with-repetitions.stata create mode 100644 Task/Combinations/Glee/combinations-1.glee create mode 100644 Task/Combinations/Glee/combinations-2.glee rename Task/Combinations/Julia/{combinations.julia => combinations-1.julia} (100%) create mode 100644 Task/Combinations/Julia/combinations-2.julia create mode 100644 Task/Combinations/Modula-2/combinations.mod2 create mode 100644 Task/Combinations/Ring/combinations.ring create mode 100644 Task/Combinations/Stata/combinations-3.stata create mode 100644 Task/Combinations/VBA/combinations.vba create mode 100644 Task/Comma-quibbling/Factor/comma-quibbling.factor create mode 100644 Task/Comma-quibbling/OCaml/comma-quibbling-1.ocaml create mode 100644 Task/Comma-quibbling/OCaml/comma-quibbling-2.ocaml create mode 100644 Task/Comma-quibbling/Ring/comma-quibbling.ring create mode 100644 Task/Comma-quibbling/VBA/comma-quibbling.vba create mode 100644 Task/Command-line-arguments/JavaScript/command-line-arguments-4.js create mode 100644 Task/Command-line-arguments/Klong/command-line-arguments.klong create mode 100644 Task/Comments/ARM-Assembly/comments.arm create mode 100644 Task/Comments/Simula/comments-3.simula create mode 100644 Task/Compare-sorting-algorithms-performance/Kotlin/compare-sorting-algorithms-performance.kotlin create mode 100644 Task/Compile-time-calculation/Scala/compile-time-calculation.scala create mode 100644 Task/Compound-data-type/Elena/compound-data-type.elena create mode 100644 Task/Concurrent-computing/Julia/concurrent-computing.julia create mode 100644 Task/Conditional-structures/BASIC256/conditional-structures.basic256 create mode 100644 Task/Conditional-structures/JCL/conditional-structures-1.jcl create mode 100644 Task/Conditional-structures/JCL/conditional-structures-2.jcl create mode 100644 Task/Conditional-structures/JCL/conditional-structures-3.jcl create mode 100644 Task/Conditional-structures/JCL/conditional-structures-4.jcl create mode 100644 Task/Conditional-structures/JCL/conditional-structures-5.jcl create mode 100644 Task/Conditional-structures/JCL/conditional-structures-6.jcl create mode 100644 Task/Conditional-structures/Julia/conditional-structures-1.julia create mode 100644 Task/Conditional-structures/Julia/conditional-structures-2.julia create mode 100644 Task/Conditional-structures/Red/conditional-structures-1.red create mode 100644 Task/Conditional-structures/Red/conditional-structures-2.red create mode 100644 Task/Conditional-structures/Red/conditional-structures-3.red create mode 100644 Task/Conditional-structures/Red/conditional-structures-4.red create mode 100644 Task/Conditional-structures/Stata/conditional-structures-1.stata create mode 100644 Task/Conditional-structures/Stata/conditional-structures-2.stata create mode 100644 Task/Conditional-structures/Stata/conditional-structures-3.stata create mode 100644 Task/Conditional-structures/Stata/conditional-structures-4.stata create mode 100644 Task/Conditional-structures/Stata/conditional-structures-5.stata create mode 100644 Task/Conditional-structures/VBA/conditional-structures-1.vba create mode 100644 Task/Conditional-structures/VBA/conditional-structures-2.vba create mode 100644 Task/Conditional-structures/VBA/conditional-structures-3.vba create mode 100644 Task/Conditional-structures/VBA/conditional-structures-4.vba create mode 100644 Task/Conditional-structures/VBA/conditional-structures-5.vba create mode 100644 Task/Conditional-structures/Visual-Basic/conditional-structures-1.vb create mode 100644 Task/Conditional-structures/Visual-Basic/conditional-structures-2.vb create mode 100644 Task/Conditional-structures/Visual-Basic/conditional-structures-3.vb create mode 100644 Task/Conditional-structures/Visual-Basic/conditional-structures-4.vb create mode 100644 Task/Conditional-structures/Visual-Basic/conditional-structures-5.vb create mode 100644 Task/Conditional-structures/Visual-Basic/conditional-structures-6.vb create mode 100644 Task/Conditional-structures/Visual-Basic/conditional-structures-7.vb create mode 100644 Task/Constrained-genericity/Julia/constrained-genericity.julia create mode 100644 Task/Constrained-random-points-on-a-circle/COBOL/constrained-random-points-on-a-circle.cobol create mode 100644 Task/Constrained-random-points-on-a-circle/Rust/constrained-random-points-on-a-circle.rust create mode 100644 Task/Continued-fraction-Arithmetic-Construct-from-rational-number/D/continued-fraction-arithmetic-construct-from-rational-number.d create mode 100644 Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Java/continued-fraction-arithmetic-construct-from-rational-number.java create mode 100644 Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Modula-2/continued-fraction-arithmetic-construct-from-rational-number.mod2 create mode 100644 Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Perl-6/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n-.pl6 create mode 100644 Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2-/Kotlin/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n1,-contined-fraction-n2-.kotlin create mode 100644 Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2-/Perl-6/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n1,-contined-fraction-n2-.pl6 create mode 100644 Task/Continued-fraction/Julia/continued-fraction.julia create mode 100644 Task/Continued-fraction/Ring/continued-fraction.ring create mode 100644 Task/Continued-fraction/Scheme/continued-fraction-1.ss create mode 100644 Task/Continued-fraction/Scheme/continued-fraction-2.ss create mode 100644 Task/Convert-decimal-number-to-rational/Factor/convert-decimal-number-to-rational.factor create mode 100644 Task/Convert-decimal-number-to-rational/Rust/convert-decimal-number-to-rational.rust create mode 100644 Task/Conways-Game-of-Life/Kotlin/conways-game-of-life.kotlin create mode 100644 Task/Conways-Game-of-Life/Python/conways-game-of-life-3.py rename Task/Copy-a-string/ABAP/{copy-a-string.abap => copy-a-string-1.abap} (100%) create mode 100644 Task/Copy-a-string/ABAP/copy-a-string-2.abap create mode 100644 Task/Copy-a-string/Crystal/copy-a-string.crystal create mode 100644 Task/Count-in-factors/Factor/count-in-factors.factor create mode 100644 Task/Count-in-octal/Factor/count-in-octal.factor create mode 100644 Task/Count-occurrences-of-a-substring/Red/count-occurrences-of-a-substring.red create mode 100644 Task/Count-occurrences-of-a-substring/Stata/count-occurrences-of-a-substring.stata create mode 100644 Task/Count-the-coins/Perl-6/count-the-coins.pl6 create mode 100644 Task/Create-a-file-on-magnetic-tape/C/create-a-file-on-magnetic-tape.c create mode 100644 Task/Create-a-file-on-magnetic-tape/D/create-a-file-on-magnetic-tape.d create mode 100644 Task/Create-a-file-on-magnetic-tape/Haskell/create-a-file-on-magnetic-tape.hs create mode 100644 Task/Create-a-file-on-magnetic-tape/Ring/create-a-file-on-magnetic-tape.ring create mode 100644 Task/Create-a-two-dimensional-array-at-runtime/Sinclair-ZX81-BASIC/create-a-two-dimensional-array-at-runtime.sinclair create mode 100644 Task/Create-a-two-dimensional-array-at-runtime/VBA/create-a-two-dimensional-array-at-runtime.vba create mode 100644 Task/Create-an-HTML-table/Julia/create-an-html-table-1.julia create mode 100644 Task/Create-an-HTML-table/Julia/create-an-html-table-2.julia create mode 100644 Task/Create-an-object-at-a-given-address/Julia/create-an-object-at-a-given-address.julia create mode 100644 Task/Currying/C/currying.c create mode 100644 Task/Currying/Ceylon/currying.ceylon create mode 100644 Task/Currying/Factor/currying-1.factor create mode 100644 Task/Currying/Factor/currying-2.factor create mode 100644 Task/Currying/Factor/currying-3.factor create mode 100644 Task/Currying/Factor/currying-4.factor create mode 100644 Task/Currying/Factor/currying-5.factor create mode 100644 Task/Currying/Python/currying-3.py create mode 100644 Task/Currying/Python/currying-4.py create mode 100644 Task/DNS-query/Crystal/dns-query.crystal create mode 100644 Task/DNS-query/Objeck/dns-query.objeck create mode 100644 Task/Date-manipulation/D/date-manipulation.d create mode 100644 Task/Date-manipulation/Julia/date-manipulation.julia create mode 100644 Task/Date-manipulation/Maple/date-manipulation-1.maple create mode 100644 Task/Date-manipulation/Maple/date-manipulation-2.maple create mode 100644 Task/Date-manipulation/Red/date-manipulation.red create mode 100644 Task/Date-manipulation/Ring/date-manipulation.ring create mode 100644 Task/Day-of-the-week/Maple/day-of-the-week.maple create mode 100644 Task/Day-of-the-week/Red/day-of-the-week.red create mode 100644 Task/Day-of-the-week/Rust/day-of-the-week.rust create mode 100644 Task/Day-of-the-week/VBA/day-of-the-week.vba create mode 100644 Task/Deal-cards-for-FreeCell/Groovy/deal-cards-for-freecell.groovy create mode 100644 Task/Deal-cards-for-FreeCell/Objeck/deal-cards-for-freecell.objeck create mode 100644 Task/Deconvolution-1D/Go/deconvolution-1d-3.go create mode 100644 Task/Deconvolution-1D/Haskell/deconvolution-1d.hs create mode 100644 Task/Deconvolution-1D/Julia/deconvolution-1d.julia create mode 100644 Task/Deconvolution-1D/REXX/deconvolution-1d.rexx create mode 100644 Task/Deconvolution-2D+/Perl-6/deconvolution-2d+.pl6 create mode 100644 Task/Deepcopy/C/deepcopy-1.c create mode 100644 Task/Deepcopy/C/deepcopy-2.c create mode 100644 Task/Deepcopy/Kotlin/deepcopy.kotlin create mode 100644 Task/Define-a-primitive-data-type/Go/define-a-primitive-data-type.go create mode 100644 Task/Define-a-primitive-data-type/Julia/define-a-primitive-data-type.julia create mode 100644 Task/Delegates/Clojure/delegates.clj create mode 100644 Task/Delegates/Julia/delegates-1.julia create mode 100644 Task/Delegates/Julia/delegates-2.julia create mode 100644 Task/Delegates/Kotlin/delegates.kotlin create mode 100644 Task/Delegates/Sidef/delegates.sidef create mode 100644 Task/Delete-a-file/VBA/delete-a-file.vba create mode 100644 Task/Detect-division-by-zero/HolyC/detect-division-by-zero.holyc create mode 100644 Task/Detect-division-by-zero/Rust/detect-division-by-zero.rust create mode 100644 Task/Detect-division-by-zero/VBA/detect-division-by-zero.vba create mode 100644 Task/Determine-if-a-string-is-numeric/Befunge/determine-if-a-string-is-numeric.bf create mode 100644 Task/Determine-if-a-string-is-numeric/VBA/determine-if-a-string-is-numeric.vba create mode 100644 Task/Digital-root-Multiplicative-digital-root/Factor/digital-root-multiplicative-digital-root.factor create mode 100644 Task/Digital-root-Multiplicative-digital-root/Ring/digital-root-multiplicative-digital-root.ring create mode 100644 Task/Digital-root/Elena/digital-root.elena create mode 100644 Task/Digital-root/Factor/digital-root.factor create mode 100644 Task/Digital-root/Modula-2/digital-root.mod2 create mode 100644 Task/Digital-root/UNIX-Shell/digital-root.sh rename Task/Dinesmans-multiple-dwelling-problem/C-sharp/{dinesmans-multiple-dwelling-problem.cs => dinesmans-multiple-dwelling-problem-1.cs} (100%) create mode 100644 Task/Dinesmans-multiple-dwelling-problem/C-sharp/dinesmans-multiple-dwelling-problem-2.cs create mode 100644 Task/Dinesmans-multiple-dwelling-problem/Julia/dinesmans-multiple-dwelling-problem.julia create mode 100644 Task/Dinesmans-multiple-dwelling-problem/K/dinesmans-multiple-dwelling-problem.k create mode 100644 Task/Dinesmans-multiple-dwelling-problem/Lua/dinesmans-multiple-dwelling-problem.lua create mode 100644 Task/Dinesmans-multiple-dwelling-problem/R/dinesmans-multiple-dwelling-problem-1.r create mode 100644 Task/Dinesmans-multiple-dwelling-problem/R/dinesmans-multiple-dwelling-problem-2.r create mode 100644 Task/Dinesmans-multiple-dwelling-problem/Ruby/dinesmans-multiple-dwelling-problem-4.rb rename Task/Dining-philosophers/Common-Lisp/{dining-philosophers.lisp => dining-philosophers-1.lisp} (100%) create mode 100644 Task/Dining-philosophers/Common-Lisp/dining-philosophers-2.lisp create mode 100644 Task/Dining-philosophers/Common-Lisp/dining-philosophers-3.lisp create mode 100644 Task/Dining-philosophers/Julia/dining-philosophers.julia create mode 100644 Task/Dining-philosophers/Kotlin/dining-philosophers.kotlin create mode 100644 Task/Discordian-date/Rust/discordian-date.rust create mode 100644 Task/Distributed-programming/Perl-6/distributed-programming-1.pl6 create mode 100644 Task/Distributed-programming/Perl-6/distributed-programming-2.pl6 create mode 100644 Task/Documentation/Forth/documentation-1.fth create mode 100644 Task/Documentation/Forth/documentation-2.fth create mode 100644 Task/Documentation/Kotlin/documentation.kotlin create mode 100644 Task/Documentation/Stata/documentation.stata create mode 100644 Task/Dot-product/BASIC/dot-product-1.basic create mode 100644 Task/Dot-product/BASIC/dot-product-2.basic create mode 100644 Task/Dot-product/Elena/dot-product.elena create mode 100644 Task/Dot-product/Modula-2/dot-product.mod2 create mode 100644 Task/Doubly-linked-list-Definition/Ring/doubly-linked-list-definition.ring create mode 100644 Task/Doubly-linked-list-Element-definition/Julia/doubly-linked-list-element-definition.julia create mode 100644 Task/Doubly-linked-list-Traversal/Ring/doubly-linked-list-traversal.ring create mode 100644 Task/Dragon-curve/Julia/dragon-curve.julia create mode 100644 Task/Draw-a-clock/BASIC/draw-a-clock.basic create mode 100644 Task/Draw-a-cuboid/Julia/draw-a-cuboid.julia create mode 100644 Task/Draw-a-cuboid/Ring/draw-a-cuboid.ring create mode 100644 Task/Draw-a-sphere/MATLAB/draw-a-sphere.m create mode 100644 Task/Draw-a-sphere/Scala/draw-a-sphere.scala create mode 100644 Task/Dutch-national-flag-problem/AWK/dutch-national-flag-problem-1.awk create mode 100644 Task/Dutch-national-flag-problem/AWK/dutch-national-flag-problem-2.awk create mode 100644 Task/Dutch-national-flag-problem/Ring/dutch-national-flag-problem.ring create mode 100644 Task/Dutch-national-flag-problem/Ruby/dutch-national-flag-problem.rb create mode 100644 Task/Dynamic-variable-names/C-sharp/dynamic-variable-names.cs create mode 100644 Task/Dynamic-variable-names/Factor/dynamic-variable-names.factor create mode 100644 Task/Dynamic-variable-names/Julia/dynamic-variable-names.julia create mode 100644 Task/Dynamic-variable-names/UNIX-Shell/dynamic-variable-names.sh rename Task/Echo-server/Perl-6/{echo-server.pl6 => echo-server-1.pl6} (77%) create mode 100644 Task/Echo-server/Perl-6/echo-server-2.pl6 create mode 100644 Task/Echo-server/Scala/echo-server.scala create mode 100644 Task/Echo-server/X86-Assembly/echo-server.x86 create mode 100644 Task/Element-wise-operations/C-sharp/element-wise-operations.cs create mode 100644 Task/Element-wise-operations/Fortran/element-wise-operations.f create mode 100644 Task/Element-wise-operations/Kotlin/element-wise-operations.kotlin create mode 100644 Task/Element-wise-operations/Maple/element-wise-operations.maple create mode 100644 Task/Element-wise-operations/Perl-6/element-wise-operations.pl6 create mode 100644 Task/Element-wise-operations/Sidef/element-wise-operations.sidef create mode 100644 Task/Element-wise-operations/Stata/element-wise-operations.stata create mode 100644 Task/Empty-directory/Factor/empty-directory.factor create mode 100644 Task/Empty-directory/Rust/empty-directory.rust create mode 100644 Task/Empty-directory/VBA/empty-directory.vba create mode 100644 Task/Empty-program/N-t-roff/empty-program-1.n create mode 100644 Task/Empty-program/N-t-roff/empty-program-2.n create mode 100644 Task/Empty-program/VBA/empty-program.vba create mode 100644 Task/Empty-string/Factor/empty-string-1.factor create mode 100644 Task/Empty-string/Factor/empty-string-2.factor create mode 100644 Task/Empty-string/HolyC/empty-string.holyc create mode 100644 Task/Empty-string/Red/empty-string.red create mode 100644 Task/Enforced-immutability/Factor/enforced-immutability.factor create mode 100644 Task/Enforced-immutability/Julia/enforced-immutability.julia create mode 100644 Task/Enforced-immutability/Ring/enforced-immutability.ring rename Task/Enforced-immutability/UNIX-Shell/{enforced-immutability.sh => enforced-immutability-1.sh} (100%) create mode 100644 Task/Enforced-immutability/UNIX-Shell/enforced-immutability-2.sh create mode 100644 Task/Entropy/BASIC/entropy-1.basic create mode 100644 Task/Entropy/BASIC/entropy-2.basic create mode 100644 Task/Entropy/BBC-BASIC/entropy.bbc rename Task/Entropy/Common-Lisp/{entropy.lisp => entropy-1.lisp} (59%) create mode 100644 Task/Entropy/Common-Lisp/entropy-2.lisp create mode 100644 Task/Entropy/Factor/entropy.factor create mode 100644 Task/Entropy/Objeck/entropy.objeck create mode 100644 Task/Enumerations/Factor/enumerations-1.factor create mode 100644 Task/Enumerations/Factor/enumerations-2.factor create mode 100644 Task/Enumerations/Shen/enumerations.shen create mode 100644 Task/Equilibrium-index/ABAP/equilibrium-index.abap create mode 100644 Task/Equilibrium-index/Aime/equilibrium-index.aime create mode 100644 Task/Equilibrium-index/Elena/equilibrium-index.elena create mode 100644 Task/Equilibrium-index/JavaScript/equilibrium-index-4.js create mode 100644 Task/Equilibrium-index/Objeck/equilibrium-index.objeck create mode 100644 Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-10.basic create mode 100644 Task/Ethiopian-multiplication/Limbo/ethiopian-multiplication.limbo create mode 100644 Task/Ethiopian-multiplication/Modula-2/ethiopian-multiplication.mod2 create mode 100644 Task/Ethiopian-multiplication/VBA/ethiopian-multiplication-1.vba create mode 100644 Task/Ethiopian-multiplication/VBA/ethiopian-multiplication-2.vba create mode 100644 Task/Ethiopian-multiplication/VBA/ethiopian-multiplication-3.vba create mode 100644 Task/Ethiopian-multiplication/VBA/ethiopian-multiplication-4.vba create mode 100644 Task/Evaluate-binomial-coefficients/Julia/evaluate-binomial-coefficients-1.julia create mode 100644 Task/Evaluate-binomial-coefficients/Julia/evaluate-binomial-coefficients-2.julia delete mode 100644 Task/Evaluate-binomial-coefficients/Julia/evaluate-binomial-coefficients.julia rename Task/Even-or-odd/Common-Lisp/{even-or-odd.lisp => even-or-odd-1.lisp} (100%) create mode 100644 Task/Even-or-odd/Common-Lisp/even-or-odd-2.lisp create mode 100644 Task/Even-or-odd/Modula-2/even-or-odd.mod2 create mode 100644 Task/Even-or-odd/Stata/even-or-odd.stata create mode 100644 Task/Even-or-odd/UNIX-Shell/even-or-odd.sh create mode 100644 Task/Even-or-odd/VBA/even-or-odd.vba create mode 100644 Task/Events/Julia/events.julia create mode 100644 Task/Events/Python/events.py create mode 100644 Task/Evolutionary-algorithm/Factor/evolutionary-algorithm.factor create mode 100644 Task/Evolutionary-algorithm/Julia/evolutionary-algorithm.julia rename Task/Evolutionary-algorithm/R/{evolutionary-algorithm.r => evolutionary-algorithm-1.r} (100%) create mode 100644 Task/Evolutionary-algorithm/R/evolutionary-algorithm-2.r create mode 100644 Task/Evolutionary-algorithm/Ring/evolutionary-algorithm.ring create mode 100644 Task/Evolutionary-algorithm/Rust/evolutionary-algorithm.rust create mode 100644 Task/Evolutionary-algorithm/Smalltalk/evolutionary-algorithm-1.st create mode 100644 Task/Evolutionary-algorithm/Smalltalk/evolutionary-algorithm-2.st delete mode 100644 Task/Evolutionary-algorithm/Smalltalk/evolutionary-algorithm.st create mode 100644 Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Elena/exceptions-catch-an-exception-thrown-in-a-nested-call.elena create mode 100644 Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Julia/exceptions-catch-an-exception-thrown-in-a-nested-call.julia create mode 100644 Task/Exceptions/HolyC/exceptions-1.holyc create mode 100644 Task/Exceptions/HolyC/exceptions-2.holyc create mode 100644 Task/Exceptions/Julia/exceptions.julia create mode 100644 Task/Exceptions/VBA/exceptions-1.vba create mode 100644 Task/Exceptions/VBA/exceptions-2.vba create mode 100644 Task/Executable-library/Clojure/executable-library-1.clj create mode 100644 Task/Executable-library/Clojure/executable-library-2.clj create mode 100644 Task/Executable-library/Julia/executable-library.julia create mode 100644 Task/Execute-Brain----/Julia/execute-brain----.julia create mode 100644 Task/Execute-Brain----/Prolog/execute-brain----.pro create mode 100644 Task/Execute-Brain----/ZX-Spectrum-Basic/execute-brain----.zx create mode 100644 Task/Execute-HQ9+/Julia/execute-hq9+.julia create mode 100644 Task/Execute-HQ9+/OCaml/execute-hq9+.ocaml create mode 100644 Task/Execute-a-Markov-algorithm/Julia/execute-a-markov-algorithm-1.julia create mode 100644 Task/Execute-a-Markov-algorithm/Julia/execute-a-markov-algorithm-2.julia create mode 100644 Task/Execute-a-Markov-algorithm/Kotlin/execute-a-markov-algorithm.kotlin create mode 100644 Task/Execute-a-system-command/HolyC/execute-a-system-command.holyc create mode 100644 Task/Execute-a-system-command/Red/execute-a-system-command.red create mode 100644 Task/Exponentiation-operator/Perl-6/exponentiation-operator.pl6 create mode 100644 Task/Exponentiation-operator/Stata/exponentiation-operator.stata create mode 100644 Task/Extend-your-language/ABAP/extend-your-language.abap create mode 100644 Task/Extend-your-language/DUP/extend-your-language-1.dup create mode 100644 Task/Extend-your-language/DUP/extend-your-language-2.dup create mode 100644 Task/Extend-your-language/Fortran/extend-your-language-1.f create mode 100644 Task/Extend-your-language/Fortran/extend-your-language-2.f create mode 100644 Task/Extend-your-language/Fortran/extend-your-language-3.f create mode 100644 Task/Extend-your-language/Go/extend-your-language.go create mode 100644 Task/Extend-your-language/Idris/extend-your-language.idris create mode 100644 Task/Extend-your-language/Ring/extend-your-language.ring create mode 100644 Task/Extensible-prime-generator/Julia/extensible-prime-generator.julia create mode 100644 Task/Extensible-prime-generator/Lingo/extensible-prime-generator-1.lingo create mode 100644 Task/Extensible-prime-generator/Lingo/extensible-prime-generator-2.lingo create mode 100644 Task/Extensible-prime-generator/PicoLisp/extensible-prime-generator.l create mode 100644 Task/Extensible-prime-generator/VBA/extensible-prime-generator.vba create mode 100644 Task/Extreme-floating-point-values/Factor/extreme-floating-point-values.factor create mode 100644 Task/Extreme-floating-point-values/REXX/extreme-floating-point-values.rexx create mode 100644 Task/Factorial/C/factorial-4.c create mode 100644 Task/Factorial/C/factorial-5.c create mode 100644 Task/Factorial/C/factorial-6.c create mode 100644 Task/Factorial/Common-Lisp/factorial-4.lisp rename Task/Factorial/Elm/{factorial.elm => factorial-1.elm} (100%) create mode 100644 Task/Factorial/Elm/factorial-2.elm create mode 100644 Task/Factorial/Elm/factorial-3.elm create mode 100644 Task/Factorial/Go/factorial-3.go create mode 100644 Task/Factorial/Go/factorial-4.go create mode 100644 Task/Factorial/HolyC/factorial-1.holyc create mode 100644 Task/Factorial/HolyC/factorial-2.holyc create mode 100644 Task/Factorial/Modula-2/factorial.mod2 create mode 100644 Task/Factorial/Nim/factorial-3.nim create mode 100644 Task/Factorial/OCaml/factorial-4.ocaml create mode 100644 Task/Factorial/Processing/factorial create mode 100644 Task/Factorial/VBA/factorial.vba create mode 100644 Task/Factors-of-a-Mersenne-number/Lingo/factors-of-a-mersenne-number-1.lingo create mode 100644 Task/Factors-of-a-Mersenne-number/Lingo/factors-of-a-mersenne-number-2.lingo create mode 100644 Task/Factors-of-a-Mersenne-number/Ring/factors-of-a-mersenne-number.ring create mode 100644 Task/Factors-of-an-integer/Ruby/factors-of-an-integer-3.rb create mode 100644 Task/Fast-Fourier-transform/APL/fast-fourier-transform-1.apl create mode 100644 Task/Fast-Fourier-transform/APL/fast-fourier-transform-2.apl rename Task/Fast-Fourier-transform/Stata/{fast-fourier-transform.stata => fast-fourier-transform-1.stata} (100%) create mode 100644 Task/Fast-Fourier-transform/Stata/fast-fourier-transform-2.stata create mode 100644 Task/Fast-Fourier-transform/SystemVerilog/fast-fourier-transform-1.v create mode 100644 Task/Fast-Fourier-transform/SystemVerilog/fast-fourier-transform-2.v create mode 100644 Task/Fast-Fourier-transform/SystemVerilog/fast-fourier-transform-3.v create mode 100644 Task/Fast-Fourier-transform/SystemVerilog/fast-fourier-transform-4.v create mode 100644 Task/Fibonacci-n-step-number-sequences/Ring/fibonacci-n-step-number-sequences.ring create mode 100644 Task/Fibonacci-n-step-number-sequences/VBA/fibonacci-n-step-number-sequences.vba create mode 100644 Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-7.lisp create mode 100644 Task/Fibonacci-sequence/Elena/fibonacci-sequence.elena create mode 100644 Task/Fibonacci-sequence/Erlang/fibonacci-sequence-4.erl create mode 100644 Task/Fibonacci-sequence/Haskell/fibonacci-sequence-15.hs create mode 100644 Task/Fibonacci-sequence/Haskell/fibonacci-sequence-16.hs create mode 100644 Task/Fibonacci-sequence/Haskell/fibonacci-sequence-17.hs create mode 100644 Task/Fibonacci-sequence/Haskell/fibonacci-sequence-18.hs create mode 100644 Task/Fibonacci-sequence/MATLAB/fibonacci-sequence-4.m create mode 100644 Task/Fibonacci-sequence/Mathematica/fibonacci-sequence-7.math create mode 100644 Task/Fibonacci-sequence/Mathematica/fibonacci-sequence-8.math create mode 100644 Task/Fibonacci-sequence/Mathematica/fibonacci-sequence-9.math create mode 100644 Task/Fibonacci-sequence/Modula-2/fibonacci-sequence.mod2 create mode 100644 Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-17.pari create mode 100644 Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-18.pari create mode 100644 Task/Fibonacci-sequence/PicoLisp/fibonacci-sequence-5.l create mode 100644 Task/Fibonacci-sequence/Python/fibonacci-sequence-13.py create mode 100644 Task/Fibonacci-sequence/Racket/fibonacci-sequence-3.rkt create mode 100644 Task/Fibonacci-sequence/Stata/fibonacci-sequence-1.stata create mode 100644 Task/Fibonacci-sequence/Stata/fibonacci-sequence-2.stata rename Task/Fibonacci-sequence/Stata/{fibonacci-sequence.stata => fibonacci-sequence-3.stata} (100%) create mode 100644 Task/Fibonacci-word-fractal/Julia/fibonacci-word-fractal.julia create mode 100644 Task/Fibonacci-word/C-sharp/fibonacci-word.cs create mode 100644 Task/Fibonacci-word/Factor/fibonacci-word.factor create mode 100644 Task/Fibonacci-word/Objeck/fibonacci-word.objeck create mode 100644 Task/Fibonacci-word/Ring/fibonacci-word.ring create mode 100644 Task/File-input-output/COBOL/file-input-output-4.cobol create mode 100644 Task/File-input-output/Elena/file-input-output.elena rename Task/File-input-output/Forth/{file-input-output.fth => file-input-output-1.fth} (100%) create mode 100644 Task/File-input-output/Forth/file-input-output-2.fth create mode 100644 Task/File-input-output/Red/file-input-output.red create mode 100644 Task/File-input-output/VBA/file-input-output.vba create mode 100644 Task/File-size/Fortran/file-size-1.f rename Task/File-size/Fortran/{file-size.f => file-size-2.f} (100%) create mode 100644 Task/File-size/Red/file-size.red create mode 100644 Task/Filter/Elena/filter.elena rename Task/Filter/Java/{filter.java => filter-1.java} (100%) create mode 100644 Task/Filter/Java/filter-2.java create mode 100644 Task/Filter/Java/filter-3.java create mode 100644 Task/Filter/Red/filter.red create mode 100644 Task/Filter/VBA/filter.vba create mode 100644 Task/Find-common-directory-path/Kotlin/find-common-directory-path.kotlin create mode 100644 Task/Find-largest-left-truncatable-prime-in-a-given-base/Go/find-largest-left-truncatable-prime-in-a-given-base.go create mode 100644 Task/Find-largest-left-truncatable-prime-in-a-given-base/Maple/find-largest-left-truncatable-prime-in-a-given-base.maple create mode 100644 Task/Find-limit-of-recursion/HolyC/find-limit-of-recursion.holyc create mode 100644 Task/Find-limit-of-recursion/Swift/find-limit-of-recursion.swift create mode 100644 Task/Find-limit-of-recursion/VBA/find-limit-of-recursion.vba create mode 100644 Task/Find-the-last-Sunday-of-each-month/Factor/find-the-last-sunday-of-each-month.factor create mode 100644 Task/Find-the-last-Sunday-of-each-month/Maple/find-the-last-sunday-of-each-month.maple create mode 100644 Task/Find-the-last-Sunday-of-each-month/Stata/find-the-last-sunday-of-each-month.stata create mode 100644 Task/Find-the-missing-permutation/Factor/find-the-missing-permutation.factor create mode 100644 Task/Find-the-missing-permutation/Maple/find-the-missing-permutation.maple create mode 100644 Task/First-class-functions-Use-numbers-analogously/Julia/first-class-functions-use-numbers-analogously.julia create mode 100644 Task/Five-weekends/Factor/five-weekends.factor create mode 100644 Task/Five-weekends/Maple/five-weekends.maple create mode 100644 Task/Five-weekends/Stata/five-weekends.stata create mode 100644 Task/Five-weekends/VBA/five-weekends.vba create mode 100644 Task/FizzBuzz/ARM-Assembly/fizzbuzz.arm create mode 100644 Task/FizzBuzz/ATS/fizzbuzz.ats create mode 100644 Task/FizzBuzz/BASIC/fizzbuzz.basic create mode 100644 Task/FizzBuzz/Clojure/fizzbuzz-14.clj create mode 100644 Task/FizzBuzz/Common-Lisp/fizzbuzz-8.lisp create mode 100644 Task/FizzBuzz/Modula-2/fizzbuzz.mod2 create mode 100644 Task/FizzBuzz/Stata/fizzbuzz.stata rename Task/FizzBuzz/Swift/{fizzbuzz.swift => fizzbuzz-1.swift} (100%) create mode 100644 Task/FizzBuzz/Swift/fizzbuzz-2.swift create mode 100644 Task/FizzBuzz/VBA/fizzbuzz.vba create mode 100644 Task/Flatten-a-list/Perl-6/flatten-a-list.pl6 create mode 100644 Task/Flipping-bits-game/Julia/flipping-bits-game.julia create mode 100644 Task/Flipping-bits-game/OCaml/flipping-bits-game.ocaml create mode 100644 Task/Flow-control-structures/360-Assembly/flow-control-structures-1.360 create mode 100644 Task/Flow-control-structures/360-Assembly/flow-control-structures-2.360 create mode 100644 Task/Flow-control-structures/360-Assembly/flow-control-structures-3.360 create mode 100644 Task/Flow-control-structures/360-Assembly/flow-control-structures-4.360 create mode 100644 Task/Flow-control-structures/360-Assembly/flow-control-structures-5.360 create mode 100644 Task/Flow-control-structures/360-Assembly/flow-control-structures-6.360 create mode 100644 Task/Flow-control-structures/Julia/flow-control-structures.julia create mode 100644 Task/Floyds-triangle/360-Assembly/floyds-triangle.360 create mode 100644 Task/Floyds-triangle/BASIC/floyds-triangle-1.basic create mode 100644 Task/Floyds-triangle/BASIC/floyds-triangle-2.basic create mode 100644 Task/Floyds-triangle/Julia/floyds-triangle.julia create mode 100644 Task/Floyds-triangle/Modula-2/floyds-triangle.mod2 create mode 100644 Task/Forest-fire/BASIC/forest-fire-11.basic create mode 100644 Task/Forest-fire/Forth/forest-fire.fth create mode 100644 Task/Forest-fire/Ring/forest-fire.ring create mode 100644 Task/Fork/D/fork.d create mode 100644 Task/Fork/Kotlin/fork.kotlin create mode 100644 Task/Formal-power-series/Julia/formal-power-series-1.julia create mode 100644 Task/Formal-power-series/Julia/formal-power-series-2.julia create mode 100644 Task/Formal-power-series/Kotlin/formal-power-series.kotlin create mode 100644 Task/Formal-power-series/Mathematica/formal-power-series.math create mode 100644 Task/Formatted-numeric-output/Factor/formatted-numeric-output.factor create mode 100644 Task/Formatted-numeric-output/Visual-Basic/formatted-numeric-output-1.vb create mode 100644 Task/Formatted-numeric-output/Visual-Basic/formatted-numeric-output-2.vb create mode 100644 Task/Forward-difference/Ring/forward-difference.ring create mode 100644 Task/Four-bit-adder/Kotlin/four-bit-adder.kotlin create mode 100644 Task/Four-bit-adder/Ring/four-bit-adder.ring create mode 100644 Task/Fractal-tree/BASIC/fractal-tree-1.basic create mode 100644 Task/Fractal-tree/BASIC/fractal-tree-2.basic create mode 100644 Task/Fractal-tree/BASIC/fractal-tree-3.basic create mode 100644 Task/Fractal-tree/BASIC/fractal-tree-4.basic create mode 100644 Task/Fractal-tree/Rust/fractal-tree.rust create mode 100644 Task/Fractran/Julia/fractran.julia create mode 100644 Task/Function-composition/Fortress/function-composition-1.fortress create mode 100644 Task/Function-composition/Fortress/function-composition-2.fortress create mode 100644 Task/Function-composition/Fortress/function-composition-3.fortress create mode 100644 Task/Function-composition/Julia/function-composition-1.julia create mode 100644 Task/Function-composition/Julia/function-composition-2.julia delete mode 100644 Task/Function-composition/Julia/function-composition.julia rename Task/Function-definition/BASIC/{function-definition.basic => function-definition-1.basic} (100%) create mode 100644 Task/Function-definition/BASIC/function-definition-2.basic create mode 100644 Task/Function-definition/HolyC/function-definition.holyc create mode 100644 Task/Function-definition/Stata/function-definition-1.stata create mode 100644 Task/Function-definition/Stata/function-definition-2.stata create mode 100644 Task/Function-definition/VBA/function-definition-1.vba create mode 100644 Task/Function-definition/VBA/function-definition-2.vba create mode 100644 Task/Function-frequency/Julia/function-frequency.julia create mode 100644 Task/GUI-Maximum-window-dimensions/C/gui-maximum-window-dimensions.c create mode 100644 Task/GUI-Maximum-window-dimensions/Scala/gui-maximum-window-dimensions.scala create mode 100644 Task/GUI-component-interaction/Maple/gui-component-interaction-1.maple create mode 100644 Task/GUI-component-interaction/Maple/gui-component-interaction-2.maple create mode 100644 Task/GUI-component-interaction/Maple/gui-component-interaction-3.maple create mode 100644 Task/GUI-enabling-disabling-of-controls/Kotlin/gui-enabling-disabling-of-controls.kotlin create mode 100644 Task/GUI-enabling-disabling-of-controls/Maple/gui-enabling-disabling-of-controls-1.maple create mode 100644 Task/GUI-enabling-disabling-of-controls/Maple/gui-enabling-disabling-of-controls-2.maple create mode 100644 Task/GUI-enabling-disabling-of-controls/Maple/gui-enabling-disabling-of-controls-3.maple create mode 100644 Task/Galton-box-animation/Kotlin/galton-box-animation.kotlin create mode 100644 Task/Gamma-function/Maple/gamma-function.maple create mode 100644 Task/Gamma-function/Stata/gamma-function.stata create mode 100644 Task/Gaussian-elimination/FreeBASIC/gaussian-elimination.freebasic rename Task/Gaussian-elimination/Go/{gaussian-elimination.go => gaussian-elimination-1.go} (100%) create mode 100644 Task/Gaussian-elimination/Go/gaussian-elimination-2.go create mode 100644 Task/Gaussian-elimination/Klong/gaussian-elimination-1.klong create mode 100644 Task/Gaussian-elimination/Klong/gaussian-elimination-2.klong create mode 100644 Task/Gaussian-elimination/Kotlin/gaussian-elimination.kotlin create mode 100644 Task/Gaussian-elimination/REXX/gaussian-elimination-3.rexx create mode 100644 Task/Gaussian-elimination/Stata/gaussian-elimination-1.stata create mode 100644 Task/Gaussian-elimination/Stata/gaussian-elimination-2.stata create mode 100644 Task/Gaussian-elimination/Stata/gaussian-elimination-3.stata create mode 100644 Task/Generate-Chess960-starting-position/C/generate-chess960-starting-position.c create mode 100644 Task/Generate-Chess960-starting-position/Scala/generate-chess960-starting-position-1.scala rename Task/Generate-Chess960-starting-position/Scala/{generate-chess960-starting-position.scala => generate-chess960-starting-position-2.scala} (100%) create mode 100644 Task/Generate-lower-case-ASCII-alphabet/ABAP/generate-lower-case-ascii-alphabet-1.abap create mode 100644 Task/Generate-lower-case-ASCII-alphabet/ABAP/generate-lower-case-ascii-alphabet-2.abap delete mode 100644 Task/Generate-lower-case-ASCII-alphabet/ABAP/generate-lower-case-ascii-alphabet.abap create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Brainf---/generate-lower-case-ascii-alphabet-1.bf create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Brainf---/generate-lower-case-ascii-alphabet-2.bf create mode 100644 Task/Generate-lower-case-ASCII-alphabet/C-sharp/generate-lower-case-ascii-alphabet-1.cs rename Task/Generate-lower-case-ASCII-alphabet/C-sharp/{generate-lower-case-ascii-alphabet.cs => generate-lower-case-ascii-alphabet-2.cs} (100%) create mode 100644 Task/Generate-lower-case-ASCII-alphabet/DUP/generate-lower-case-ascii-alphabet.dup create mode 100644 Task/Generate-lower-case-ASCII-alphabet/Elena/generate-lower-case-ascii-alphabet.elena create mode 100644 Task/Generate-lower-case-ASCII-alphabet/OCaml/generate-lower-case-ascii-alphabet.ocaml create mode 100644 Task/Generate-lower-case-ASCII-alphabet/VBA/generate-lower-case-ascii-alphabet.vba create mode 100644 Task/Generator-Exponential/Lingo/generator-exponential-1.lingo create mode 100644 Task/Generator-Exponential/Lingo/generator-exponential-2.lingo create mode 100644 Task/Generator-Exponential/Lingo/generator-exponential-3.lingo create mode 100644 Task/Generic-swap/Crystal/generic-swap.crystal rename Task/Generic-swap/Haskell/{generic-swap.hs => generic-swap-1.hs} (100%) create mode 100644 Task/Generic-swap/Haskell/generic-swap-2.hs create mode 100644 Task/Globally-replace-text-in-several-files/Kotlin/globally-replace-text-in-several-files.kotlin create mode 100644 Task/Globally-replace-text-in-several-files/Red/globally-replace-text-in-several-files.red create mode 100644 Task/Globally-replace-text-in-several-files/Scala/globally-replace-text-in-several-files.scala create mode 100644 Task/Gray-code/Perl-6/gray-code.pl6 create mode 100644 Task/Gray-code/Ring/gray-code.ring create mode 100644 Task/Grayscale-image/Kotlin/grayscale-image.kotlin create mode 100644 Task/Grayscale-image/Maple/grayscale-image.maple create mode 100644 Task/Greatest-common-divisor/Elena/greatest-common-divisor.elena create mode 100644 Task/Greatest-common-divisor/Klong/greatest-common-divisor.klong create mode 100644 Task/Greatest-common-divisor/Simula/greatest-common-divisor.simula create mode 100644 Task/Greatest-common-divisor/Stata/greatest-common-divisor.stata create mode 100644 Task/Greatest-common-divisor/XLISP/greatest-common-divisor.xlisp create mode 100644 Task/Greatest-element-of-a-list/Aime/greatest-element-of-a-list-1.aime create mode 100644 Task/Greatest-element-of-a-list/Aime/greatest-element-of-a-list-2.aime delete mode 100644 Task/Greatest-element-of-a-list/Aime/greatest-element-of-a-list.aime create mode 100644 Task/Greatest-element-of-a-list/Emacs-Lisp/greatest-element-of-a-list-3.l create mode 100644 Task/Greatest-element-of-a-list/Futhark/greatest-element-of-a-list.futhark rename Task/Greatest-element-of-a-list/NewLISP/{greatest-element-of-a-list.newlisp => greatest-element-of-a-list-1.newlisp} (100%) create mode 100644 Task/Greatest-element-of-a-list/NewLISP/greatest-element-of-a-list-2.newlisp create mode 100644 Task/Greatest-element-of-a-list/Red/greatest-element-of-a-list.red create mode 100644 Task/Greatest-element-of-a-list/Stata/greatest-element-of-a-list-1.stata create mode 100644 Task/Greatest-element-of-a-list/Stata/greatest-element-of-a-list-2.stata create mode 100644 Task/Greatest-subsequential-sum/Ring/greatest-subsequential-sum.ring create mode 100644 Task/Greyscale-bars-Display/Ring/greyscale-bars-display.ring create mode 100644 Task/Guess-the-number-With-feedback/Elena/guess-the-number-with-feedback.elena create mode 100644 Task/Guess-the-number-With-feedback/HolyC/guess-the-number-with-feedback.holyc create mode 100644 Task/Guess-the-number-With-feedback/Scala/guess-the-number-with-feedback.scala create mode 100644 Task/Guess-the-number-With-feedback/VBScript/guess-the-number-with-feedback.vb create mode 100644 Task/Guess-the-number/Elena/guess-the-number.elena create mode 100644 Task/Guess-the-number/HolyC/guess-the-number.holyc create mode 100644 Task/Guess-the-number/VBA/guess-the-number.vba create mode 100644 Task/HTTP/JavaScript/http-3.js create mode 100644 Task/HTTP/JavaScript/http-4.js create mode 100644 Task/HTTP/JavaScript/http-5.js create mode 100644 Task/HTTP/Pascal/http-1.pascal rename Task/HTTP/Pascal/{http.pascal => http-2.pascal} (100%) create mode 100644 Task/HTTPS-Authenticated/Haskell/https-authenticated.hs create mode 100644 Task/HTTPS-Authenticated/Kotlin/https-authenticated.kotlin create mode 100644 Task/HTTPS-Authenticated/Perl-6/https-authenticated.pl6 create mode 100644 Task/HTTPS-Authenticated/Scala/https-authenticated.scala create mode 100644 Task/HTTPS-Client-authenticated/Go/https-client-authenticated.go create mode 100644 Task/HTTPS-Client-authenticated/Kotlin/https-client-authenticated.kotlin create mode 100644 Task/HTTPS-Client-authenticated/Scala/https-client-authenticated.scala create mode 100644 Task/HTTPS/NewLISP/https.newlisp create mode 100644 Task/HTTPS/Pascal/https.pascal create mode 100644 Task/HTTPS/Perl-6/https-1.pl6 create mode 100644 Task/HTTPS/Perl-6/https-2.pl6 create mode 100644 Task/Hailstone-sequence/Elena/hailstone-sequence.elena create mode 100644 Task/Hailstone-sequence/Julia/hailstone-sequence-1.julia create mode 100644 Task/Hailstone-sequence/Julia/hailstone-sequence-2.julia create mode 100644 Task/Hailstone-sequence/Julia/hailstone-sequence-3.julia delete mode 100644 Task/Hailstone-sequence/Julia/hailstone-sequence.julia create mode 100644 Task/Hamming-numbers/Ada/hamming-numbers.ada create mode 100644 Task/Hamming-numbers/Python/hamming-numbers-6.py rename Task/Hamming-numbers/R/{hamming-numbers.r => hamming-numbers-1.r} (100%) create mode 100644 Task/Hamming-numbers/R/hamming-numbers-2.r create mode 100644 Task/Handle-a-signal/D/handle-a-signal.d create mode 100644 Task/Happy-numbers/Elena/happy-numbers.elena create mode 100644 Task/Happy-numbers/VBA/happy-numbers.vba create mode 100644 Task/Harshad-or-Niven-series/Factor/harshad-or-niven-series.factor create mode 100644 Task/Harshad-or-Niven-series/PicoLisp/harshad-or-niven-series.l create mode 100644 Task/Harshad-or-Niven-series/Rust/harshad-or-niven-series.rust create mode 100644 Task/Hash-from-two-arrays/Perl-6/hash-from-two-arrays.pl6 create mode 100644 Task/Hash-from-two-arrays/Ring/hash-from-two-arrays.ring create mode 100644 Task/Hash-join/C++/hash-join.cpp create mode 100644 Task/Hash-join/Perl-6/hash-join.pl6 create mode 100644 Task/Haversine-formula/C++/haversine-formula.cpp create mode 100644 Task/Haversine-formula/Elena/haversine-formula.elena create mode 100644 Task/Hello-world-Graphical/FreeBASIC/hello-world-graphical-1.freebasic create mode 100644 Task/Hello-world-Graphical/FreeBASIC/hello-world-graphical-2.freebasic delete mode 100644 Task/Hello-world-Graphical/FreeBASIC/hello-world-graphical.freebasic create mode 100644 Task/Hello-world-Graphical/HolyC/hello-world-graphical-1.holyc create mode 100644 Task/Hello-world-Graphical/HolyC/hello-world-graphical-2.holyc create mode 100644 Task/Hello-world-Graphical/HolyC/hello-world-graphical-3.holyc create mode 100644 Task/Hello-world-Graphical/N-t-roff/hello-world-graphical.n create mode 100644 Task/Hello-world-Graphical/PARI-GP/hello-world-graphical.pari create mode 100644 Task/Hello-world-Graphical/Perl-6/hello-world-graphical.pl6 create mode 100644 Task/Hello-world-Graphical/Python/hello-world-graphical-7.py create mode 100644 Task/Hello-world-Graphical/Python/hello-world-graphical-8.py create mode 100644 Task/Hello-world-Graphical/Red/hello-world-graphical.red create mode 100644 Task/Hello-world-Line-printer/Clojure/hello-world-line-printer.clj create mode 100644 Task/Hello-world-Line-printer/N-t-roff/hello-world-line-printer.n create mode 100644 Task/Hello-world-Newbie/ARM-Assembly/hello-world-newbie.arm rename Task/Hello-world-Newline-omission/Ada/{hello-world-newline-omission.ada => hello-world-newline-omission-1.ada} (74%) create mode 100644 Task/Hello-world-Newline-omission/Ada/hello-world-newline-omission-2.ada create mode 100644 Task/Hello-world-Newline-omission/Befunge/hello-world-newline-omission.bf create mode 100644 Task/Hello-world-Newline-omission/Elena/hello-world-newline-omission.elena create mode 100644 Task/Hello-world-Newline-omission/Gambas/hello-world-newline-omission.gambas create mode 100644 Task/Hello-world-Newline-omission/HolyC/hello-world-newline-omission-1.holyc create mode 100644 Task/Hello-world-Newline-omission/HolyC/hello-world-newline-omission-2.holyc create mode 100644 Task/Hello-world-Newline-omission/Icon/hello-world-newline-omission.icon create mode 100644 Task/Hello-world-Newline-omission/Modula-2/hello-world-newline-omission.mod2 create mode 100644 Task/Hello-world-Newline-omission/N-t-roff/hello-world-newline-omission.n create mode 100644 Task/Hello-world-Standard-error/ARM-Assembly/hello-world-standard-error.arm create mode 100644 Task/Hello-world-Standard-error/N-t-roff/hello-world-standard-error.n create mode 100644 Task/Hello-world-Text/C/hello-world-text-4.c create mode 100644 Task/Hello-world-Text/Common-Lisp/hello-world-text-3.lisp create mode 100644 Task/Hello-world-Text/HolyC/hello-world-text.holyc create mode 100644 Task/Hello-world-Text/N-t-roff/hello-world-text.n create mode 100644 Task/Hello-world-Text/PL-M/hello-world-text.plm create mode 100644 Task/Hello-world-Text/Rust/hello-world-text-1.rust rename Task/Hello-world-Text/Rust/{hello-world-text.rust => hello-world-text-2.rust} (100%) create mode 100644 Task/Hello-world-Text/Visual-Basic-.NET/hello-world-text.visual create mode 100644 Task/Hello-world-Web-server/Crystal/hello-world-web-server.crystal create mode 100644 Task/Hello-world-Web-server/Perl-6/hello-world-web-server-1.pl6 create mode 100644 Task/Hello-world-Web-server/Perl-6/hello-world-web-server-2.pl6 delete mode 100644 Task/Hello-world-Web-server/Perl-6/hello-world-web-server.pl6 create mode 100644 Task/Here-document/C/here-document.c create mode 100644 Task/Here-document/JavaScript/here-document.js create mode 100644 Task/Here-document/UNIX-Shell/here-document-6.sh create mode 100644 Task/Heronian-triangles/C/heronian-triangles.c create mode 100644 Task/Heronian-triangles/Ring/heronian-triangles.ring create mode 100644 Task/Hickerson-series-of-almost-integers/Scala/hickerson-series-of-almost-integers.scala create mode 100644 Task/Higher-order-functions/Elena/higher-order-functions.elena create mode 100644 Task/Higher-order-functions/Ring/higher-order-functions.ring create mode 100644 Task/History-variables/Elena/history-variables.elena create mode 100644 Task/History-variables/Java/history-variables-1.java create mode 100644 Task/History-variables/Java/history-variables-2.java create mode 100644 Task/History-variables/Java/history-variables-3.java create mode 100644 Task/History-variables/Java/history-variables-4.java create mode 100644 Task/Hofstadter-Figure-Figure-sequences/Ring/hofstadter-figure-figure-sequences.ring create mode 100644 Task/Horizontal-sundial-calculations/GW-BASIC/horizontal-sundial-calculations.gw-basic create mode 100644 Task/Horizontal-sundial-calculations/Modula-2/horizontal-sundial-calculations.mod2 create mode 100644 Task/Horizontal-sundial-calculations/Ring/horizontal-sundial-calculations.ring create mode 100644 Task/Horners-rule-for-polynomial-evaluation/Elena/horners-rule-for-polynomial-evaluation.elena create mode 100644 Task/Horners-rule-for-polynomial-evaluation/Modula-2/horners-rule-for-polynomial-evaluation.mod2 create mode 100644 Task/Huffman-coding/Lua/huffman-coding.lua create mode 100644 Task/Huffman-coding/Red/huffman-coding.red create mode 100644 Task/I-before-E-except-after-C/D/i-before-e-except-after-c.d create mode 100644 Task/I-before-E-except-after-C/Factor/i-before-e-except-after-c.factor create mode 100644 Task/I-before-E-except-after-C/Ring/i-before-e-except-after-c.ring create mode 100644 Task/IBAN/AWK/iban-1.awk create mode 100644 Task/IBAN/AWK/iban-2.awk create mode 100644 Task/IBAN/AWK/iban-3.awk create mode 100644 Task/IBAN/Fortran/iban.f create mode 100644 Task/IBAN/Ring/iban.ring create mode 100644 Task/Identity-matrix/Rust/identity-matrix.rust create mode 100644 Task/Identity-matrix/Stata/identity-matrix-1.stata create mode 100644 Task/Identity-matrix/Stata/identity-matrix-2.stata create mode 100644 Task/Image-convolution/Julia/image-convolution.julia create mode 100644 Task/Image-convolution/Kotlin/image-convolution.kotlin create mode 100644 Task/Image-noise/Kotlin/image-noise.kotlin create mode 100644 Task/Include-a-file/VBScript/include-a-file-3.vb create mode 100644 Task/Increment-a-numerical-string/Elena/increment-a-numerical-string.elena create mode 100644 Task/Increment-a-numerical-string/HolyC/increment-a-numerical-string.holyc create mode 100644 Task/Infinity/Perl-6/infinity.pl6 create mode 100644 Task/Infinity/ZX-Spectrum-Basic/infinity-1.zx create mode 100644 Task/Infinity/ZX-Spectrum-Basic/infinity-2.zx rename Task/Inheritance-Multiple/D/{inheritance-multiple.d => inheritance-multiple-1.d} (100%) create mode 100644 Task/Inheritance-Multiple/D/inheritance-multiple-2.d create mode 100644 Task/Inheritance-Multiple/D/inheritance-multiple-3.d create mode 100644 Task/Inheritance-Multiple/D/inheritance-multiple-4.d create mode 100644 Task/Integer-comparison/HolyC/integer-comparison.holyc create mode 100644 Task/Integer-sequence/Elena/integer-sequence.elena create mode 100644 Task/Integer-sequence/Modula-2/integer-sequence.mod2 create mode 100644 Task/Interactive-programming/Java/interactive-programming.java create mode 100644 Task/Inverted-index/Kotlin/inverted-index.kotlin create mode 100644 Task/Inverted-syntax/D/inverted-syntax.d create mode 100644 Task/Inverted-syntax/Factor/inverted-syntax-1.factor create mode 100644 Task/Inverted-syntax/Factor/inverted-syntax-2.factor create mode 100644 Task/Inverted-syntax/Julia/inverted-syntax.julia create mode 100644 Task/Inverted-syntax/Scala/inverted-syntax.scala create mode 100644 Task/Iterated-digits-squaring/C-sharp/iterated-digits-squaring.cs create mode 100644 Task/Iterated-digits-squaring/Factor/iterated-digits-squaring.factor create mode 100644 Task/Iterated-digits-squaring/Julia/iterated-digits-squaring-3.julia create mode 100644 Task/JSON/Kotlin/json.kotlin create mode 100644 Task/Jensens-Device/Ring/jensens-device.ring create mode 100644 Task/Josephus-problem/BASIC/josephus-problem-1.basic create mode 100644 Task/Josephus-problem/BASIC/josephus-problem-2.basic create mode 100644 Task/Josephus-problem/BBC-BASIC/josephus-problem.bbc create mode 100644 Task/Josephus-problem/MATLAB/josephus-problem.m create mode 100644 Task/Josephus-problem/Modula-2/josephus-problem.mod2 create mode 100644 Task/Josephus-problem/Perl-6/josephus-problem.pl6 create mode 100644 Task/Josephus-problem/PicoLisp/josephus-problem.l create mode 100644 Task/Josephus-problem/Python/josephus-problem-4.py create mode 100644 Task/Joystick-position/Haskell/joystick-position.hs create mode 100644 Task/Joystick-position/ZX-Spectrum-Basic/joystick-position.zx create mode 100644 Task/Jump-anywhere/Go/jump-anywhere.go create mode 100644 Task/Jump-anywhere/Julia/jump-anywhere.julia create mode 100644 Task/K-d-tree/Kotlin/k-d-tree.kotlin create mode 100644 Task/K-means++-clustering/00META.yaml create mode 100644 Task/K-means++-clustering/JavaScript/k-means++-clustering.js create mode 100644 Task/K-means++-clustering/Kotlin/k-means++-clustering.kotlin create mode 100644 Task/Kaprekar-numbers/Erlang/kaprekar-numbers.erl create mode 100644 Task/Kaprekar-numbers/Factor/kaprekar-numbers.factor create mode 100644 Task/Kaprekar-numbers/Modula-2/kaprekar-numbers.mod2 create mode 100644 Task/Keyboard-input-Flush-the-keyboard-buffer/Julia/keyboard-input-flush-the-keyboard-buffer.julia create mode 100644 Task/Keyboard-input-Keypress-check/Elena/keyboard-input-keypress-check.elena create mode 100644 Task/Keyboard-input-Keypress-check/Perl/keyboard-input-keypress-check-1.pl create mode 100644 Task/Keyboard-input-Keypress-check/Perl/keyboard-input-keypress-check-2.pl create mode 100644 Task/Keyboard-input-Keypress-check/Scala/keyboard-input-keypress-check.scala create mode 100644 Task/Keyboard-input-Obtain-a-Y-or-N-response/Julia/keyboard-input-obtain-a-y-or-n-response.julia create mode 100644 Task/Keyboard-macros/Kotlin/keyboard-macros.kotlin create mode 100644 Task/Knapsack-problem-0-1/Racket/knapsack-problem-0-1-3.rkt create mode 100644 Task/Knapsack-problem-0-1/Racket/knapsack-problem-0-1-4.rkt create mode 100644 Task/Knapsack-problem-0-1/Racket/knapsack-problem-0-1-5.rkt create mode 100644 Task/Knapsack-problem-0-1/Racket/knapsack-problem-0-1-6.rkt create mode 100644 Task/Knapsack-problem-0-1/Ring/knapsack-problem-0-1.ring create mode 100644 Task/Knapsack-problem-Bounded/R/knapsack-problem-bounded-1.r create mode 100644 Task/Knapsack-problem-Bounded/R/knapsack-problem-bounded-2.r create mode 100644 Task/Knapsack-problem-Continuous/Scala/knapsack-problem-continuous.scala create mode 100644 Task/Knapsack-problem-Unbounded/Julia/knapsack-problem-unbounded.julia create mode 100644 Task/Knuth-shuffle/BASIC/knuth-shuffle-3.basic create mode 100644 Task/Knuth-shuffle/Julia/knuth-shuffle.julia create mode 100644 Task/Knuth-shuffle/Stata/knuth-shuffle.stata create mode 100644 Task/Knuths-algorithm-S/Rust/knuths-algorithm-s.rust create mode 100644 Task/Knuths-algorithm-S/Scala/knuths-algorithm-s.scala create mode 100644 Task/LU-decomposition/Kotlin/lu-decomposition.kotlin rename Task/LU-decomposition/Stata/{lu-decomposition.stata => lu-decomposition-1.stata} (100%) create mode 100644 Task/LU-decomposition/Stata/lu-decomposition-2.stata create mode 100644 Task/LU-decomposition/Stata/lu-decomposition-3.stata create mode 100644 Task/LZW-compression/BaCon/lzw-compression.bacon create mode 100644 Task/LZW-compression/Julia/lzw-compression.julia create mode 100644 Task/LZW-compression/Ring/lzw-compression.ring create mode 100644 Task/Langtons-ant/Kotlin/langtons-ant.kotlin create mode 100644 Task/Langtons-ant/REXX/langtons-ant-1.rexx create mode 100644 Task/Langtons-ant/REXX/langtons-ant-2.rexx create mode 100644 Task/Langtons-ant/REXX/langtons-ant-3.rexx delete mode 100644 Task/Langtons-ant/REXX/langtons-ant.rexx create mode 100644 Task/Langtons-ant/VBA/langtons-ant.vba create mode 100644 Task/Largest-int-from-concatenated-ints/Common-Lisp/largest-int-from-concatenated-ints-1.lisp rename Task/Largest-int-from-concatenated-ints/Common-Lisp/{largest-int-from-concatenated-ints.lisp => largest-int-from-concatenated-ints-2.lisp} (100%) create mode 100644 Task/Largest-int-from-concatenated-ints/Factor/largest-int-from-concatenated-ints.factor create mode 100644 Task/Largest-int-from-concatenated-ints/REXX/largest-int-from-concatenated-ints-1.rexx create mode 100644 Task/Largest-int-from-concatenated-ints/REXX/largest-int-from-concatenated-ints-2.rexx create mode 100644 Task/Largest-int-from-concatenated-ints/REXX/largest-int-from-concatenated-ints-3.rexx create mode 100644 Task/Largest-int-from-concatenated-ints/REXX/largest-int-from-concatenated-ints-4.rexx delete mode 100644 Task/Largest-int-from-concatenated-ints/REXX/largest-int-from-concatenated-ints.rexx create mode 100644 Task/Last-Friday-of-each-month/Factor/last-friday-of-each-month.factor create mode 100644 Task/Last-Friday-of-each-month/Maple/last-friday-of-each-month.maple create mode 100644 Task/Last-Friday-of-each-month/Stata/last-friday-of-each-month.stata create mode 100644 Task/Last-letter-first-letter/BaCon/last-letter-first-letter-1.bacon create mode 100644 Task/Last-letter-first-letter/BaCon/last-letter-first-letter-2.bacon create mode 100644 Task/Last-letter-first-letter/Clojure/last-letter-first-letter-1.clj create mode 100644 Task/Last-letter-first-letter/Clojure/last-letter-first-letter-2.clj create mode 100644 Task/Last-letter-first-letter/Julia/last-letter-first-letter.julia create mode 100644 Task/Last-letter-first-letter/Ring/last-letter-first-letter.ring create mode 100644 Task/Leap-year/GW-BASIC/leap-year.gw-basic rename Task/Leap-year/Java/{leap-year.java => leap-year-1.java} (100%) create mode 100644 Task/Leap-year/Java/leap-year-2.java rename Task/Leap-year/MATLAB/{leap-year.m => leap-year-1.m} (100%) create mode 100644 Task/Leap-year/MATLAB/leap-year-2.m create mode 100644 Task/Leap-year/Modula-2/leap-year.mod2 create mode 100644 Task/Leap-year/Visual-Basic/leap-year-1.vb create mode 100644 Task/Leap-year/Visual-Basic/leap-year-2.vb create mode 100644 Task/Least-common-multiple/Elena/least-common-multiple.elena create mode 100644 Task/Least-common-multiple/GW-BASIC/least-common-multiple.gw-basic create mode 100644 Task/Least-common-multiple/Modula-2/least-common-multiple.mod2 create mode 100644 Task/Left-factorials/Factor/left-factorials.factor create mode 100644 Task/Left-factorials/Forth/left-factorials.fth create mode 100644 Task/Left-factorials/Standard-ML/left-factorials.ml create mode 100644 Task/Letter-frequency/Aime/letter-frequency-1.aime create mode 100644 Task/Letter-frequency/Aime/letter-frequency-2.aime create mode 100644 Task/Letter-frequency/BaCon/letter-frequency.bacon create mode 100644 Task/Levenshtein-distance/Factor/levenshtein-distance.factor create mode 100644 Task/Levenshtein-distance/Julia/levenshtein-distance-1.julia create mode 100644 Task/Levenshtein-distance/Julia/levenshtein-distance-2.julia create mode 100644 Task/Levenshtein-distance/Julia/levenshtein-distance-3.julia delete mode 100644 Task/Levenshtein-distance/Julia/levenshtein-distance.julia rename Task/Levenshtein-distance/Kotlin/{levenshtein-distance.kotlin => levenshtein-distance-1.kotlin} (100%) create mode 100644 Task/Levenshtein-distance/Kotlin/levenshtein-distance-2.kotlin create mode 100644 Task/Levenshtein-distance/Ring/levenshtein-distance.ring create mode 100644 Task/Linear-congruential-generator/Rust/linear-congruential-generator.rust create mode 100644 Task/Linear-congruential-generator/Stata/linear-congruential-generator.stata create mode 100644 Task/List-comprehensions/C/list-comprehensions-1.c create mode 100644 Task/List-comprehensions/C/list-comprehensions-2.c rename Task/List-comprehensions/C/{list-comprehensions.c => list-comprehensions-3.c} (100%) create mode 100644 Task/List-comprehensions/Haskell/list-comprehensions-5.hs create mode 100644 Task/List-comprehensions/Haskell/list-comprehensions-6.hs create mode 100644 Task/List-comprehensions/Java/list-comprehensions.java create mode 100644 Task/List-comprehensions/JavaScript/list-comprehensions-5.js create mode 100644 Task/List-comprehensions/OCaml/list-comprehensions-4.ocaml create mode 100644 Task/List-comprehensions/Python/list-comprehensions-3.py create mode 100644 Task/List-comprehensions/Python/list-comprehensions-4.py create mode 100644 Task/List-comprehensions/Python/list-comprehensions-5.py create mode 100644 Task/List-comprehensions/Python/list-comprehensions-6.py create mode 100644 Task/List-comprehensions/Python/list-comprehensions-7.py create mode 100644 Task/List-comprehensions/Stata/list-comprehensions.stata create mode 100644 Task/Literals-Floating-point/Elena/literals-floating-point.elena create mode 100644 Task/Literals-Floating-point/Julia/literals-floating-point.julia create mode 100644 Task/Literals-Floating-point/Stata/literals-floating-point.stata create mode 100644 Task/Literals-Integer/Factor/literals-integer-1.factor create mode 100644 Task/Literals-Integer/Factor/literals-integer-2.factor create mode 100644 Task/Literals-Integer/HolyC/literals-integer-1.holyc create mode 100644 Task/Literals-Integer/HolyC/literals-integer-2.holyc create mode 100644 Task/Literals-Integer/Limbo/literals-integer.limbo create mode 100644 Task/Logical-operations/Elena/logical-operations.elena rename Task/Logical-operations/Haskell/{logical-operations.hs => logical-operations-1.hs} (51%) create mode 100644 Task/Logical-operations/Haskell/logical-operations-2.hs create mode 100644 Task/Logical-operations/Haskell/logical-operations-3.hs create mode 100644 Task/Logical-operations/HolyC/logical-operations.holyc create mode 100644 Task/Logical-operations/Modula-2/logical-operations.mod2 create mode 100644 Task/Logical-operations/REXX/logical-operations-1.rexx create mode 100644 Task/Logical-operations/REXX/logical-operations-2.rexx delete mode 100644 Task/Logical-operations/REXX/logical-operations.rexx create mode 100644 Task/Long-multiplication/COBOL/long-multiplication.cobol create mode 100644 Task/Long-multiplication/Ceylon/long-multiplication.ceylon create mode 100644 Task/Long-multiplication/Julia/long-multiplication-1.julia create mode 100644 Task/Long-multiplication/Julia/long-multiplication-2.julia create mode 100644 Task/Longest-increasing-subsequence/Julia/longest-increasing-subsequence.julia create mode 100644 Task/Longest-increasing-subsequence/Ring/longest-increasing-subsequence.ring create mode 100644 Task/Longest-increasing-subsequence/Rust/longest-increasing-subsequence.rust create mode 100644 Task/Longest-string-challenge/Haskell/longest-string-challenge.hs create mode 100644 Task/Longest-string-challenge/Julia/longest-string-challenge.julia create mode 100644 Task/Longest-string-challenge/Ring/longest-string-challenge.ring create mode 100644 Task/Look-and-say-sequence/BASIC256/look-and-say-sequence.basic256 create mode 100644 Task/Look-and-say-sequence/Ceylon/look-and-say-sequence.ceylon create mode 100644 Task/Look-and-say-sequence/Q/look-and-say-sequence.q create mode 100644 Task/Look-and-say-sequence/Scala/look-and-say-sequence-3.scala rename Task/Loop-over-multiple-arrays-simultaneously/AppleScript/{loop-over-multiple-arrays-simultaneously.applescript => loop-over-multiple-arrays-simultaneously-1.applescript} (100%) create mode 100644 Task/Loop-over-multiple-arrays-simultaneously/AppleScript/loop-over-multiple-arrays-simultaneously-2.applescript create mode 100644 Task/Loop-over-multiple-arrays-simultaneously/JavaScript/loop-over-multiple-arrays-simultaneously-7.js create mode 100644 Task/Loop-over-multiple-arrays-simultaneously/Red/loop-over-multiple-arrays-simultaneously.red create mode 100644 Task/Loops-Break/ALGOL-60/loops-break.alg rename Task/Loops-Break/Stata/{loops-break.stata => loops-break-1.stata} (100%) create mode 100644 Task/Loops-Break/Stata/loops-break-2.stata rename Task/Loops-Continue/D/{loops-continue.d => loops-continue-1.d} (100%) create mode 100644 Task/Loops-Continue/D/loops-continue-2.d create mode 100644 Task/Loops-Continue/Red/loops-continue.red create mode 100644 Task/Loops-Do-while/Fortress/loops-do-while.fortress create mode 100644 Task/Loops-Do-while/GW-BASIC/loops-do-while-1.gw-basic create mode 100644 Task/Loops-Do-while/GW-BASIC/loops-do-while-2.gw-basic create mode 100644 Task/Loops-Do-while/Haskell/loops-do-while-4.hs create mode 100644 Task/Loops-Do-while/JavaScript/loops-do-while-8.js create mode 100644 Task/Loops-Do-while/JavaScript/loops-do-while-9.js create mode 100644 Task/Loops-Do-while/Red/loops-do-while.red create mode 100644 Task/Loops-Downward-for/GW-BASIC/loops-downward-for.gw-basic create mode 100644 Task/Loops-For/BASIC/loops-for-17.basic create mode 100644 Task/Loops-For/Klong/loops-for.klong create mode 100644 Task/Loops-For/PHP/loops-for-3.php create mode 100644 Task/Loops-For/Perl/loops-for-4.pl create mode 100644 Task/Loops-For/Python/loops-for-3.py rename Task/Loops-For/Stata/{loops-for.stata => loops-for-1.stata} (100%) create mode 100644 Task/Loops-For/Stata/loops-for-2.stata create mode 100644 Task/Loops-Foreach/Aime/loops-foreach.aime create mode 100644 Task/Loops-Foreach/Red/loops-foreach.red create mode 100644 Task/Loops-Infinite/C/loops-infinite-5.c create mode 100644 Task/Loops-Infinite/Emacs-Lisp/loops-infinite.l create mode 100644 Task/Loops-Infinite/Fortress/loops-infinite.fortress create mode 100644 Task/Loops-Infinite/Perl/loops-infinite-1.pl rename Task/Loops-Infinite/Perl/{loops-infinite.pl => loops-infinite-2.pl} (100%) create mode 100644 Task/Loops-Infinite/Red/loops-infinite.red create mode 100644 Task/Loops-N-plus-one-half/ALGOL-60/loops-n-plus-one-half.alg create mode 100644 Task/Loops-N-plus-one-half/Fortran/loops-n-plus-one-half-3.f rename Task/Loops-N-plus-one-half/Haskell/{loops-n-plus-one-half.hs => loops-n-plus-one-half-1.hs} (54%) create mode 100644 Task/Loops-N-plus-one-half/Haskell/loops-n-plus-one-half-2.hs rename Task/Loops-N-plus-one-half/Perl/{loops-n-plus-one-half.pl => loops-n-plus-one-half-1.pl} (73%) create mode 100644 Task/Loops-N-plus-one-half/Perl/loops-n-plus-one-half-2.pl create mode 100644 Task/Loops-Nested/ALGOL-60/loops-nested.alg create mode 100644 Task/Loops-Nested/Factor/loops-nested.factor create mode 100644 Task/Loops-While/BASIC/loops-while-3.basic create mode 100644 Task/Loops-While/Fortress/loops-while.fortress create mode 100644 Task/Loops-While/PL-SQL/loops-while.sql create mode 100644 Task/Loops-While/Perl/loops-while-3.pl create mode 100644 Task/Loops-While/X86-Assembly/loops-while.x86 create mode 100644 Task/Lucas-Lehmer-test/Forth/lucas-lehmer-test.fth create mode 100644 Task/Lucas-Lehmer-test/Julia/lucas-lehmer-test.julia create mode 100644 Task/Lucas-Lehmer-test/R/lucas-lehmer-test.r create mode 100644 Task/Lucas-Lehmer-test/Rust/lucas-lehmer-test.rust create mode 100644 Task/Ludic-numbers/Ring/ludic-numbers.ring create mode 100644 Task/Luhn-test-of-credit-card-numbers/8th/luhn-test-of-credit-card-numbers.8th create mode 100644 Task/Luhn-test-of-credit-card-numbers/Befunge/luhn-test-of-credit-card-numbers.bf create mode 100644 Task/Luhn-test-of-credit-card-numbers/Julia/luhn-test-of-credit-card-numbers-1.julia create mode 100644 Task/Luhn-test-of-credit-card-numbers/Julia/luhn-test-of-credit-card-numbers-2.julia delete mode 100644 Task/Luhn-test-of-credit-card-numbers/Julia/luhn-test-of-credit-card-numbers.julia create mode 100644 Task/Luhn-test-of-credit-card-numbers/Perl-6/luhn-test-of-credit-card-numbers.pl6 create mode 100644 Task/Luhn-test-of-credit-card-numbers/VBA/luhn-test-of-credit-card-numbers.vba create mode 100644 Task/MD5-Implementation/Lingo/md5-implementation-1.lingo create mode 100644 Task/MD5-Implementation/Lingo/md5-implementation-2.lingo create mode 100644 Task/MD5-Implementation/Scala/md5-implementation.scala create mode 100644 Task/Mad-Libs/AppleScript/mad-libs.applescript create mode 100644 Task/Mad-Libs/Julia/mad-libs.julia create mode 100644 Task/Magic-squares-of-odd-order/BASIC/magic-squares-of-odd-order.basic create mode 100644 Task/Main-step-of-GOST-28147-89/Julia/main-step-of-gost-28147-89.julia create mode 100644 Task/Main-step-of-GOST-28147-89/Kotlin/main-step-of-gost-28147-89.kotlin create mode 100644 Task/Make-directory-path/Aime/make-directory-path.aime create mode 100644 Task/Make-directory-path/AppleScript/make-directory-path.applescript create mode 100644 Task/Make-directory-path/D/make-directory-path.d create mode 100644 Task/Make-directory-path/Julia/make-directory-path.julia create mode 100644 Task/Make-directory-path/Lua/make-directory-path.lua create mode 100644 Task/Make-directory-path/Objeck/make-directory-path.objeck create mode 100644 Task/Man-or-boy-test/Rust/man-or-boy-test.rust create mode 100644 Task/Man-or-boy-test/Swift/man-or-boy-test-3.swift create mode 100644 Task/Mandelbrot-set/BASIC/mandelbrot-set-10.basic create mode 100644 Task/Mandelbrot-set/BASIC/mandelbrot-set-11.basic create mode 100644 Task/Mandelbrot-set/C/mandelbrot-set-3.c create mode 100644 Task/Mandelbrot-set/Maple/mandelbrot-set.maple create mode 100644 Task/Mandelbrot-set/Metapost/mandelbrot-set-1.metapost create mode 100644 Task/Mandelbrot-set/Metapost/mandelbrot-set-2.metapost create mode 100644 Task/Mandelbrot-set/Processing/mandelbrot-set create mode 100644 Task/Mandelbrot-set/Rust/mandelbrot-set.rust create mode 100644 Task/Map-range/Maple/map-range.maple create mode 100644 Task/Map-range/Stata/map-range-1.stata create mode 100644 Task/Map-range/Stata/map-range-2.stata create mode 100644 Task/Matrix-arithmetic/Perl/matrix-arithmetic.pl create mode 100644 Task/Matrix-arithmetic/Sidef/matrix-arithmetic.sidef create mode 100644 Task/Matrix-arithmetic/Stata/matrix-arithmetic-1.stata create mode 100644 Task/Matrix-arithmetic/Stata/matrix-arithmetic-2.stata create mode 100644 Task/Matrix-exponentiation-operator/Sidef/matrix-exponentiation-operator.sidef create mode 100644 Task/Matrix-exponentiation-operator/Stata/matrix-exponentiation-operator-1.stata create mode 100644 Task/Matrix-exponentiation-operator/Stata/matrix-exponentiation-operator-2.stata create mode 100644 Task/Matrix-multiplication/Klong/matrix-multiplication.klong create mode 100644 Task/Matrix-multiplication/Stata/matrix-multiplication-1.stata create mode 100644 Task/Matrix-multiplication/Stata/matrix-multiplication-2.stata create mode 100644 Task/Matrix-transposition/REXX/matrix-transposition.rexx create mode 100644 Task/Matrix-transposition/Stata/matrix-transposition-1.stata create mode 100644 Task/Matrix-transposition/Stata/matrix-transposition-2.stata create mode 100644 Task/Maximum-triangle-path-sum/Elena/maximum-triangle-path-sum.elena create mode 100644 Task/Maximum-triangle-path-sum/Julia/maximum-triangle-path-sum.julia create mode 100644 Task/Maximum-triangle-path-sum/Perl-6/maximum-triangle-path-sum.pl6 create mode 100644 Task/Maximum-triangle-path-sum/Ring/maximum-triangle-path-sum.ring create mode 100644 Task/Maximum-triangle-path-sum/Stata/maximum-triangle-path-sum.stata create mode 100644 Task/Maze-generation/BASIC/maze-generation.basic create mode 100644 Task/Maze-generation/Batch-File/maze-generation.bat create mode 100644 Task/Maze-generation/Julia/maze-generation-1.julia create mode 100644 Task/Maze-generation/Julia/maze-generation-2.julia delete mode 100644 Task/Maze-generation/Julia/maze-generation.julia create mode 100644 Task/Maze-solving/Julia/maze-solving.julia create mode 100644 Task/Maze-solving/Kotlin/maze-solving.kotlin create mode 100644 Task/Median-filter/Julia/median-filter.julia create mode 100644 Task/Median-filter/Kotlin/median-filter.kotlin create mode 100644 Task/Memory-allocation/Julia/memory-allocation.julia create mode 100644 Task/Memory-layout-of-a-data-structure/Julia/memory-layout-of-a-data-structure.julia create mode 100644 Task/Memory-layout-of-a-data-structure/Scala/memory-layout-of-a-data-structure.scala create mode 100644 Task/Menu/Julia/menu.julia create mode 100644 Task/Menu/Rust/menu.rust create mode 100644 Task/Menu/Scala/menu.scala create mode 100644 Task/Metaprogramming/Scala/metaprogramming.scala create mode 100644 Task/Metered-concurrency/Kotlin/metered-concurrency.kotlin create mode 100644 Task/Metered-concurrency/Scala/metered-concurrency.scala create mode 100644 Task/Metronome/Julia/metronome.julia create mode 100644 Task/Metronome/Scala/metronome.scala create mode 100644 Task/Middle-three-digits/Elena/middle-three-digits.elena create mode 100644 Task/Middle-three-digits/Factor/middle-three-digits.factor create mode 100644 Task/Middle-three-digits/VBA/middle-three-digits.vba create mode 100644 Task/Minesweeper-game/Ceylon/minesweeper-game.ceylon create mode 100644 Task/Minesweeper-game/Rust/minesweeper-game.rust create mode 100644 Task/Minesweeper-game/VBA/minesweeper-game-1.vba create mode 100644 Task/Minesweeper-game/VBA/minesweeper-game-2.vba create mode 100644 Task/Modular-inverse/C-sharp/modular-inverse.cs create mode 100644 Task/Modular-inverse/Factor/modular-inverse.factor create mode 100644 Task/Modular-inverse/GW-BASIC/modular-inverse.gw-basic create mode 100644 Task/Modular-inverse/Modula-2/modular-inverse.mod2 create mode 100644 Task/Modular-inverse/PureBasic/modular-inverse.purebasic rename Task/Monte-Carlo-methods/Go/{monte-carlo-methods.go => monte-carlo-methods-1.go} (100%) create mode 100644 Task/Monte-Carlo-methods/Go/monte-carlo-methods-2.go create mode 100644 Task/Monte-Carlo-methods/Rust/monte-carlo-methods.rust create mode 100644 Task/Morse-code/ABAP/morse-code.abap create mode 100644 Task/Morse-code/Modula-2/morse-code.mod2 create mode 100644 Task/Morse-code/Red/morse-code-1.red create mode 100644 Task/Morse-code/Red/morse-code-2.red create mode 100644 Task/Morse-code/Ring/morse-code.ring create mode 100644 Task/Morse-code/VBA/morse-code.vba create mode 100644 Task/Move-to-front-algorithm/Aime/move-to-front-algorithm.aime create mode 100644 Task/Move-to-front-algorithm/Bracmat/move-to-front-algorithm.bracmat create mode 100644 Task/Move-to-front-algorithm/Julia/move-to-front-algorithm.julia create mode 100644 Task/Move-to-front-algorithm/Ring/move-to-front-algorithm.ring create mode 100644 Task/Multifactorial/Aime/multifactorial.aime create mode 100644 Task/Multifactorial/BBC-BASIC/multifactorial.bbc create mode 100644 Task/Multifactorial/Factor/multifactorial.factor create mode 100644 Task/Multifactorial/Maple/multifactorial.maple create mode 100644 Task/Multiple-distinct-objects/Julia/multiple-distinct-objects-1.julia create mode 100644 Task/Multiple-distinct-objects/Julia/multiple-distinct-objects-2.julia create mode 100644 Task/Multiple-regression/Kotlin/multiple-regression.kotlin create mode 100644 Task/Multiple-regression/Stata/multiple-regression-1.stata create mode 100644 Task/Multiple-regression/Stata/multiple-regression-2.stata create mode 100644 Task/Multiple-regression/Stata/multiple-regression-3.stata create mode 100644 Task/Multiple-regression/Stata/multiple-regression-4.stata create mode 100644 Task/Multiplication-tables/GW-BASIC/multiplication-tables.gw-basic create mode 100644 Task/Multiplication-tables/HolyC/multiplication-tables.holyc create mode 100644 Task/Multiplication-tables/JavaScript/multiplication-tables-4.js create mode 100644 Task/Multiplication-tables/Modula-2/multiplication-tables.mod2 create mode 100644 Task/Multiplication-tables/VBA/multiplication-tables.vba create mode 100644 Task/Multiplicative-order/Clojure/multiplicative-order.clj create mode 100644 Task/Multiplicative-order/Java/multiplicative-order.java create mode 100644 Task/Multiplicative-order/Kotlin/multiplicative-order.kotlin create mode 100644 Task/Multiplicative-order/Sidef/multiplicative-order.sidef rename Task/Multisplit/Haskell/{multisplit.hs => multisplit-1.hs} (100%) create mode 100644 Task/Multisplit/Haskell/multisplit-2.hs rename Task/Multisplit/JavaScript/{multisplit.js => multisplit-1.js} (100%) create mode 100644 Task/Multisplit/JavaScript/multisplit-2.js create mode 100644 Task/Multisplit/Ring/multisplit.ring create mode 100644 Task/Munching-squares/AWK/munching-squares.awk create mode 100644 Task/Munching-squares/Factor/munching-squares.factor create mode 100644 Task/Munching-squares/Kotlin/munching-squares.kotlin create mode 100644 Task/Munching-squares/REXX/munching-squares.rexx create mode 100644 Task/Munching-squares/Ring/munching-squares.ring create mode 100644 Task/Mutual-recursion/Elena/mutual-recursion.elena create mode 100644 Task/Mutual-recursion/Maple/mutual-recursion.maple rename Task/N-queens-problem/Clojure/{n-queens-problem.clj => n-queens-problem-1.clj} (100%) create mode 100644 Task/N-queens-problem/Clojure/n-queens-problem-2.clj create mode 100644 Task/N-queens-problem/Prolog/n-queens-problem-6.pro create mode 100644 Task/N-queens-problem/Sidef/n-queens-problem.sidef create mode 100644 Task/N-queens-problem/Stata/n-queens-problem-4.stata create mode 100644 Task/N-queens-problem/Wart/n-queens-problem.wart create mode 100644 Task/Named-parameters/Go/named-parameters.go create mode 100644 Task/Narcissist/D/narcissist.d create mode 100644 Task/Narcissist/Julia/narcissist.julia create mode 100644 Task/Narcissist/Scala/narcissist.scala create mode 100644 Task/Narcissistic-decimal-number/COBOL/narcissistic-decimal-number.cobol create mode 100644 Task/Narcissistic-decimal-number/Factor/narcissistic-decimal-number.factor create mode 100644 Task/Narcissistic-decimal-number/Maple/narcissistic-decimal-number.maple create mode 100644 Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-4.rexx create mode 100644 Task/Natural-sorting/Haskell/natural-sorting.hs create mode 100644 Task/Natural-sorting/PowerShell/natural-sorting.psh create mode 100644 Task/Nautical-bell/Mathematica/nautical-bell.math create mode 100644 Task/Nautical-bell/Ring/nautical-bell.ring create mode 100644 Task/Non-continuous-subsequences/Julia/non-continuous-subsequences.julia create mode 100644 Task/Non-continuous-subsequences/Ring/non-continuous-subsequences.ring create mode 100644 Task/Non-decimal-radices-Convert/Maple/non-decimal-radices-convert.maple create mode 100644 Task/Non-decimal-radices-Convert/R/non-decimal-radices-convert.r create mode 100644 Task/Non-decimal-radices-Convert/Ring/non-decimal-radices-convert.ring create mode 100644 Task/Non-decimal-radices-Convert/Scala/non-decimal-radices-convert.scala create mode 100644 Task/Non-decimal-radices-Input/Scala/non-decimal-radices-input.scala create mode 100644 Task/Non-decimal-radices-Output/Scala/non-decimal-radices-output.scala rename Task/Nth-root/Go/{nth-root.go => nth-root-1.go} (100%) create mode 100644 Task/Nth-root/Go/nth-root-2.go create mode 100644 Task/Nth/Elena/nth.elena create mode 100644 Task/Nth/GW-BASIC/nth.gw-basic create mode 100644 Task/Nth/Modula-2/nth.mod2 create mode 100644 Task/Nth/Stata/nth.stata create mode 100644 Task/Null-object/AutoIt/null-object.autoit create mode 100644 Task/Null-object/Haskell/null-object-4.hs create mode 100644 Task/Null-object/Haskell/null-object-5.hs create mode 100644 Task/Null-object/Visual-Basic/null-object-1.vb create mode 100644 Task/Null-object/Visual-Basic/null-object-2.vb create mode 100644 Task/Number-names/JavaScript/number-names.js create mode 100644 Task/Number-reversal-game/Ring/number-reversal-game.ring create mode 100644 Task/Numerical-integration-Gauss-Legendre-Quadrature/MATLAB/numerical-integration-gauss-legendre-quadrature.m create mode 100644 Task/Numerical-integration/Ring/numerical-integration.ring create mode 100644 Task/Numerical-integration/Stata/numerical-integration.stata create mode 100644 Task/Object-serialization/Haskell/object-serialization.hs create mode 100644 Task/Object-serialization/Julia/object-serialization.julia create mode 100644 Task/Object-serialization/Kotlin/object-serialization.kotlin create mode 100644 Task/Odd-word-problem/Ceylon/odd-word-problem.ceylon create mode 100644 Task/Odd-word-problem/Julia/odd-word-problem.julia create mode 100644 Task/Odd-word-problem/Ring/odd-word-problem.ring create mode 100644 Task/Odd-word-problem/VBA/odd-word-problem-1.vba create mode 100644 Task/Odd-word-problem/VBA/odd-word-problem-2.vba create mode 100644 Task/Odd-word-problem/VBA/odd-word-problem-3.vba create mode 100644 Task/Old-lady-swallowed-a-fly/Fortran/old-lady-swallowed-a-fly.f create mode 100644 Task/Old-lady-swallowed-a-fly/Julia/old-lady-swallowed-a-fly-1.julia create mode 100644 Task/Old-lady-swallowed-a-fly/Julia/old-lady-swallowed-a-fly-2.julia create mode 100644 Task/Old-lady-swallowed-a-fly/Modula-2/old-lady-swallowed-a-fly.mod2 rename Task/One-dimensional-cellular-automata/Forth/{one-dimensional-cellular-automata.fth => one-dimensional-cellular-automata-1.fth} (100%) create mode 100644 Task/One-dimensional-cellular-automata/Forth/one-dimensional-cellular-automata-2.fth create mode 100644 Task/One-dimensional-cellular-automata/Kotlin/one-dimensional-cellular-automata.kotlin rename Task/One-dimensional-cellular-automata/PARI-GP/{one-dimensional-cellular-automata.pari => one-dimensional-cellular-automata-1.pari} (100%) create mode 100644 Task/One-dimensional-cellular-automata/PARI-GP/one-dimensional-cellular-automata-2.pari create mode 100644 Task/One-dimensional-cellular-automata/PARI-GP/one-dimensional-cellular-automata-3.pari create mode 100644 Task/One-dimensional-cellular-automata/Perl-6/one-dimensional-cellular-automata.pl6 create mode 100644 Task/One-dimensional-cellular-automata/Ring/one-dimensional-cellular-automata.ring create mode 100644 Task/One-of-n-lines-in-a-file/Kotlin/one-of-n-lines-in-a-file.kotlin create mode 100644 Task/OpenGL/BaCon/opengl.bacon create mode 100644 Task/OpenGL/Lingo/opengl.lingo create mode 100644 Task/OpenGL/Ring/opengl.ring create mode 100644 Task/Optional-parameters/Kotlin/optional-parameters.kotlin create mode 100644 Task/Order-disjoint-list-items/C++/order-disjoint-list-items.cpp create mode 100644 Task/Order-disjoint-list-items/Perl-6/order-disjoint-list-items.pl6 create mode 100644 Task/Order-two-numerical-lists/Aime/order-two-numerical-lists.aime create mode 100644 Task/Order-two-numerical-lists/J/order-two-numerical-lists-3.j create mode 100644 Task/Order-two-numerical-lists/Julia/order-two-numerical-lists.julia create mode 100644 Task/Ordered-Partitions/C++/ordered-partitions.cpp create mode 100644 Task/Ordered-Partitions/Julia/ordered-partitions.julia create mode 100644 Task/Ordered-words/Maple/ordered-words.maple create mode 100644 Task/Ordered-words/Red/ordered-words.red rename Task/Palindrome-detection/Common-Lisp/{palindrome-detection.lisp => palindrome-detection-1.lisp} (100%) create mode 100644 Task/Palindrome-detection/Common-Lisp/palindrome-detection-2.lisp create mode 100644 Task/Palindrome-detection/Falcon/palindrome-detection-1.falcon create mode 100644 Task/Palindrome-detection/Falcon/palindrome-detection-2.falcon create mode 100644 Task/Palindrome-detection/Modula-2/palindrome-detection.mod2 create mode 100644 Task/Palindrome-detection/Processing/palindrome-detection create mode 100644 Task/Palindrome-detection/UNIX-Shell/palindrome-detection.sh rename Task/Pangram-checker/ATS/{pangram-checker.ats => pangram-checker-1.ats} (100%) create mode 100644 Task/Pangram-checker/ATS/pangram-checker-2.ats create mode 100644 Task/Pangram-checker/Maple/pangram-checker-1.maple create mode 100644 Task/Pangram-checker/Maple/pangram-checker-2.maple create mode 100644 Task/Paraffins/Scala/paraffins.scala create mode 100644 Task/Parallel-calculations/Julia/parallel-calculations.julia create mode 100644 Task/Parallel-calculations/Kotlin/parallel-calculations.kotlin create mode 100644 Task/Parallel-calculations/Perl/parallel-calculations.pl create mode 100644 Task/Parametric-polymorphism/Julia/parametric-polymorphism.julia create mode 100644 Task/Parametrized-SQL-statement/Haskell/parametrized-sql-statement.hs create mode 100644 Task/Parametrized-SQL-statement/Julia/parametrized-sql-statement.julia create mode 100644 Task/Parametrized-SQL-statement/Kotlin/parametrized-sql-statement.kotlin create mode 100644 Task/Parse-an-IP-Address/Julia/parse-an-ip-address.julia create mode 100644 Task/Parse-an-IP-Address/Scala/parse-an-ip-address.scala create mode 100644 Task/Parsing-RPN-calculator-algorithm/Factor/parsing-rpn-calculator-algorithm-1.factor create mode 100644 Task/Parsing-RPN-calculator-algorithm/Factor/parsing-rpn-calculator-algorithm-2.factor create mode 100644 Task/Parsing-RPN-calculator-algorithm/Maxima/parsing-rpn-calculator-algorithm-1.maxima create mode 100644 Task/Parsing-RPN-calculator-algorithm/Maxima/parsing-rpn-calculator-algorithm-2.maxima create mode 100644 Task/Parsing-RPN-calculator-algorithm/N-t-roff/parsing-rpn-calculator-algorithm-1.n create mode 100644 Task/Parsing-RPN-calculator-algorithm/N-t-roff/parsing-rpn-calculator-algorithm-2.n create mode 100644 Task/Parsing-RPN-calculator-algorithm/N-t-roff/parsing-rpn-calculator-algorithm-3.n create mode 100644 Task/Parsing-RPN-calculator-algorithm/N-t-roff/parsing-rpn-calculator-algorithm-4.n create mode 100644 Task/Parsing-RPN-calculator-algorithm/PARI-GP/parsing-rpn-calculator-algorithm-1.pari create mode 100644 Task/Parsing-RPN-calculator-algorithm/PARI-GP/parsing-rpn-calculator-algorithm-2.pari create mode 100644 Task/Parsing-RPN-calculator-algorithm/UNIX-Shell/parsing-rpn-calculator-algorithm-1.sh create mode 100644 Task/Parsing-RPN-calculator-algorithm/UNIX-Shell/parsing-rpn-calculator-algorithm-2.sh create mode 100644 Task/Parsing-RPN-to-infix-conversion/C/parsing-rpn-to-infix-conversion.c create mode 100644 Task/Parsing-RPN-to-infix-conversion/Julia/parsing-rpn-to-infix-conversion.julia create mode 100644 Task/Parsing-RPN-to-infix-conversion/Kotlin/parsing-rpn-to-infix-conversion.kotlin create mode 100644 Task/Parsing-Shunting-yard-algorithm/8th/parsing-shunting-yard-algorithm.8th create mode 100644 Task/Parsing-Shunting-yard-algorithm/D/parsing-shunting-yard-algorithm.d create mode 100644 Task/Parsing-Shunting-yard-algorithm/Julia/parsing-shunting-yard-algorithm.julia create mode 100644 Task/Parsing-Shunting-yard-algorithm/Kotlin/parsing-shunting-yard-algorithm.kotlin create mode 100644 Task/Parsing-Shunting-yard-algorithm/Rust/parsing-shunting-yard-algorithm.rust create mode 100644 Task/Parsing-Shunting-yard-algorithm/UNIX-Shell/parsing-shunting-yard-algorithm-1.sh create mode 100644 Task/Parsing-Shunting-yard-algorithm/UNIX-Shell/parsing-shunting-yard-algorithm-2.sh create mode 100644 Task/Partial-function-application/Factor/partial-function-application.factor create mode 100644 Task/Partial-function-application/Julia/partial-function-application.julia create mode 100644 Task/Pascals-triangle-Puzzle/Julia/pascals-triangle-puzzle.julia create mode 100644 Task/Pascals-triangle-Puzzle/Scala/pascals-triangle-puzzle.scala create mode 100644 Task/Pascals-triangle/Commodore-BASIC/pascals-triangle-1.commodore create mode 100644 Task/Pascals-triangle/Commodore-BASIC/pascals-triangle-2.commodore create mode 100644 Task/Pascals-triangle/Modula-2/pascals-triangle.mod2 create mode 100644 Task/Pascals-triangle/Perl/pascals-triangle-4.pl create mode 100644 Task/Pascals-triangle/Rust/pascals-triangle.rust create mode 100644 Task/Pascals-triangle/Scala/pascals-triangle-3.scala create mode 100644 Task/Pascals-triangle/Stata/pascals-triangle-1.stata create mode 100644 Task/Pascals-triangle/Stata/pascals-triangle-2.stata create mode 100644 Task/Pascals-triangle/ZX-Spectrum-Basic/pascals-triangle-1.zx create mode 100644 Task/Pascals-triangle/ZX-Spectrum-Basic/pascals-triangle-2.zx create mode 100644 Task/Pattern-matching/C++/pattern-matching-1.cpp create mode 100644 Task/Pattern-matching/C++/pattern-matching-2.cpp create mode 100644 Task/Pattern-matching/Kotlin/pattern-matching.kotlin create mode 100644 Task/Pattern-matching/REXX/pattern-matching.rexx create mode 100644 Task/Penneys-game/Factor/penneys-game.factor create mode 100644 Task/Penneys-game/Kotlin/penneys-game.kotlin create mode 100644 Task/Penneys-game/PicoLisp/penneys-game.l create mode 100644 Task/Penneys-game/VBA/penneys-game.vba create mode 100644 Task/Percentage-difference-between-images/Julia/percentage-difference-between-images.julia create mode 100644 Task/Percentage-difference-between-images/Kotlin/percentage-difference-between-images.kotlin create mode 100644 Task/Percentage-difference-between-images/Python/percentage-difference-between-images-1.py rename Task/Percentage-difference-between-images/Python/{percentage-difference-between-images.py => percentage-difference-between-images-2.py} (100%) create mode 100644 Task/Percolation-Bond-percolation/Julia/percolation-bond-percolation.julia create mode 100644 Task/Percolation-Bond-percolation/Kotlin/percolation-bond-percolation.kotlin create mode 100644 Task/Percolation-Mean-cluster-density/Julia/percolation-mean-cluster-density.julia create mode 100644 Task/Percolation-Mean-cluster-density/Kotlin/percolation-mean-cluster-density.kotlin create mode 100644 Task/Percolation-Mean-run-density/Julia/percolation-mean-run-density.julia create mode 100644 Task/Percolation-Mean-run-density/Kotlin/percolation-mean-run-density.kotlin create mode 100644 Task/Percolation-Site-percolation/Julia/percolation-site-percolation.julia create mode 100644 Task/Percolation-Site-percolation/Kotlin/percolation-site-percolation.kotlin create mode 100644 Task/Perfect-numbers/Modula-2/perfect-numbers.mod2 create mode 100644 Task/Permutation-test/Java/permutation-test.java rename Task/Permutations-Derangements/Perl/{permutations-derangements.pl => permutations-derangements-1.pl} (100%) create mode 100644 Task/Permutations-Derangements/Perl/permutations-derangements-2.pl create mode 100644 Task/Permutations-Rank-of-a-permutation/Perl/permutations-rank-of-a-permutation.pl create mode 100644 Task/Permutations-Rank-of-a-permutation/Ring/permutations-rank-of-a-permutation.ring create mode 100644 Task/Permutations-by-swapping/C/permutations-by-swapping.c create mode 100644 Task/Permutations-by-swapping/Julia/permutations-by-swapping-1.julia create mode 100644 Task/Permutations-by-swapping/Julia/permutations-by-swapping-2.julia rename Task/Permutations-by-swapping/Lua/{permutations-by-swapping.lua => permutations-by-swapping-1.lua} (100%) create mode 100644 Task/Permutations-by-swapping/Lua/permutations-by-swapping-2.lua create mode 100644 Task/Permutations-by-swapping/Scala/permutations-by-swapping.scala create mode 100644 Task/Permutations/Fortran/permutations-4.f rename Task/Permutations/Smalltalk/{permutations.st => permutations-1.st} (100%) create mode 100644 Task/Permutations/Smalltalk/permutations-2.st create mode 100644 Task/Permutations/Smalltalk/permutations-3.st create mode 100644 Task/Pernicious-numbers/AWK/pernicious-numbers.awk create mode 100644 Task/Pernicious-numbers/Factor/pernicious-numbers.factor rename Task/Pernicious-numbers/Haskell/{pernicious-numbers.hs => pernicious-numbers-1.hs} (100%) create mode 100644 Task/Pernicious-numbers/Haskell/pernicious-numbers-2.hs create mode 100644 Task/Pernicious-numbers/Modula-2/pernicious-numbers.mod2 create mode 100644 Task/Pernicious-numbers/Ring/pernicious-numbers.ring create mode 100644 Task/Phrase-reversals/Elena/phrase-reversals.elena create mode 100644 Task/Phrase-reversals/Factor/phrase-reversals.factor create mode 100644 Task/Phrase-reversals/VBA/phrase-reversals.vba create mode 100644 Task/Pi/JavaScript/pi-1.js create mode 100644 Task/Pi/JavaScript/pi-2.js rename Task/Pi/JavaScript/{pi.js => pi-3.js} (100%) rename Task/Pick-random-element/BASIC/{pick-random-element.basic => pick-random-element-1.basic} (100%) create mode 100644 Task/Pick-random-element/BASIC/pick-random-element-2.basic create mode 100644 Task/Pick-random-element/Red/pick-random-element.red create mode 100644 Task/Pick-random-element/VBA/pick-random-element.vba create mode 100644 Task/Pig-the-dice-game/Ring/pig-the-dice-game.ring create mode 100644 Task/Pig-the-dice-game/VBA/pig-the-dice-game.vba create mode 100644 Task/Pinstripe-Display/Julia/pinstripe-display.julia create mode 100644 Task/Pinstripe-Display/Ring/pinstripe-display.ring create mode 100644 Task/Pinstripe-Display/Sinclair-ZX81-BASIC/pinstripe-display.sinclair create mode 100644 Task/Playing-cards/Factor/playing-cards.factor rename Task/Playing-cards/Smalltalk/{playing-cards.st => playing-cards-1.st} (100%) create mode 100644 Task/Playing-cards/Smalltalk/playing-cards-2.st create mode 100644 Task/Playing-cards/Smalltalk/playing-cards-3.st create mode 100644 Task/Plot-coordinate-pairs/Kotlin/plot-coordinate-pairs.kotlin create mode 100644 Task/Plot-coordinate-pairs/Ring/plot-coordinate-pairs.ring create mode 100644 Task/Polymorphic-copy/Elena/polymorphic-copy.elena create mode 100644 Task/Polymorphic-copy/Scala/polymorphic-copy.scala create mode 100644 Task/Polymorphism/Elena/polymorphism.elena create mode 100644 Task/Polynomial-long-division/APL/polynomial-long-division.apl create mode 100644 Task/Polynomial-long-division/Clojure/polynomial-long-division.clj create mode 100644 Task/Polynomial-long-division/Java/polynomial-long-division.java create mode 100644 Task/Polynomial-long-division/Kotlin/polynomial-long-division.kotlin create mode 100644 Task/Polynomial-long-division/REXX/polynomial-long-division.rexx create mode 100644 Task/Polynomial-regression/D/polynomial-regression.d create mode 100644 Task/Polynomial-regression/Java/polynomial-regression.java create mode 100644 Task/Polynomial-regression/Kotlin/polynomial-regression.kotlin create mode 100644 Task/Polynomial-regression/Modula-2/polynomial-regression.mod2 rename Task/Power-set/PARI-GP/{power-set.pari => power-set-1.pari} (100%) create mode 100644 Task/Power-set/PARI-GP/power-set-2.pari create mode 100644 Task/Power-set/Perl/power-set-11.pl create mode 100644 Task/Power-set/Ring/power-set.ring create mode 100644 Task/Power-set/Swift/power-set-1.swift create mode 100644 Task/Power-set/Swift/power-set-2.swift create mode 100644 Task/Pragmatic-directives/C/pragmatic-directives.c create mode 100644 Task/Pragmatic-directives/Scala/pragmatic-directives.scala create mode 100644 Task/Price-fraction/Gambas/price-fraction.gambas create mode 100644 Task/Price-fraction/VBA/price-fraction.vba rename Task/Primality-by-trial-division/Common-Lisp/{primality-by-trial-division.lisp => primality-by-trial-division-1.lisp} (100%) create mode 100644 Task/Primality-by-trial-division/Common-Lisp/primality-by-trial-division-2.lisp create mode 100644 Task/Primality-by-trial-division/Lingo/primality-by-trial-division-1.lingo create mode 100644 Task/Primality-by-trial-division/Lingo/primality-by-trial-division-2.lingo rename Task/Primality-by-trial-division/Sidef/{primality-by-trial-division.sidef => primality-by-trial-division-1.sidef} (100%) create mode 100644 Task/Primality-by-trial-division/Sidef/primality-by-trial-division-2.sidef create mode 100644 Task/Primality-by-trial-division/VBA/primality-by-trial-division.vba create mode 100644 Task/Prime-decomposition/Stata/prime-decomposition.stata create mode 100644 Task/Priority-queue/Nim/priority-queue-3.nim create mode 100644 Task/Priority-queue/XLISP/priority-queue-1.xlisp create mode 100644 Task/Priority-queue/XLISP/priority-queue-10.xlisp create mode 100644 Task/Priority-queue/XLISP/priority-queue-2.xlisp create mode 100644 Task/Priority-queue/XLISP/priority-queue-3.xlisp create mode 100644 Task/Priority-queue/XLISP/priority-queue-4.xlisp create mode 100644 Task/Priority-queue/XLISP/priority-queue-5.xlisp create mode 100644 Task/Priority-queue/XLISP/priority-queue-6.xlisp create mode 100644 Task/Priority-queue/XLISP/priority-queue-7.xlisp create mode 100644 Task/Priority-queue/XLISP/priority-queue-8.xlisp create mode 100644 Task/Priority-queue/XLISP/priority-queue-9.xlisp create mode 100644 Task/Probabilistic-choice/Ring/probabilistic-choice.ring create mode 100644 Task/Probabilistic-choice/Rust/probabilistic-choice.rust create mode 100644 Task/Probabilistic-choice/Stata/probabilistic-choice.stata create mode 100644 Task/Problem-of-Apollonius/Julia/problem-of-apollonius-1.julia create mode 100644 Task/Problem-of-Apollonius/Julia/problem-of-apollonius-2.julia delete mode 100644 Task/Problem-of-Apollonius/Julia/problem-of-apollonius.julia create mode 100644 Task/Program-name/ARM-Assembly/program-name.arm create mode 100644 Task/Program-termination/Julia/program-termination.julia create mode 100644 Task/Program-termination/Simula/program-termination.simula create mode 100644 Task/Pythagorean-triples/360-Assembly/pythagorean-triples.360 create mode 100644 Task/Pythagorean-triples/Rust/pythagorean-triples.rust create mode 100644 Task/Quaternion-type/Elena/quaternion-type.elena create mode 100644 Task/Quaternion-type/Rust/quaternion-type.rust create mode 100644 Task/Queue-Definition/Elena/queue-definition.elena create mode 100644 Task/Queue-Definition/Perl-6/queue-definition.pl6 create mode 100644 Task/Queue-Usage/Julia/queue-usage.julia create mode 100644 Task/Quickselect-algorithm/Julia/quickselect-algorithm.julia create mode 100644 Task/Quickselect-algorithm/Maple/quickselect-algorithm.maple create mode 100644 Task/Quine/JavaScript/quine-8.js create mode 100644 Task/Quine/MATLAB/quine-4.m create mode 100644 Task/Quine/Python/quine-13.py create mode 100644 Task/Quine/Rust/quine-3.rust create mode 100644 Task/RSA-code/Java/rsa-code.java create mode 100644 Task/RSA-code/Julia/rsa-code.julia create mode 100644 Task/Random-number-generator--device-/D/random-number-generator--device-.d create mode 100644 Task/Random-number-generator--device-/Scala/random-number-generator--device-.scala create mode 100644 Task/Random-number-generator--included-/Elena/random-number-generator--included-.elena create mode 100644 Task/Random-numbers/Elena/random-numbers.elena rename Task/Random-numbers/Haskell/{random-numbers.hs => random-numbers-1.hs} (100%) create mode 100644 Task/Random-numbers/Haskell/random-numbers-2.hs create mode 100644 Task/Random-numbers/Haskell/random-numbers-3.hs create mode 100644 Task/Random-numbers/Lingo/random-numbers-1.lingo create mode 100644 Task/Random-numbers/Lingo/random-numbers-2.lingo rename Task/Random-numbers/Scala/{random-numbers.scala => random-numbers-1.scala} (100%) create mode 100644 Task/Random-numbers/Scala/random-numbers-2.scala create mode 100644 Task/Random-numbers/Standard-ML/random-numbers-3.ml rename Task/Random-numbers/Stata/{random-numbers.stata => random-numbers-1.stata} (100%) create mode 100644 Task/Random-numbers/Stata/random-numbers-2.stata create mode 100644 Task/Range-expansion/Ring/range-expansion.ring create mode 100644 Task/Range-extraction/Clojure/range-extraction.clj create mode 100644 Task/Range-extraction/Factor/range-extraction.factor create mode 100644 Task/Range-extraction/Ring/range-extraction.ring create mode 100644 Task/Ranking-methods/C/ranking-methods.c create mode 100644 Task/Ranking-methods/D/ranking-methods.d create mode 100644 Task/Rate-counter/D/rate-counter.d create mode 100644 Task/Ray-casting-algorithm/Julia/ray-casting-algorithm-1.julia create mode 100644 Task/Ray-casting-algorithm/Julia/ray-casting-algorithm-2.julia create mode 100644 Task/Ray-casting-algorithm/Visual-Basic-.NET/ray-casting-algorithm.visual create mode 100644 Task/Read-a-configuration-file/C/read-a-configuration-file.c create mode 100644 Task/Read-a-configuration-file/Julia/read-a-configuration-file.julia create mode 100644 Task/Read-a-configuration-file/PowerShell/read-a-configuration-file-4.psh create mode 100644 Task/Read-a-configuration-file/PowerShell/read-a-configuration-file-5.psh create mode 100644 Task/Read-a-configuration-file/PowerShell/read-a-configuration-file-6.psh create mode 100644 Task/Read-a-configuration-file/PowerShell/read-a-configuration-file-7.psh create mode 100644 Task/Read-a-configuration-file/PowerShell/read-a-configuration-file-8.psh create mode 100644 Task/Read-a-configuration-file/Rust/read-a-configuration-file.rust create mode 100644 Task/Read-a-file-line-by-line/Maple/read-a-file-line-by-line.maple create mode 100644 Task/Read-a-specific-line-from-a-file/Red/read-a-specific-line-from-a-file.red create mode 100644 Task/Read-a-specific-line-from-a-file/Rust/read-a-specific-line-from-a-file-1.rust create mode 100644 Task/Read-a-specific-line-from-a-file/Rust/read-a-specific-line-from-a-file-2.rust create mode 100644 Task/Real-constants-and-functions/Scala/real-constants-and-functions.scala create mode 100644 Task/Record-sound/Julia/record-sound.julia create mode 100644 Task/Reduced-row-echelon-form/J/reduced-row-echelon-form-4.j create mode 100644 Task/Reduced-row-echelon-form/Kotlin/reduced-row-echelon-form.kotlin create mode 100644 Task/Reduced-row-echelon-form/Ring/reduced-row-echelon-form.ring create mode 100644 Task/Regular-expressions/Factor/regular-expressions.factor create mode 100644 Task/Regular-expressions/Maple/regular-expressions.maple create mode 100644 Task/Regular-expressions/Ring/regular-expressions.ring create mode 100644 Task/Remove-duplicate-elements/Aime/remove-duplicate-elements-1.aime create mode 100644 Task/Remove-duplicate-elements/Aime/remove-duplicate-elements-2.aime create mode 100644 Task/Remove-duplicate-elements/Elena/remove-duplicate-elements.elena rename Task/Remove-duplicate-elements/Fortran/{remove-duplicate-elements.f => remove-duplicate-elements-1.f} (100%) create mode 100644 Task/Remove-duplicate-elements/Fortran/remove-duplicate-elements-2.f create mode 100644 Task/Remove-duplicate-elements/GW-BASIC/remove-duplicate-elements.gw-basic create mode 100644 Task/Remove-duplicate-elements/Gambas/remove-duplicate-elements.gambas create mode 100644 Task/Remove-duplicate-elements/Modula-2/remove-duplicate-elements.mod2 create mode 100644 Task/Remove-duplicate-elements/Red/remove-duplicate-elements.red create mode 100644 Task/Remove-duplicate-elements/VBA/remove-duplicate-elements.vba create mode 100644 Task/Remove-lines-from-a-file/VBA/remove-lines-from-a-file-1.vba create mode 100644 Task/Remove-lines-from-a-file/VBA/remove-lines-from-a-file-2.vba create mode 100644 Task/Rename-a-file/BaCon/rename-a-file.bacon create mode 100644 Task/Rep-string/BaCon/rep-string.bacon create mode 100644 Task/Rep-string/Ring/rep-string.ring create mode 100644 Task/Repeat-a-string/BaCon/repeat-a-string-1.bacon create mode 100644 Task/Repeat-a-string/BaCon/repeat-a-string-2.bacon create mode 100644 Task/Repeat-a-string/Red/repeat-a-string.red create mode 100644 Task/Resistor-mesh/Java/resistor-mesh.java create mode 100644 Task/Resistor-mesh/Modula-2/resistor-mesh.mod2 create mode 100644 Task/Respond-to-an-unknown-method-call/Julia/respond-to-an-unknown-method-call.julia create mode 100644 Task/Return-multiple-values/Objeck/return-multiple-values.objeck create mode 100644 Task/Return-multiple-values/VBA/return-multiple-values-1.vba create mode 100644 Task/Return-multiple-values/VBA/return-multiple-values-2.vba create mode 100644 Task/Return-multiple-values/VBA/return-multiple-values-3.vba create mode 100644 Task/Return-multiple-values/VBA/return-multiple-values-4.vba create mode 100644 Task/Reverse-a-string/Fortran/reverse-a-string-3.f create mode 100644 Task/Reverse-a-string/Modula-2/reverse-a-string.mod2 rename Task/Reverse-a-string/Nim/{reverse-a-string.nim => reverse-a-string-1.nim} (100%) create mode 100644 Task/Reverse-a-string/Nim/reverse-a-string-2.nim create mode 100644 Task/Reverse-a-string/Red/reverse-a-string.red create mode 100644 Task/Reverse-words-in-a-string/Factor/reverse-words-in-a-string.factor create mode 100644 Task/Reverse-words-in-a-string/Lua/reverse-words-in-a-string-1.lua rename Task/Reverse-words-in-a-string/Lua/{reverse-words-in-a-string.lua => reverse-words-in-a-string-2.lua} (100%) create mode 100644 Task/Reverse-words-in-a-string/Modula-2/reverse-words-in-a-string.mod2 create mode 100644 Task/Reverse-words-in-a-string/Nial/reverse-words-in-a-string.nial create mode 100644 Task/Reverse-words-in-a-string/R/reverse-words-in-a-string-1.r create mode 100644 Task/Reverse-words-in-a-string/R/reverse-words-in-a-string-2.r create mode 100644 Task/Reverse-words-in-a-string/Red/reverse-words-in-a-string.red create mode 100644 Task/Reverse-words-in-a-string/VBA/reverse-words-in-a-string.vba create mode 100644 Task/Rock-paper-scissors/Kotlin/rock-paper-scissors.kotlin create mode 100644 Task/Rock-paper-scissors/PHP/rock-paper-scissors.php create mode 100644 Task/Rock-paper-scissors/Ring/rock-paper-scissors.ring create mode 100644 Task/Rock-paper-scissors/Rust/rock-paper-scissors.rust create mode 100644 Task/Roman-numerals-Decode/Elena/roman-numerals-decode.elena create mode 100644 Task/Roman-numerals-Decode/UNIX-Shell/roman-numerals-decode.sh create mode 100644 Task/Roman-numerals-Decode/VBA/roman-numerals-decode.vba create mode 100644 Task/Roman-numerals-Encode/Clojure/roman-numerals-encode-5.clj create mode 100644 Task/Roman-numerals-Encode/Clojure/roman-numerals-encode-6.clj create mode 100644 Task/Roman-numerals-Encode/Elena/roman-numerals-encode.elena rename Task/Roman-numerals-Encode/Kotlin/{roman-numerals-encode.kotlin => roman-numerals-encode-1.kotlin} (100%) create mode 100644 Task/Roman-numerals-Encode/Kotlin/roman-numerals-encode-2.kotlin create mode 100644 Task/Roman-numerals-Encode/Modula-2/roman-numerals-encode.mod2 create mode 100644 Task/Roman-numerals-Encode/Perl-6/roman-numerals-encode.pl6 create mode 100644 Task/Roman-numerals-Encode/Python/roman-numerals-encode-5.py create mode 100644 Task/Roman-numerals-Encode/SETL/roman-numerals-encode.setl create mode 100644 Task/Roots-of-unity/Stata/roots-of-unity.stata create mode 100644 Task/Rot-13/Applesoft-BASIC/rot-13.applesoft create mode 100644 Task/Rot-13/Elena/rot-13.elena create mode 100644 Task/Rot-13/PowerBASIC/rot-13.powerbasic create mode 100644 Task/Rot-13/Stata/rot-13.stata create mode 100644 Task/Rot-13/Visual-Basic/rot-13-1.vb create mode 100644 Task/Rot-13/Visual-Basic/rot-13-2.vb create mode 100644 Task/Run-length-encoding/BaCon/run-length-encoding.bacon create mode 100644 Task/Run-length-encoding/Ceylon/run-length-encoding.ceylon create mode 100644 Task/Run-length-encoding/Elena/run-length-encoding.elena create mode 100644 Task/Run-length-encoding/Factor/run-length-encoding.factor create mode 100644 Task/Run-length-encoding/Julia/run-length-encoding.julia create mode 100644 Task/Run-length-encoding/Ring/run-length-encoding.ring create mode 100644 Task/Run-length-encoding/VBA/run-length-encoding.vba create mode 100644 Task/Runge-Kutta-method/Julia/runge-kutta-method-1.julia create mode 100644 Task/Runge-Kutta-method/Julia/runge-kutta-method-2.julia delete mode 100644 Task/Runge-Kutta-method/Julia/runge-kutta-method.julia create mode 100644 Task/Runge-Kutta-method/Nim/runge-kutta-method.nim create mode 100644 Task/Runge-Kutta-method/Stata/runge-kutta-method.stata create mode 100644 Task/Runtime-evaluation-In-an-environment/Elena/runtime-evaluation-in-an-environment.elena create mode 100644 Task/Runtime-evaluation-In-an-environment/Julia/runtime-evaluation-in-an-environment-1.julia create mode 100644 Task/Runtime-evaluation-In-an-environment/Julia/runtime-evaluation-in-an-environment-2.julia create mode 100644 Task/Runtime-evaluation-In-an-environment/Scala/runtime-evaluation-in-an-environment.scala create mode 100644 Task/Runtime-evaluation/Elena/runtime-evaluation.elena create mode 100644 Task/Runtime-evaluation/Java/runtime-evaluation.java create mode 100644 Task/Runtime-evaluation/Julia/runtime-evaluation-1.julia create mode 100644 Task/Runtime-evaluation/Julia/runtime-evaluation-2.julia create mode 100644 Task/S-Expressions/Julia/s-expressions.julia create mode 100644 Task/S-Expressions/Kotlin/s-expressions.kotlin create mode 100644 Task/SEDOLs/Gambas/sedols.gambas create mode 100644 Task/SEDOLs/Julia/sedols.julia create mode 100644 Task/SHA-1/J/sha-1-4.j create mode 100644 Task/SHA-1/Lingo/sha-1.lingo create mode 100644 Task/SHA-1/Ring/sha-1.ring create mode 100644 Task/SHA-256/J/sha-256-3.j create mode 100644 Task/SHA-256/J/sha-256-4.j create mode 100644 Task/SHA-256/Ring/sha-256.ring create mode 100644 Task/SOAP/C/soap-1.c create mode 100644 Task/SOAP/C/soap-2.c create mode 100644 Task/SOAP/C/soap-3.c create mode 100644 Task/SOAP/Clojure/soap.clj create mode 100644 Task/SOAP/Kotlin/soap.kotlin create mode 100644 Task/SQL-based-authentication/Julia/sql-based-authentication.julia create mode 100644 Task/SQL-based-authentication/Kotlin/sql-based-authentication.kotlin create mode 100644 Task/Safe-addition/D/safe-addition.d create mode 100644 Task/Safe-addition/Java/safe-addition.java create mode 100644 Task/Safe-addition/Julia/safe-addition.julia create mode 100644 Task/Safe-addition/Scala/safe-addition.scala create mode 100644 Task/Same-Fringe/Julia/same-fringe.julia create mode 100644 Task/Same-Fringe/Perl-6/same-fringe.pl6 create mode 100644 Task/Scope-Function-names-and-labels/Ring/scope-function-names-and-labels.ring create mode 100644 Task/Scope-Function-names-and-labels/Scala/scope-function-names-and-labels.scala create mode 100644 Task/Search-a-list/Maple/search-a-list.maple create mode 100644 Task/Secure-temporary-file/Perl-6/secure-temporary-file.pl6 create mode 100644 Task/Self-describing-numbers/Factor/self-describing-numbers.factor create mode 100644 Task/Self-describing-numbers/Modula-2/self-describing-numbers.mod2 create mode 100644 Task/Self-describing-numbers/Red/self-describing-numbers.red create mode 100644 Task/Self-describing-numbers/Ring/self-describing-numbers.ring create mode 100644 Task/Self-describing-numbers/Rust/self-describing-numbers.rust create mode 100644 Task/Self-describing-numbers/Scala/self-describing-numbers.scala create mode 100644 Task/Semiprime/Factor/semiprime-1.factor create mode 100644 Task/Semiprime/Factor/semiprime-2.factor create mode 100644 Task/Semiprime/Lingo/semiprime-1.lingo create mode 100644 Task/Semiprime/Lingo/semiprime-2.lingo create mode 100644 Task/Semiprime/Rust/semiprime.rust create mode 100644 Task/Semordnilap/Octave/semordnilap.octave create mode 100644 Task/Semordnilap/Stata/semordnilap.stata create mode 100644 Task/Send-an-unknown-method-call/Julia/send-an-unknown-method-call.julia create mode 100644 Task/Send-email/C/send-email.c create mode 100644 Task/Send-email/Groovy/send-email.groovy create mode 100644 Task/Send-email/Haskell/send-email-1.hs create mode 100644 Task/Send-email/Haskell/send-email-2.hs create mode 100644 Task/Send-email/Julia/send-email.julia create mode 100644 Task/Sequence-of-non-squares/Factor/sequence-of-non-squares.factor create mode 100644 Task/Sequence-of-non-squares/VBA/sequence-of-non-squares.vba create mode 100644 Task/Set-consolidation/Ring/set-consolidation.ring create mode 100644 Task/Set-of-real-numbers/Julia/set-of-real-numbers.julia rename Task/Set/Lua/{set.lua => set-1.lua} (100%) create mode 100644 Task/Set/Lua/set-2.lua create mode 100644 Task/Set/Ring/set.ring create mode 100644 Task/Seven-sided-dice-from-five-sided-dice/Perl-6/seven-sided-dice-from-five-sided-dice.pl6 create mode 100644 Task/Seven-sided-dice-from-five-sided-dice/Ring/seven-sided-dice-from-five-sided-dice.ring create mode 100644 Task/Shell-one-liner/Go/shell-one-liner.go create mode 100644 Task/Short-circuit-evaluation/Factor/short-circuit-evaluation.factor create mode 100644 Task/Short-circuit-evaluation/Modula-2/short-circuit-evaluation.mod2 create mode 100644 Task/Short-circuit-evaluation/Ring/short-circuit-evaluation.ring create mode 100644 Task/Short-circuit-evaluation/Rust/short-circuit-evaluation.rust create mode 100644 Task/Short-circuit-evaluation/Stata/short-circuit-evaluation-1.stata create mode 100644 Task/Short-circuit-evaluation/Stata/short-circuit-evaluation-2.stata rename Task/Show-the-epoch/ABAP/{show-the-epoch.abap => show-the-epoch-1.abap} (100%) create mode 100644 Task/Show-the-epoch/ABAP/show-the-epoch-2.abap create mode 100644 Task/Show-the-epoch/Lingo/show-the-epoch.lingo create mode 100644 Task/Show-the-epoch/Stata/show-the-epoch.stata create mode 100644 Task/Sierpinski-carpet/Perl-6/sierpinski-carpet.pl6 create mode 100644 Task/Sierpinski-triangle-Graphical/ATS/sierpinski-triangle-graphical.ats create mode 100644 Task/Sierpinski-triangle-Graphical/Erlang/sierpinski-triangle-graphical.erl create mode 100644 Task/Sierpinski-triangle-Graphical/Julia/sierpinski-triangle-graphical.julia create mode 100644 Task/Sierpinski-triangle-Graphical/Python/sierpinski-triangle-graphical-3.py create mode 100644 Task/Sierpinski-triangle/MATLAB/sierpinski-triangle-3.m create mode 100644 Task/Sieve-of-Eratosthenes/C++/sieve-of-eratosthenes-3.cpp create mode 100644 Task/Sieve-of-Eratosthenes/Go/sieve-of-eratosthenes-6.go create mode 100644 Task/Sieve-of-Eratosthenes/Limbo/sieve-of-eratosthenes.limbo create mode 100644 Task/Sieve-of-Eratosthenes/Lingo/sieve-of-eratosthenes-1.lingo create mode 100644 Task/Sieve-of-Eratosthenes/Lingo/sieve-of-eratosthenes-2.lingo create mode 100644 Task/Sieve-of-Eratosthenes/SAS/sieve-of-eratosthenes.sas create mode 100644 Task/Simple-database/Kotlin/simple-database.kotlin create mode 100644 Task/Simple-database/Perl-6/simple-database-1.pl6 create mode 100644 Task/Simple-database/Perl-6/simple-database-2.pl6 create mode 100644 Task/Simple-database/Perl/simple-database.pl create mode 100644 Task/Simple-windowed-application/Factor/simple-windowed-application.factor create mode 100644 Task/Simple-windowed-application/Julia/simple-windowed-application.julia rename Task/Simple-windowed-application/Kotlin/{simple-windowed-application.kotlin => simple-windowed-application-1.kotlin} (100%) create mode 100644 Task/Simple-windowed-application/Kotlin/simple-windowed-application-2.kotlin create mode 100644 Task/Simple-windowed-application/Phix/simple-windowed-application-1.phix rename Task/Simple-windowed-application/Phix/{simple-windowed-application.phix => simple-windowed-application-2.phix} (70%) create mode 100644 Task/Simulate-input-Keyboard/Python/simulate-input-keyboard-1.py rename Task/Simulate-input-Keyboard/Python/{simulate-input-keyboard.py => simulate-input-keyboard-2.py} (100%) create mode 100644 Task/Simulate-input-Keyboard/Rust/simulate-input-keyboard.rust create mode 100644 Task/Simulate-input-Mouse/C/simulate-input-mouse.c create mode 100644 Task/Simulate-input-Mouse/Python/simulate-input-mouse-3.py create mode 100644 Task/Simulate-input-Mouse/Ring/simulate-input-mouse.ring create mode 100644 Task/Simulate-input-Mouse/Rust/simulate-input-mouse.rust create mode 100644 Task/Singleton/Julia/singleton.julia create mode 100644 Task/Singly-linked-list-Element-definition/Elena/singly-linked-list-element-definition.elena create mode 100644 Task/Singly-linked-list-Element-definition/Julia/singly-linked-list-element-definition.julia create mode 100644 Task/Singly-linked-list-Element-definition/Stata/singly-linked-list-element-definition-1.stata create mode 100644 Task/Singly-linked-list-Element-definition/Stata/singly-linked-list-element-definition-10.stata create mode 100644 Task/Singly-linked-list-Element-definition/Stata/singly-linked-list-element-definition-11.stata create mode 100644 Task/Singly-linked-list-Element-definition/Stata/singly-linked-list-element-definition-12.stata create mode 100644 Task/Singly-linked-list-Element-definition/Stata/singly-linked-list-element-definition-13.stata create mode 100644 Task/Singly-linked-list-Element-definition/Stata/singly-linked-list-element-definition-14.stata create mode 100644 Task/Singly-linked-list-Element-definition/Stata/singly-linked-list-element-definition-2.stata create mode 100644 Task/Singly-linked-list-Element-definition/Stata/singly-linked-list-element-definition-3.stata create mode 100644 Task/Singly-linked-list-Element-definition/Stata/singly-linked-list-element-definition-4.stata create mode 100644 Task/Singly-linked-list-Element-definition/Stata/singly-linked-list-element-definition-5.stata create mode 100644 Task/Singly-linked-list-Element-definition/Stata/singly-linked-list-element-definition-6.stata create mode 100644 Task/Singly-linked-list-Element-definition/Stata/singly-linked-list-element-definition-7.stata create mode 100644 Task/Singly-linked-list-Element-definition/Stata/singly-linked-list-element-definition-8.stata create mode 100644 Task/Singly-linked-list-Element-definition/Stata/singly-linked-list-element-definition-9.stata create mode 100644 Task/Singly-linked-list-Element-insertion/Elena/singly-linked-list-element-insertion.elena create mode 100644 Task/Singly-linked-list-Element-insertion/Julia/singly-linked-list-element-insertion.julia create mode 100644 Task/Singly-linked-list-Traversal/Elena/singly-linked-list-traversal.elena create mode 100644 Task/Singly-linked-list-Traversal/Julia/singly-linked-list-traversal.julia create mode 100644 Task/Singly-linked-list-Traversal/Limbo/singly-linked-list-traversal.limbo create mode 100644 Task/Singly-linked-list-Traversal/Scala/singly-linked-list-traversal.scala create mode 100644 Task/Sleep/Elena/sleep.elena create mode 100644 Task/Sleep/Red/sleep.red create mode 100644 Task/Sockets/Elena/sockets.elena create mode 100644 Task/Sockets/Kotlin/sockets.kotlin create mode 100644 Task/Sockets/Ursa/sockets.ursa create mode 100644 Task/Sokoban/Kotlin/sokoban.kotlin create mode 100644 Task/Solve-a-Hidato-puzzle/Kotlin/solve-a-hidato-puzzle.kotlin create mode 100644 Task/Solve-a-Holy-Knights-tour/Go/solve-a-holy-knights-tour.go create mode 100644 Task/Solve-a-Holy-Knights-tour/Haskell/solve-a-holy-knights-tour-4.hs create mode 100644 Task/Solve-a-Hopido-puzzle/Kotlin/solve-a-hopido-puzzle.kotlin create mode 100644 Task/Solve-a-Numbrix-puzzle/Kotlin/solve-a-numbrix-puzzle.kotlin create mode 100644 Task/Solve-a-Numbrix-puzzle/Perl-6/solve-a-numbrix-puzzle.pl6 create mode 100644 Task/Solve-the-no-connection-puzzle/Kotlin/solve-the-no-connection-puzzle.kotlin create mode 100644 Task/Sort-an-integer-array/Red/sort-an-integer-array.red create mode 100644 Task/Sort-an-integer-array/Stata/sort-an-integer-array-1.stata create mode 100644 Task/Sort-an-integer-array/Stata/sort-an-integer-array-2.stata rename Task/Sort-an-integer-array/Stata/{sort-an-integer-array.stata => sort-an-integer-array-3.stata} (100%) create mode 100644 Task/Sort-disjoint-sublist/Elena/sort-disjoint-sublist.elena rename Task/Sort-disjoint-sublist/K/{sort-disjoint-sublist.k => sort-disjoint-sublist-1.k} (100%) create mode 100644 Task/Sort-disjoint-sublist/K/sort-disjoint-sublist-2.k create mode 100644 Task/Sort-disjoint-sublist/Kotlin/sort-disjoint-sublist.kotlin create mode 100644 Task/Sort-disjoint-sublist/Nial/sort-disjoint-sublist.nial create mode 100644 Task/Sort-stability/Kotlin/sort-stability.kotlin create mode 100644 Task/Sort-using-a-custom-comparator/Elena/sort-using-a-custom-comparator.elena create mode 100644 Task/Sort-using-a-custom-comparator/Perl-6/sort-using-a-custom-comparator.pl6 create mode 100644 Task/Sorting-algorithms-Bogosort/Elena/sorting-algorithms-bogosort.elena create mode 100644 Task/Sorting-algorithms-Bogosort/Gambas/sorting-algorithms-bogosort.gambas create mode 100644 Task/Sorting-algorithms-Bogosort/Maple/sorting-algorithms-bogosort.maple create mode 100644 Task/Sorting-algorithms-Bogosort/Ring/sorting-algorithms-bogosort.ring create mode 100644 Task/Sorting-algorithms-Bubble-sort/COBOL/sorting-algorithms-bubble-sort-1.cobol rename Task/Sorting-algorithms-Bubble-sort/COBOL/{sorting-algorithms-bubble-sort.cobol => sorting-algorithms-bubble-sort-2.cobol} (100%) create mode 100644 Task/Sorting-algorithms-Bubble-sort/Gambas/sorting-algorithms-bubble-sort.gambas create mode 100644 Task/Sorting-algorithms-Bubble-sort/Maple/sorting-algorithms-bubble-sort.maple create mode 100644 Task/Sorting-algorithms-Bubble-sort/N-t-roff/sorting-algorithms-bubble-sort.n create mode 100644 Task/Sorting-algorithms-Bubble-sort/Shen/sorting-algorithms-bubble-sort-1.shen create mode 100644 Task/Sorting-algorithms-Bubble-sort/Shen/sorting-algorithms-bubble-sort-2.shen create mode 100644 Task/Sorting-algorithms-Bubble-sort/Shen/sorting-algorithms-bubble-sort-3.shen create mode 100644 Task/Sorting-algorithms-Bubble-sort/Shen/sorting-algorithms-bubble-sort-4.shen create mode 100644 Task/Sorting-algorithms-Cocktail-sort/Elena/sorting-algorithms-cocktail-sort.elena create mode 100644 Task/Sorting-algorithms-Cocktail-sort/Gambas/sorting-algorithms-cocktail-sort.gambas create mode 100644 Task/Sorting-algorithms-Cocktail-sort/Maple/sorting-algorithms-cocktail-sort.maple create mode 100644 Task/Sorting-algorithms-Comb-sort/Elena/sorting-algorithms-comb-sort.elena create mode 100644 Task/Sorting-algorithms-Comb-sort/Gambas/sorting-algorithms-comb-sort.gambas create mode 100644 Task/Sorting-algorithms-Comb-sort/Maple/sorting-algorithms-comb-sort.maple rename Task/Sorting-algorithms-Comb-sort/Pascal/{sorting-algorithms-comb-sort.pascal => sorting-algorithms-comb-sort-1.pascal} (90%) create mode 100644 Task/Sorting-algorithms-Comb-sort/Pascal/sorting-algorithms-comb-sort-2.pascal create mode 100644 Task/Sorting-algorithms-Comb-sort/Scala/sorting-algorithms-comb-sort.scala create mode 100644 Task/Sorting-algorithms-Counting-sort/BASIC256/sorting-algorithms-counting-sort.basic256 create mode 100644 Task/Sorting-algorithms-Counting-sort/Elena/sorting-algorithms-counting-sort.elena create mode 100644 Task/Sorting-algorithms-Counting-sort/Perl-6/sorting-algorithms-counting-sort.pl6 create mode 100644 Task/Sorting-algorithms-Counting-sort/Rust/sorting-algorithms-counting-sort.rust create mode 100644 Task/Sorting-algorithms-Gnome-sort/Elena/sorting-algorithms-gnome-sort.elena create mode 100644 Task/Sorting-algorithms-Gnome-sort/Gambas/sorting-algorithms-gnome-sort.gambas create mode 100644 Task/Sorting-algorithms-Gnome-sort/Maple/sorting-algorithms-gnome-sort.maple create mode 100644 Task/Sorting-algorithms-Heapsort/Maple/sorting-algorithms-heapsort.maple create mode 100644 Task/Sorting-algorithms-Heapsort/Ring/sorting-algorithms-heapsort.ring create mode 100644 Task/Sorting-algorithms-Insertion-sort/ALGOL-W/sorting-algorithms-insertion-sort-1.alg create mode 100644 Task/Sorting-algorithms-Insertion-sort/ALGOL-W/sorting-algorithms-insertion-sort-2.alg create mode 100644 Task/Sorting-algorithms-Insertion-sort/Elena/sorting-algorithms-insertion-sort.elena create mode 100644 Task/Sorting-algorithms-Insertion-sort/Maple/sorting-algorithms-insertion-sort.maple create mode 100644 Task/Sorting-algorithms-Insertion-sort/N-t-roff/sorting-algorithms-insertion-sort-1.n create mode 100644 Task/Sorting-algorithms-Insertion-sort/N-t-roff/sorting-algorithms-insertion-sort-2.n create mode 100644 Task/Sorting-algorithms-Insertion-sort/Stata/sorting-algorithms-insertion-sort.stata create mode 100644 Task/Sorting-algorithms-Merge-sort/Maple/sorting-algorithms-merge-sort.maple create mode 100644 Task/Sorting-algorithms-Pancake-sort/Clojure/sorting-algorithms-pancake-sort.clj create mode 100644 Task/Sorting-algorithms-Pancake-sort/Elena/sorting-algorithms-pancake-sort.elena create mode 100644 Task/Sorting-algorithms-Pancake-sort/Rust/sorting-algorithms-pancake-sort.rust create mode 100644 Task/Sorting-algorithms-Permutation-sort/Factor/sorting-algorithms-permutation-sort.factor create mode 100644 Task/Sorting-algorithms-Permutation-sort/Maple/sorting-algorithms-permutation-sort.maple create mode 100644 Task/Sorting-algorithms-Permutation-sort/Ring/sorting-algorithms-permutation-sort.ring create mode 100644 Task/Sorting-algorithms-Quicksort/Elena/sorting-algorithms-quicksort.elena create mode 100644 Task/Sorting-algorithms-Quicksort/Java/sorting-algorithms-quicksort-1.java create mode 100644 Task/Sorting-algorithms-Quicksort/Java/sorting-algorithms-quicksort-2.java delete mode 100644 Task/Sorting-algorithms-Quicksort/Java/sorting-algorithms-quicksort.java create mode 100644 Task/Sorting-algorithms-Quicksort/Maple/sorting-algorithms-quicksort.maple create mode 100644 Task/Sorting-algorithms-Quicksort/Ring/sorting-algorithms-quicksort.ring create mode 100644 Task/Sorting-algorithms-Quicksort/Standard-ML/sorting-algorithms-quicksort-1.ml rename Task/Sorting-algorithms-Quicksort/Standard-ML/{sorting-algorithms-quicksort.ml => sorting-algorithms-quicksort-2.ml} (55%) create mode 100644 Task/Sorting-algorithms-Quicksort/TypeScript/sorting-algorithms-quicksort.type create mode 100644 Task/Sorting-algorithms-Selection-sort/Elena/sorting-algorithms-selection-sort.elena create mode 100644 Task/Sorting-algorithms-Selection-sort/Gambas/sorting-algorithms-selection-sort.gambas create mode 100644 Task/Sorting-algorithms-Selection-sort/Maple/sorting-algorithms-selection-sort.maple create mode 100644 Task/Sorting-algorithms-Selection-sort/N-t-roff/sorting-algorithms-selection-sort-1.n create mode 100644 Task/Sorting-algorithms-Selection-sort/N-t-roff/sorting-algorithms-selection-sort-2.n create mode 100644 Task/Sorting-algorithms-Selection-sort/Stata/sorting-algorithms-selection-sort.stata create mode 100644 Task/Sorting-algorithms-Shell-sort/Maple/sorting-algorithms-shell-sort.maple create mode 100644 Task/Sorting-algorithms-Sleep-sort/Elena/sorting-algorithms-sleep-sort.elena create mode 100644 Task/Sorting-algorithms-Sleep-sort/Kotlin/sorting-algorithms-sleep-sort.kotlin create mode 100644 Task/Sorting-algorithms-Stooge-sort/Clojure/sorting-algorithms-stooge-sort.clj create mode 100644 Task/Sorting-algorithms-Stooge-sort/Elena/sorting-algorithms-stooge-sort.elena create mode 100644 Task/Sorting-algorithms-Stooge-sort/Scala/sorting-algorithms-stooge-sort.scala create mode 100644 Task/Sorting-algorithms-Strand-sort/Ring/sorting-algorithms-strand-sort.ring create mode 100644 Task/Soundex/C++/soundex.cpp create mode 100644 Task/Soundex/Julia/soundex.julia create mode 100644 Task/Soundex/Lua/soundex.lua create mode 100644 Task/Soundex/NetRexx/soundex.netrexx create mode 100644 Task/Soundex/PowerShell/soundex-3.psh create mode 100644 Task/Soundex/PowerShell/soundex-4.psh create mode 100644 Task/Soundex/Ring/soundex.ring rename Task/Soundex/Stata/{soundex.stata => soundex-1.stata} (100%) create mode 100644 Task/Soundex/Stata/soundex-2.stata create mode 100644 Task/Sparkline-in-unicode/C/sparkline-in-unicode.c create mode 100644 Task/Special-variables/Java/special-variables.java create mode 100644 Task/Speech-synthesis/AutoIt/speech-synthesis.autoit create mode 100644 Task/Speech-synthesis/Kotlin/speech-synthesis.kotlin create mode 100644 Task/Spiral-matrix/Prolog/spiral-matrix.pro create mode 100644 Task/Spiral-matrix/Ring/spiral-matrix.ring create mode 100644 Task/Spiral-matrix/Stata/spiral-matrix.stata create mode 100644 Task/Stable-marriage-problem/Ceylon/stable-marriage-problem.ceylon create mode 100644 Task/Stable-marriage-problem/Julia/stable-marriage-problem.julia create mode 100644 Task/Stack-traces/Julia/stack-traces.julia create mode 100644 Task/Stair-climbing-puzzle/Julia/stair-climbing-puzzle-1.julia create mode 100644 Task/Stair-climbing-puzzle/Julia/stair-climbing-puzzle-2.julia create mode 100644 Task/Stair-climbing-puzzle/Kotlin/stair-climbing-puzzle.kotlin create mode 100644 Task/State-name-puzzle/Julia/state-name-puzzle-1.julia create mode 100644 Task/State-name-puzzle/Julia/state-name-puzzle-2.julia create mode 100644 Task/State-name-puzzle/Kotlin/state-name-puzzle.kotlin create mode 100644 Task/Statistics-Basic/Factor/statistics-basic.factor create mode 100644 Task/Statistics-Basic/Julia/statistics-basic.julia create mode 100644 Task/Statistics-Basic/Klong/statistics-basic.klong create mode 100644 Task/Statistics-Basic/PicoLisp/statistics-basic.l create mode 100644 Task/Statistics-Basic/R/statistics-basic.r create mode 100644 Task/Statistics-Basic/Ring/statistics-basic.ring rename Task/Stem-and-leaf-plot/Haskell/{stem-and-leaf-plot.hs => stem-and-leaf-plot-1.hs} (100%) create mode 100644 Task/Stem-and-leaf-plot/Haskell/stem-and-leaf-plot-2.hs rename Task/Stem-and-leaf-plot/JavaScript/{stem-and-leaf-plot.js => stem-and-leaf-plot-1.js} (100%) create mode 100644 Task/Stem-and-leaf-plot/JavaScript/stem-and-leaf-plot-2.js create mode 100644 Task/Stem-and-leaf-plot/Ring/stem-and-leaf-plot.ring create mode 100644 Task/Stern-Brocot-sequence/PicoLisp/stern-brocot-sequence.l create mode 100644 Task/Stern-Brocot-sequence/Ring/stern-brocot-sequence.ring create mode 100644 Task/String-append/Ada/string-append.ada create mode 100644 Task/String-append/Factor/string-append.factor create mode 100644 Task/String-append/Falcon/string-append.falcon create mode 100644 Task/String-append/Stata/string-append.stata create mode 100644 Task/String-case/Fortran/string-case-4.f create mode 100644 Task/String-case/Red/string-case.red create mode 100644 Task/String-case/Simula/string-case.simula create mode 100644 Task/String-comparison/Factor/string-comparison.factor create mode 100644 Task/String-comparison/Falcon/string-comparison.falcon rename Task/String-concatenation/ABAP/{string-concatenation.abap => string-concatenation-1.abap} (100%) create mode 100644 Task/String-concatenation/ABAP/string-concatenation-2.abap create mode 100644 Task/String-concatenation/Falcon/string-concatenation.falcon create mode 100644 Task/String-concatenation/Perl-6/string-concatenation.pl6 create mode 100644 Task/String-concatenation/Red/string-concatenation.red create mode 100644 Task/String-concatenation/Simula/string-concatenation.simula create mode 100644 Task/String-concatenation/Stata/string-concatenation-1.stata create mode 100644 Task/String-concatenation/Stata/string-concatenation-2.stata create mode 100644 Task/String-concatenation/VBA/string-concatenation.vba create mode 100644 Task/String-interpolation--included-/Falcon/string-interpolation--included-.falcon rename Task/String-interpolation--included-/Nim/{string-interpolation--included-.nim => string-interpolation--included--1.nim} (100%) create mode 100644 Task/String-interpolation--included-/Nim/string-interpolation--included--2.nim create mode 100644 Task/String-interpolation--included-/Python/string-interpolation--included--5.py create mode 100644 Task/String-interpolation--included-/Stata/string-interpolation--included-.stata create mode 100644 Task/String-interpolation--included-/Visual-Basic-.NET/string-interpolation--included-.visual rename Task/String-length/Aime/{string-length.aime => string-length-1.aime} (100%) create mode 100644 Task/String-length/Aime/string-length-2.aime create mode 100644 Task/String-length/BaCon/string-length.bacon create mode 100644 Task/String-length/HolyC/string-length.holyc create mode 100644 Task/String-length/JavaScript/string-length-3.js create mode 100644 Task/String-length/Rust/string-length-1.rust create mode 100644 Task/String-length/Rust/string-length-2.rust delete mode 100644 Task/String-length/Rust/string-length.rust create mode 100644 Task/String-matching/Falcon/string-matching.falcon create mode 100644 Task/String-prepend/Falcon/string-prepend.falcon create mode 100644 Task/String-prepend/Red/string-prepend.red create mode 100644 Task/String-prepend/Rust/string-prepend.rust create mode 100644 Task/String-prepend/Stata/string-prepend.stata create mode 100644 Task/Strip-a-set-of-characters-from-a-string/Elena/strip-a-set-of-characters-from-a-string.elena create mode 100644 Task/Strip-a-set-of-characters-from-a-string/Factor/strip-a-set-of-characters-from-a-string.factor create mode 100644 Task/Strip-a-set-of-characters-from-a-string/Red/strip-a-set-of-characters-from-a-string.red create mode 100644 Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-1.rust create mode 100644 Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-2.rust create mode 100644 Task/Strip-a-set-of-characters-from-a-string/Rust/strip-a-set-of-characters-from-a-string-3.rust create mode 100644 Task/Strip-comments-from-a-string/ALGOL-W/strip-comments-from-a-string.alg create mode 100644 Task/Strip-comments-from-a-string/Objeck/strip-comments-from-a-string.objeck create mode 100644 Task/Strip-comments-from-a-string/Red/strip-comments-from-a-string-1.red create mode 100644 Task/Strip-comments-from-a-string/Red/strip-comments-from-a-string-2.red create mode 100644 Task/Strip-control-codes-and-extended-characters-from-a-string/Factor/strip-control-codes-and-extended-characters-from-a-string.factor create mode 100644 Task/Strip-whitespace-from-a-string-Top-and-tail/Elena/strip-whitespace-from-a-string-top-and-tail.elena create mode 100644 Task/Strip-whitespace-from-a-string-Top-and-tail/Red/strip-whitespace-from-a-string-top-and-tail.red create mode 100644 Task/Strip-whitespace-from-a-string-Top-and-tail/Stata/strip-whitespace-from-a-string-top-and-tail.stata create mode 100644 Task/Substring-Top-and-tail/Elena/substring-top-and-tail.elena create mode 100644 Task/Substring-Top-and-tail/Factor/substring-top-and-tail.factor create mode 100644 Task/Substring/Falcon/substring.falcon create mode 100644 Task/Substring/Rust/substring.rust create mode 100644 Task/Substring/Stata/substring.stata create mode 100644 Task/Subtractive-generator/Kotlin/subtractive-generator.kotlin create mode 100644 Task/Sudoku/Ada/sudoku.ada create mode 100644 Task/Sudoku/Kotlin/sudoku.kotlin create mode 100644 Task/Sudoku/Stata/sudoku-1.stata create mode 100644 Task/Sudoku/Stata/sudoku-2.stata create mode 100644 Task/Sum-and-product-of-an-array/Nim/sum-and-product-of-an-array-3.nim create mode 100644 Task/Sum-and-product-of-an-array/Stata/sum-and-product-of-an-array.stata create mode 100644 Task/Sum-digits-of-an-integer/Befunge/sum-digits-of-an-integer.bf create mode 100644 Task/Sum-digits-of-an-integer/Crystal/sum-digits-of-an-integer.crystal create mode 100644 Task/Sum-digits-of-an-integer/Modula-2/sum-digits-of-an-integer.mod2 create mode 100644 Task/Sum-digits-of-an-integer/Stata/sum-digits-of-an-integer.stata create mode 100644 Task/Sum-digits-of-an-integer/Swift/sum-digits-of-an-integer.swift create mode 100644 Task/Sum-multiples-of-3-and-5/360-Assembly/sum-multiples-of-3-and-5.360 create mode 100644 Task/Sum-multiples-of-3-and-5/Factor/sum-multiples-of-3-and-5.factor create mode 100644 Task/Sum-multiples-of-3-and-5/Objeck/sum-multiples-of-3-and-5.objeck create mode 100644 Task/Sum-multiples-of-3-and-5/Rust/sum-multiples-of-3-and-5.rust create mode 100644 Task/Sum-multiples-of-3-and-5/Simula/sum-multiples-of-3-and-5.simula create mode 100644 Task/Sum-multiples-of-3-and-5/VBA/sum-multiples-of-3-and-5-1.vba create mode 100644 Task/Sum-multiples-of-3-and-5/VBA/sum-multiples-of-3-and-5-2.vba create mode 100644 Task/Sum-multiples-of-3-and-5/VBA/sum-multiples-of-3-and-5-3.vba create mode 100644 Task/Sum-multiples-of-3-and-5/VBA/sum-multiples-of-3-and-5-4.vba create mode 100644 Task/Sum-of-a-series/Maple/sum-of-a-series.maple create mode 100644 Task/Sum-of-a-series/Red/sum-of-a-series.red create mode 100644 Task/Sum-of-a-series/Stata/sum-of-a-series.stata create mode 100644 Task/Sum-of-squares/Astro/sum-of-squares.astro create mode 100644 Task/Sum-of-squares/Stata/sum-of-squares.stata create mode 100644 Task/Sutherland-Hodgman-polygon-clipping/Mathematica/sutherland-hodgman-polygon-clipping.math create mode 100644 Task/Symmetric-difference/JavaScript/symmetric-difference-5.js create mode 100644 Task/Symmetric-difference/JavaScript/symmetric-difference-6.js create mode 100644 Task/Synchronous-concurrency/Forth/synchronous-concurrency.fth create mode 100644 Task/Synchronous-concurrency/Julia/synchronous-concurrency.julia create mode 100644 Task/Synchronous-concurrency/Kotlin/synchronous-concurrency.kotlin create mode 100644 Task/Synchronous-concurrency/Pony/synchronous-concurrency.pony create mode 100644 Task/System-time/ABAP/system-time.abap create mode 100644 Task/System-time/Elena/system-time.elena create mode 100644 Task/System-time/Falcon/system-time.falcon create mode 100644 Task/System-time/HolyC/system-time.holyc create mode 100644 Task/System-time/Modula-2/system-time.mod2 create mode 100644 Task/System-time/Stata/system-time.stata create mode 100644 Task/Table-creation-Postal-addresses/Julia/table-creation-postal-addresses.julia create mode 100644 Task/Table-creation-Postal-addresses/Kotlin/table-creation-postal-addresses.kotlin create mode 100644 Task/Table-creation-Postal-addresses/Lua/table-creation-postal-addresses.lua create mode 100644 Task/Table-creation-Postal-addresses/Perl-6/table-creation-postal-addresses.pl6 create mode 100644 Task/Table-creation-Postal-addresses/Ring/table-creation-postal-addresses.ring create mode 100644 Task/Table-creation-Postal-addresses/Stata/table-creation-postal-addresses.stata create mode 100644 Task/Take-notes-on-the-command-line/Kotlin/take-notes-on-the-command-line.kotlin create mode 100644 Task/Take-notes-on-the-command-line/Rust/take-notes-on-the-command-line.rust create mode 100644 Task/Temperature-conversion/AutoIt/temperature-conversion.autoit create mode 100644 Task/Temperature-conversion/Elena/temperature-conversion.elena create mode 100644 Task/Temperature-conversion/Factor/temperature-conversion.factor create mode 100644 Task/Temperature-conversion/UNIX-Shell/temperature-conversion-1.sh create mode 100644 Task/Temperature-conversion/UNIX-Shell/temperature-conversion-2.sh create mode 100644 Task/Temperature-conversion/VBA/temperature-conversion.vba create mode 100644 Task/Terminal-control-Clear-the-screen/Elena/terminal-control-clear-the-screen.elena create mode 100644 Task/Terminal-control-Coloured-text/Ring/terminal-control-coloured-text.ring create mode 100644 Task/Terminal-control-Coloured-text/Scala/terminal-control-coloured-text.scala create mode 100644 Task/Terminal-control-Cursor-movement/Scala/terminal-control-cursor-movement.scala create mode 100644 Task/Terminal-control-Cursor-positioning/D/terminal-control-cursor-positioning.d create mode 100644 Task/Terminal-control-Cursor-positioning/Elena/terminal-control-cursor-positioning.elena create mode 100644 Task/Terminal-control-Cursor-positioning/Ring/terminal-control-cursor-positioning.ring create mode 100644 Task/Terminal-control-Cursor-positioning/Scala/terminal-control-cursor-positioning.scala create mode 100644 Task/Terminal-control-Dimensions/Scala/terminal-control-dimensions.scala create mode 100644 Task/Terminal-control-Display-an-extended-character/Ring/terminal-control-display-an-extended-character.ring create mode 100644 Task/Terminal-control-Hiding-the-cursor/Python/terminal-control-hiding-the-cursor.py create mode 100644 Task/Terminal-control-Hiding-the-cursor/Scala/terminal-control-hiding-the-cursor.scala create mode 100644 Task/Terminal-control-Inverse-video/Scala/terminal-control-inverse-video.scala create mode 100644 Task/Terminal-control-Positional-read/Python/terminal-control-positional-read.py create mode 100644 Task/Terminal-control-Preserve-screen/Befunge/terminal-control-preserve-screen.bf create mode 100644 Task/Terminal-control-Preserve-screen/Perl/terminal-control-preserve-screen.pl create mode 100644 Task/Terminal-control-Unicode-output/Go/terminal-control-unicode-output.go create mode 100644 Task/Ternary-logic/Elena/ternary-logic.elena create mode 100644 Task/Ternary-logic/Julia/ternary-logic.julia create mode 100644 Task/Ternary-logic/Perl-6/ternary-logic.pl6 create mode 100644 Task/Test-a-function/Julia/test-a-function.julia create mode 100644 Task/Test-a-function/VBA/test-a-function.vba create mode 100644 Task/Text-processing-1/Julia/text-processing-1.julia create mode 100644 Task/Text-processing-1/Kotlin/text-processing-1.kotlin create mode 100644 Task/Text-processing-1/Phix/text-processing-1.phix create mode 100644 Task/Text-processing-2/Julia/text-processing-2.julia create mode 100644 Task/Text-processing-2/Kotlin/text-processing-2.kotlin create mode 100644 Task/Text-processing-2/Perl-6/text-processing-2.pl6 create mode 100644 Task/Text-processing-Max-licenses-in-use/Julia/text-processing-max-licenses-in-use.julia create mode 100644 Task/Text-processing-Max-licenses-in-use/Kotlin/text-processing-max-licenses-in-use.kotlin create mode 100644 Task/Textonyms/Clojure/textonyms.clj create mode 100644 Task/The-ISAAC-Cipher/Julia/the-isaac-cipher.julia create mode 100644 Task/The-ISAAC-Cipher/Modula-2/the-isaac-cipher.mod2 create mode 100644 Task/The-Twelve-Days-of-Christmas/Elena/the-twelve-days-of-christmas.elena create mode 100644 Task/The-Twelve-Days-of-Christmas/Factor/the-twelve-days-of-christmas.factor create mode 100644 Task/The-Twelve-Days-of-Christmas/PureBasic/the-twelve-days-of-christmas.purebasic create mode 100644 Task/The-Twelve-Days-of-Christmas/Ring/the-twelve-days-of-christmas.ring create mode 100644 Task/The-Twelve-Days-of-Christmas/VBA/the-twelve-days-of-christmas.vba create mode 100644 Task/Tic-tac-toe/Fortran/tic-tac-toe.f create mode 100644 Task/Tic-tac-toe/Kotlin/tic-tac-toe.kotlin create mode 100644 Task/Tic-tac-toe/Lingo/tic-tac-toe.lingo create mode 100644 Task/Tic-tac-toe/VBA/tic-tac-toe.vba create mode 100644 Task/Time-a-function/Elena/time-a-function.elena create mode 100644 Task/Tokenize-a-string/360-Assembly/tokenize-a-string.360 create mode 100644 Task/Tokenize-a-string/Falcon/tokenize-a-string.falcon create mode 100644 Task/Tokenize-a-string/Gambas/tokenize-a-string.gambas create mode 100644 Task/Tokenize-a-string/Maple/tokenize-a-string.maple create mode 100644 Task/Tokenize-a-string/Nial/tokenize-a-string-1.nial create mode 100644 Task/Tokenize-a-string/Nial/tokenize-a-string-2.nial create mode 100644 Task/Tokenize-a-string/Nial/tokenize-a-string-3.nial create mode 100644 Task/Tokenize-a-string/Nial/tokenize-a-string-4.nial create mode 100644 Task/Tokenize-a-string/Red/tokenize-a-string.red create mode 100644 Task/Tokenize-a-string/VBA/tokenize-a-string.vba create mode 100644 Task/Top-rank-per-group/Ceylon/top-rank-per-group.ceylon create mode 100644 Task/Top-rank-per-group/R/top-rank-per-group-5.r create mode 100644 Task/Top-rank-per-group/Ring/top-rank-per-group.ring create mode 100644 Task/Topic-variable/Scala/topic-variable.scala create mode 100644 Task/Topological-sort/C-sharp/topological-sort-1.cs create mode 100644 Task/Topological-sort/C-sharp/topological-sort-2.cs create mode 100644 Task/Topological-sort/C-sharp/topological-sort-3.cs create mode 100644 Task/Topological-sort/Julia/topological-sort.julia create mode 100644 Task/Topological-sort/Kotlin/topological-sort.kotlin create mode 100644 Task/Topswops/C++/topswops.cpp rename Task/Towers-of-Hanoi/ALGOL-68/{towers-of-hanoi.alg => towers-of-hanoi-1.alg} (100%) create mode 100644 Task/Towers-of-Hanoi/ALGOL-68/towers-of-hanoi-2.alg create mode 100644 Task/Towers-of-Hanoi/Befunge/towers-of-hanoi.bf rename Task/Towers-of-Hanoi/COBOL/{towers-of-hanoi.cobol => towers-of-hanoi-1.cobol} (100%) create mode 100644 Task/Towers-of-Hanoi/COBOL/towers-of-hanoi-2.cobol create mode 100644 Task/Towers-of-Hanoi/Elena/towers-of-hanoi.elena create mode 100644 Task/Towers-of-Hanoi/HolyC/towers-of-hanoi.holyc create mode 100644 Task/Towers-of-Hanoi/MIPS-Assembly/towers-of-hanoi.mips create mode 100644 Task/Towers-of-Hanoi/Maple/towers-of-hanoi.maple create mode 100644 Task/Towers-of-Hanoi/Modula-2/towers-of-hanoi.mod2 create mode 100644 Task/Towers-of-Hanoi/Stata/towers-of-hanoi.stata create mode 100644 Task/Trabb-Pardo-Knuth-algorithm/Elena/trabb-pardo-knuth-algorithm.elena create mode 100644 Task/Trabb-Pardo-Knuth-algorithm/Factor/trabb-pardo-knuth-algorithm.factor create mode 100644 Task/Trabb-Pardo-Knuth-algorithm/Maple/trabb-pardo-knuth-algorithm.maple create mode 100644 Task/Trabb-Pardo-Knuth-algorithm/PL-M/trabb-pardo-knuth-algorithm.plm create mode 100644 Task/Tree-traversal/Elena/tree-traversal.elena create mode 100644 Task/Trigonometric-functions/Modula-2/trigonometric-functions.mod2 create mode 100644 Task/Truncatable-primes/Factor/truncatable-primes.factor create mode 100644 Task/Truncatable-primes/Maple/truncatable-primes.maple create mode 100644 Task/Truncatable-primes/Ring/truncatable-primes.ring create mode 100644 Task/Truncate-a-file/Clojure/truncate-a-file.clj create mode 100644 Task/Twelve-statements/Clojure/twelve-statements.clj create mode 100644 Task/Twelve-statements/Pascal/twelve-statements.pascal create mode 100644 Task/Twelve-statements/Scala/twelve-statements.scala create mode 100644 Task/URL-decoding/BaCon/url-decoding.bacon create mode 100644 Task/URL-decoding/Factor/url-decoding.factor create mode 100644 Task/URL-decoding/Lingo/url-decoding-1.lingo create mode 100644 Task/URL-decoding/Lingo/url-decoding-2.lingo create mode 100644 Task/URL-decoding/Perl-6/url-decoding.pl6 create mode 100644 Task/URL-decoding/UNIX-Shell/url-decoding-1.sh create mode 100644 Task/URL-decoding/UNIX-Shell/url-decoding-2.sh rename Task/URL-decoding/UNIX-Shell/{url-decoding.sh => url-decoding-3.sh} (100%) create mode 100644 Task/Ulam-spiral--for-primes-/JavaScript/ulam-spiral--for-primes-.js create mode 100644 Task/Ulam-spiral--for-primes-/Julia/ulam-spiral--for-primes-.julia create mode 100644 Task/Ulam-spiral--for-primes-/Ring/ulam-spiral--for-primes-.ring create mode 100644 Task/Unbias-a-random-generator/Elena/unbias-a-random-generator.elena rename Task/Unbias-a-random-generator/Java/{unbias-a-random-generator.java => unbias-a-random-generator-1.java} (100%) create mode 100644 Task/Unbias-a-random-generator/Java/unbias-a-random-generator-2.java create mode 100644 Task/Unbias-a-random-generator/Julia/unbias-a-random-generator.julia create mode 100644 Task/Unbias-a-random-generator/Rust/unbias-a-random-generator.rust create mode 100644 Task/Undefined-values/Ring/undefined-values.ring create mode 100644 Task/Unicode-strings/D/unicode-strings.d create mode 100644 Task/Unicode-variable-names/BaCon/unicode-variable-names.bacon create mode 100644 Task/Unicode-variable-names/C/unicode-variable-names.c create mode 100644 Task/Unicode-variable-names/Stata/unicode-variable-names.stata create mode 100644 Task/Universal-Turing-machine/Kotlin/universal-turing-machine.kotlin create mode 100644 Task/Unix-ls/Erlang/unix-ls.erl create mode 100644 Task/Unix-ls/Kotlin/unix-ls.kotlin create mode 100644 Task/Unix-ls/Standard-ML/unix-ls-1.ml create mode 100644 Task/Unix-ls/Standard-ML/unix-ls-2.ml create mode 100644 Task/Update-a-configuration-file/Kotlin/update-a-configuration-file.kotlin create mode 100644 Task/Use-another-language-to-call-a-function/Kotlin/use-another-language-to-call-a-function-1.kotlin create mode 100644 Task/Use-another-language-to-call-a-function/Kotlin/use-another-language-to-call-a-function-2.kotlin create mode 100644 Task/Use-another-language-to-call-a-function/Kotlin/use-another-language-to-call-a-function-3.kotlin create mode 100644 Task/Use-another-language-to-call-a-function/Scala/use-another-language-to-call-a-function-1.scala create mode 100644 Task/Use-another-language-to-call-a-function/Scala/use-another-language-to-call-a-function-2.scala create mode 100644 Task/Use-another-language-to-call-a-function/Scala/use-another-language-to-call-a-function-3.scala create mode 100644 Task/User-input-Text/HolyC/user-input-text.holyc create mode 100644 Task/User-input-Text/Red/user-input-text.red create mode 100644 Task/Vampire-number/Factor/vampire-number.factor rename Task/Vampire-number/Perl/{vampire-number.pl => vampire-number-1.pl} (100%) create mode 100644 Task/Vampire-number/Perl/vampire-number-2.pl create mode 100644 Task/Vampire-number/Ring/vampire-number.ring create mode 100644 Task/Vampire-number/Sidef/vampire-number.sidef create mode 100644 Task/Van-der-Corput-sequence/Modula-2/van-der-corput-sequence.mod2 create mode 100644 Task/Variable-size-Set/Scala/variable-size-set.scala create mode 100644 Task/Variables/Falcon/variables.falcon create mode 100644 Task/Variables/HicEst/variables.hicest create mode 100644 Task/Variables/HolyC/variables-1.holyc create mode 100644 Task/Variables/HolyC/variables-2.holyc create mode 100644 Task/Variables/HolyC/variables-3.holyc create mode 100644 Task/Variables/HolyC/variables-4.holyc create mode 100644 Task/Variables/HolyC/variables-5.holyc create mode 100644 Task/Variables/Python/variables.py create mode 100644 Task/Variables/Visual-Basic-.NET/variables.visual create mode 100644 Task/Variadic-function/Batch-File/variadic-function.bat create mode 100644 Task/Variadic-function/Factor/variadic-function-1.factor create mode 100644 Task/Variadic-function/Factor/variadic-function-2.factor create mode 100644 Task/Variadic-function/Ring/variadic-function.ring create mode 100644 Task/Vector-products/Factor/vector-products.factor create mode 100644 Task/Vector-products/Modula-2/vector-products.mod2 create mode 100644 Task/Verify-distribution-uniformity-Chi-squared-test/Kotlin/verify-distribution-uniformity-chi-squared-test.kotlin create mode 100644 Task/Verify-distribution-uniformity-Naive/Julia/verify-distribution-uniformity-naive.julia create mode 100644 Task/Video-display-modes/Kotlin/video-display-modes.kotlin create mode 100644 Task/Video-display-modes/Perl-6/video-display-modes.pl6 create mode 100644 Task/Video-display-modes/Scala/video-display-modes.scala create mode 100644 Task/Vigen-re-cipher-Cryptanalysis/Go/vigen-re-cipher-cryptanalysis.go create mode 100644 Task/Vigen-re-cipher-Cryptanalysis/Haskell/vigen-re-cipher-cryptanalysis.hs create mode 100644 Task/Vigen-re-cipher-Cryptanalysis/Java/vigen-re-cipher-cryptanalysis.java create mode 100644 Task/Vigen-re-cipher/Applesoft-BASIC/vigen-re-cipher.applesoft create mode 100644 Task/Vigen-re-cipher/Elena/vigen-re-cipher.elena create mode 100644 Task/Vigen-re-cipher/Factor/vigen-re-cipher.factor create mode 100644 Task/Vigen-re-cipher/Red/vigen-re-cipher.red create mode 100644 Task/Vigen-re-cipher/Ring/vigen-re-cipher.ring create mode 100644 Task/Vigen-re-cipher/Scala/vigen-re-cipher.scala create mode 100644 Task/Vigen-re-cipher/VBA/vigen-re-cipher.vba rename Task/Vigen-re-cipher/VBScript/{vigen-re-cipher.vb => vigen-re-cipher-1.vb} (100%) create mode 100644 Task/Vigen-re-cipher/VBScript/vigen-re-cipher-2.vb create mode 100644 Task/Visualize-a-tree/Kotlin/visualize-a-tree.kotlin create mode 100644 Task/Vogels-approximation-method/C/vogels-approximation-method.c create mode 100644 Task/Vogels-approximation-method/Go/vogels-approximation-method.go create mode 100644 Task/Vogels-approximation-method/Sidef/vogels-approximation-method.sidef create mode 100644 Task/Voronoi-diagram/Julia/voronoi-diagram-1.julia create mode 100644 Task/Voronoi-diagram/Julia/voronoi-diagram-2.julia create mode 100644 Task/Voronoi-diagram/Perl-6/voronoi-diagram.pl6 create mode 100644 Task/Voronoi-diagram/Ring/voronoi-diagram.ring create mode 100644 Task/Voronoi-diagram/Rust/voronoi-diagram.rust create mode 100644 Task/Walk-a-directory-Non-recursively/Julia/walk-a-directory-non-recursively.julia create mode 100644 Task/Walk-a-directory-Recursively/Julia/walk-a-directory-recursively.julia create mode 100644 Task/Walk-a-directory-Recursively/Kotlin/walk-a-directory-recursively.kotlin create mode 100644 Task/Web-scraping/Ceylon/web-scraping.ceylon create mode 100644 Task/Web-scraping/Maple/web-scraping.maple create mode 100644 Task/Web-scraping/VBA/web-scraping.vba create mode 100644 Task/Window-creation-X11/Julia/window-creation-x11.julia create mode 100644 Task/Window-creation/Red/window-creation.red create mode 100644 Task/Window-creation/VBA/window-creation.vba create mode 100644 Task/Window-management/Gambas/window-management.gambas create mode 100644 Task/Wireworld/Elena/wireworld.elena create mode 100644 Task/Word-wrap/Factor/word-wrap.factor create mode 100644 Task/Word-wrap/Julia/word-wrap.julia create mode 100644 Task/Word-wrap/Ring/word-wrap.ring create mode 100644 Task/World-Cup-group-stage/Elena/world-cup-group-stage.elena create mode 100644 Task/Write-float-arrays-to-a-text-file/COBOL/write-float-arrays-to-a-text-file.cobol create mode 100644 Task/Write-float-arrays-to-a-text-file/Ring/write-float-arrays-to-a-text-file.ring create mode 100644 Task/Write-language-name-in-3D-ASCII/Modula-2/write-language-name-in-3d-ascii.mod2 create mode 100644 Task/Write-to-Windows-event-log/C/write-to-windows-event-log.c create mode 100644 Task/Write-to-Windows-event-log/D/write-to-windows-event-log.d create mode 100644 Task/Write-to-Windows-event-log/Lingo/write-to-windows-event-log.lingo create mode 100644 Task/Write-to-Windows-event-log/Perl/write-to-windows-event-log.pl rename Task/Write-to-Windows-event-log/PowerShell/{write-to-windows-event-log.psh => write-to-windows-event-log-1.psh} (100%) create mode 100644 Task/Write-to-Windows-event-log/PowerShell/write-to-windows-event-log-2.psh create mode 100644 Task/Write-to-Windows-event-log/PowerShell/write-to-windows-event-log-3.psh create mode 100644 Task/Write-to-Windows-event-log/Scala/write-to-windows-event-log.scala create mode 100644 Task/XML-DOM-serialization/MATLAB/xml-dom-serialization.m create mode 100644 Task/XML-DOM-serialization/Perl-6/xml-dom-serialization-1.pl6 create mode 100644 Task/XML-DOM-serialization/Perl-6/xml-dom-serialization-2.pl6 create mode 100644 Task/XML-Input/Julia/xml-input.julia create mode 100644 Task/XML-Input/VBA/xml-input.vba create mode 100644 Task/XML-Output/Perl-6/xml-output-1.pl6 create mode 100644 Task/XML-Output/Perl-6/xml-output-2.pl6 create mode 100644 Task/XML-XPath/C/xml-xpath.c create mode 100644 Task/XML-XPath/Perl-6/xml-xpath.pl6 create mode 100644 Task/Xiaolin-Wus-line-algorithm/Julia/xiaolin-wus-line-algorithm.julia create mode 100644 Task/Y-combinator/Elm/y-combinator.elm create mode 100644 Task/Y-combinator/Kitten/y-combinator.kitten create mode 100644 Task/Y-combinator/Python/y-combinator-3.py create mode 100644 Task/Yahoo--search-interface/Kotlin/yahoo--search-interface.kotlin create mode 100644 Task/Yin-and-yang/Julia/yin-and-yang.julia create mode 100644 Task/Zebra-puzzle/ALGOL-68/zebra-puzzle.alg create mode 100644 Task/Zebra-puzzle/Julia/zebra-puzzle.julia create mode 100644 Task/Zebra-puzzle/Nial/zebra-puzzle.nial rename Task/Zebra-puzzle/Ruby/{zebra-puzzle.rb => zebra-puzzle-1.rb} (100%) create mode 100644 Task/Zebra-puzzle/Ruby/zebra-puzzle-2.rb create mode 100644 Task/Zeckendorf-arithmetic/D/zeckendorf-arithmetic.d create mode 100644 Task/Zeckendorf-arithmetic/Java/zeckendorf-arithmetic.java create mode 100644 Task/Zeckendorf-arithmetic/Kotlin/zeckendorf-arithmetic.kotlin create mode 100644 Task/Zeckendorf-number-representation/Lingo/zeckendorf-number-representation-1.lingo create mode 100644 Task/Zeckendorf-number-representation/Lingo/zeckendorf-number-representation-2.lingo create mode 100644 Task/Zeckendorf-number-representation/Ring/zeckendorf-number-representation.ring create mode 100644 Task/Zero-to-the-zero-power/Dc/zero-to-the-zero-power.dc create mode 100644 Task/Zero-to-the-zero-power/Falcon/zero-to-the-zero-power.falcon create mode 100644 Task/Zero-to-the-zero-power/HolyC/zero-to-the-zero-power.holyc rename Task/Zero-to-the-zero-power/JavaScript/{zero-to-the-zero-power.js => zero-to-the-zero-power-1.js} (100%) create mode 100644 Task/Zero-to-the-zero-power/JavaScript/zero-to-the-zero-power-2.js create mode 100644 Task/Zero-to-the-zero-power/Python/zero-to-the-zero-power-1.py rename Task/Zero-to-the-zero-power/Python/{zero-to-the-zero-power.py => zero-to-the-zero-power-2.py} (100%) create mode 100644 Task/Zhang-Suen-thinning-algorithm/C/zhang-suen-thinning-algorithm.c create mode 100644 Task/Zhang-Suen-thinning-algorithm/Julia/zhang-suen-thinning-algorithm.julia create mode 100644 Task/Zig-zag-matrix/Octave/zig-zag-matrix-1.octave create mode 100644 Task/Zig-zag-matrix/Octave/zig-zag-matrix-2.octave create mode 100644 Task/Zig-zag-matrix/Ring/zig-zag-matrix.ring create mode 100644 Task/Zig-zag-matrix/Scilab/zig-zag-matrix.scilab create mode 100644 Task/Zig-zag-matrix/Stata/zig-zag-matrix-1.stata create mode 100644 Task/Zig-zag-matrix/Stata/zig-zag-matrix-2.stata create mode 100644 Task/Zig-zag-matrix/Stata/zig-zag-matrix-3.stata diff --git a/Lang/360-Assembly/00DESCRIPTION b/Lang/360-Assembly/00DESCRIPTION index d3a26430c9..0d8684195e 100644 --- a/Lang/360-Assembly/00DESCRIPTION +++ b/Lang/360-Assembly/00DESCRIPTION @@ -1,4 +1,4 @@ -{{stub}}{{language}} +{{language}} [[Category:Assembly]] IBM 360 assembly language. @@ -16,4 +16,14 @@ themselves in popular use to all assembly-language dialects on the System/360 an its descendants. The 360 assembly was introduced with the System/360 in 1964. ==Wikipedia article== -[[wp:IBM_Basic_assembly_language_and_successors|IBM Basic assembly language and successors]] \ No newline at end of file +[[wp:IBM_Basic_assembly_language_and_successors|IBM Basic assembly language and successors]] + +==See also== + +WikiBooks Article: https://en.wikibooks.org/wiki/360_Assembly/360_Instructions + +IBM manuals: + +* IBM System/360 Principles of operation (c. 1963) : http://bitsavers.trailing-edge.com/pdf/ibm/360/princOps/A22-6821-0_360PrincOps.pdf + +* A programmer instrodution to IBM System/360 Assembler Language : http://bitsavers.trailing-edge.com/pdf/ibm/360/asm/SC20-1646-6_int360asm_Aug70.pdf \ No newline at end of file diff --git a/Lang/360-Assembly/Flow-control-structures b/Lang/360-Assembly/Flow-control-structures new file mode 120000 index 0000000000..a50465c37f --- /dev/null +++ b/Lang/360-Assembly/Flow-control-structures @@ -0,0 +1 @@ +../../Task/Flow-control-structures/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Floyds-triangle b/Lang/360-Assembly/Floyds-triangle new file mode 120000 index 0000000000..6ff33ce099 --- /dev/null +++ b/Lang/360-Assembly/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Pythagorean-triples b/Lang/360-Assembly/Pythagorean-triples new file mode 120000 index 0000000000..e57fb36ef3 --- /dev/null +++ b/Lang/360-Assembly/Pythagorean-triples @@ -0,0 +1 @@ +../../Task/Pythagorean-triples/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Sum-multiples-of-3-and-5 b/Lang/360-Assembly/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..b2f0838f57 --- /dev/null +++ b/Lang/360-Assembly/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Tokenize-a-string b/Lang/360-Assembly/Tokenize-a-string new file mode 120000 index 0000000000..07e47081fc --- /dev/null +++ b/Lang/360-Assembly/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/360-Assembly \ No newline at end of file diff --git a/Lang/8th/AKS-test-for-primes b/Lang/8th/AKS-test-for-primes new file mode 120000 index 0000000000..320889546e --- /dev/null +++ b/Lang/8th/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/8th \ No newline at end of file diff --git a/Lang/8th/Arithmetic-geometric-mean b/Lang/8th/Arithmetic-geometric-mean new file mode 120000 index 0000000000..8f5df14cee --- /dev/null +++ b/Lang/8th/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/8th \ No newline at end of file diff --git a/Lang/8th/Luhn-test-of-credit-card-numbers b/Lang/8th/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..67e69b059f --- /dev/null +++ b/Lang/8th/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/8th \ No newline at end of file diff --git a/Lang/8th/Parsing-Shunting-yard-algorithm b/Lang/8th/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..8792316a4a --- /dev/null +++ b/Lang/8th/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/8th \ No newline at end of file diff --git a/Lang/ABAP/Equilibrium-index b/Lang/ABAP/Equilibrium-index new file mode 120000 index 0000000000..ff4c431f40 --- /dev/null +++ b/Lang/ABAP/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/ABAP \ No newline at end of file diff --git a/Lang/ABAP/Extend-your-language b/Lang/ABAP/Extend-your-language new file mode 120000 index 0000000000..c60482e724 --- /dev/null +++ b/Lang/ABAP/Extend-your-language @@ -0,0 +1 @@ +../../Task/Extend-your-language/ABAP \ No newline at end of file diff --git a/Lang/ABAP/Morse-code b/Lang/ABAP/Morse-code new file mode 120000 index 0000000000..f8971da5bf --- /dev/null +++ b/Lang/ABAP/Morse-code @@ -0,0 +1 @@ +../../Task/Morse-code/ABAP \ No newline at end of file diff --git a/Lang/ABAP/System-time b/Lang/ABAP/System-time new file mode 120000 index 0000000000..f495bf792d --- /dev/null +++ b/Lang/ABAP/System-time @@ -0,0 +1 @@ +../../Task/System-time/ABAP \ No newline at end of file diff --git a/Lang/ALGOL-60/Loops-Break b/Lang/ALGOL-60/Loops-Break new file mode 120000 index 0000000000..de21e714f7 --- /dev/null +++ b/Lang/ALGOL-60/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Loops-N-plus-one-half b/Lang/ALGOL-60/Loops-N-plus-one-half new file mode 120000 index 0000000000..6d3f4adb68 --- /dev/null +++ b/Lang/ALGOL-60/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Loops-Nested b/Lang/ALGOL-60/Loops-Nested new file mode 120000 index 0000000000..c2e592c27d --- /dev/null +++ b/Lang/ALGOL-60/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-68/Aliquot-sequence-classifications b/Lang/ALGOL-68/Aliquot-sequence-classifications new file mode 120000 index 0000000000..4f7f4d4110 --- /dev/null +++ b/Lang/ALGOL-68/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Zebra-puzzle b/Lang/ALGOL-68/Zebra-puzzle new file mode 120000 index 0000000000..94816bc4c5 --- /dev/null +++ b/Lang/ALGOL-68/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-W/Sorting-algorithms-Insertion-sort b/Lang/ALGOL-W/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..52f7881571 --- /dev/null +++ b/Lang/ALGOL-W/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/ALGOL-W \ No newline at end of file diff --git a/Lang/ALGOL-W/Strip-comments-from-a-string b/Lang/ALGOL-W/Strip-comments-from-a-string new file mode 120000 index 0000000000..6030f738f6 --- /dev/null +++ b/Lang/ALGOL-W/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/ALGOL-W \ No newline at end of file diff --git a/Lang/APL/Anagrams b/Lang/APL/Anagrams new file mode 120000 index 0000000000..7b9dc560b0 --- /dev/null +++ b/Lang/APL/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/APL \ No newline at end of file diff --git a/Lang/APL/Apply-a-callback-to-an-array b/Lang/APL/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..09131a4e83 --- /dev/null +++ b/Lang/APL/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/APL \ No newline at end of file diff --git a/Lang/APL/Arithmetic-Integer b/Lang/APL/Arithmetic-Integer new file mode 120000 index 0000000000..849833b704 --- /dev/null +++ b/Lang/APL/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/APL \ No newline at end of file diff --git a/Lang/APL/Boolean-values b/Lang/APL/Boolean-values new file mode 120000 index 0000000000..f69a45af45 --- /dev/null +++ b/Lang/APL/Boolean-values @@ -0,0 +1 @@ +../../Task/Boolean-values/APL \ No newline at end of file diff --git a/Lang/APL/Fast-Fourier-transform b/Lang/APL/Fast-Fourier-transform new file mode 120000 index 0000000000..7aacf4061a --- /dev/null +++ b/Lang/APL/Fast-Fourier-transform @@ -0,0 +1 @@ +../../Task/Fast-Fourier-transform/APL \ No newline at end of file diff --git a/Lang/APL/Polynomial-long-division b/Lang/APL/Polynomial-long-division new file mode 120000 index 0000000000..d8e160a660 --- /dev/null +++ b/Lang/APL/Polynomial-long-division @@ -0,0 +1 @@ +../../Task/Polynomial-long-division/APL \ No newline at end of file diff --git a/Lang/ARM-Assembly/Address-of-a-variable b/Lang/ARM-Assembly/Address-of-a-variable new file mode 120000 index 0000000000..da409ff23c --- /dev/null +++ b/Lang/ARM-Assembly/Address-of-a-variable @@ -0,0 +1 @@ +../../Task/Address-of-a-variable/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Arithmetic-Integer b/Lang/ARM-Assembly/Arithmetic-Integer new file mode 120000 index 0000000000..c8d1fbafb3 --- /dev/null +++ b/Lang/ARM-Assembly/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Balanced-brackets b/Lang/ARM-Assembly/Balanced-brackets new file mode 120000 index 0000000000..1ded1065c0 --- /dev/null +++ b/Lang/ARM-Assembly/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Call-a-function b/Lang/ARM-Assembly/Call-a-function new file mode 120000 index 0000000000..63e838e129 --- /dev/null +++ b/Lang/ARM-Assembly/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Comments b/Lang/ARM-Assembly/Comments new file mode 120000 index 0000000000..c007c10efd --- /dev/null +++ b/Lang/ARM-Assembly/Comments @@ -0,0 +1 @@ +../../Task/Comments/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/FizzBuzz b/Lang/ARM-Assembly/FizzBuzz new file mode 120000 index 0000000000..061b4b56ce --- /dev/null +++ b/Lang/ARM-Assembly/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Hello-world-Newbie b/Lang/ARM-Assembly/Hello-world-Newbie new file mode 120000 index 0000000000..392e3633d0 --- /dev/null +++ b/Lang/ARM-Assembly/Hello-world-Newbie @@ -0,0 +1 @@ +../../Task/Hello-world-Newbie/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Hello-world-Standard-error b/Lang/ARM-Assembly/Hello-world-Standard-error new file mode 120000 index 0000000000..eef9ac0c48 --- /dev/null +++ b/Lang/ARM-Assembly/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/ARM-Assembly \ No newline at end of file diff --git a/Lang/ARM-Assembly/Program-name b/Lang/ARM-Assembly/Program-name new file mode 120000 index 0000000000..2c1166a109 --- /dev/null +++ b/Lang/ARM-Assembly/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/ARM-Assembly \ No newline at end of file diff --git a/Lang/ATS/FizzBuzz b/Lang/ATS/FizzBuzz new file mode 120000 index 0000000000..19e8cafa40 --- /dev/null +++ b/Lang/ATS/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/ATS \ No newline at end of file diff --git a/Lang/ATS/Sierpinski-triangle-Graphical b/Lang/ATS/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..2d377ce099 --- /dev/null +++ b/Lang/ATS/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/ATS \ No newline at end of file diff --git a/Lang/AWK/00DESCRIPTION b/Lang/AWK/00DESCRIPTION index fc87255dc6..1ae6ff2ef6 100644 --- a/Lang/AWK/00DESCRIPTION +++ b/Lang/AWK/00DESCRIPTION @@ -26,4 +26,7 @@ A few decades later, Kernighan continues to maintain the [[nawk|reference implem *[http://awk.info AWK Community Portal] ==Online-Execution== -* [http://ideone.com ideone.com] - gawk, mawk (both are kept up to date) \ No newline at end of file +* [http://ideone.com ideone.com] - gawk, mawk (both are kept up to date) + +==Todo== +[[Reports:Tasks_not_implemented_in_AWK]] \ No newline at end of file diff --git a/Lang/AWK/Dutch-national-flag-problem b/Lang/AWK/Dutch-national-flag-problem new file mode 120000 index 0000000000..76e5f4843e --- /dev/null +++ b/Lang/AWK/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/AWK \ No newline at end of file diff --git a/Lang/AWK/IBAN b/Lang/AWK/IBAN new file mode 120000 index 0000000000..800b2462ff --- /dev/null +++ b/Lang/AWK/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/AWK \ No newline at end of file diff --git a/Lang/AWK/Munching-squares b/Lang/AWK/Munching-squares new file mode 120000 index 0000000000..f394ff50fc --- /dev/null +++ b/Lang/AWK/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/AWK \ No newline at end of file diff --git a/Lang/AWK/Pernicious-numbers b/Lang/AWK/Pernicious-numbers new file mode 120000 index 0000000000..f2d4bf72c2 --- /dev/null +++ b/Lang/AWK/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/AWK \ No newline at end of file diff --git a/Lang/Ada/Amicable-pairs b/Lang/Ada/Amicable-pairs new file mode 120000 index 0000000000..9b4f5db61f --- /dev/null +++ b/Lang/Ada/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Ada \ No newline at end of file diff --git a/Lang/Ada/String-append b/Lang/Ada/String-append new file mode 120000 index 0000000000..71cebd719e --- /dev/null +++ b/Lang/Ada/String-append @@ -0,0 +1 @@ +../../Task/String-append/Ada \ No newline at end of file diff --git a/Lang/Ada/Sudoku b/Lang/Ada/Sudoku new file mode 120000 index 0000000000..8ec6313ff6 --- /dev/null +++ b/Lang/Ada/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Ada \ No newline at end of file diff --git a/Lang/Aime/Equilibrium-index b/Lang/Aime/Equilibrium-index new file mode 120000 index 0000000000..6f5a05fecd --- /dev/null +++ b/Lang/Aime/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/Aime \ No newline at end of file diff --git a/Lang/Aime/Letter-frequency b/Lang/Aime/Letter-frequency new file mode 120000 index 0000000000..8a0a089d6c --- /dev/null +++ b/Lang/Aime/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/Aime \ No newline at end of file diff --git a/Lang/Aime/Loops-Foreach b/Lang/Aime/Loops-Foreach new file mode 120000 index 0000000000..deac8788f1 --- /dev/null +++ b/Lang/Aime/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Aime \ No newline at end of file diff --git a/Lang/Aime/Make-directory-path b/Lang/Aime/Make-directory-path new file mode 120000 index 0000000000..b72558a499 --- /dev/null +++ b/Lang/Aime/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/Aime \ No newline at end of file diff --git a/Lang/Aime/Move-to-front-algorithm b/Lang/Aime/Move-to-front-algorithm new file mode 120000 index 0000000000..a0f1426c86 --- /dev/null +++ b/Lang/Aime/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Aime \ No newline at end of file diff --git a/Lang/Aime/Multifactorial b/Lang/Aime/Multifactorial new file mode 120000 index 0000000000..2b50618261 --- /dev/null +++ b/Lang/Aime/Multifactorial @@ -0,0 +1 @@ +../../Task/Multifactorial/Aime \ No newline at end of file diff --git a/Lang/Aime/Order-two-numerical-lists b/Lang/Aime/Order-two-numerical-lists new file mode 120000 index 0000000000..37c55e1ac2 --- /dev/null +++ b/Lang/Aime/Order-two-numerical-lists @@ -0,0 +1 @@ +../../Task/Order-two-numerical-lists/Aime \ No newline at end of file diff --git a/Lang/Aime/Remove-duplicate-elements b/Lang/Aime/Remove-duplicate-elements new file mode 120000 index 0000000000..46c4e4c3af --- /dev/null +++ b/Lang/Aime/Remove-duplicate-elements @@ -0,0 +1 @@ +../../Task/Remove-duplicate-elements/Aime \ No newline at end of file diff --git a/Lang/AppleScript/Mad-Libs b/Lang/AppleScript/Mad-Libs new file mode 120000 index 0000000000..8d3a1303ac --- /dev/null +++ b/Lang/AppleScript/Mad-Libs @@ -0,0 +1 @@ +../../Task/Mad-Libs/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Make-directory-path b/Lang/AppleScript/Make-directory-path new file mode 120000 index 0000000000..2b954bf4da --- /dev/null +++ b/Lang/AppleScript/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/AppleScript \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Caesar-cipher b/Lang/Applesoft-BASIC/Caesar-cipher new file mode 120000 index 0000000000..0b901c8862 --- /dev/null +++ b/Lang/Applesoft-BASIC/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Rot-13 b/Lang/Applesoft-BASIC/Rot-13 new file mode 120000 index 0000000000..c118346d5a --- /dev/null +++ b/Lang/Applesoft-BASIC/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Vigen-re-cipher b/Lang/Applesoft-BASIC/Vigen-re-cipher new file mode 120000 index 0000000000..73edf66d62 --- /dev/null +++ b/Lang/Applesoft-BASIC/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Astro/Sum-of-squares b/Lang/Astro/Sum-of-squares new file mode 120000 index 0000000000..ef65146ee4 --- /dev/null +++ b/Lang/Astro/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Astro \ No newline at end of file diff --git a/Lang/AutoIt/Anonymous-recursion b/Lang/AutoIt/Anonymous-recursion new file mode 120000 index 0000000000..8dd4c521d7 --- /dev/null +++ b/Lang/AutoIt/Anonymous-recursion @@ -0,0 +1 @@ +../../Task/Anonymous-recursion/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/Associative-array-Creation b/Lang/AutoIt/Associative-array-Creation new file mode 120000 index 0000000000..3f66564e53 --- /dev/null +++ b/Lang/AutoIt/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/Null-object b/Lang/AutoIt/Null-object new file mode 120000 index 0000000000..a7e32c1faf --- /dev/null +++ b/Lang/AutoIt/Null-object @@ -0,0 +1 @@ +../../Task/Null-object/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/Speech-synthesis b/Lang/AutoIt/Speech-synthesis new file mode 120000 index 0000000000..ad086eb5b0 --- /dev/null +++ b/Lang/AutoIt/Speech-synthesis @@ -0,0 +1 @@ +../../Task/Speech-synthesis/AutoIt \ No newline at end of file diff --git a/Lang/AutoIt/Temperature-conversion b/Lang/AutoIt/Temperature-conversion new file mode 120000 index 0000000000..3960e35582 --- /dev/null +++ b/Lang/AutoIt/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/AutoIt \ No newline at end of file diff --git a/Lang/BASIC/Animate-a-pendulum b/Lang/BASIC/Animate-a-pendulum new file mode 120000 index 0000000000..d3550214c8 --- /dev/null +++ b/Lang/BASIC/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Arithmetic-geometric-mean b/Lang/BASIC/Arithmetic-geometric-mean new file mode 120000 index 0000000000..2d2799ac0d --- /dev/null +++ b/Lang/BASIC/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Dot-product b/Lang/BASIC/Dot-product new file mode 120000 index 0000000000..5a469c2632 --- /dev/null +++ b/Lang/BASIC/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Draw-a-clock b/Lang/BASIC/Draw-a-clock new file mode 120000 index 0000000000..685a5d905c --- /dev/null +++ b/Lang/BASIC/Draw-a-clock @@ -0,0 +1 @@ +../../Task/Draw-a-clock/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Entropy b/Lang/BASIC/Entropy new file mode 120000 index 0000000000..78a5924f61 --- /dev/null +++ b/Lang/BASIC/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/BASIC \ No newline at end of file diff --git a/Lang/BASIC/FizzBuzz b/Lang/BASIC/FizzBuzz new file mode 120000 index 0000000000..306c9d57c0 --- /dev/null +++ b/Lang/BASIC/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Floyds-triangle b/Lang/BASIC/Floyds-triangle new file mode 120000 index 0000000000..d4146d3b72 --- /dev/null +++ b/Lang/BASIC/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Fractal-tree b/Lang/BASIC/Fractal-tree new file mode 120000 index 0000000000..e28161e067 --- /dev/null +++ b/Lang/BASIC/Fractal-tree @@ -0,0 +1 @@ +../../Task/Fractal-tree/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Josephus-problem b/Lang/BASIC/Josephus-problem new file mode 120000 index 0000000000..98f20f3d56 --- /dev/null +++ b/Lang/BASIC/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Magic-squares-of-odd-order b/Lang/BASIC/Magic-squares-of-odd-order new file mode 120000 index 0000000000..0ef57377fa --- /dev/null +++ b/Lang/BASIC/Magic-squares-of-odd-order @@ -0,0 +1 @@ +../../Task/Magic-squares-of-odd-order/BASIC \ No newline at end of file diff --git a/Lang/BASIC/Maze-generation b/Lang/BASIC/Maze-generation new file mode 120000 index 0000000000..30b47be5d7 --- /dev/null +++ b/Lang/BASIC/Maze-generation @@ -0,0 +1 @@ +../../Task/Maze-generation/BASIC \ No newline at end of file diff --git a/Lang/BASIC256/Conditional-structures b/Lang/BASIC256/Conditional-structures new file mode 120000 index 0000000000..dddc7350c9 --- /dev/null +++ b/Lang/BASIC256/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Look-and-say-sequence b/Lang/BASIC256/Look-and-say-sequence new file mode 120000 index 0000000000..1dec45a761 --- /dev/null +++ b/Lang/BASIC256/Look-and-say-sequence @@ -0,0 +1 @@ +../../Task/Look-and-say-sequence/BASIC256 \ No newline at end of file diff --git a/Lang/BASIC256/Sorting-algorithms-Counting-sort b/Lang/BASIC256/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..c35d7a1d16 --- /dev/null +++ b/Lang/BASIC256/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/BASIC256 \ No newline at end of file diff --git a/Lang/BBC-BASIC/Entropy b/Lang/BBC-BASIC/Entropy new file mode 120000 index 0000000000..14e54ab862 --- /dev/null +++ b/Lang/BBC-BASIC/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Josephus-problem b/Lang/BBC-BASIC/Josephus-problem new file mode 120000 index 0000000000..5c42548fcc --- /dev/null +++ b/Lang/BBC-BASIC/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/BBC-BASIC \ No newline at end of file diff --git a/Lang/BBC-BASIC/Multifactorial b/Lang/BBC-BASIC/Multifactorial new file mode 120000 index 0000000000..cf11148299 --- /dev/null +++ b/Lang/BBC-BASIC/Multifactorial @@ -0,0 +1 @@ +../../Task/Multifactorial/BBC-BASIC \ No newline at end of file diff --git a/Lang/BaCon/Align-columns b/Lang/BaCon/Align-columns new file mode 120000 index 0000000000..8c0f5e2de1 --- /dev/null +++ b/Lang/BaCon/Align-columns @@ -0,0 +1 @@ +../../Task/Align-columns/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Anagrams b/Lang/BaCon/Anagrams new file mode 120000 index 0000000000..4c26d2fddc --- /dev/null +++ b/Lang/BaCon/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Anagrams-Deranged-anagrams b/Lang/BaCon/Anagrams-Deranged-anagrams new file mode 120000 index 0000000000..315a077b55 --- /dev/null +++ b/Lang/BaCon/Anagrams-Deranged-anagrams @@ -0,0 +1 @@ +../../Task/Anagrams-Deranged-anagrams/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Averages-Median b/Lang/BaCon/Averages-Median new file mode 120000 index 0000000000..cb3d63a261 --- /dev/null +++ b/Lang/BaCon/Averages-Median @@ -0,0 +1 @@ +../../Task/Averages-Median/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Calendar b/Lang/BaCon/Calendar new file mode 120000 index 0000000000..2836322fed --- /dev/null +++ b/Lang/BaCon/Calendar @@ -0,0 +1 @@ +../../Task/Calendar/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Calendar---for-REAL-programmers b/Lang/BaCon/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..eb6a0c3315 --- /dev/null +++ b/Lang/BaCon/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Color-of-a-screen-pixel b/Lang/BaCon/Color-of-a-screen-pixel new file mode 120000 index 0000000000..0d5d280d79 --- /dev/null +++ b/Lang/BaCon/Color-of-a-screen-pixel @@ -0,0 +1 @@ +../../Task/Color-of-a-screen-pixel/BaCon \ No newline at end of file diff --git a/Lang/BaCon/LZW-compression b/Lang/BaCon/LZW-compression new file mode 120000 index 0000000000..7ce1ac910a --- /dev/null +++ b/Lang/BaCon/LZW-compression @@ -0,0 +1 @@ +../../Task/LZW-compression/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Last-letter-first-letter b/Lang/BaCon/Last-letter-first-letter new file mode 120000 index 0000000000..1bd0bed0f7 --- /dev/null +++ b/Lang/BaCon/Last-letter-first-letter @@ -0,0 +1 @@ +../../Task/Last-letter-first-letter/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Letter-frequency b/Lang/BaCon/Letter-frequency new file mode 120000 index 0000000000..4bbe5f0b27 --- /dev/null +++ b/Lang/BaCon/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/BaCon \ No newline at end of file diff --git a/Lang/BaCon/OpenGL b/Lang/BaCon/OpenGL new file mode 120000 index 0000000000..a3d4b95eb0 --- /dev/null +++ b/Lang/BaCon/OpenGL @@ -0,0 +1 @@ +../../Task/OpenGL/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Rename-a-file b/Lang/BaCon/Rename-a-file new file mode 120000 index 0000000000..c89251961d --- /dev/null +++ b/Lang/BaCon/Rename-a-file @@ -0,0 +1 @@ +../../Task/Rename-a-file/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Rep-string b/Lang/BaCon/Rep-string new file mode 120000 index 0000000000..5d54309910 --- /dev/null +++ b/Lang/BaCon/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Repeat-a-string b/Lang/BaCon/Repeat-a-string new file mode 120000 index 0000000000..a5a841c41d --- /dev/null +++ b/Lang/BaCon/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Run-length-encoding b/Lang/BaCon/Run-length-encoding new file mode 120000 index 0000000000..7a2f3f53ca --- /dev/null +++ b/Lang/BaCon/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/BaCon \ No newline at end of file diff --git a/Lang/BaCon/String-length b/Lang/BaCon/String-length new file mode 120000 index 0000000000..32a4a8e3f7 --- /dev/null +++ b/Lang/BaCon/String-length @@ -0,0 +1 @@ +../../Task/String-length/BaCon \ No newline at end of file diff --git a/Lang/BaCon/URL-decoding b/Lang/BaCon/URL-decoding new file mode 120000 index 0000000000..a5c1d3cdf1 --- /dev/null +++ b/Lang/BaCon/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/BaCon \ No newline at end of file diff --git a/Lang/BaCon/Unicode-variable-names b/Lang/BaCon/Unicode-variable-names new file mode 120000 index 0000000000..4ad64ca74f --- /dev/null +++ b/Lang/BaCon/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/BaCon \ No newline at end of file diff --git a/Lang/Batch-File/Maze-generation b/Lang/Batch-File/Maze-generation new file mode 120000 index 0000000000..7f77ef0764 --- /dev/null +++ b/Lang/Batch-File/Maze-generation @@ -0,0 +1 @@ +../../Task/Maze-generation/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Variadic-function b/Lang/Batch-File/Variadic-function new file mode 120000 index 0000000000..6112a50682 --- /dev/null +++ b/Lang/Batch-File/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Batch-File \ No newline at end of file diff --git a/Lang/Befunge/24-game b/Lang/Befunge/24-game new file mode 120000 index 0000000000..d8e25a6e18 --- /dev/null +++ b/Lang/Befunge/24-game @@ -0,0 +1 @@ +../../Task/24-game/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Bitwise-operations b/Lang/Befunge/Bitwise-operations new file mode 120000 index 0000000000..f6ae7d7231 --- /dev/null +++ b/Lang/Befunge/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Box-the-compass b/Lang/Befunge/Box-the-compass new file mode 120000 index 0000000000..37bf0a15f3 --- /dev/null +++ b/Lang/Befunge/Box-the-compass @@ -0,0 +1 @@ +../../Task/Box-the-compass/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Determine-if-a-string-is-numeric b/Lang/Befunge/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..b6df4fe5fd --- /dev/null +++ b/Lang/Befunge/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Hello-world-Newline-omission b/Lang/Befunge/Hello-world-Newline-omission new file mode 120000 index 0000000000..3cdb768c6a --- /dev/null +++ b/Lang/Befunge/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Luhn-test-of-credit-card-numbers b/Lang/Befunge/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..b4cd7a7a54 --- /dev/null +++ b/Lang/Befunge/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Sum-digits-of-an-integer b/Lang/Befunge/Sum-digits-of-an-integer new file mode 120000 index 0000000000..06ccd08572 --- /dev/null +++ b/Lang/Befunge/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Terminal-control-Preserve-screen b/Lang/Befunge/Terminal-control-Preserve-screen new file mode 120000 index 0000000000..8fa8e0cb60 --- /dev/null +++ b/Lang/Befunge/Terminal-control-Preserve-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Preserve-screen/Befunge \ No newline at end of file diff --git a/Lang/Befunge/Towers-of-Hanoi b/Lang/Befunge/Towers-of-Hanoi new file mode 120000 index 0000000000..11c9660989 --- /dev/null +++ b/Lang/Befunge/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Befunge \ No newline at end of file diff --git a/Lang/Bracmat/Move-to-front-algorithm b/Lang/Bracmat/Move-to-front-algorithm new file mode 120000 index 0000000000..d8cb46d0ab --- /dev/null +++ b/Lang/Bracmat/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Bracmat \ No newline at end of file diff --git a/Lang/Brainf---/Generate-lower-case-ASCII-alphabet b/Lang/Brainf---/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..bd1965655e --- /dev/null +++ b/Lang/Brainf---/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Brainf--- \ No newline at end of file diff --git a/Lang/C++/00DESCRIPTION b/Lang/C++/00DESCRIPTION index ee87626e06..98b9c95c62 100644 --- a/Lang/C++/00DESCRIPTION +++ b/Lang/C++/00DESCRIPTION @@ -24,7 +24,7 @@ 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''' (still currently called '''C++1z''') is a minor improvement to C++14 that has reached ''Draft International Standard'' [https://en.wikipedia.org/wiki/C++17] in March 2017, meaning publication is due very soon. 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#cxx14]. +* '''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] {{language programming paradigm|Imperative}} diff --git a/Lang/C++/Arbitrary-precision-integers--included- b/Lang/C++/Arbitrary-precision-integers--included- new file mode 120000 index 0000000000..efd64bac63 --- /dev/null +++ b/Lang/C++/Arbitrary-precision-integers--included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers--included-/C++ \ No newline at end of file diff --git a/Lang/C++/Average-loop-length b/Lang/C++/Average-loop-length new file mode 120000 index 0000000000..b9df2d286a --- /dev/null +++ b/Lang/C++/Average-loop-length @@ -0,0 +1 @@ +../../Task/Average-loop-length/C++ \ No newline at end of file diff --git a/Lang/C++/Bernoulli-numbers b/Lang/C++/Bernoulli-numbers new file mode 120000 index 0000000000..36dde32f70 --- /dev/null +++ b/Lang/C++/Bernoulli-numbers @@ -0,0 +1 @@ +../../Task/Bernoulli-numbers/C++ \ No newline at end of file diff --git a/Lang/C++/Hash-join b/Lang/C++/Hash-join new file mode 120000 index 0000000000..351cde22fa --- /dev/null +++ b/Lang/C++/Hash-join @@ -0,0 +1 @@ +../../Task/Hash-join/C++ \ No newline at end of file diff --git a/Lang/C++/Haversine-formula b/Lang/C++/Haversine-formula new file mode 120000 index 0000000000..682f56964d --- /dev/null +++ b/Lang/C++/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/C++ \ No newline at end of file diff --git a/Lang/C++/Order-disjoint-list-items b/Lang/C++/Order-disjoint-list-items new file mode 120000 index 0000000000..113843e1ed --- /dev/null +++ b/Lang/C++/Order-disjoint-list-items @@ -0,0 +1 @@ +../../Task/Order-disjoint-list-items/C++ \ No newline at end of file diff --git a/Lang/C++/Ordered-Partitions b/Lang/C++/Ordered-Partitions new file mode 120000 index 0000000000..4e34d986e0 --- /dev/null +++ b/Lang/C++/Ordered-Partitions @@ -0,0 +1 @@ +../../Task/Ordered-Partitions/C++ \ No newline at end of file diff --git a/Lang/C++/Pattern-matching b/Lang/C++/Pattern-matching new file mode 120000 index 0000000000..ccc6240ada --- /dev/null +++ b/Lang/C++/Pattern-matching @@ -0,0 +1 @@ +../../Task/Pattern-matching/C++ \ No newline at end of file diff --git a/Lang/C++/Soundex b/Lang/C++/Soundex new file mode 120000 index 0000000000..7be0cc2aa2 --- /dev/null +++ b/Lang/C++/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/C++ \ No newline at end of file diff --git a/Lang/C++/Topswops b/Lang/C++/Topswops new file mode 120000 index 0000000000..58400a0612 --- /dev/null +++ b/Lang/C++/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/C++ \ No newline at end of file diff --git a/Lang/C-sharp/Dynamic-variable-names b/Lang/C-sharp/Dynamic-variable-names new file mode 120000 index 0000000000..5f53e184fe --- /dev/null +++ b/Lang/C-sharp/Dynamic-variable-names @@ -0,0 +1 @@ +../../Task/Dynamic-variable-names/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Element-wise-operations b/Lang/C-sharp/Element-wise-operations new file mode 120000 index 0000000000..9b70526604 --- /dev/null +++ b/Lang/C-sharp/Element-wise-operations @@ -0,0 +1 @@ +../../Task/Element-wise-operations/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Fibonacci-word b/Lang/C-sharp/Fibonacci-word new file mode 120000 index 0000000000..03517dd9dc --- /dev/null +++ b/Lang/C-sharp/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Iterated-digits-squaring b/Lang/C-sharp/Iterated-digits-squaring new file mode 120000 index 0000000000..2f522a9679 --- /dev/null +++ b/Lang/C-sharp/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Modular-inverse b/Lang/C-sharp/Modular-inverse new file mode 120000 index 0000000000..4b42873623 --- /dev/null +++ b/Lang/C-sharp/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Topological-sort b/Lang/C-sharp/Topological-sort new file mode 120000 index 0000000000..10777111ee --- /dev/null +++ b/Lang/C-sharp/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/C-sharp \ No newline at end of file diff --git a/Lang/C/00DESCRIPTION b/Lang/C/00DESCRIPTION index a13bdf35b5..5e993cdf2a 100644 --- a/Lang/C/00DESCRIPTION +++ b/Lang/C/00DESCRIPTION @@ -27,4 +27,7 @@ C has since spread to many other [[:Category:Platforms|platforms]], and is now o ==Citation== *[[wp:C_%28programming_language%29|Wikipedia:C (programming language)]] +==Todo== +[[Reports:Tasks_not_implemented_in_C]] + {{language programming paradigm|Imperative}} \ No newline at end of file diff --git a/Lang/C/Aliquot-sequence-classifications b/Lang/C/Aliquot-sequence-classifications new file mode 120000 index 0000000000..a125530f66 --- /dev/null +++ b/Lang/C/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/C \ No newline at end of file diff --git a/Lang/C/Create-a-file-on-magnetic-tape b/Lang/C/Create-a-file-on-magnetic-tape new file mode 120000 index 0000000000..c03854c247 --- /dev/null +++ b/Lang/C/Create-a-file-on-magnetic-tape @@ -0,0 +1 @@ +../../Task/Create-a-file-on-magnetic-tape/C \ No newline at end of file diff --git a/Lang/C/Currying b/Lang/C/Currying new file mode 120000 index 0000000000..e24de5c226 --- /dev/null +++ b/Lang/C/Currying @@ -0,0 +1 @@ +../../Task/Currying/C \ No newline at end of file diff --git a/Lang/C/Deepcopy b/Lang/C/Deepcopy new file mode 120000 index 0000000000..72daea4641 --- /dev/null +++ b/Lang/C/Deepcopy @@ -0,0 +1 @@ +../../Task/Deepcopy/C \ No newline at end of file diff --git a/Lang/C/GUI-Maximum-window-dimensions b/Lang/C/GUI-Maximum-window-dimensions new file mode 120000 index 0000000000..9425dcf1de --- /dev/null +++ b/Lang/C/GUI-Maximum-window-dimensions @@ -0,0 +1 @@ +../../Task/GUI-Maximum-window-dimensions/C \ No newline at end of file diff --git a/Lang/C/Generate-Chess960-starting-position b/Lang/C/Generate-Chess960-starting-position new file mode 120000 index 0000000000..5aa6023849 --- /dev/null +++ b/Lang/C/Generate-Chess960-starting-position @@ -0,0 +1 @@ +../../Task/Generate-Chess960-starting-position/C \ No newline at end of file diff --git a/Lang/C/Here-document b/Lang/C/Here-document new file mode 120000 index 0000000000..7073b2683b --- /dev/null +++ b/Lang/C/Here-document @@ -0,0 +1 @@ +../../Task/Here-document/C \ No newline at end of file diff --git a/Lang/C/Heronian-triangles b/Lang/C/Heronian-triangles new file mode 120000 index 0000000000..b1a2e5ee90 --- /dev/null +++ b/Lang/C/Heronian-triangles @@ -0,0 +1 @@ +../../Task/Heronian-triangles/C \ No newline at end of file diff --git a/Lang/C/Parsing-RPN-to-infix-conversion b/Lang/C/Parsing-RPN-to-infix-conversion new file mode 120000 index 0000000000..006c84f03f --- /dev/null +++ b/Lang/C/Parsing-RPN-to-infix-conversion @@ -0,0 +1 @@ +../../Task/Parsing-RPN-to-infix-conversion/C \ No newline at end of file diff --git a/Lang/C/Permutations-by-swapping b/Lang/C/Permutations-by-swapping new file mode 120000 index 0000000000..8d975c12ad --- /dev/null +++ b/Lang/C/Permutations-by-swapping @@ -0,0 +1 @@ +../../Task/Permutations-by-swapping/C \ No newline at end of file diff --git a/Lang/C/Pragmatic-directives b/Lang/C/Pragmatic-directives new file mode 120000 index 0000000000..fb3e5b30a4 --- /dev/null +++ b/Lang/C/Pragmatic-directives @@ -0,0 +1 @@ +../../Task/Pragmatic-directives/C \ No newline at end of file diff --git a/Lang/C/Ranking-methods b/Lang/C/Ranking-methods new file mode 120000 index 0000000000..e9a43e7ca8 --- /dev/null +++ b/Lang/C/Ranking-methods @@ -0,0 +1 @@ +../../Task/Ranking-methods/C \ No newline at end of file diff --git a/Lang/C/Read-a-configuration-file b/Lang/C/Read-a-configuration-file new file mode 120000 index 0000000000..c1d308af0d --- /dev/null +++ b/Lang/C/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/C \ No newline at end of file diff --git a/Lang/C/SOAP b/Lang/C/SOAP new file mode 120000 index 0000000000..2fbd2cb7d3 --- /dev/null +++ b/Lang/C/SOAP @@ -0,0 +1 @@ +../../Task/SOAP/C \ No newline at end of file diff --git a/Lang/C/Send-email b/Lang/C/Send-email new file mode 120000 index 0000000000..5008079c00 --- /dev/null +++ b/Lang/C/Send-email @@ -0,0 +1 @@ +../../Task/Send-email/C \ No newline at end of file diff --git a/Lang/C/Simulate-input-Mouse b/Lang/C/Simulate-input-Mouse new file mode 120000 index 0000000000..e065bcb025 --- /dev/null +++ b/Lang/C/Simulate-input-Mouse @@ -0,0 +1 @@ +../../Task/Simulate-input-Mouse/C \ No newline at end of file diff --git a/Lang/C/Sparkline-in-unicode b/Lang/C/Sparkline-in-unicode new file mode 120000 index 0000000000..b013ffbe82 --- /dev/null +++ b/Lang/C/Sparkline-in-unicode @@ -0,0 +1 @@ +../../Task/Sparkline-in-unicode/C \ No newline at end of file diff --git a/Lang/C/Unicode-variable-names b/Lang/C/Unicode-variable-names new file mode 120000 index 0000000000..896386ef01 --- /dev/null +++ b/Lang/C/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/C \ No newline at end of file diff --git a/Lang/C/Vogels-approximation-method b/Lang/C/Vogels-approximation-method new file mode 120000 index 0000000000..83028ecafb --- /dev/null +++ b/Lang/C/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/C \ No newline at end of file diff --git a/Lang/C/Write-to-Windows-event-log b/Lang/C/Write-to-Windows-event-log new file mode 120000 index 0000000000..1db242acac --- /dev/null +++ b/Lang/C/Write-to-Windows-event-log @@ -0,0 +1 @@ +../../Task/Write-to-Windows-event-log/C \ No newline at end of file diff --git a/Lang/C/XML-XPath b/Lang/C/XML-XPath new file mode 120000 index 0000000000..a3da233bb1 --- /dev/null +++ b/Lang/C/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/C \ No newline at end of file diff --git a/Lang/C/Zhang-Suen-thinning-algorithm b/Lang/C/Zhang-Suen-thinning-algorithm new file mode 120000 index 0000000000..0bb4f0ab23 --- /dev/null +++ b/Lang/C/Zhang-Suen-thinning-algorithm @@ -0,0 +1 @@ +../../Task/Zhang-Suen-thinning-algorithm/C \ No newline at end of file diff --git a/Lang/COBOL/Constrained-random-points-on-a-circle b/Lang/COBOL/Constrained-random-points-on-a-circle new file mode 120000 index 0000000000..a6eea2da3f --- /dev/null +++ b/Lang/COBOL/Constrained-random-points-on-a-circle @@ -0,0 +1 @@ +../../Task/Constrained-random-points-on-a-circle/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Long-multiplication b/Lang/COBOL/Long-multiplication new file mode 120000 index 0000000000..580581d539 --- /dev/null +++ b/Lang/COBOL/Long-multiplication @@ -0,0 +1 @@ +../../Task/Long-multiplication/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Narcissistic-decimal-number b/Lang/COBOL/Narcissistic-decimal-number new file mode 120000 index 0000000000..611b262953 --- /dev/null +++ b/Lang/COBOL/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Write-float-arrays-to-a-text-file b/Lang/COBOL/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..da741da45a --- /dev/null +++ b/Lang/COBOL/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/COBOL \ No newline at end of file diff --git a/Lang/Ceylon/Arbitrary-precision-integers--included- b/Lang/Ceylon/Arbitrary-precision-integers--included- new file mode 120000 index 0000000000..2cec5eed79 --- /dev/null +++ b/Lang/Ceylon/Arbitrary-precision-integers--included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers--included-/Ceylon \ No newline at end of file diff --git a/Lang/Ceylon/Binary-digits b/Lang/Ceylon/Binary-digits new file mode 120000 index 0000000000..176789fce5 --- /dev/null +++ b/Lang/Ceylon/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Ceylon \ No newline at end of file diff --git a/Lang/Ceylon/Currying b/Lang/Ceylon/Currying new file mode 120000 index 0000000000..c8eeb94fa6 --- /dev/null +++ b/Lang/Ceylon/Currying @@ -0,0 +1 @@ +../../Task/Currying/Ceylon \ No newline at end of file diff --git a/Lang/Ceylon/Long-multiplication b/Lang/Ceylon/Long-multiplication new file mode 120000 index 0000000000..160e025dc1 --- /dev/null +++ b/Lang/Ceylon/Long-multiplication @@ -0,0 +1 @@ +../../Task/Long-multiplication/Ceylon \ No newline at end of file diff --git a/Lang/Ceylon/Look-and-say-sequence b/Lang/Ceylon/Look-and-say-sequence new file mode 120000 index 0000000000..d5cf2205ce --- /dev/null +++ b/Lang/Ceylon/Look-and-say-sequence @@ -0,0 +1 @@ +../../Task/Look-and-say-sequence/Ceylon \ No newline at end of file diff --git a/Lang/Ceylon/Minesweeper-game b/Lang/Ceylon/Minesweeper-game new file mode 120000 index 0000000000..7845318258 --- /dev/null +++ b/Lang/Ceylon/Minesweeper-game @@ -0,0 +1 @@ +../../Task/Minesweeper-game/Ceylon \ No newline at end of file diff --git a/Lang/Ceylon/Odd-word-problem b/Lang/Ceylon/Odd-word-problem new file mode 120000 index 0000000000..aad54bf69f --- /dev/null +++ b/Lang/Ceylon/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/Ceylon \ No newline at end of file diff --git a/Lang/Ceylon/Run-length-encoding b/Lang/Ceylon/Run-length-encoding new file mode 120000 index 0000000000..9a78c6bab6 --- /dev/null +++ b/Lang/Ceylon/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/Ceylon \ No newline at end of file diff --git a/Lang/Ceylon/Stable-marriage-problem b/Lang/Ceylon/Stable-marriage-problem new file mode 120000 index 0000000000..bbaa8b23a6 --- /dev/null +++ b/Lang/Ceylon/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/Ceylon \ No newline at end of file diff --git a/Lang/Ceylon/Top-rank-per-group b/Lang/Ceylon/Top-rank-per-group new file mode 120000 index 0000000000..68d20693e3 --- /dev/null +++ b/Lang/Ceylon/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Ceylon \ No newline at end of file diff --git a/Lang/Ceylon/Web-scraping b/Lang/Ceylon/Web-scraping new file mode 120000 index 0000000000..ba362aa408 --- /dev/null +++ b/Lang/Ceylon/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Ceylon \ No newline at end of file diff --git a/Lang/Clojure/Delegates b/Lang/Clojure/Delegates new file mode 120000 index 0000000000..3492c86c1a --- /dev/null +++ b/Lang/Clojure/Delegates @@ -0,0 +1 @@ +../../Task/Delegates/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Executable-library b/Lang/Clojure/Executable-library new file mode 120000 index 0000000000..239a3c17af --- /dev/null +++ b/Lang/Clojure/Executable-library @@ -0,0 +1 @@ +../../Task/Executable-library/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Hello-world-Line-printer b/Lang/Clojure/Hello-world-Line-printer new file mode 120000 index 0000000000..c3a2c7f7dd --- /dev/null +++ b/Lang/Clojure/Hello-world-Line-printer @@ -0,0 +1 @@ +../../Task/Hello-world-Line-printer/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Last-letter-first-letter b/Lang/Clojure/Last-letter-first-letter new file mode 120000 index 0000000000..f2fc0e13ca --- /dev/null +++ b/Lang/Clojure/Last-letter-first-letter @@ -0,0 +1 @@ +../../Task/Last-letter-first-letter/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Multiplicative-order b/Lang/Clojure/Multiplicative-order new file mode 120000 index 0000000000..49d350575b --- /dev/null +++ b/Lang/Clojure/Multiplicative-order @@ -0,0 +1 @@ +../../Task/Multiplicative-order/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Polynomial-long-division b/Lang/Clojure/Polynomial-long-division new file mode 120000 index 0000000000..bae0756118 --- /dev/null +++ b/Lang/Clojure/Polynomial-long-division @@ -0,0 +1 @@ +../../Task/Polynomial-long-division/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Range-extraction b/Lang/Clojure/Range-extraction new file mode 120000 index 0000000000..42acb89bee --- /dev/null +++ b/Lang/Clojure/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/Clojure \ No newline at end of file diff --git a/Lang/Clojure/SOAP b/Lang/Clojure/SOAP new file mode 120000 index 0000000000..b7ce43a661 --- /dev/null +++ b/Lang/Clojure/SOAP @@ -0,0 +1 @@ +../../Task/SOAP/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sorting-algorithms-Pancake-sort b/Lang/Clojure/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..4f3a5ee929 --- /dev/null +++ b/Lang/Clojure/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sorting-algorithms-Stooge-sort b/Lang/Clojure/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..d1720ae4e2 --- /dev/null +++ b/Lang/Clojure/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Textonyms b/Lang/Clojure/Textonyms new file mode 120000 index 0000000000..c62669594b --- /dev/null +++ b/Lang/Clojure/Textonyms @@ -0,0 +1 @@ +../../Task/Textonyms/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Truncate-a-file b/Lang/Clojure/Truncate-a-file new file mode 120000 index 0000000000..049d79f4fe --- /dev/null +++ b/Lang/Clojure/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Twelve-statements b/Lang/Clojure/Twelve-statements new file mode 120000 index 0000000000..43a020838a --- /dev/null +++ b/Lang/Clojure/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/Clojure \ No newline at end of file diff --git a/Lang/Commodore-BASIC/Pascals-triangle b/Lang/Commodore-BASIC/Pascals-triangle new file mode 120000 index 0000000000..f026fc09e2 --- /dev/null +++ b/Lang/Commodore-BASIC/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/Commodore-BASIC \ No newline at end of file diff --git a/Lang/Common-Lisp/Atomic-updates b/Lang/Common-Lisp/Atomic-updates new file mode 120000 index 0000000000..ea3adc6c81 --- /dev/null +++ b/Lang/Common-Lisp/Atomic-updates @@ -0,0 +1 @@ +../../Task/Atomic-updates/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Combinations-with-repetitions b/Lang/Common-Lisp/Combinations-with-repetitions new file mode 120000 index 0000000000..a5f9cb6826 --- /dev/null +++ b/Lang/Common-Lisp/Combinations-with-repetitions @@ -0,0 +1 @@ +../../Task/Combinations-with-repetitions/Common-Lisp \ No newline at end of file diff --git a/Lang/Crystal/99-Bottles-of-Beer b/Lang/Crystal/99-Bottles-of-Beer new file mode 120000 index 0000000000..95143b7ad4 --- /dev/null +++ b/Lang/Crystal/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Caesar-cipher b/Lang/Crystal/Caesar-cipher new file mode 120000 index 0000000000..5d5efb1170 --- /dev/null +++ b/Lang/Crystal/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Copy-a-string b/Lang/Crystal/Copy-a-string new file mode 120000 index 0000000000..a4cd28d8ba --- /dev/null +++ b/Lang/Crystal/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/Crystal \ No newline at end of file diff --git a/Lang/Crystal/DNS-query b/Lang/Crystal/DNS-query new file mode 120000 index 0000000000..ae572db62a --- /dev/null +++ b/Lang/Crystal/DNS-query @@ -0,0 +1 @@ +../../Task/DNS-query/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Generic-swap b/Lang/Crystal/Generic-swap new file mode 120000 index 0000000000..4b8fb7248a --- /dev/null +++ b/Lang/Crystal/Generic-swap @@ -0,0 +1 @@ +../../Task/Generic-swap/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Hello-world-Web-server b/Lang/Crystal/Hello-world-Web-server new file mode 120000 index 0000000000..157e3c09aa --- /dev/null +++ b/Lang/Crystal/Hello-world-Web-server @@ -0,0 +1 @@ +../../Task/Hello-world-Web-server/Crystal \ No newline at end of file diff --git a/Lang/Crystal/Sum-digits-of-an-integer b/Lang/Crystal/Sum-digits-of-an-integer new file mode 120000 index 0000000000..19fddd57f4 --- /dev/null +++ b/Lang/Crystal/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Crystal \ No newline at end of file diff --git a/Lang/D/00DESCRIPTION b/Lang/D/00DESCRIPTION index 4fad299405..47a40d28fb 100644 --- a/Lang/D/00DESCRIPTION +++ b/Lang/D/00DESCRIPTION @@ -14,7 +14,12 @@ {{language programming paradigm|object-oriented}} {{language programming paradigm|Functional}} {{language programming paradigm|generic}} -'''D''' is an [[object-oriented]], [[imperative programming|imperative]], multi-[[:Category:Programming Paradigms|paradigm]] systems programming language designed by Walter Bright of Digital Mars. Although it originated as a re-engineering of [[C++]], and is thus predominantly influenced by that language, it is not a variant of C++. Rather, D redesigns some C++ features and is influenced by concepts from other programming languages such as [[Python]], [[Java]], [[C sharp|C#]] and [[Eiffel]]. +'''D''' is an [[object-oriented]], [[imperative programming|imperative]], multi-[[:Category:Programming Paradigms|paradigm]] systems programming language designed by Walter Bright of Digital Mars. +Although it originated as a re-engineering of [[C++]], and is thus predominantly influenced by that language, it is not a variant of C++. +Rather, D redesigns some C++ features and is influenced by concepts from other programming languages such as [[Python]], [[Java]], [[C sharp|C#]] and [[Eiffel]]. ==Citations== -* [[wp:D (programming language)|Wikipedia:D (programming language)]] \ No newline at end of file +* [[wp:D (programming language)|Wikipedia:D (programming language)]] + +==Todo== +[[Reports:Tasks_not_implemented_in_D]] \ No newline at end of file diff --git a/Lang/D/Active-Directory-Connect b/Lang/D/Active-Directory-Connect new file mode 120000 index 0000000000..c8ce37058b --- /dev/null +++ b/Lang/D/Active-Directory-Connect @@ -0,0 +1 @@ +../../Task/Active-Directory-Connect/D \ No newline at end of file diff --git a/Lang/D/Active-Directory-Search-for-a-user b/Lang/D/Active-Directory-Search-for-a-user new file mode 120000 index 0000000000..01d51feca7 --- /dev/null +++ b/Lang/D/Active-Directory-Search-for-a-user @@ -0,0 +1 @@ +../../Task/Active-Directory-Search-for-a-user/D \ No newline at end of file diff --git a/Lang/D/Active-object b/Lang/D/Active-object new file mode 120000 index 0000000000..21bcabe13e --- /dev/null +++ b/Lang/D/Active-object @@ -0,0 +1 @@ +../../Task/Active-object/D \ No newline at end of file diff --git a/Lang/D/Append-a-record-to-the-end-of-a-text-file b/Lang/D/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..0b78605bcd --- /dev/null +++ b/Lang/D/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/D \ No newline at end of file diff --git a/Lang/D/Continued-fraction-Arithmetic-Construct-from-rational-number b/Lang/D/Continued-fraction-Arithmetic-Construct-from-rational-number new file mode 120000 index 0000000000..6d6311376a --- /dev/null +++ b/Lang/D/Continued-fraction-Arithmetic-Construct-from-rational-number @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-Construct-from-rational-number/D \ No newline at end of file diff --git a/Lang/D/Create-a-file-on-magnetic-tape b/Lang/D/Create-a-file-on-magnetic-tape new file mode 120000 index 0000000000..2b6186e20f --- /dev/null +++ b/Lang/D/Create-a-file-on-magnetic-tape @@ -0,0 +1 @@ +../../Task/Create-a-file-on-magnetic-tape/D \ No newline at end of file diff --git a/Lang/D/Date-manipulation b/Lang/D/Date-manipulation new file mode 120000 index 0000000000..c6eaa6e5ff --- /dev/null +++ b/Lang/D/Date-manipulation @@ -0,0 +1 @@ +../../Task/Date-manipulation/D \ No newline at end of file diff --git a/Lang/D/Fork b/Lang/D/Fork new file mode 120000 index 0000000000..97d5404f82 --- /dev/null +++ b/Lang/D/Fork @@ -0,0 +1 @@ +../../Task/Fork/D \ No newline at end of file diff --git a/Lang/D/Handle-a-signal b/Lang/D/Handle-a-signal new file mode 120000 index 0000000000..221e4145eb --- /dev/null +++ b/Lang/D/Handle-a-signal @@ -0,0 +1 @@ +../../Task/Handle-a-signal/D \ No newline at end of file diff --git a/Lang/D/I-before-E-except-after-C b/Lang/D/I-before-E-except-after-C new file mode 120000 index 0000000000..5cf99cd130 --- /dev/null +++ b/Lang/D/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/D \ No newline at end of file diff --git a/Lang/D/Inverted-syntax b/Lang/D/Inverted-syntax new file mode 120000 index 0000000000..e735a27074 --- /dev/null +++ b/Lang/D/Inverted-syntax @@ -0,0 +1 @@ +../../Task/Inverted-syntax/D \ No newline at end of file diff --git a/Lang/D/Make-directory-path b/Lang/D/Make-directory-path new file mode 120000 index 0000000000..6cecd5991c --- /dev/null +++ b/Lang/D/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/D \ No newline at end of file diff --git a/Lang/D/Narcissist b/Lang/D/Narcissist new file mode 120000 index 0000000000..ea790ee713 --- /dev/null +++ b/Lang/D/Narcissist @@ -0,0 +1 @@ +../../Task/Narcissist/D \ No newline at end of file diff --git a/Lang/D/Parsing-Shunting-yard-algorithm b/Lang/D/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..35605c1bea --- /dev/null +++ b/Lang/D/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/D \ No newline at end of file diff --git a/Lang/D/Polynomial-regression b/Lang/D/Polynomial-regression new file mode 120000 index 0000000000..a34ef8e913 --- /dev/null +++ b/Lang/D/Polynomial-regression @@ -0,0 +1 @@ +../../Task/Polynomial-regression/D \ No newline at end of file diff --git a/Lang/D/Random-number-generator--device- b/Lang/D/Random-number-generator--device- new file mode 120000 index 0000000000..71246e0896 --- /dev/null +++ b/Lang/D/Random-number-generator--device- @@ -0,0 +1 @@ +../../Task/Random-number-generator--device-/D \ No newline at end of file diff --git a/Lang/D/Ranking-methods b/Lang/D/Ranking-methods new file mode 120000 index 0000000000..dc940f50b9 --- /dev/null +++ b/Lang/D/Ranking-methods @@ -0,0 +1 @@ +../../Task/Ranking-methods/D \ No newline at end of file diff --git a/Lang/D/Rate-counter b/Lang/D/Rate-counter new file mode 120000 index 0000000000..99d13ddfc0 --- /dev/null +++ b/Lang/D/Rate-counter @@ -0,0 +1 @@ +../../Task/Rate-counter/D \ No newline at end of file diff --git a/Lang/D/Safe-addition b/Lang/D/Safe-addition new file mode 120000 index 0000000000..2e85c8db02 --- /dev/null +++ b/Lang/D/Safe-addition @@ -0,0 +1 @@ +../../Task/Safe-addition/D \ No newline at end of file diff --git a/Lang/D/Terminal-control-Cursor-positioning b/Lang/D/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..a6ac99ce78 --- /dev/null +++ b/Lang/D/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/D \ No newline at end of file diff --git a/Lang/D/Unicode-strings b/Lang/D/Unicode-strings new file mode 120000 index 0000000000..a23db9a6c9 --- /dev/null +++ b/Lang/D/Unicode-strings @@ -0,0 +1 @@ +../../Task/Unicode-strings/D \ No newline at end of file diff --git a/Lang/D/Write-to-Windows-event-log b/Lang/D/Write-to-Windows-event-log new file mode 120000 index 0000000000..e0b10d6c49 --- /dev/null +++ b/Lang/D/Write-to-Windows-event-log @@ -0,0 +1 @@ +../../Task/Write-to-Windows-event-log/D \ No newline at end of file diff --git a/Lang/D/Zeckendorf-arithmetic b/Lang/D/Zeckendorf-arithmetic new file mode 120000 index 0000000000..6b2da1e905 --- /dev/null +++ b/Lang/D/Zeckendorf-arithmetic @@ -0,0 +1 @@ +../../Task/Zeckendorf-arithmetic/D \ No newline at end of file diff --git a/Lang/DUP/Extend-your-language b/Lang/DUP/Extend-your-language new file mode 120000 index 0000000000..809c311758 --- /dev/null +++ b/Lang/DUP/Extend-your-language @@ -0,0 +1 @@ +../../Task/Extend-your-language/DUP \ No newline at end of file diff --git a/Lang/DUP/Generate-lower-case-ASCII-alphabet b/Lang/DUP/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..ad3a1c5a64 --- /dev/null +++ b/Lang/DUP/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/DUP \ No newline at end of file diff --git a/Lang/Dc/Zero-to-the-zero-power b/Lang/Dc/Zero-to-the-zero-power new file mode 120000 index 0000000000..a21d2ee882 --- /dev/null +++ b/Lang/Dc/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Dc \ No newline at end of file diff --git a/Lang/Delphi/00DESCRIPTION b/Lang/Delphi/00DESCRIPTION index 3e2f6ac4af..93461eb5b6 100644 --- a/Lang/Delphi/00DESCRIPTION +++ b/Lang/Delphi/00DESCRIPTION @@ -29,4 +29,7 @@ The Delphi XE2 version added support for 64-bit applications. It also added a cr ==See Also== * [[wp:Embarcadero Delphi|Delphi on Wikipedia]] * [http://www.embarcadero.com/products/delphi Delphi page at Embarcadero.com] -* [[wp:Oxygene (programming language)|Oxygene on Wikipedia]] \ No newline at end of file +* [[wp:Oxygene (programming language)|Oxygene on Wikipedia]] + +==Todo== +[[Reports:Tasks_not_implemented_in_Delphi]] \ No newline at end of file diff --git a/Lang/Delphi/Bitcoin-address-validation b/Lang/Delphi/Bitcoin-address-validation new file mode 120000 index 0000000000..3ed7f7e628 --- /dev/null +++ b/Lang/Delphi/Bitcoin-address-validation @@ -0,0 +1 @@ +../../Task/Bitcoin-address-validation/Delphi \ No newline at end of file diff --git a/Lang/Elena/00DESCRIPTION b/Lang/Elena/00DESCRIPTION index b909c1eb0a..77f6f39b97 100644 --- a/Lang/Elena/00DESCRIPTION +++ b/Lang/Elena/00DESCRIPTION @@ -9,232 +9,605 @@ |LCT=yes}} {{language programming paradigm|Object-oriented}}{{language programming paradigm|dynamic}} -== Overview == +ELENA is a general-purpose, object-oriented, polymorphic language with late binding. It features message dispatching/manipulation, dynamic object mutation, a script engine / interpreter and mix-ins. -ELENA is a general-purpose, object-oriented, polymorphic language with late binding. It features message dispatching / manipulation, dynamic object mutation, a script engine / interpreter and group object support. +== The simplest program == -Any program or library consists of modules containing classes and symbols. +To create a simple console program we have to declare the program symbol in the project root namespace: -The main way to interact with objects in ELENA is sending a message. The message name is structured and consists of a verb, a signature and a parameter counter. The verb defines a message action, for example read or write some data. There are only limited set of possible verbs. The signature is user defined and describes the message parameters. If the signature is not provided the message is considered to be generic and can be qualified (by dispatching). - -If the object wants to handle the message it has to contain the method with the same name. If no method mapping was found the flow is considered to be broken and the control goes to the next alternative flow (exception handler) or the program is stopped. It is possible to declare generic handler which will be called for all incoming messages. - -== Namespaces == - -Any ELENA program or library consists of modules (files with .NL extension) containing -classes and symbols. Every class or symbol may be referred by its namespace -(or to put it other way around a symbol namespace is a path to the symbol module). - -All source files (files with .L extension) located in the same folder are compiled into -the corresponding module. A project file (a file with .PRJ extension) defines the root -namespace and the output type (stand-alone executable, VM executable or a library). -The project may produce several modules if it contains the files located in sub folders -(the new module namespace consists of the root one plus the folder relative path) - -== Messaging == - -As in the most of dynamic object-oriented languages the main way to interact with objects in ELENA is sending a message. Unlike others the message name is structured and consists of a verb, a signature and a parameter counter. The verb defines a message action, for example read or write some data. There are only limited set of possible verbs (e.g. eval[uate], add, set, get, run, seek and so on). In general the signature is user defined and describes the message parameters. It can be used to define some custom -action as well (e.g. writeLine, which in fact is eval&writeLine(1)). If the signature is not provided the message is considered to be generic and can be qualified (for example by dispatching). - -If the object wants to handle the message it has to contain the method with the same name. If no method mapping was found the flow is considered to be broken and the control goes to the next alternative flow (exception handler) or the program is stopped. - -The simple code to send a message looks like this: - - console write:"Hello World". - -Note: "write" is a generic message; a literal constant is a parameter. - -Several messages can be send in one statement, the parameter itself may be result of object interactions: - - console write "2 + 2 =" write:(2 add:2). - -We could use operators to have the shorter code: - - console << "2+2=" << 2 + 2. - -Note: In most cases "<<" is a synonym to "write" and "+" to "add". - -Several parameters can be passed in the message as well: - - control foreach: (1,2,3) do:printingLn. - -The generic message can have several parameters as well: - - consoleEx writeLine:”a+b=”: (a + b). - - -== Classes, Roles and Symbols == - -ELENA is an object-oriented language, so to create a program we have to declare new classes. - -A class encapsulates data (fields) with code (methods) to access it. In most cases it is not possible to get a direct access to the class content (it makes sense for dynamic languages when in the most cases code is generic and can be applied for different "types"). Usually the fields refer to another classes and so on until we reach "primitive" ones which content are considered as raw data (e.g. numeric or literal values). - -To work with the class we have to create its instance with the help of the special methods - constructors. A constructor is used mostly to initialize the class fields. There are special type of classes which do not have fields and constructors and can be used directly (roles). - -Classes form the inheritance tree. There is the common super class - system'Object. -ELENA does not support multiple inheritance, though it is possible to inherit the code using redirect handler (so called "horizontal inheritance"). When the parent is not provided the class inherits directly system'Object (the super class). - - class BaseClass - { - object theField1. - object theField2. - - field1 = theField1. - - field2 = theField. - } - - class DerivedClass :: BaseClass - { - constructor new field1:aField2 field2:aField2 - [ - theField1 := aField1. - theField2 := aField2. - ] - - add field1:aField2 field2:aField2 - = MyClass new Field1:(theField1 + aField1) Field2:(theField2 + aField2). - } - -To create a class instance we have to send a message (usually new) to its symbol (a class symbol is declared implicitly for every class and can be used as a normal one) - - var anObject := DerivedClass new field1:1 field2:1. // DerivedClass is a symbol - -Singletons cannot have constructors and their symbols can be used directly - - class ClassHelper = - { - sumOf:a:b - = a add field1:b field2:a. - } - - ... - - var aSum := ClassHelper sumOf:1:2. - -In general the symbol is a named expression and can be used to declare initialized objects, constants, reusable expressions and so on. - - symbol ZeroClass = DerivedClass new field:0 field:0. - -A static symbol is the class instance which state is preserved. There could be only one instance of static symbol. - - static SingletonClass = DerivedClass new field:0 field:0. - -== Code blocks == - -ELENA code block consists of a sequence of statements. The block is enclosed in square brackets and may contain nested sub code blocks (which in fact are inline action classes). The statement terminator is a dot. - - printAckermann n:n m:m + public program = [ - control forrange int:0 int:n do: (&int:i) - [ - control forrange int:0 int:m do: (&int:j) - [ - ... - - console writeLine - ]. - ]. - ] - -When a method should return a result (other than self) return statement is used. It should be the last statement in the block. - - [ - ... - - ^ aRetVal / anArray length - ] - -If the code block contains only return statement the simplified syntax can be used: - - Number = convertor toReal:theValue. - -It is possible to declare the block variable and assigns the value to it. The variable name must be unique within the code block scope. - - var aRetVal := Integer new:0. - - -== Conditional branching == - -ELENA like Smalltalk does not support any special language constructs to implement the conditional branching. Instead special Boolean symbols (system’true and system’false) are used. All conditional operations should return these symbols as a result. - -There are three branching methods : if[1] , if[2], else[1] - - (m == 0) if: - [ - n + 1 - ] - : [ - m + n ]. -Note that code in square brackets are in fact nested action classes ( an action class is a class supporting evaluate message). So this code is can be written in this form: +Everything in ELENA is an object. To interact with it we have to send a message. The simplest (generic, i.e. without an explicit signature) message consists of an action and a parameter list. - (m == 0) if: +The statement should be terminated by a dot (ELENA is inspired by Smalltalk and uses its syntax notations). + + public program = + [ + console writeLine("Hello!"). + ]. + +In our example the action is writeLine and the parameter list consists of a single literal constant. The message target is console object (implementing input / output operations with a program console). + +Several message operations can be done in a single statement separated by a semicolon: + + public program = + [ + console writeLine("Hello!"); writeLine("How are you?"). + ]. + +The result will be: + + Hello! + How are you? + +We may read a user input by sending readLine message without parameters: + + public program = + [ + console write("What is your name:"); writeLine("Hello " + console readLine). + ]. + +The result will be: + + What is your name:Alex + Hello Alex + +Console::write method is similar to writeLine except that it writes to the output screen without a new line character. + +== Declaring a variable == + +A variable can be declared in an assignment statement starting with var attribute: + + var myVariable := "A text". + +where we declare a variable myVariable and initialize it with a literal constant value. + +The assigning value can be an expression itself: + + public program = + [ + console writeLine("Hello!"); writeLine("How are you?"). + var s := console readLine. + ]. + +ELENA is a dynamic language and in normal case we may not specify the variable type: + + public program = + [ + var s := "Hello". + console writeLine(s). + + s := 2. + console writeLine(s). + ]. + +The output will be: + + Hello + 2 + +But it is still possible to specify the variable expected type: + + T s := "Hello". + console writeLine(s). + +where system'LiteralValue is a class representing text as a sequence of UTF-8 characters. + +We may use a class alias to simplify the code: + + literal s := "Hello". // literal is a LiteralValue alias + console writeLine(s). + +Note that despite it we may still assign the objects of different types without a compile-time error: + + literal s := "Hello". + s := T(2). + +Why? ELENA is a dynamic language and in most cases resolves the types in run-time. So our code will be actually +compiled as follow: + + literal s := "Hello". + s := T(2) + +It is guaranteed that the result of the cast message is an instance of LiteralValue, so if the object supports the message the conversion will be done quietly. + +The output will be: + + system'RealNumber : Method $system'IntNumber not found + Call stack: + system'Exception#class.new$system'LiteralValue[1]:exceptions.l(125) + system'MethodNotFoundException#class.new$system'Object$system'Message[2]:exceptions.l(213) + system'#inline1BF.start[1]:win32_app.l(252) + mytest'program.#invoke[0]:test.l(5) + system'BaseFunction.eval[0]:control.l(172) + system'#inline1BF.start[1]:win32_app.l(37) + system'startUp(5) + +== Basic Types == + +=== The Boolean Type === + +Boolean type is used in conditional operations and may accept only two Boolean literals - true and false. + + import extensions. + + public program = + [ + bool b1 := true. + bool b2 := false. + + console printLine(b1,"==",b1," is ",b1==b1). + console printLine(b2,"==",b2," is ",b2==b2). + console printLine(b1,"==",b2," is ",b1==b2). + console printLine(b2,"==",b1," is ",b1==b2). + ]. + +Note that implicit extension method - extensions'outputOp.printLine[] - was used to simplify the output operations. + +The output is: + + true==true is true + false==false is true + true==false is false + false==true is false + +=== The Numeric types === + +The most used numeric types in ELENA are 32-bit signed integer number (represented by **IntNumber**), 64-bit signed integer number (represented by **LongNumber**) and 64-bit floating-point number (represented by **RealNumber**): + + import extensions. + + public rogram = + [ + int n := -234. + long l := 1235456765l. + real r := 2.3456r. + + console printLine("Integer number - ",n). + console printLine("Long integer number - ",l). + console printLine("Real number - ",r). + ]. + +The output is: + + Integer number - -234 + Long integer number - 1235456765 + Real number - 2.3456 + +=== The string type === + +LiteralValue is used to store the text encoded in UTF-8. LiteralValus is read-only collection of CharValue classes each representing UTF-32 symbol. Note that one character may be encoded with more than one byte! + + import extensions. + + public program = + [ + var s := "Hello". + + console printLine("The first character of ",s," is ", s[0]). + console printLine("The last character of ",s," is ", s[s length - 1]). + ]. + +The output is: + + The first character of Hello is H + The last character of Hello is o + +The same code for example with a Russian text will not work. Because every character is encoded with a two bytes and this should be taken into account. + + import extensions. + + public program = + [ + var s := "Привет". + + console printLine("The first character of ",s," is ", s[0]). + console printLine("The last character of ",s," is ", s[s length - 1]). + ]. + +The output is: + + The first character of Привет is П + An index is out of range + Call stack: + system'Exception#class.new$system'LiteralValue[1]:exceptions.l(125) + system'OutOfRangeException#class.new[0]:exceptions.l(149) + system'LiteralValue.getAt$system'IntNumber[1]:memory.l(1191) + mytest'program.#invoke[0]:test.l(8) + system'BaseFunction.eval[0]:control.l(172) + system'#inline1BF.start[1]:win32_app.l(37) + system'startUp(5) + +We may use another class representing UTF-16 text (WideLiteralValue) to solve this problem: + + import extensions. + + public program = + [ + var s := "Привет"w. // UTF-16 string + + console printLine("The first character of ",s," is ", s[0]). + console printLine("The last character of ",s," is ", s[s length - 1]). + ]. + +The output will be correct this time: + + The first character of Привет is П + The last character of Привет is т + +But this code will not work with Chinese text or any other requiring more than 2 bytes per symbol. So instead we may use enumerators: + + import system'routines. + import extensions. + + public program = + [ + var s := "Привет". + + console printLine("The first character of ",s," is ", s enumerator; firstMember). + console printLine("The last character of ",s," is ", s enumerator; lastMember). + ]. + +The output will be correct for any UTF-8 text: + + The first character of Привет is П + The last character of Привет is т + +=== Array type === + +It is possible to declare a dynamic or static array. + + import extensions. + + public program = + [ + var staticArray := (1,2,3). + var dynamicArray := Array new(3). + dynamicArray[0] := 1. + dynamicArray[1] := "b". + dynamicArray[2] := 2.3r. + + console printLine("static array ",staticArray). + console printLine("dynamic array ",dynamicArray). + ]. + +The output is: + + static array 1,2,3 + dynamic array 1,b,2.3 + +== Basic arithmetic operations == + +ELENA supports basic arithmetic operations with integer and floating-point numbers: + + import extensions. + + public program = + [ + var n1 := 12. + var n2 := 5. + var n3 := -3. + var r1 := 2.3r. + + console printLine(n1, " + ", n2, " = ", n1 + n2). + console printLine(n1, " - ", n2, " = ", n1 - n2). + console printLine(n1, " * ", n3, " = ", n1 * n3). + console printLine(n1, " / ", n2, " = ", n1 / n2). + + console printLine(n1, " + ", n2, " * ", r1 ," = ", n1 + n2 * r1). + ]. + +The result is: + + 12 + 5 = 17 + 12 - 5 = 7 + 12 * -3 = -36 + 12 / 5 = 2 + 12 + 5 * 2.3 = 23.5 + +== Conditions, Multi-select, Loops == + +Conditional statement in ELENA are defined as follows: + + if() + [ /* doSomething if TRUE*/ ]; + [ /*doSomehting if ELSE*/ ]. + +We could omit else part + + if() + [ /*doSomehting if TRUE*/ ]. + +Usually Boolean expression is a result of a comparison operation: + + public program = + [ + console writeLine("Hello!"); writeLine("How are you?"). + var s := console readLine. + if(s == "good") + [ console writeLine("Me too") ]; + [ console writeLine("What happends?") ] + ]. + +Several conditions can be checked: + + public program = + [ + console writeLine("Hello!"); writeLine("How are you?"). + var s := console readLine. + if((s == "good") || (s == "fine")) + [ console writeLine("Me too") ]; + [ console writeLine("What happens?") ] + ]. + +A switch statement can be implemented using => operator: + + public program = + [ + console writeLine("Hello!"); writeLine("How are you?"). + var s := console readLine. + s => + "good" [ console writeLine("Me too") ]; + "fine" [ console writeLine("Glad to hear") ]; + "bad" [ console writeLine("What's wrong?") ]; + "so so" [ console writeLine("It happens") ]; + ! [ console writeLine("What happens?") ]. + ]. + +We could declare *while* loop which will be repeated until the condition is true: + + public program = + [ + console writeLine("Hello!"); writeLine("Guess what?"). + var s := console readLine. + while (s != "nothing") + [ + console writeLine("Guess what?"). + s := console readLine + ] + ]. + +Alternatively *until* loop is executed until the condition is met : + + public program = + [ + console writeLine("Hello!"); writeLine("Guess what?"). + var s := console readLine. + until (s == "nothing") + [ + console writeLine("Guess what?"). + s := console readLine + ] + ]. + +== Classes, Fields Methods, Constructors == + +Everything in ELENA is a class. So to implement some tasks we will have to declare our own classes. + +=== Declaring a simple class === + +Let's create a simple class : + + import extensions. + + class MyClass { - eval - [ - ^ n + 1. - ] + // a field + literal myString. + + // a constructor + constructor new(literal s) + [ + myString := s. + ] + + // a method + printString + [ + console printLine(myString). + ] } - : { - eval - [ - ^ m + n. - ] - }. - -This expression can be written using special operators - - (m == 0) - ? [ ^n + 1 ] - ! [ ^m + n ]. - -Note: the main difference between using explicit messages and conditional operators is that the compiler may optimize the resulting code in the later case. - -We could omit true or else part - - (m == 0) - ! [ ^m / n ]. - -It is possible to use *if* template code : - - if (m == 0) - [ n := n + 1. ]; - [ n := m + n. ]. - -In this case the compiler always use optimized code for branching - -Boolean symbols supports basic logical operations (AND, OR, XOR and NOT), so several conditions can be checked - - if (aChar >= 48) and:(aChar < 58) + + public program = [ - theToken append:aChar. - ]; + // creating a class instance by sending new message to the class + var myClass := MyClass new("This is printed by my class."). + + myClass printString. + ]. + +The output will be: + + This is printed by my class. + +Note that in ELENA a class is an object itself and can be used by like any other object. + +=== Class Inheritance === + +We may inherit our class. When the parent is not explicitly declared - the class inherits system'Object super class + + import extensions. + + class MyParent + { + constructor new + [ + console printLine("Parent Constructor.") + ] + + print + [ + console printLine("I'm a Parent Class.") + ] + } + + class MyChild :: MyParent + { + + constructor new + <= new; // calling the parent constructor + [ + console printLine("Child Constructor.") + ] + + print + [ + // calling the parent method + super print. + + console printLine("I'm a Child Class.") + ] + } + + public program = [ - Exception new:"Invalid expression"; raise. - ] + var myClass := MyChild new. + + myClass print. + ]. -Note that in this case both condition will be evaluated even if the first one is false If we want to use short-circuit evaluation expression brackets should be used - if ((x >= 0)and:$(array@x != 0)) +The output is: + + Parent Constructor. + Child Constructor. + I'm a Parent Class. + I'm a Child Class. + +=== Private methods === + +It is possible to declare the private methods which cannot be called outside the class. + + import extensions. + + class MyClass + { + private printPrivate + [ + console printLine("private print.") + ] + + printPublic + [ + console print("Calling from public print - "). + + // $self is a reference to the current object + self printPrivate. + ] + } + + program = [ - ... - ] + // Note that if the constructor explicitly is not declared + // the system'Object one (without input parameters) is inherited + var myClass := MyClass new. + + myClass printPublic. + myClass printPrivate. + ]. + + The output is: -A switch statement can be implemented using => operator + Calling from public print - private print. + mytest'MyClass : Method mytest#printPrivate not found + Call stack: + system'Exception#class.new$system'LiteralValue[1]:exceptions.l(125) + system'MethodNotFoundException#class.new$system'Object$system'Message[2]:exceptions.l(213) + system'#inline1BF.start[1]:win32_app.l(252) + mytest'program.#invoke[0]:test.l(24) + system'BaseFunction.eval[0]:control.l(172) + system'#inline1BF.start[1]:win32_app.l(37) + system'startUp(5) - aBulls => - -1 [ consoleEx writeLine:"Not a valid guess.". ^ true ]; - 4 [ - consoleEx writeLine:"Congratulations! You have won!". - ^ false - ]; - ! [ - theAttempt append:1. - - consoleEx writeLine: - "Your Score is " : aBulls - : " bulls and " : aCows : " cows". - - ^ true - ]. \ No newline at end of file +=== Properties === + +In normal case the class fields cannot be accessed outside the class. That's why we may declare a special method to access it: + + import extensions. + + class MyClass + { + int _x. + + int x = _x. // get accessor + + set x(int o) // set accessor + [ + _x := o. + ] + } + + public program = + [ + var myClass := MyClass new. + + myClass x := 2. + + console printLine("MyClass.x=", myClass x). + ]. + +The output is: + + MyClass.x=2 + +We may simplify our code if we will use prop attribute: + + import extensions. + + class MyClass + { + int prop x :: _x. + } + + public program = + [ + var myClass := MyClass new. + + myClass x := 2. + + console printLine("MyClass.x=", myClass x). + ]. + +== Exception Handling == + +We may use try-catch statement to handle the possible exceptions: + + import extensions. + import system'io. + + public program = + [ + try(console printLine(File new("notexistingfile.txt"); content)) + { + on(Exception ex) + [ + console printLine("Unknown error - ",ex). + ] + + on(IOException ex) + [ + console printLine("I/O error - ",ex). + ] + } + ]. + +The output is : + + I/O error - Cannot open the file + Call stack: + system'Exception#class.new$system'LiteralValue[1]:exceptions.l(125) + system'io'IOException#class.new$system'LiteralValue[1]:io\ioexceptions.l(10)system'io'FileStream#class.new$system'WideLiteralValue$system'IntNumber$system'IntNumber$system'IntNumber$system'IntNmber[5]:io\win32_files.l(52) + system'io'FileStream#class.openForRead[1]:io\win32_files.l(29) + system'io'StreamReader#class.new[1]:io\win32_files.l(207) + system'io'fileControl.reader[1]:io\win32_files.l(269) + system'io'File.read$system'text'TextBuilder[1]:io\files.l(59) + system'io'File.content[0]:io\files.l(33) + mytest'program.#invoke[0]:test.l(6) + system'BaseFunction.eval[0]:control.l(172) + system'#inline1BF.start[1]:win32_app.l(37) + system'startUp(5) + +== See also == +* ELENA on [https://github.com/ELENA-LANG/elena-lang/ Github] +* ELENA on [https://www.reddit.com/r/elena_lang/ Reddit] \ No newline at end of file diff --git a/Lang/Elena/AKS-test-for-primes b/Lang/Elena/AKS-test-for-primes new file mode 120000 index 0000000000..fb3a3fa61b --- /dev/null +++ b/Lang/Elena/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/Elena \ No newline at end of file diff --git a/Lang/Elena/Abundant,-deficient-and-perfect-number-classifications b/Lang/Elena/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..20ef051b93 --- /dev/null +++ b/Lang/Elena/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/Elena \ No newline at end of file diff --git a/Lang/Elena/Amicable-pairs b/Lang/Elena/Amicable-pairs new file mode 120000 index 0000000000..c78a9492d7 --- /dev/null +++ b/Lang/Elena/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Elena \ No newline at end of file diff --git a/Lang/Elena/Averages-Root-mean-square b/Lang/Elena/Averages-Root-mean-square new file mode 120000 index 0000000000..5edb5cf0fe --- /dev/null +++ b/Lang/Elena/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/Elena \ No newline at end of file diff --git a/Lang/Elena/Call-a-function b/Lang/Elena/Call-a-function new file mode 120000 index 0000000000..27a70859b6 --- /dev/null +++ b/Lang/Elena/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/Elena \ No newline at end of file diff --git a/Lang/Elena/Compound-data-type b/Lang/Elena/Compound-data-type new file mode 120000 index 0000000000..73915f04d9 --- /dev/null +++ b/Lang/Elena/Compound-data-type @@ -0,0 +1 @@ +../../Task/Compound-data-type/Elena \ No newline at end of file diff --git a/Lang/Elena/Digital-root b/Lang/Elena/Digital-root new file mode 120000 index 0000000000..abe7a62168 --- /dev/null +++ b/Lang/Elena/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Elena \ No newline at end of file diff --git a/Lang/Elena/Dot-product b/Lang/Elena/Dot-product new file mode 120000 index 0000000000..a4f8c2f47b --- /dev/null +++ b/Lang/Elena/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/Elena \ No newline at end of file diff --git a/Lang/Elena/Equilibrium-index b/Lang/Elena/Equilibrium-index new file mode 120000 index 0000000000..213fa24d2e --- /dev/null +++ b/Lang/Elena/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/Elena \ No newline at end of file diff --git a/Lang/Elena/Exceptions-Catch-an-exception-thrown-in-a-nested-call b/Lang/Elena/Exceptions-Catch-an-exception-thrown-in-a-nested-call new file mode 120000 index 0000000000..69d95fbbb1 --- /dev/null +++ b/Lang/Elena/Exceptions-Catch-an-exception-thrown-in-a-nested-call @@ -0,0 +1 @@ +../../Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Elena \ No newline at end of file diff --git a/Lang/Elena/Fibonacci-sequence b/Lang/Elena/Fibonacci-sequence new file mode 120000 index 0000000000..347f56d184 --- /dev/null +++ b/Lang/Elena/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Elena \ No newline at end of file diff --git a/Lang/Elena/File-input-output b/Lang/Elena/File-input-output new file mode 120000 index 0000000000..64722ce9c9 --- /dev/null +++ b/Lang/Elena/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Elena \ No newline at end of file diff --git a/Lang/Elena/Filter b/Lang/Elena/Filter new file mode 120000 index 0000000000..bb7f587e75 --- /dev/null +++ b/Lang/Elena/Filter @@ -0,0 +1 @@ +../../Task/Filter/Elena \ No newline at end of file diff --git a/Lang/Elena/Generate-lower-case-ASCII-alphabet b/Lang/Elena/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..1ce0fcf558 --- /dev/null +++ b/Lang/Elena/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/Elena \ No newline at end of file diff --git a/Lang/Elena/Greatest-common-divisor b/Lang/Elena/Greatest-common-divisor new file mode 120000 index 0000000000..d99f95f9b0 --- /dev/null +++ b/Lang/Elena/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/Elena \ No newline at end of file diff --git a/Lang/Elena/Guess-the-number b/Lang/Elena/Guess-the-number new file mode 120000 index 0000000000..d152076bed --- /dev/null +++ b/Lang/Elena/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/Elena \ No newline at end of file diff --git a/Lang/Elena/Guess-the-number-With-feedback b/Lang/Elena/Guess-the-number-With-feedback new file mode 120000 index 0000000000..dc648aacdc --- /dev/null +++ b/Lang/Elena/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/Elena \ No newline at end of file diff --git a/Lang/Elena/Hailstone-sequence b/Lang/Elena/Hailstone-sequence new file mode 120000 index 0000000000..66ce6ef99d --- /dev/null +++ b/Lang/Elena/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Elena \ No newline at end of file diff --git a/Lang/Elena/Happy-numbers b/Lang/Elena/Happy-numbers new file mode 120000 index 0000000000..d2cac43708 --- /dev/null +++ b/Lang/Elena/Happy-numbers @@ -0,0 +1 @@ +../../Task/Happy-numbers/Elena \ No newline at end of file diff --git a/Lang/Elena/Haversine-formula b/Lang/Elena/Haversine-formula new file mode 120000 index 0000000000..a52111819d --- /dev/null +++ b/Lang/Elena/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/Elena \ No newline at end of file diff --git a/Lang/Elena/Hello-world-Newline-omission b/Lang/Elena/Hello-world-Newline-omission new file mode 120000 index 0000000000..5de6753a1b --- /dev/null +++ b/Lang/Elena/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Elena \ No newline at end of file diff --git a/Lang/Elena/Higher-order-functions b/Lang/Elena/Higher-order-functions new file mode 120000 index 0000000000..da07ad4447 --- /dev/null +++ b/Lang/Elena/Higher-order-functions @@ -0,0 +1 @@ +../../Task/Higher-order-functions/Elena \ No newline at end of file diff --git a/Lang/Elena/History-variables b/Lang/Elena/History-variables new file mode 120000 index 0000000000..f553495740 --- /dev/null +++ b/Lang/Elena/History-variables @@ -0,0 +1 @@ +../../Task/History-variables/Elena \ No newline at end of file diff --git a/Lang/Elena/Horners-rule-for-polynomial-evaluation b/Lang/Elena/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..e1453009f0 --- /dev/null +++ b/Lang/Elena/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/Elena \ No newline at end of file diff --git a/Lang/Elena/Increment-a-numerical-string b/Lang/Elena/Increment-a-numerical-string new file mode 120000 index 0000000000..5cc891cbab --- /dev/null +++ b/Lang/Elena/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/Elena \ No newline at end of file diff --git a/Lang/Elena/Integer-sequence b/Lang/Elena/Integer-sequence new file mode 120000 index 0000000000..8fc311c43b --- /dev/null +++ b/Lang/Elena/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/Elena \ No newline at end of file diff --git a/Lang/Elena/Keyboard-input-Keypress-check b/Lang/Elena/Keyboard-input-Keypress-check new file mode 120000 index 0000000000..1c0c33bf74 --- /dev/null +++ b/Lang/Elena/Keyboard-input-Keypress-check @@ -0,0 +1 @@ +../../Task/Keyboard-input-Keypress-check/Elena \ No newline at end of file diff --git a/Lang/Elena/Least-common-multiple b/Lang/Elena/Least-common-multiple new file mode 120000 index 0000000000..4da45f9d05 --- /dev/null +++ b/Lang/Elena/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/Elena \ No newline at end of file diff --git a/Lang/Elena/Literals-Floating-point b/Lang/Elena/Literals-Floating-point new file mode 120000 index 0000000000..42d75878ac --- /dev/null +++ b/Lang/Elena/Literals-Floating-point @@ -0,0 +1 @@ +../../Task/Literals-Floating-point/Elena \ No newline at end of file diff --git a/Lang/Elena/Logical-operations b/Lang/Elena/Logical-operations new file mode 120000 index 0000000000..911541f8f8 --- /dev/null +++ b/Lang/Elena/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/Elena \ No newline at end of file diff --git a/Lang/Elena/Maximum-triangle-path-sum b/Lang/Elena/Maximum-triangle-path-sum new file mode 120000 index 0000000000..debbe4a171 --- /dev/null +++ b/Lang/Elena/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/Elena \ No newline at end of file diff --git a/Lang/Elena/Middle-three-digits b/Lang/Elena/Middle-three-digits new file mode 120000 index 0000000000..1954b5f6de --- /dev/null +++ b/Lang/Elena/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Elena \ No newline at end of file diff --git a/Lang/Elena/Mutual-recursion b/Lang/Elena/Mutual-recursion new file mode 120000 index 0000000000..a3dae84f38 --- /dev/null +++ b/Lang/Elena/Mutual-recursion @@ -0,0 +1 @@ +../../Task/Mutual-recursion/Elena \ No newline at end of file diff --git a/Lang/Elena/Nth b/Lang/Elena/Nth new file mode 120000 index 0000000000..5edc12d3f0 --- /dev/null +++ b/Lang/Elena/Nth @@ -0,0 +1 @@ +../../Task/Nth/Elena \ No newline at end of file diff --git a/Lang/Elena/Phrase-reversals b/Lang/Elena/Phrase-reversals new file mode 120000 index 0000000000..766911f95f --- /dev/null +++ b/Lang/Elena/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Elena \ No newline at end of file diff --git a/Lang/Elena/Polymorphic-copy b/Lang/Elena/Polymorphic-copy new file mode 120000 index 0000000000..c8ad03f425 --- /dev/null +++ b/Lang/Elena/Polymorphic-copy @@ -0,0 +1 @@ +../../Task/Polymorphic-copy/Elena \ No newline at end of file diff --git a/Lang/Elena/Polymorphism b/Lang/Elena/Polymorphism new file mode 120000 index 0000000000..4728d00575 --- /dev/null +++ b/Lang/Elena/Polymorphism @@ -0,0 +1 @@ +../../Task/Polymorphism/Elena \ No newline at end of file diff --git a/Lang/Elena/Quaternion-type b/Lang/Elena/Quaternion-type new file mode 120000 index 0000000000..1637f784c6 --- /dev/null +++ b/Lang/Elena/Quaternion-type @@ -0,0 +1 @@ +../../Task/Quaternion-type/Elena \ No newline at end of file diff --git a/Lang/Elena/Queue-Definition b/Lang/Elena/Queue-Definition new file mode 120000 index 0000000000..add8def788 --- /dev/null +++ b/Lang/Elena/Queue-Definition @@ -0,0 +1 @@ +../../Task/Queue-Definition/Elena \ No newline at end of file diff --git a/Lang/Elena/Random-number-generator--included- b/Lang/Elena/Random-number-generator--included- new file mode 120000 index 0000000000..e16f4a0f99 --- /dev/null +++ b/Lang/Elena/Random-number-generator--included- @@ -0,0 +1 @@ +../../Task/Random-number-generator--included-/Elena \ No newline at end of file diff --git a/Lang/Elena/Random-numbers b/Lang/Elena/Random-numbers new file mode 120000 index 0000000000..98986fd8e6 --- /dev/null +++ b/Lang/Elena/Random-numbers @@ -0,0 +1 @@ +../../Task/Random-numbers/Elena \ No newline at end of file diff --git a/Lang/Elena/Remove-duplicate-elements b/Lang/Elena/Remove-duplicate-elements new file mode 120000 index 0000000000..11661f55bb --- /dev/null +++ b/Lang/Elena/Remove-duplicate-elements @@ -0,0 +1 @@ +../../Task/Remove-duplicate-elements/Elena \ No newline at end of file diff --git a/Lang/Elena/Roman-numerals-Decode b/Lang/Elena/Roman-numerals-Decode new file mode 120000 index 0000000000..10faad6057 --- /dev/null +++ b/Lang/Elena/Roman-numerals-Decode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Decode/Elena \ No newline at end of file diff --git a/Lang/Elena/Roman-numerals-Encode b/Lang/Elena/Roman-numerals-Encode new file mode 120000 index 0000000000..282590a63a --- /dev/null +++ b/Lang/Elena/Roman-numerals-Encode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Encode/Elena \ No newline at end of file diff --git a/Lang/Elena/Rot-13 b/Lang/Elena/Rot-13 new file mode 120000 index 0000000000..c4bc966f7b --- /dev/null +++ b/Lang/Elena/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/Elena \ No newline at end of file diff --git a/Lang/Elena/Run-length-encoding b/Lang/Elena/Run-length-encoding new file mode 120000 index 0000000000..8fa59827d2 --- /dev/null +++ b/Lang/Elena/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/Elena \ No newline at end of file diff --git a/Lang/Elena/Runtime-evaluation b/Lang/Elena/Runtime-evaluation new file mode 120000 index 0000000000..48b471b1a5 --- /dev/null +++ b/Lang/Elena/Runtime-evaluation @@ -0,0 +1 @@ +../../Task/Runtime-evaluation/Elena \ No newline at end of file diff --git a/Lang/Elena/Runtime-evaluation-In-an-environment b/Lang/Elena/Runtime-evaluation-In-an-environment new file mode 120000 index 0000000000..0d5ca49894 --- /dev/null +++ b/Lang/Elena/Runtime-evaluation-In-an-environment @@ -0,0 +1 @@ +../../Task/Runtime-evaluation-In-an-environment/Elena \ No newline at end of file diff --git a/Lang/Elena/Singly-linked-list-Element-definition b/Lang/Elena/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..c1e2ff1272 --- /dev/null +++ b/Lang/Elena/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Elena \ No newline at end of file diff --git a/Lang/Elena/Singly-linked-list-Element-insertion b/Lang/Elena/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..9c355349f7 --- /dev/null +++ b/Lang/Elena/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Elena \ No newline at end of file diff --git a/Lang/Elena/Singly-linked-list-Traversal b/Lang/Elena/Singly-linked-list-Traversal new file mode 120000 index 0000000000..43648dc4f6 --- /dev/null +++ b/Lang/Elena/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Elena \ No newline at end of file diff --git a/Lang/Elena/Sleep b/Lang/Elena/Sleep new file mode 120000 index 0000000000..6556c5a75b --- /dev/null +++ b/Lang/Elena/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Elena \ No newline at end of file diff --git a/Lang/Elena/Sockets b/Lang/Elena/Sockets new file mode 120000 index 0000000000..f5d1fd58ad --- /dev/null +++ b/Lang/Elena/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Elena \ No newline at end of file diff --git a/Lang/Elena/Sort-disjoint-sublist b/Lang/Elena/Sort-disjoint-sublist new file mode 120000 index 0000000000..141c382cc9 --- /dev/null +++ b/Lang/Elena/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Elena \ No newline at end of file diff --git a/Lang/Elena/Sort-using-a-custom-comparator b/Lang/Elena/Sort-using-a-custom-comparator new file mode 120000 index 0000000000..aca7f03509 --- /dev/null +++ b/Lang/Elena/Sort-using-a-custom-comparator @@ -0,0 +1 @@ +../../Task/Sort-using-a-custom-comparator/Elena \ No newline at end of file diff --git a/Lang/Elena/Sorting-algorithms-Bogosort b/Lang/Elena/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..e10ecfc8bd --- /dev/null +++ b/Lang/Elena/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Elena \ No newline at end of file diff --git a/Lang/Elena/Sorting-algorithms-Cocktail-sort b/Lang/Elena/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..fadd5a63d7 --- /dev/null +++ b/Lang/Elena/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Elena \ No newline at end of file diff --git a/Lang/Elena/Sorting-algorithms-Comb-sort b/Lang/Elena/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..a0794d76a0 --- /dev/null +++ b/Lang/Elena/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Elena \ No newline at end of file diff --git a/Lang/Elena/Sorting-algorithms-Counting-sort b/Lang/Elena/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..724318b299 --- /dev/null +++ b/Lang/Elena/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Elena \ No newline at end of file diff --git a/Lang/Elena/Sorting-algorithms-Gnome-sort b/Lang/Elena/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..af18654e0d --- /dev/null +++ b/Lang/Elena/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Elena \ No newline at end of file diff --git a/Lang/Elena/Sorting-algorithms-Insertion-sort b/Lang/Elena/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..94fa359cac --- /dev/null +++ b/Lang/Elena/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Elena \ No newline at end of file diff --git a/Lang/Elena/Sorting-algorithms-Pancake-sort b/Lang/Elena/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..f66b7ba9a2 --- /dev/null +++ b/Lang/Elena/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Elena \ No newline at end of file diff --git a/Lang/Elena/Sorting-algorithms-Quicksort b/Lang/Elena/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..df317dcdff --- /dev/null +++ b/Lang/Elena/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Elena \ No newline at end of file diff --git a/Lang/Elena/Sorting-algorithms-Selection-sort b/Lang/Elena/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..9eab2f739b --- /dev/null +++ b/Lang/Elena/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Elena \ No newline at end of file diff --git a/Lang/Elena/Sorting-algorithms-Sleep-sort b/Lang/Elena/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..e9c103c412 --- /dev/null +++ b/Lang/Elena/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Elena \ No newline at end of file diff --git a/Lang/Elena/Sorting-algorithms-Stooge-sort b/Lang/Elena/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..c5748b09f1 --- /dev/null +++ b/Lang/Elena/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Elena \ No newline at end of file diff --git a/Lang/Elena/Strip-a-set-of-characters-from-a-string b/Lang/Elena/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..7655cb364b --- /dev/null +++ b/Lang/Elena/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Elena \ No newline at end of file diff --git a/Lang/Elena/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Elena/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..51369a5785 --- /dev/null +++ b/Lang/Elena/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Elena \ No newline at end of file diff --git a/Lang/Elena/Substring-Top-and-tail b/Lang/Elena/Substring-Top-and-tail new file mode 120000 index 0000000000..f20e7ddc98 --- /dev/null +++ b/Lang/Elena/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Elena \ No newline at end of file diff --git a/Lang/Elena/System-time b/Lang/Elena/System-time new file mode 120000 index 0000000000..4d93f90cb7 --- /dev/null +++ b/Lang/Elena/System-time @@ -0,0 +1 @@ +../../Task/System-time/Elena \ No newline at end of file diff --git a/Lang/Elena/Temperature-conversion b/Lang/Elena/Temperature-conversion new file mode 120000 index 0000000000..d81bad9212 --- /dev/null +++ b/Lang/Elena/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Elena \ No newline at end of file diff --git a/Lang/Elena/Terminal-control-Clear-the-screen b/Lang/Elena/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..e7b75b8ef6 --- /dev/null +++ b/Lang/Elena/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Elena \ No newline at end of file diff --git a/Lang/Elena/Terminal-control-Cursor-positioning b/Lang/Elena/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..012ea06ded --- /dev/null +++ b/Lang/Elena/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/Elena \ No newline at end of file diff --git a/Lang/Elena/Ternary-logic b/Lang/Elena/Ternary-logic new file mode 120000 index 0000000000..18957378b6 --- /dev/null +++ b/Lang/Elena/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Elena \ No newline at end of file diff --git a/Lang/Elena/The-Twelve-Days-of-Christmas b/Lang/Elena/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..e4e78822c9 --- /dev/null +++ b/Lang/Elena/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Elena \ No newline at end of file diff --git a/Lang/Elena/Time-a-function b/Lang/Elena/Time-a-function new file mode 120000 index 0000000000..46456f9214 --- /dev/null +++ b/Lang/Elena/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Elena \ No newline at end of file diff --git a/Lang/Elena/Towers-of-Hanoi b/Lang/Elena/Towers-of-Hanoi new file mode 120000 index 0000000000..ba57d14b34 --- /dev/null +++ b/Lang/Elena/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Elena \ No newline at end of file diff --git a/Lang/Elena/Trabb-Pardo-Knuth-algorithm b/Lang/Elena/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..cad4823ef3 --- /dev/null +++ b/Lang/Elena/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Elena \ No newline at end of file diff --git a/Lang/Elena/Tree-traversal b/Lang/Elena/Tree-traversal new file mode 120000 index 0000000000..6790f62992 --- /dev/null +++ b/Lang/Elena/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/Elena \ No newline at end of file diff --git a/Lang/Elena/Unbias-a-random-generator b/Lang/Elena/Unbias-a-random-generator new file mode 120000 index 0000000000..429f75aa26 --- /dev/null +++ b/Lang/Elena/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/Elena \ No newline at end of file diff --git a/Lang/Elena/Vigen-re-cipher b/Lang/Elena/Vigen-re-cipher new file mode 120000 index 0000000000..20d7273251 --- /dev/null +++ b/Lang/Elena/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Elena \ No newline at end of file diff --git a/Lang/Elena/Wireworld b/Lang/Elena/Wireworld new file mode 120000 index 0000000000..6f50a3e357 --- /dev/null +++ b/Lang/Elena/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/Elena \ No newline at end of file diff --git a/Lang/Elena/World-Cup-group-stage b/Lang/Elena/World-Cup-group-stage new file mode 120000 index 0000000000..d19dfc43ea --- /dev/null +++ b/Lang/Elena/World-Cup-group-stage @@ -0,0 +1 @@ +../../Task/World-Cup-group-stage/Elena \ No newline at end of file diff --git a/Lang/Elixir/00DESCRIPTION b/Lang/Elixir/00DESCRIPTION index 7075e16e09..f1790862d2 100644 --- a/Lang/Elixir/00DESCRIPTION +++ b/Lang/Elixir/00DESCRIPTION @@ -2,6 +2,10 @@ {{language |site=http://elixir-lang.org}} {{implementation|Erlang}} +{{language programming paradigm|functional}} +{{language programming paradigm|concurrent}} +{{language programming paradigm|distributed}} +{{language programming paradigm|declarative}} Elixir is a dynamic, functional language designed for building scalable and maintainable applications. Elixir leverages the Erlang VM, known for running low-latency, distributed and fault-tolerant systems, while also being successfully used in web development and the embedded software domain. diff --git a/Lang/Elm/Y-combinator b/Lang/Elm/Y-combinator new file mode 120000 index 0000000000..3bfa309ef1 --- /dev/null +++ b/Lang/Elm/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Elm \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Loops-Infinite b/Lang/Emacs-Lisp/Loops-Infinite new file mode 120000 index 0000000000..4b344dd8dc --- /dev/null +++ b/Lang/Emacs-Lisp/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Erlang/Bitmap-Read-a-PPM-file b/Lang/Erlang/Bitmap-Read-a-PPM-file new file mode 120000 index 0000000000..bb73d81d18 --- /dev/null +++ b/Lang/Erlang/Bitmap-Read-a-PPM-file @@ -0,0 +1 @@ +../../Task/Bitmap-Read-a-PPM-file/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Bitmap-Write-a-PPM-file b/Lang/Erlang/Bitmap-Write-a-PPM-file new file mode 120000 index 0000000000..f0dd896c63 --- /dev/null +++ b/Lang/Erlang/Bitmap-Write-a-PPM-file @@ -0,0 +1 @@ +../../Task/Bitmap-Write-a-PPM-file/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Kaprekar-numbers b/Lang/Erlang/Kaprekar-numbers new file mode 120000 index 0000000000..ab15c31ad0 --- /dev/null +++ b/Lang/Erlang/Kaprekar-numbers @@ -0,0 +1 @@ +../../Task/Kaprekar-numbers/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Sierpinski-triangle-Graphical b/Lang/Erlang/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..5d0ce50ee0 --- /dev/null +++ b/Lang/Erlang/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Unix-ls b/Lang/Erlang/Unix-ls new file mode 120000 index 0000000000..4e0bc3e28e --- /dev/null +++ b/Lang/Erlang/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/Erlang \ No newline at end of file diff --git a/Lang/Euphoria/00DESCRIPTION b/Lang/Euphoria/00DESCRIPTION index bcb9823ab8..702dca9e88 100644 --- a/Lang/Euphoria/00DESCRIPTION +++ b/Lang/Euphoria/00DESCRIPTION @@ -1,4 +1,3 @@ -{{Stub}} {{language |exec=interpreted |site=http://www.openeuphoria.org/ diff --git a/Lang/Excel/100-doors b/Lang/Excel/100-doors new file mode 120000 index 0000000000..918198d750 --- /dev/null +++ b/Lang/Excel/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Excel \ No newline at end of file diff --git a/Lang/Factor/00DESCRIPTION b/Lang/Factor/00DESCRIPTION index a16654ee74..cf632a703e 100644 --- a/Lang/Factor/00DESCRIPTION +++ b/Lang/Factor/00DESCRIPTION @@ -14,6 +14,7 @@ Factor is a stack language similar to, but of a higher level than, [[Forth]]. ==Links== +*[http://factorcode.org Factor programming language] *[http://planet.factorcode.org Planet Factor] {{Language programming paradigm|Concatenative}} \ No newline at end of file diff --git a/Lang/Factor/24-game-Solve b/Lang/Factor/24-game-Solve new file mode 120000 index 0000000000..1d1b5fc5f5 --- /dev/null +++ b/Lang/Factor/24-game-Solve @@ -0,0 +1 @@ +../../Task/24-game-Solve/Factor \ No newline at end of file diff --git a/Lang/Factor/Abundant,-deficient-and-perfect-number-classifications b/Lang/Factor/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..d781a62a97 --- /dev/null +++ b/Lang/Factor/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/Factor \ No newline at end of file diff --git a/Lang/Factor/Almost-prime b/Lang/Factor/Almost-prime new file mode 120000 index 0000000000..505ceebd4d --- /dev/null +++ b/Lang/Factor/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Factor \ No newline at end of file diff --git a/Lang/Factor/Amicable-pairs b/Lang/Factor/Amicable-pairs new file mode 120000 index 0000000000..2b98053366 --- /dev/null +++ b/Lang/Factor/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/Factor \ No newline at end of file diff --git a/Lang/Factor/Arithmetic-Rational b/Lang/Factor/Arithmetic-Rational new file mode 120000 index 0000000000..9c03a2a883 --- /dev/null +++ b/Lang/Factor/Arithmetic-Rational @@ -0,0 +1 @@ +../../Task/Arithmetic-Rational/Factor \ No newline at end of file diff --git a/Lang/Factor/Arithmetic-geometric-mean b/Lang/Factor/Arithmetic-geometric-mean new file mode 120000 index 0000000000..8e907a5f0c --- /dev/null +++ b/Lang/Factor/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Factor \ No newline at end of file diff --git a/Lang/Factor/Benfords-law b/Lang/Factor/Benfords-law new file mode 120000 index 0000000000..cb207052e2 --- /dev/null +++ b/Lang/Factor/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Factor \ No newline at end of file diff --git a/Lang/Factor/CSV-data-manipulation b/Lang/Factor/CSV-data-manipulation new file mode 120000 index 0000000000..f581708483 --- /dev/null +++ b/Lang/Factor/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Factor \ No newline at end of file diff --git a/Lang/Factor/CSV-to-HTML-translation b/Lang/Factor/CSV-to-HTML-translation new file mode 120000 index 0000000000..d9132a08c6 --- /dev/null +++ b/Lang/Factor/CSV-to-HTML-translation @@ -0,0 +1 @@ +../../Task/CSV-to-HTML-translation/Factor \ No newline at end of file diff --git a/Lang/Factor/Caesar-cipher b/Lang/Factor/Caesar-cipher new file mode 120000 index 0000000000..24d872b06d --- /dev/null +++ b/Lang/Factor/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Factor \ No newline at end of file diff --git a/Lang/Factor/Call-a-function b/Lang/Factor/Call-a-function new file mode 120000 index 0000000000..bff01f5bc8 --- /dev/null +++ b/Lang/Factor/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/Factor \ No newline at end of file diff --git a/Lang/Factor/Case-sensitivity-of-identifiers b/Lang/Factor/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..272d59b6d0 --- /dev/null +++ b/Lang/Factor/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/Factor \ No newline at end of file diff --git a/Lang/Factor/Catalan-numbers-Pascals-triangle b/Lang/Factor/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..93fd8312b2 --- /dev/null +++ b/Lang/Factor/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Factor \ No newline at end of file diff --git a/Lang/Factor/Catamorphism b/Lang/Factor/Catamorphism new file mode 120000 index 0000000000..faa7226e8a --- /dev/null +++ b/Lang/Factor/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Factor \ No newline at end of file diff --git a/Lang/Factor/Chinese-remainder-theorem b/Lang/Factor/Chinese-remainder-theorem new file mode 120000 index 0000000000..5577440707 --- /dev/null +++ b/Lang/Factor/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/Factor \ No newline at end of file diff --git a/Lang/Factor/Comma-quibbling b/Lang/Factor/Comma-quibbling new file mode 120000 index 0000000000..667f886931 --- /dev/null +++ b/Lang/Factor/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Factor \ No newline at end of file diff --git a/Lang/Factor/Convert-decimal-number-to-rational b/Lang/Factor/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..1a44637e0d --- /dev/null +++ b/Lang/Factor/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/Factor \ No newline at end of file diff --git a/Lang/Factor/Count-in-factors b/Lang/Factor/Count-in-factors new file mode 120000 index 0000000000..f609f6a418 --- /dev/null +++ b/Lang/Factor/Count-in-factors @@ -0,0 +1 @@ +../../Task/Count-in-factors/Factor \ No newline at end of file diff --git a/Lang/Factor/Count-in-octal b/Lang/Factor/Count-in-octal new file mode 120000 index 0000000000..8b1a683668 --- /dev/null +++ b/Lang/Factor/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/Factor \ No newline at end of file diff --git a/Lang/Factor/Currying b/Lang/Factor/Currying new file mode 120000 index 0000000000..c9c0c7abd8 --- /dev/null +++ b/Lang/Factor/Currying @@ -0,0 +1 @@ +../../Task/Currying/Factor \ No newline at end of file diff --git a/Lang/Factor/Digital-root b/Lang/Factor/Digital-root new file mode 120000 index 0000000000..b5ce0fa33f --- /dev/null +++ b/Lang/Factor/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Factor \ No newline at end of file diff --git a/Lang/Factor/Digital-root-Multiplicative-digital-root b/Lang/Factor/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..ecf62170cd --- /dev/null +++ b/Lang/Factor/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/Factor \ No newline at end of file diff --git a/Lang/Factor/Dynamic-variable-names b/Lang/Factor/Dynamic-variable-names new file mode 120000 index 0000000000..14b4d33f85 --- /dev/null +++ b/Lang/Factor/Dynamic-variable-names @@ -0,0 +1 @@ +../../Task/Dynamic-variable-names/Factor \ No newline at end of file diff --git a/Lang/Factor/Empty-directory b/Lang/Factor/Empty-directory new file mode 120000 index 0000000000..2d0c06754e --- /dev/null +++ b/Lang/Factor/Empty-directory @@ -0,0 +1 @@ +../../Task/Empty-directory/Factor \ No newline at end of file diff --git a/Lang/Factor/Empty-string b/Lang/Factor/Empty-string new file mode 120000 index 0000000000..6dc23df6da --- /dev/null +++ b/Lang/Factor/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Factor \ No newline at end of file diff --git a/Lang/Factor/Enforced-immutability b/Lang/Factor/Enforced-immutability new file mode 120000 index 0000000000..285c9755ae --- /dev/null +++ b/Lang/Factor/Enforced-immutability @@ -0,0 +1 @@ +../../Task/Enforced-immutability/Factor \ No newline at end of file diff --git a/Lang/Factor/Entropy b/Lang/Factor/Entropy new file mode 120000 index 0000000000..d4df8534d4 --- /dev/null +++ b/Lang/Factor/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Factor \ No newline at end of file diff --git a/Lang/Factor/Enumerations b/Lang/Factor/Enumerations new file mode 120000 index 0000000000..49f8e30e22 --- /dev/null +++ b/Lang/Factor/Enumerations @@ -0,0 +1 @@ +../../Task/Enumerations/Factor \ No newline at end of file diff --git a/Lang/Factor/Evolutionary-algorithm b/Lang/Factor/Evolutionary-algorithm new file mode 120000 index 0000000000..0dcf6ab7bb --- /dev/null +++ b/Lang/Factor/Evolutionary-algorithm @@ -0,0 +1 @@ +../../Task/Evolutionary-algorithm/Factor \ No newline at end of file diff --git a/Lang/Factor/Extreme-floating-point-values b/Lang/Factor/Extreme-floating-point-values new file mode 120000 index 0000000000..7d1bdcfd7d --- /dev/null +++ b/Lang/Factor/Extreme-floating-point-values @@ -0,0 +1 @@ +../../Task/Extreme-floating-point-values/Factor \ No newline at end of file diff --git a/Lang/Factor/Fibonacci-word b/Lang/Factor/Fibonacci-word new file mode 120000 index 0000000000..2eb28d9c59 --- /dev/null +++ b/Lang/Factor/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Factor \ No newline at end of file diff --git a/Lang/Factor/Find-the-last-Sunday-of-each-month b/Lang/Factor/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..3fdadbd9ca --- /dev/null +++ b/Lang/Factor/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Factor \ No newline at end of file diff --git a/Lang/Factor/Find-the-missing-permutation b/Lang/Factor/Find-the-missing-permutation new file mode 120000 index 0000000000..eee1d917a0 --- /dev/null +++ b/Lang/Factor/Find-the-missing-permutation @@ -0,0 +1 @@ +../../Task/Find-the-missing-permutation/Factor \ No newline at end of file diff --git a/Lang/Factor/Five-weekends b/Lang/Factor/Five-weekends new file mode 120000 index 0000000000..6cdcbe891f --- /dev/null +++ b/Lang/Factor/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/Factor \ No newline at end of file diff --git a/Lang/Factor/Formatted-numeric-output b/Lang/Factor/Formatted-numeric-output new file mode 120000 index 0000000000..f01fbadcb0 --- /dev/null +++ b/Lang/Factor/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/Factor \ No newline at end of file diff --git a/Lang/Factor/Harshad-or-Niven-series b/Lang/Factor/Harshad-or-Niven-series new file mode 120000 index 0000000000..a45ce72e41 --- /dev/null +++ b/Lang/Factor/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/Factor \ No newline at end of file diff --git a/Lang/Factor/I-before-E-except-after-C b/Lang/Factor/I-before-E-except-after-C new file mode 120000 index 0000000000..24221bdef5 --- /dev/null +++ b/Lang/Factor/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Factor \ No newline at end of file diff --git a/Lang/Factor/Inverted-syntax b/Lang/Factor/Inverted-syntax new file mode 120000 index 0000000000..275676ec83 --- /dev/null +++ b/Lang/Factor/Inverted-syntax @@ -0,0 +1 @@ +../../Task/Inverted-syntax/Factor \ No newline at end of file diff --git a/Lang/Factor/Iterated-digits-squaring b/Lang/Factor/Iterated-digits-squaring new file mode 120000 index 0000000000..26c0fe8c24 --- /dev/null +++ b/Lang/Factor/Iterated-digits-squaring @@ -0,0 +1 @@ +../../Task/Iterated-digits-squaring/Factor \ No newline at end of file diff --git a/Lang/Factor/Kaprekar-numbers b/Lang/Factor/Kaprekar-numbers new file mode 120000 index 0000000000..26b72aa32b --- /dev/null +++ b/Lang/Factor/Kaprekar-numbers @@ -0,0 +1 @@ +../../Task/Kaprekar-numbers/Factor \ No newline at end of file diff --git a/Lang/Factor/Largest-int-from-concatenated-ints b/Lang/Factor/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..015fb1d837 --- /dev/null +++ b/Lang/Factor/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/Factor \ No newline at end of file diff --git a/Lang/Factor/Last-Friday-of-each-month b/Lang/Factor/Last-Friday-of-each-month new file mode 120000 index 0000000000..05e5152e4f --- /dev/null +++ b/Lang/Factor/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/Factor \ No newline at end of file diff --git a/Lang/Factor/Left-factorials b/Lang/Factor/Left-factorials new file mode 120000 index 0000000000..e4e59d35cd --- /dev/null +++ b/Lang/Factor/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/Factor \ No newline at end of file diff --git a/Lang/Factor/Levenshtein-distance b/Lang/Factor/Levenshtein-distance new file mode 120000 index 0000000000..f97c7fbe3f --- /dev/null +++ b/Lang/Factor/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Factor \ No newline at end of file diff --git a/Lang/Factor/Literals-Integer b/Lang/Factor/Literals-Integer new file mode 120000 index 0000000000..258af4c75b --- /dev/null +++ b/Lang/Factor/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/Factor \ No newline at end of file diff --git a/Lang/Factor/Loops-Nested b/Lang/Factor/Loops-Nested new file mode 120000 index 0000000000..20596aa970 --- /dev/null +++ b/Lang/Factor/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/Factor \ No newline at end of file diff --git a/Lang/Factor/Middle-three-digits b/Lang/Factor/Middle-three-digits new file mode 120000 index 0000000000..280fd218c9 --- /dev/null +++ b/Lang/Factor/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Factor \ No newline at end of file diff --git a/Lang/Factor/Modular-inverse b/Lang/Factor/Modular-inverse new file mode 120000 index 0000000000..9296475a05 --- /dev/null +++ b/Lang/Factor/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/Factor \ No newline at end of file diff --git a/Lang/Factor/Multifactorial b/Lang/Factor/Multifactorial new file mode 120000 index 0000000000..a5c5f060ff --- /dev/null +++ b/Lang/Factor/Multifactorial @@ -0,0 +1 @@ +../../Task/Multifactorial/Factor \ No newline at end of file diff --git a/Lang/Factor/Munching-squares b/Lang/Factor/Munching-squares new file mode 120000 index 0000000000..6236081d58 --- /dev/null +++ b/Lang/Factor/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Factor \ No newline at end of file diff --git a/Lang/Factor/Narcissistic-decimal-number b/Lang/Factor/Narcissistic-decimal-number new file mode 120000 index 0000000000..175171c34d --- /dev/null +++ b/Lang/Factor/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Factor \ No newline at end of file diff --git a/Lang/Factor/Parsing-RPN-calculator-algorithm b/Lang/Factor/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..82808465b9 --- /dev/null +++ b/Lang/Factor/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/Factor \ No newline at end of file diff --git a/Lang/Factor/Partial-function-application b/Lang/Factor/Partial-function-application new file mode 120000 index 0000000000..4bd1bfdd00 --- /dev/null +++ b/Lang/Factor/Partial-function-application @@ -0,0 +1 @@ +../../Task/Partial-function-application/Factor \ No newline at end of file diff --git a/Lang/Factor/Penneys-game b/Lang/Factor/Penneys-game new file mode 120000 index 0000000000..af6b8b0b25 --- /dev/null +++ b/Lang/Factor/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/Factor \ No newline at end of file diff --git a/Lang/Factor/Pernicious-numbers b/Lang/Factor/Pernicious-numbers new file mode 120000 index 0000000000..d7a95aae4b --- /dev/null +++ b/Lang/Factor/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Factor \ No newline at end of file diff --git a/Lang/Factor/Phrase-reversals b/Lang/Factor/Phrase-reversals new file mode 120000 index 0000000000..5d12bcf13c --- /dev/null +++ b/Lang/Factor/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/Factor \ No newline at end of file diff --git a/Lang/Factor/Playing-cards b/Lang/Factor/Playing-cards new file mode 120000 index 0000000000..b4093691ba --- /dev/null +++ b/Lang/Factor/Playing-cards @@ -0,0 +1 @@ +../../Task/Playing-cards/Factor \ No newline at end of file diff --git a/Lang/Factor/Range-extraction b/Lang/Factor/Range-extraction new file mode 120000 index 0000000000..af09f4d786 --- /dev/null +++ b/Lang/Factor/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/Factor \ No newline at end of file diff --git a/Lang/Factor/Regular-expressions b/Lang/Factor/Regular-expressions new file mode 120000 index 0000000000..6f7482539a --- /dev/null +++ b/Lang/Factor/Regular-expressions @@ -0,0 +1 @@ +../../Task/Regular-expressions/Factor \ No newline at end of file diff --git a/Lang/Factor/Reverse-words-in-a-string b/Lang/Factor/Reverse-words-in-a-string new file mode 120000 index 0000000000..9a3a4253fe --- /dev/null +++ b/Lang/Factor/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Factor \ No newline at end of file diff --git a/Lang/Factor/Run-length-encoding b/Lang/Factor/Run-length-encoding new file mode 120000 index 0000000000..06a60eb055 --- /dev/null +++ b/Lang/Factor/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/Factor \ No newline at end of file diff --git a/Lang/Factor/Self-describing-numbers b/Lang/Factor/Self-describing-numbers new file mode 120000 index 0000000000..73c34d90c4 --- /dev/null +++ b/Lang/Factor/Self-describing-numbers @@ -0,0 +1 @@ +../../Task/Self-describing-numbers/Factor \ No newline at end of file diff --git a/Lang/Factor/Semiprime b/Lang/Factor/Semiprime new file mode 120000 index 0000000000..06644c3e0f --- /dev/null +++ b/Lang/Factor/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Factor \ No newline at end of file diff --git a/Lang/Factor/Sequence-of-non-squares b/Lang/Factor/Sequence-of-non-squares new file mode 120000 index 0000000000..ee5f584d3f --- /dev/null +++ b/Lang/Factor/Sequence-of-non-squares @@ -0,0 +1 @@ +../../Task/Sequence-of-non-squares/Factor \ No newline at end of file diff --git a/Lang/Factor/Short-circuit-evaluation b/Lang/Factor/Short-circuit-evaluation new file mode 120000 index 0000000000..685cdfce0e --- /dev/null +++ b/Lang/Factor/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Factor \ No newline at end of file diff --git a/Lang/Factor/Simple-windowed-application b/Lang/Factor/Simple-windowed-application new file mode 120000 index 0000000000..03dfb4148e --- /dev/null +++ b/Lang/Factor/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Factor \ No newline at end of file diff --git a/Lang/Factor/Sorting-algorithms-Permutation-sort b/Lang/Factor/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..2f15ed522f --- /dev/null +++ b/Lang/Factor/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Factor \ No newline at end of file diff --git a/Lang/Factor/Statistics-Basic b/Lang/Factor/Statistics-Basic new file mode 120000 index 0000000000..575120165c --- /dev/null +++ b/Lang/Factor/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/Factor \ No newline at end of file diff --git a/Lang/Factor/String-append b/Lang/Factor/String-append new file mode 120000 index 0000000000..b91613c9b5 --- /dev/null +++ b/Lang/Factor/String-append @@ -0,0 +1 @@ +../../Task/String-append/Factor \ No newline at end of file diff --git a/Lang/Factor/String-comparison b/Lang/Factor/String-comparison new file mode 120000 index 0000000000..2ae8c989b1 --- /dev/null +++ b/Lang/Factor/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Factor \ No newline at end of file diff --git a/Lang/Factor/Strip-a-set-of-characters-from-a-string b/Lang/Factor/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..3c05d685b7 --- /dev/null +++ b/Lang/Factor/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Factor \ No newline at end of file diff --git a/Lang/Factor/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Factor/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..03141754fc --- /dev/null +++ b/Lang/Factor/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Factor \ No newline at end of file diff --git a/Lang/Factor/Substring-Top-and-tail b/Lang/Factor/Substring-Top-and-tail new file mode 120000 index 0000000000..185059c778 --- /dev/null +++ b/Lang/Factor/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Factor \ No newline at end of file diff --git a/Lang/Factor/Sum-multiples-of-3-and-5 b/Lang/Factor/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..0a94124659 --- /dev/null +++ b/Lang/Factor/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Factor \ No newline at end of file diff --git a/Lang/Factor/Temperature-conversion b/Lang/Factor/Temperature-conversion new file mode 120000 index 0000000000..da268bf83a --- /dev/null +++ b/Lang/Factor/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Factor \ No newline at end of file diff --git a/Lang/Factor/The-Twelve-Days-of-Christmas b/Lang/Factor/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..0071bed081 --- /dev/null +++ b/Lang/Factor/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Factor \ No newline at end of file diff --git a/Lang/Factor/Trabb-Pardo-Knuth-algorithm b/Lang/Factor/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..3c652ab70a --- /dev/null +++ b/Lang/Factor/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Factor \ No newline at end of file diff --git a/Lang/Factor/Truncatable-primes b/Lang/Factor/Truncatable-primes new file mode 120000 index 0000000000..e8409320cd --- /dev/null +++ b/Lang/Factor/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/Factor \ No newline at end of file diff --git a/Lang/Factor/URL-decoding b/Lang/Factor/URL-decoding new file mode 120000 index 0000000000..3b2c1dfea7 --- /dev/null +++ b/Lang/Factor/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Factor \ No newline at end of file diff --git a/Lang/Factor/Vampire-number b/Lang/Factor/Vampire-number new file mode 120000 index 0000000000..070d3f93b2 --- /dev/null +++ b/Lang/Factor/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/Factor \ No newline at end of file diff --git a/Lang/Factor/Variadic-function b/Lang/Factor/Variadic-function new file mode 120000 index 0000000000..11a87c236d --- /dev/null +++ b/Lang/Factor/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Factor \ No newline at end of file diff --git a/Lang/Factor/Vector-products b/Lang/Factor/Vector-products new file mode 120000 index 0000000000..2205112336 --- /dev/null +++ b/Lang/Factor/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Factor \ No newline at end of file diff --git a/Lang/Factor/Vigen-re-cipher b/Lang/Factor/Vigen-re-cipher new file mode 120000 index 0000000000..0afebb961d --- /dev/null +++ b/Lang/Factor/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Factor \ No newline at end of file diff --git a/Lang/Factor/Word-wrap b/Lang/Factor/Word-wrap new file mode 120000 index 0000000000..fb06da7309 --- /dev/null +++ b/Lang/Factor/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Factor \ No newline at end of file diff --git a/Lang/Falcon/Palindrome-detection b/Lang/Falcon/Palindrome-detection new file mode 120000 index 0000000000..74eb612064 --- /dev/null +++ b/Lang/Falcon/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Falcon \ No newline at end of file diff --git a/Lang/Falcon/String-append b/Lang/Falcon/String-append new file mode 120000 index 0000000000..dd72f5566c --- /dev/null +++ b/Lang/Falcon/String-append @@ -0,0 +1 @@ +../../Task/String-append/Falcon \ No newline at end of file diff --git a/Lang/Falcon/String-comparison b/Lang/Falcon/String-comparison new file mode 120000 index 0000000000..ce39320597 --- /dev/null +++ b/Lang/Falcon/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Falcon \ No newline at end of file diff --git a/Lang/Falcon/String-concatenation b/Lang/Falcon/String-concatenation new file mode 120000 index 0000000000..3dc18c4740 --- /dev/null +++ b/Lang/Falcon/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Falcon \ No newline at end of file diff --git a/Lang/Falcon/String-interpolation--included- b/Lang/Falcon/String-interpolation--included- new file mode 120000 index 0000000000..3528461617 --- /dev/null +++ b/Lang/Falcon/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Falcon \ No newline at end of file diff --git a/Lang/Falcon/String-matching b/Lang/Falcon/String-matching new file mode 120000 index 0000000000..cc476aa333 --- /dev/null +++ b/Lang/Falcon/String-matching @@ -0,0 +1 @@ +../../Task/String-matching/Falcon \ No newline at end of file diff --git a/Lang/Falcon/String-prepend b/Lang/Falcon/String-prepend new file mode 120000 index 0000000000..c965fbb10a --- /dev/null +++ b/Lang/Falcon/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Falcon \ No newline at end of file diff --git a/Lang/Falcon/Substring b/Lang/Falcon/Substring new file mode 120000 index 0000000000..6206721097 --- /dev/null +++ b/Lang/Falcon/Substring @@ -0,0 +1 @@ +../../Task/Substring/Falcon \ No newline at end of file diff --git a/Lang/Falcon/System-time b/Lang/Falcon/System-time new file mode 120000 index 0000000000..af3bc0cd89 --- /dev/null +++ b/Lang/Falcon/System-time @@ -0,0 +1 @@ +../../Task/System-time/Falcon \ No newline at end of file diff --git a/Lang/Falcon/Tokenize-a-string b/Lang/Falcon/Tokenize-a-string new file mode 120000 index 0000000000..c0b23abc44 --- /dev/null +++ b/Lang/Falcon/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Falcon \ No newline at end of file diff --git a/Lang/Falcon/Variables b/Lang/Falcon/Variables new file mode 120000 index 0000000000..7e0538a7fb --- /dev/null +++ b/Lang/Falcon/Variables @@ -0,0 +1 @@ +../../Task/Variables/Falcon \ No newline at end of file diff --git a/Lang/Falcon/Zero-to-the-zero-power b/Lang/Falcon/Zero-to-the-zero-power new file mode 120000 index 0000000000..6c8721a7f7 --- /dev/null +++ b/Lang/Falcon/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/Falcon \ No newline at end of file diff --git a/Lang/Forth/CSV-to-HTML-translation b/Lang/Forth/CSV-to-HTML-translation new file mode 120000 index 0000000000..4451b703e4 --- /dev/null +++ b/Lang/Forth/CSV-to-HTML-translation @@ -0,0 +1 @@ +../../Task/CSV-to-HTML-translation/Forth \ No newline at end of file diff --git a/Lang/Forth/Documentation b/Lang/Forth/Documentation new file mode 120000 index 0000000000..a7a49a990e --- /dev/null +++ b/Lang/Forth/Documentation @@ -0,0 +1 @@ +../../Task/Documentation/Forth \ No newline at end of file diff --git a/Lang/Forth/Forest-fire b/Lang/Forth/Forest-fire new file mode 120000 index 0000000000..ff66c834ed --- /dev/null +++ b/Lang/Forth/Forest-fire @@ -0,0 +1 @@ +../../Task/Forest-fire/Forth \ No newline at end of file diff --git a/Lang/Forth/Left-factorials b/Lang/Forth/Left-factorials new file mode 120000 index 0000000000..116f127fd4 --- /dev/null +++ b/Lang/Forth/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/Forth \ No newline at end of file diff --git a/Lang/Forth/Lucas-Lehmer-test b/Lang/Forth/Lucas-Lehmer-test new file mode 120000 index 0000000000..d3b37d69dd --- /dev/null +++ b/Lang/Forth/Lucas-Lehmer-test @@ -0,0 +1 @@ +../../Task/Lucas-Lehmer-test/Forth \ No newline at end of file diff --git a/Lang/Forth/Synchronous-concurrency b/Lang/Forth/Synchronous-concurrency new file mode 120000 index 0000000000..cd34279ec8 --- /dev/null +++ b/Lang/Forth/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Forth \ No newline at end of file diff --git a/Lang/Fortran/00DESCRIPTION b/Lang/Fortran/00DESCRIPTION index 31b2e35530..fbd223967c 100644 --- a/Lang/Fortran/00DESCRIPTION +++ b/Lang/Fortran/00DESCRIPTION @@ -7,8 +7,8 @@ |LCT=yes |tags=fortran |bnf=http://fortran.comsci.us/syntax/statement/index.html}}{{language programming paradigm|Imperative}}{{Language programming paradigm|Procedural}}{{Language programming paradigm|Object-oriented}}{{Language programming paradigm|Concurrent}} -Fortran is the oldest programming language still in widespread use. The language has evolved considerably since it was first released in 1957. Fortran was original developed for scientific and engineering applications, and remains especially suited to numeric computation and scientific computing. By convention, versions before Fortran 90 are spelled with all uppercase letters (e.g. FORTRAN 66, FORTRAN 77), while starting with Fortran 90, the mixed case spelling is used (i.e. Fortran 90, Fortran 95, Fortran 2003 and [http://j3-fortran.org/doc/year/12/12-007.pdf Fortran 2008]). The most recent standard is Fortran 2008 (ISO/IEC 1539-1:2010). The next, informally known as [http://j3-fortran.org/doc/year/16/16-007r2.pdf Fortran 2015], is underway. +Fortran is the oldest programming language still in widespread use. The language has evolved considerably since it was first released in 1957. Fortran was original developed for scientific and engineering applications, and remains especially suited to numeric computation and scientific computing. By convention, versions before Fortran 90 are spelled with all uppercase letters (e.g. FORTRAN IV, FORTRAN 66, FORTRAN 77), while starting with Fortran 90, the mixed case spelling is used (i.e. Fortran 90, Fortran 95, Fortran 2003 and [http://j3-fortran.org/doc/year/12/12-007.pdf Fortran 2008]). The most recent standard is Fortran 2008 (ISO/IEC 1539-1:2010). The next, informally known as [https://j3-fortran.org/doc/year/18/18-007.pdf Fortran 2018], is underway. FORTRAN 77, being quite old, lacks almost everything one expects from a modern programming language. It uses a fixed-length line and column oriented line format which was motivated by punch cards. Due to its age, and since FORTRAN compilers generally gave very good performance for numerical code, a lot of code, especially scientific code, was written in FORTRAN. Also, for quite a while there was no free Fortran 90 compiler, which also caused a lot of FORTRAN 77 code to be written even quite some time after Fortran 90 was standardized. Because of the large body of code written in FORTRAN 77 it remains relevant today. Indeed, every modern Fortran compiler still accepts FORTRAN 77 code. -Fortran 90 was a major revision of the language. It introduced a new free-form source code format, modern programming language features like modules, pointers and user-defined types, an improved type system for built-in types and superiour built-in array handling. Newer Fortran standards (Fortran 2003 and Fortran 2008) added further modern features, like support for [[object oriented programming]], [[inheritance]], [[polymorphism]], [[parallel processing]], and [[interoperability]] with the C programming language. \ No newline at end of file +Fortran 90 was a major revision of the language. It introduced a new free-form source code format, modern programming language features like modules, pointers and user-defined types, an improved type system for built-in types and superiour built-in array handling. Newer Fortran standards (Fortran 2003 and Fortran 2008) added further modern features, like support for [[object oriented programming]], [[inheritance]], [[polymorphism]], [[parallel processing]], and [[interoperability]] with the [[:Category:C|C programming language]]. \ No newline at end of file diff --git a/Lang/Fortran/Catamorphism b/Lang/Fortran/Catamorphism new file mode 120000 index 0000000000..9cc7cc205e --- /dev/null +++ b/Lang/Fortran/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Element-wise-operations b/Lang/Fortran/Element-wise-operations new file mode 120000 index 0000000000..4f31b65f0c --- /dev/null +++ b/Lang/Fortran/Element-wise-operations @@ -0,0 +1 @@ +../../Task/Element-wise-operations/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Extend-your-language b/Lang/Fortran/Extend-your-language new file mode 120000 index 0000000000..48a7fc605a --- /dev/null +++ b/Lang/Fortran/Extend-your-language @@ -0,0 +1 @@ +../../Task/Extend-your-language/Fortran \ No newline at end of file diff --git a/Lang/Fortran/IBAN b/Lang/Fortran/IBAN new file mode 120000 index 0000000000..1985c3133e --- /dev/null +++ b/Lang/Fortran/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Old-lady-swallowed-a-fly b/Lang/Fortran/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..c9b52a86f3 --- /dev/null +++ b/Lang/Fortran/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Tic-tac-toe b/Lang/Fortran/Tic-tac-toe new file mode 120000 index 0000000000..bb4ab7c96c --- /dev/null +++ b/Lang/Fortran/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Fortran \ No newline at end of file diff --git a/Lang/Fortress/Call-a-function b/Lang/Fortress/Call-a-function new file mode 120000 index 0000000000..006ea2d49c --- /dev/null +++ b/Lang/Fortress/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/Fortress \ No newline at end of file diff --git a/Lang/Fortress/Function-composition b/Lang/Fortress/Function-composition new file mode 120000 index 0000000000..c6374478a6 --- /dev/null +++ b/Lang/Fortress/Function-composition @@ -0,0 +1 @@ +../../Task/Function-composition/Fortress \ No newline at end of file diff --git a/Lang/Fortress/Loops-Do-while b/Lang/Fortress/Loops-Do-while new file mode 120000 index 0000000000..6b90f6c6a5 --- /dev/null +++ b/Lang/Fortress/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Fortress \ No newline at end of file diff --git a/Lang/Fortress/Loops-Infinite b/Lang/Fortress/Loops-Infinite new file mode 120000 index 0000000000..f044766cbc --- /dev/null +++ b/Lang/Fortress/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Fortress \ No newline at end of file diff --git a/Lang/Fortress/Loops-While b/Lang/Fortress/Loops-While new file mode 120000 index 0000000000..87c3616235 --- /dev/null +++ b/Lang/Fortress/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Fortress \ No newline at end of file diff --git a/Lang/FreeBASIC/Gaussian-elimination b/Lang/FreeBASIC/Gaussian-elimination new file mode 120000 index 0000000000..c05f2781af --- /dev/null +++ b/Lang/FreeBASIC/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/FreeBASIC \ No newline at end of file diff --git a/Lang/Futhark/Greatest-element-of-a-list b/Lang/Futhark/Greatest-element-of-a-list new file mode 120000 index 0000000000..c0356f534b --- /dev/null +++ b/Lang/Futhark/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Futhark \ No newline at end of file diff --git a/Lang/GW-BASIC/Almost-prime b/Lang/GW-BASIC/Almost-prime new file mode 120000 index 0000000000..148e4b32da --- /dev/null +++ b/Lang/GW-BASIC/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Horizontal-sundial-calculations b/Lang/GW-BASIC/Horizontal-sundial-calculations new file mode 120000 index 0000000000..9629cb1c74 --- /dev/null +++ b/Lang/GW-BASIC/Horizontal-sundial-calculations @@ -0,0 +1 @@ +../../Task/Horizontal-sundial-calculations/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Leap-year b/Lang/GW-BASIC/Leap-year new file mode 120000 index 0000000000..259a2fafdb --- /dev/null +++ b/Lang/GW-BASIC/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Least-common-multiple b/Lang/GW-BASIC/Least-common-multiple new file mode 120000 index 0000000000..4c8b975f8b --- /dev/null +++ b/Lang/GW-BASIC/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Loops-Do-while b/Lang/GW-BASIC/Loops-Do-while new file mode 120000 index 0000000000..b454a928d1 --- /dev/null +++ b/Lang/GW-BASIC/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Loops-Downward-for b/Lang/GW-BASIC/Loops-Downward-for new file mode 120000 index 0000000000..c7c8baed32 --- /dev/null +++ b/Lang/GW-BASIC/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Modular-inverse b/Lang/GW-BASIC/Modular-inverse new file mode 120000 index 0000000000..025d0dc503 --- /dev/null +++ b/Lang/GW-BASIC/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Multiplication-tables b/Lang/GW-BASIC/Multiplication-tables new file mode 120000 index 0000000000..9952ddfc72 --- /dev/null +++ b/Lang/GW-BASIC/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Nth b/Lang/GW-BASIC/Nth new file mode 120000 index 0000000000..d6d2925ace --- /dev/null +++ b/Lang/GW-BASIC/Nth @@ -0,0 +1 @@ +../../Task/Nth/GW-BASIC \ No newline at end of file diff --git a/Lang/GW-BASIC/Remove-duplicate-elements b/Lang/GW-BASIC/Remove-duplicate-elements new file mode 120000 index 0000000000..9903fb3159 --- /dev/null +++ b/Lang/GW-BASIC/Remove-duplicate-elements @@ -0,0 +1 @@ +../../Task/Remove-duplicate-elements/GW-BASIC \ No newline at end of file diff --git a/Lang/Gambas/Ackermann-function b/Lang/Gambas/Ackermann-function new file mode 120000 index 0000000000..4b787a470d --- /dev/null +++ b/Lang/Gambas/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Collections b/Lang/Gambas/Collections new file mode 120000 index 0000000000..4c650ff846 --- /dev/null +++ b/Lang/Gambas/Collections @@ -0,0 +1 @@ +../../Task/Collections/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Hello-world-Newline-omission b/Lang/Gambas/Hello-world-Newline-omission new file mode 120000 index 0000000000..6b22fd0223 --- /dev/null +++ b/Lang/Gambas/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Price-fraction b/Lang/Gambas/Price-fraction new file mode 120000 index 0000000000..43d30690a3 --- /dev/null +++ b/Lang/Gambas/Price-fraction @@ -0,0 +1 @@ +../../Task/Price-fraction/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Remove-duplicate-elements b/Lang/Gambas/Remove-duplicate-elements new file mode 120000 index 0000000000..2dac827e9d --- /dev/null +++ b/Lang/Gambas/Remove-duplicate-elements @@ -0,0 +1 @@ +../../Task/Remove-duplicate-elements/Gambas \ No newline at end of file diff --git a/Lang/Gambas/SEDOLs b/Lang/Gambas/SEDOLs new file mode 120000 index 0000000000..27e35e0e4a --- /dev/null +++ b/Lang/Gambas/SEDOLs @@ -0,0 +1 @@ +../../Task/SEDOLs/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Sorting-algorithms-Bogosort b/Lang/Gambas/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..6e16824f95 --- /dev/null +++ b/Lang/Gambas/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Sorting-algorithms-Bubble-sort b/Lang/Gambas/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..92c2b3c0c3 --- /dev/null +++ b/Lang/Gambas/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Sorting-algorithms-Cocktail-sort b/Lang/Gambas/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..a752897c84 --- /dev/null +++ b/Lang/Gambas/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Sorting-algorithms-Comb-sort b/Lang/Gambas/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..e070bb1edc --- /dev/null +++ b/Lang/Gambas/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Sorting-algorithms-Gnome-sort b/Lang/Gambas/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..10c67a4bf6 --- /dev/null +++ b/Lang/Gambas/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Sorting-algorithms-Selection-sort b/Lang/Gambas/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..e15fe03d82 --- /dev/null +++ b/Lang/Gambas/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Tokenize-a-string b/Lang/Gambas/Tokenize-a-string new file mode 120000 index 0000000000..54748c6fe8 --- /dev/null +++ b/Lang/Gambas/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Gambas \ No newline at end of file diff --git a/Lang/Gambas/Window-management b/Lang/Gambas/Window-management new file mode 120000 index 0000000000..6a183e69d8 --- /dev/null +++ b/Lang/Gambas/Window-management @@ -0,0 +1 @@ +../../Task/Window-management/Gambas \ No newline at end of file diff --git a/Lang/Glee/Combinations b/Lang/Glee/Combinations new file mode 120000 index 0000000000..e38b359a8c --- /dev/null +++ b/Lang/Glee/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/Glee \ No newline at end of file diff --git a/Lang/Go/00DESCRIPTION b/Lang/Go/00DESCRIPTION index 5d3553ff07..81c0f9132c 100644 --- a/Lang/Go/00DESCRIPTION +++ b/Lang/Go/00DESCRIPTION @@ -23,4 +23,7 @@ Not to be confused with [[:Category:Go!|Go!]] * [http://tour.golang.org/ Go Tour and Tutorial] * [http://golang.org/ref/spec Go language specification] * [http://golang.org/pkg/ Go standard library documentation] -* [https://github.com/golang/go/wiki/ Community maintained Go wiki] \ No newline at end of file +* [https://github.com/golang/go/wiki/ Community maintained Go wiki] + +==Todo== +[[Reports:Tasks_not_implemented_in_Go]] \ No newline at end of file diff --git a/Lang/Go/9-billion-names-of-God-the-integer b/Lang/Go/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..a99ce49cf8 --- /dev/null +++ b/Lang/Go/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/Go \ No newline at end of file diff --git a/Lang/Go/Aliquot-sequence-classifications b/Lang/Go/Aliquot-sequence-classifications new file mode 120000 index 0000000000..3d6a25f035 --- /dev/null +++ b/Lang/Go/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/Go \ No newline at end of file diff --git a/Lang/Go/Calendar b/Lang/Go/Calendar new file mode 120000 index 0000000000..704bf551b2 --- /dev/null +++ b/Lang/Go/Calendar @@ -0,0 +1 @@ +../../Task/Calendar/Go \ No newline at end of file diff --git a/Lang/Go/Carmichael-3-strong-pseudoprimes b/Lang/Go/Carmichael-3-strong-pseudoprimes new file mode 120000 index 0000000000..40b792a69a --- /dev/null +++ b/Lang/Go/Carmichael-3-strong-pseudoprimes @@ -0,0 +1 @@ +../../Task/Carmichael-3-strong-pseudoprimes/Go \ No newline at end of file diff --git a/Lang/Go/Catalan-numbers-Pascals-triangle b/Lang/Go/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..3594817450 --- /dev/null +++ b/Lang/Go/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Go \ No newline at end of file diff --git a/Lang/Go/Combinations-and-permutations b/Lang/Go/Combinations-and-permutations new file mode 120000 index 0000000000..f91d73cd08 --- /dev/null +++ b/Lang/Go/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/Go \ No newline at end of file diff --git a/Lang/Go/Define-a-primitive-data-type b/Lang/Go/Define-a-primitive-data-type new file mode 120000 index 0000000000..0cbd75110a --- /dev/null +++ b/Lang/Go/Define-a-primitive-data-type @@ -0,0 +1 @@ +../../Task/Define-a-primitive-data-type/Go \ No newline at end of file diff --git a/Lang/Go/Extend-your-language b/Lang/Go/Extend-your-language new file mode 120000 index 0000000000..dedcfa06a2 --- /dev/null +++ b/Lang/Go/Extend-your-language @@ -0,0 +1 @@ +../../Task/Extend-your-language/Go \ No newline at end of file diff --git a/Lang/Go/Find-largest-left-truncatable-prime-in-a-given-base b/Lang/Go/Find-largest-left-truncatable-prime-in-a-given-base new file mode 120000 index 0000000000..6ea6e1745d --- /dev/null +++ b/Lang/Go/Find-largest-left-truncatable-prime-in-a-given-base @@ -0,0 +1 @@ +../../Task/Find-largest-left-truncatable-prime-in-a-given-base/Go \ No newline at end of file diff --git a/Lang/Go/HTTPS-Client-authenticated b/Lang/Go/HTTPS-Client-authenticated new file mode 120000 index 0000000000..ada9e79957 --- /dev/null +++ b/Lang/Go/HTTPS-Client-authenticated @@ -0,0 +1 @@ +../../Task/HTTPS-Client-authenticated/Go \ No newline at end of file diff --git a/Lang/Go/Jump-anywhere b/Lang/Go/Jump-anywhere new file mode 120000 index 0000000000..8d114df3c5 --- /dev/null +++ b/Lang/Go/Jump-anywhere @@ -0,0 +1 @@ +../../Task/Jump-anywhere/Go \ No newline at end of file diff --git a/Lang/Go/Named-parameters b/Lang/Go/Named-parameters new file mode 120000 index 0000000000..b0a75860fc --- /dev/null +++ b/Lang/Go/Named-parameters @@ -0,0 +1 @@ +../../Task/Named-parameters/Go \ No newline at end of file diff --git a/Lang/Go/Solve-a-Holy-Knights-tour b/Lang/Go/Solve-a-Holy-Knights-tour new file mode 120000 index 0000000000..1d034b403d --- /dev/null +++ b/Lang/Go/Solve-a-Holy-Knights-tour @@ -0,0 +1 @@ +../../Task/Solve-a-Holy-Knights-tour/Go \ No newline at end of file diff --git a/Lang/Go/Terminal-control-Unicode-output b/Lang/Go/Terminal-control-Unicode-output new file mode 120000 index 0000000000..7532989408 --- /dev/null +++ b/Lang/Go/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/Go \ No newline at end of file diff --git a/Lang/Go/Vigen-re-cipher-Cryptanalysis b/Lang/Go/Vigen-re-cipher-Cryptanalysis new file mode 120000 index 0000000000..afccf481ac --- /dev/null +++ b/Lang/Go/Vigen-re-cipher-Cryptanalysis @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher-Cryptanalysis/Go \ No newline at end of file diff --git a/Lang/Go/Vogels-approximation-method b/Lang/Go/Vogels-approximation-method new file mode 120000 index 0000000000..6c070a1e55 --- /dev/null +++ b/Lang/Go/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/Go \ No newline at end of file diff --git a/Lang/Groovy/00DESCRIPTION b/Lang/Groovy/00DESCRIPTION index 9f4b9842e2..9009c2157f 100644 --- a/Lang/Groovy/00DESCRIPTION +++ b/Lang/Groovy/00DESCRIPTION @@ -7,7 +7,7 @@ |gc=yes |site=http://groovy.codehaus.org |LCT=yes}}{{language programming paradigm|Object-oriented}}[[runs on vm::java virtual machine| ]] -'''Groovy''' is an [[object-oriented]] programming language for the [[Java]] platform as an alternative to the Java programming language. It can be viewed as a scripting language for the Java platform, as it has features similar to those of [[Python]], [[Ruby]], [[Perl]], and [[Smalltalk]]. In some contexts, the name JSR 241 is used as an alternate identifier for Groovy. +'''Groovy''' is an [[object-oriented]] programming language for the [[Java]] platform as an alternative to the Java programming language. It can be viewed as a scripting language for the Java platform, as it has features similar to those of [[Python]], [[Ruby]], [[Perl]], and [[Smalltalk]]. In some contexts, the name JSR 241 is used as an alternate identifier for Groovy. Since 11/2015 Groovy is a top level Apache project. '''Groovy''' ... * is an agile and dynamic language for the [[Java Virtual Machine]] @@ -22,7 +22,8 @@ Useful Groovy links: +* [http://groovylang.org Apache Groovy Homepage] * [[wp:Groovy_(programming_language)|Wikipedia]] -* [http://groovy.codehaus.org/Articles Groovy articles] * [http://www.jcp.org/en/jsr/detail?id=241 JSR 241] +* [https://github.com/kdabir/awesome-groovy awesome-groovy] * [http://snipplr.com/all/language/groovy Code Snippet Repository] \ No newline at end of file diff --git a/Lang/Groovy/Deal-cards-for-FreeCell b/Lang/Groovy/Deal-cards-for-FreeCell new file mode 120000 index 0000000000..3c9e3200cd --- /dev/null +++ b/Lang/Groovy/Deal-cards-for-FreeCell @@ -0,0 +1 @@ +../../Task/Deal-cards-for-FreeCell/Groovy \ No newline at end of file diff --git a/Lang/Haskell/00DESCRIPTION b/Lang/Haskell/00DESCRIPTION index b4906ce73f..fe49ebce44 100644 --- a/Lang/Haskell/00DESCRIPTION +++ b/Lang/Haskell/00DESCRIPTION @@ -9,9 +9,16 @@ |bnf=http://haskell.org/onlinereport/index.html}}{{codepad}} {{language programming paradigm|Declarative}} {{language programming paradigm|functional}} -'''Haskell''' is a standardized purely [[functional programming]] language with non-strict semantics, named after the logician Haskell Curry. It is one of the more popular functional languages, and the [[lazy evaluation|lazy]] functional language on which the most research is being performed. +'''Haskell''' is a standardized purely [[functional programming]] language with non-strict semantics, named after the logician Haskell Curry. +It is one of the more popular functional languages, and the [[lazy evaluation|lazy]] functional language on which the most research is being performed. -Although Haskell has a comparatively small user community, its strengths have been well applied to a few projects. Audrey Tang's Pugs is an implementation for the forthcoming [[Perl 6]] language with an [[interpreter]] and [[compiler|compilers]] that proved useful already after just a few months of its writing. Darcs is a revision control system, with several innovative features. Linspire GNU/[[Linux]] chose Haskell for system tools development. +Although Haskell has a comparatively small user community, its strengths have been well applied to a few projects. +Audrey Tang's Pugs is an implementation for the forthcoming [[Perl 6]] language with an [[interpreter]] and [[compiler|compilers]] that proved useful already after just a few months of its writing. +Darcs is a revision control system, with several innovative features. +Linspire GNU/[[Linux]] chose Haskell for system tools development. ==Citations== -* [[wp:Haskell_%28programming_language%29|Wikipedia:Haskell (programming language)]] \ No newline at end of file +* [[wp:Haskell_%28programming_language%29|Wikipedia:Haskell (programming language)]] + +==Todo== +[[Reports:Tasks_not_implemented_in_Haskell]] \ No newline at end of file diff --git a/Lang/Haskell/Active-Directory-Connect b/Lang/Haskell/Active-Directory-Connect new file mode 120000 index 0000000000..455a281e75 --- /dev/null +++ b/Lang/Haskell/Active-Directory-Connect @@ -0,0 +1 @@ +../../Task/Active-Directory-Connect/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Active-Directory-Search-for-a-user b/Lang/Haskell/Active-Directory-Search-for-a-user new file mode 120000 index 0000000000..48f629a33b --- /dev/null +++ b/Lang/Haskell/Active-Directory-Search-for-a-user @@ -0,0 +1 @@ +../../Task/Active-Directory-Search-for-a-user/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Catmull-Clark-subdivision-surface b/Lang/Haskell/Catmull-Clark-subdivision-surface new file mode 120000 index 0000000000..d669b66cf6 --- /dev/null +++ b/Lang/Haskell/Catmull-Clark-subdivision-surface @@ -0,0 +1 @@ +../../Task/Catmull-Clark-subdivision-surface/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Create-a-file-on-magnetic-tape b/Lang/Haskell/Create-a-file-on-magnetic-tape new file mode 120000 index 0000000000..a26c166618 --- /dev/null +++ b/Lang/Haskell/Create-a-file-on-magnetic-tape @@ -0,0 +1 @@ +../../Task/Create-a-file-on-magnetic-tape/Haskell \ No newline at end of file diff --git a/Lang/Haskell/HTTPS-Authenticated b/Lang/Haskell/HTTPS-Authenticated new file mode 120000 index 0000000000..a864d35654 --- /dev/null +++ b/Lang/Haskell/HTTPS-Authenticated @@ -0,0 +1 @@ +../../Task/HTTPS-Authenticated/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Joystick-position b/Lang/Haskell/Joystick-position new file mode 120000 index 0000000000..1e3559e8cb --- /dev/null +++ b/Lang/Haskell/Joystick-position @@ -0,0 +1 @@ +../../Task/Joystick-position/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Longest-string-challenge b/Lang/Haskell/Longest-string-challenge new file mode 120000 index 0000000000..292d042d29 --- /dev/null +++ b/Lang/Haskell/Longest-string-challenge @@ -0,0 +1 @@ +../../Task/Longest-string-challenge/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Natural-sorting b/Lang/Haskell/Natural-sorting new file mode 120000 index 0000000000..7a43580036 --- /dev/null +++ b/Lang/Haskell/Natural-sorting @@ -0,0 +1 @@ +../../Task/Natural-sorting/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Object-serialization b/Lang/Haskell/Object-serialization new file mode 120000 index 0000000000..a8e6c5b882 --- /dev/null +++ b/Lang/Haskell/Object-serialization @@ -0,0 +1 @@ +../../Task/Object-serialization/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Parametrized-SQL-statement b/Lang/Haskell/Parametrized-SQL-statement new file mode 120000 index 0000000000..237acefde6 --- /dev/null +++ b/Lang/Haskell/Parametrized-SQL-statement @@ -0,0 +1 @@ +../../Task/Parametrized-SQL-statement/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Send-email b/Lang/Haskell/Send-email new file mode 120000 index 0000000000..a182000d6e --- /dev/null +++ b/Lang/Haskell/Send-email @@ -0,0 +1 @@ +../../Task/Send-email/Haskell \ No newline at end of file diff --git a/Lang/HolyC/00DESCRIPTION b/Lang/HolyC/00DESCRIPTION index 737f7285b5..d93aaee2ca 100644 --- a/Lang/HolyC/00DESCRIPTION +++ b/Lang/HolyC/00DESCRIPTION @@ -1,5 +1,22 @@ -{{stub}} {{language -|site=http://www.templeos.org/Wb/Doc/HolyC.html}} +|exec=machine +|gc=no +|checking=no +|parampass=value +|strength=weak +|safety=unsafe +|site=http://www.templeos.org/}} -'''HolyC''' is a programming language developed by Terry Davis for The Temple Operating System ([http://www.templeos.org/ TempleOS]) \ No newline at end of file +'''HolyC''' is a variation of [[C|C]] developed by Terry A. Davis. HolyC is the official programming language for The Temple Operating System ([http://www.templeos.org/ TempleOS]). + +The official HolyC documentation is provided with TempleOS. ([https://templeos.sheikhs.space/Wb/Doc/HolyC.html mirror], [https://web.archive.org/web/20170325000321/http://www.templeos.org/Wb/Doc/HolyC.html archive]). + +== Related Resources == + +* [https://en.wikipedia.org/wiki/TempleOS TempleOS - Wikipedia] +* [http://www.codersnotes.com/notes/a-constructive-look-at-templeos/ A Constructive Look At TempleOS] +* [https://www.jwhitham.org//2015/07/porting-third-party-programs-to-templeos.html Porting third-party programs to TempleOS] +* [https://github.com/minexew/Shrine GitHub - minexew/Shrine] +* [https://github.com/jamesalbert/HolyC-for-Linux GitHub - jamesalbert/HolyC-for-Linux: run HolyC on Linux secularly] +* [https://archive.org/details/TempleOS_Website_Archive templeos.org backup] +* [https://templeos.sheikhs.space/Wb/Home/Web/AppStore/AppStore.html TempleOS App Store] \ No newline at end of file diff --git a/Lang/HolyC/100-doors b/Lang/HolyC/100-doors new file mode 120000 index 0000000000..9f1b7c8a24 --- /dev/null +++ b/Lang/HolyC/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Arithmetic-Integer b/Lang/HolyC/Arithmetic-Integer new file mode 120000 index 0000000000..7f83eb4bee --- /dev/null +++ b/Lang/HolyC/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Arrays b/Lang/HolyC/Arrays new file mode 120000 index 0000000000..7d25935f25 --- /dev/null +++ b/Lang/HolyC/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Character-codes b/Lang/HolyC/Character-codes new file mode 120000 index 0000000000..83ebf1ef87 --- /dev/null +++ b/Lang/HolyC/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Check-that-file-exists b/Lang/HolyC/Check-that-file-exists new file mode 120000 index 0000000000..41b7192b9a --- /dev/null +++ b/Lang/HolyC/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Detect-division-by-zero b/Lang/HolyC/Detect-division-by-zero new file mode 120000 index 0000000000..acf2171bae --- /dev/null +++ b/Lang/HolyC/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Empty-string b/Lang/HolyC/Empty-string new file mode 120000 index 0000000000..25b550ac18 --- /dev/null +++ b/Lang/HolyC/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Exceptions b/Lang/HolyC/Exceptions new file mode 120000 index 0000000000..a642ff135e --- /dev/null +++ b/Lang/HolyC/Exceptions @@ -0,0 +1 @@ +../../Task/Exceptions/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Execute-a-system-command b/Lang/HolyC/Execute-a-system-command new file mode 120000 index 0000000000..d6ba6c6f70 --- /dev/null +++ b/Lang/HolyC/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Factorial b/Lang/HolyC/Factorial new file mode 120000 index 0000000000..cc782c63c4 --- /dev/null +++ b/Lang/HolyC/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Find-limit-of-recursion b/Lang/HolyC/Find-limit-of-recursion new file mode 120000 index 0000000000..59aa5c8ee7 --- /dev/null +++ b/Lang/HolyC/Find-limit-of-recursion @@ -0,0 +1 @@ +../../Task/Find-limit-of-recursion/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Function-definition b/Lang/HolyC/Function-definition new file mode 120000 index 0000000000..06fa6ae54a --- /dev/null +++ b/Lang/HolyC/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Guess-the-number b/Lang/HolyC/Guess-the-number new file mode 120000 index 0000000000..287af6c0d8 --- /dev/null +++ b/Lang/HolyC/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Guess-the-number-With-feedback b/Lang/HolyC/Guess-the-number-With-feedback new file mode 120000 index 0000000000..75bb352bdf --- /dev/null +++ b/Lang/HolyC/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Hello-world-Graphical b/Lang/HolyC/Hello-world-Graphical new file mode 120000 index 0000000000..acf2ca5f56 --- /dev/null +++ b/Lang/HolyC/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Hello-world-Newline-omission b/Lang/HolyC/Hello-world-Newline-omission new file mode 120000 index 0000000000..60ee4cc4c4 --- /dev/null +++ b/Lang/HolyC/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Hello-world-Text b/Lang/HolyC/Hello-world-Text new file mode 120000 index 0000000000..1a535d06e2 --- /dev/null +++ b/Lang/HolyC/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Increment-a-numerical-string b/Lang/HolyC/Increment-a-numerical-string new file mode 120000 index 0000000000..b4944ce582 --- /dev/null +++ b/Lang/HolyC/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Integer-comparison b/Lang/HolyC/Integer-comparison new file mode 120000 index 0000000000..bf36ee527f --- /dev/null +++ b/Lang/HolyC/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Literals-Integer b/Lang/HolyC/Literals-Integer new file mode 120000 index 0000000000..0fdd420614 --- /dev/null +++ b/Lang/HolyC/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Logical-operations b/Lang/HolyC/Logical-operations new file mode 120000 index 0000000000..2f47f801c7 --- /dev/null +++ b/Lang/HolyC/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Multiplication-tables b/Lang/HolyC/Multiplication-tables new file mode 120000 index 0000000000..02a94ca518 --- /dev/null +++ b/Lang/HolyC/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/HolyC \ No newline at end of file diff --git a/Lang/HolyC/String-length b/Lang/HolyC/String-length new file mode 120000 index 0000000000..5b5f0d8dea --- /dev/null +++ b/Lang/HolyC/String-length @@ -0,0 +1 @@ +../../Task/String-length/HolyC \ No newline at end of file diff --git a/Lang/HolyC/System-time b/Lang/HolyC/System-time new file mode 120000 index 0000000000..64031dcfc2 --- /dev/null +++ b/Lang/HolyC/System-time @@ -0,0 +1 @@ +../../Task/System-time/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Towers-of-Hanoi b/Lang/HolyC/Towers-of-Hanoi new file mode 120000 index 0000000000..5b3206549f --- /dev/null +++ b/Lang/HolyC/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/HolyC \ No newline at end of file diff --git a/Lang/HolyC/User-input-Text b/Lang/HolyC/User-input-Text new file mode 120000 index 0000000000..a3274372eb --- /dev/null +++ b/Lang/HolyC/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Variables b/Lang/HolyC/Variables new file mode 120000 index 0000000000..8857674839 --- /dev/null +++ b/Lang/HolyC/Variables @@ -0,0 +1 @@ +../../Task/Variables/HolyC \ No newline at end of file diff --git a/Lang/HolyC/Zero-to-the-zero-power b/Lang/HolyC/Zero-to-the-zero-power new file mode 120000 index 0000000000..bbd415a297 --- /dev/null +++ b/Lang/HolyC/Zero-to-the-zero-power @@ -0,0 +1 @@ +../../Task/Zero-to-the-zero-power/HolyC \ No newline at end of file diff --git a/Lang/Hy/00DESCRIPTION b/Lang/Hy/00DESCRIPTION index 5a454a90bf..05640cc643 100644 --- a/Lang/Hy/00DESCRIPTION +++ b/Lang/Hy/00DESCRIPTION @@ -1,6 +1,6 @@ {{language}} {{implementation|Lisp}} -A Lispy syntax for [[Python]]. The implementation can generate Python source code, not just bytecode, so you can use Hy with, e.g., PyPy just as well as CPython. +A Lispy syntax for [[Python]]. The implementation generates Python abstract syntax trees (AST), not just bytecode, so you can use Hy with, e.g., PyPy just as well as CPython. Website: http://hylang.org \ No newline at end of file diff --git a/Lang/I/00DESCRIPTION b/Lang/I/00DESCRIPTION index 6dd69d18ca..86327cd42e 100644 --- a/Lang/I/00DESCRIPTION +++ b/Lang/I/00DESCRIPTION @@ -1 +1 @@ -{{stub}}{{language|I}} \ No newline at end of file +{{stub}}{{language|i}} \ No newline at end of file diff --git a/Lang/Idris/Extend-your-language b/Lang/Idris/Extend-your-language new file mode 120000 index 0000000000..c5738eed35 --- /dev/null +++ b/Lang/Idris/Extend-your-language @@ -0,0 +1 @@ +../../Task/Extend-your-language/Idris \ No newline at end of file diff --git a/Lang/J/00DESCRIPTION b/Lang/J/00DESCRIPTION index def3c6335b..a558e645d5 100644 --- a/Lang/J/00DESCRIPTION +++ b/Lang/J/00DESCRIPTION @@ -33,9 +33,12 @@ The notation draws heavily from concepts of [[wp:Abstract algebra|Abstract algeb == Reading J == -J is meant to be read with the aid of a computer. J sentences are single lines and trying variations and simplifications of an expression is common practice. The first step in understanding any J sentence is to understand the data you started with and the data which resulted. 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. +J is meant to be read with the aid of a computer. J sentences are single lines and trying variations and simplifications of an expression is common practice. The first step in understanding any J sentence is to understand the data you started with and the data which resulted. +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. 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]]. +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. +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. @@ -63,11 +66,14 @@ By themselves, these experiments mean nothing, but if you know that +/ was findi == Some Perspective == -If you wish to use J you will also have to learn a few grammatical rules (J's parser has [http://www.jsoftware.com/help/dictionary/dicte.htm 9 reduction rules] and "shift" and "accept" - the above examples use four of those rules). J verbs have two definitions - a single argument "monadic" definition and a two argument "dyadic" definition. These terms are borrowed from music and are distinct from Haskell's use of the word "monad". The dyadic definitions are in some sense related to LISP's "cons cell" but are implemented as grammar rather than data structure, and are a pervasive part of the language. +If you wish to use J you will also have to learn a few grammatical rules (J's parser has [http://www.jsoftware.com/help/dictionary/dicte.htm 9 reduction rules] and "shift" and "accept" - the above examples use four of those rules). J verbs have two definitions - a single argument "monadic" definition and a two argument "dyadic" definition. +These terms are borrowed from music and are distinct from Haskell's use of the word "monad". +The dyadic definitions are in some sense related to LISP's "cons cell" but are implemented as grammar rather than data structure, and are a pervasive part of the language. Another pervasive feature of the language is [[wp:Rank_(J_programming_language)|rank]]. -The language represents capabilities of hardware. For example, if language did not have an internal stack, a word's definition could not be used during the execution of that word. All current J implementations support recursion, but in some sense this is a convenience, and it's reasonable to imagine J implementations which do not (perhaps in a "compile to silicon" implementation). +The language represents capabilities of hardware. +For example, if language did not have an internal stack, a word's definition could not be used during the execution of that word. All current J implementations support recursion, but in some sense this is a convenience, and it's reasonable to imagine J implementations which do not (perhaps in a "compile to silicon" implementation). == J on RosettaCode == @@ -91,10 +97,17 @@ Discussion of the goals of the J community on RC and general guidelines for pres == Try me == -Want to try one of those cryptic J lines you see peppered through RC? Try pasting it into this [http://joebo.github.io/j-emscripten/ browser-based implementation of J]. +Want to try one of those cryptic J lines you see peppered through RC? +Try pasting it into this [http://joebo.github.io/j-emscripten/ browser-based implementation of J]. -If you want to be a bit more interactive, and get some guidance from J gurus, you can join the actual J IRC channel on Freenode, #jsoftware. Buubot and several other J eval bots run there. 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 you want to be a bit more interactive, and get some guidance from J gurus, you can join the actual J IRC channel on Freenode, #jsoftware. Buubot and several other J eval bots run there. +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 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. \ No newline at end of file +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. + +==Todo== +[[Reports:Tasks_not_implemented_in_J]] \ No newline at end of file diff --git a/Lang/J/Carmichael-3-strong-pseudoprimes b/Lang/J/Carmichael-3-strong-pseudoprimes new file mode 120000 index 0000000000..88cb62eceb --- /dev/null +++ b/Lang/J/Carmichael-3-strong-pseudoprimes @@ -0,0 +1 @@ +../../Task/Carmichael-3-strong-pseudoprimes/J \ No newline at end of file diff --git a/Lang/JCL/00DESCRIPTION b/Lang/JCL/00DESCRIPTION index 4d3d27c049..4a2c7efeb2 100644 --- a/Lang/JCL/00DESCRIPTION +++ b/Lang/JCL/00DESCRIPTION @@ -1 +1,36 @@ -{{stub}}{{language}} \ No newline at end of file +{{language}} +[[Category:JCL]] +IBM Job Control Language + +Job Control Language, commonly named JCL, refers to certain scripting languages, particularly IBM mainframe operating systems, whose role is to run a batch job. + +There are two distinct IBM Job Control languages: +* DOS JCL for system DOS/360, VSE, z/VSE +* OS JCL for system OS/360, MVS, z/OS +
+Although they have syntax and design rules in common, they are quite different languages. + +In the JCL, the unit is the job, which consists of one or more steps. Each step consists of the execution of a specific program. + +It is possible to create JCL scripts that can be called in other JCL scripts by passing parameters if necessary. Such scripts are called procedures. + +==DOS JCL== +DOS JCL parameters are positional, which makes them harder to read and write, but easier for the system to parse. + +==OS JCL== +In general, the OS JCL is more flexible and easier to use than the DOS JCL. + +===Basic cards=== +The JCL statements are called cards because the method of providing new input to a computer system was 80-column punched cards. +The OS JCL has only three basic cards: +* the JOB card, which identifies the job and provides information related to it; +* the EXEC card, which allows each step to identify which program to call; +* the DD card that identifies the datasets (files) to use during a step. +
+In the following examples JCL refers only to IBM OS JCL. + +==Wikipedia article== +https://en.wikipedia.org/wiki/Job_Control_Language + +==See also== +https://www.ibm.com/support/knowledgecenter/zosbasics/com.ibm.zos.zjcl/zjclc_basicjclconcepts.htm \ No newline at end of file diff --git a/Lang/JCL/Conditional-structures b/Lang/JCL/Conditional-structures new file mode 120000 index 0000000000..91e2e49cae --- /dev/null +++ b/Lang/JCL/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/JCL \ No newline at end of file diff --git a/Lang/Java/00DESCRIPTION b/Lang/Java/00DESCRIPTION index 71ff53eaa0..e774c36704 100644 --- a/Lang/Java/00DESCRIPTION +++ b/Lang/Java/00DESCRIPTION @@ -18,7 +18,9 @@ {{language programming paradigm|reflective}}[[runs on vm::java virtual machine| ]] The '''Java''' programming language, developed by [[Sun Microsystems]], is a language aimed at allowing "high-performance", virtual application development. -Java source files (.java files) are typically [[Compiler|compiled]] to an intermediate [[bytecode]] (all platform) executable (.class files) and executed by a [[Java Virtual Machine]]. Most modern JVMs further compile the bytecode into your processor's native machine code during execution. This native code translation is mostly done via a [[Just-In-Time|JIT]] compiler that is built in the JVM. Some Java compilers (such as [[GCJ]]) can compile Java code to native machine code ahead-of-time rather than just-in-time. +Java source files (.java files) are typically [[Compiler|compiled]] to an intermediate [[bytecode]] (all platform) executable (.class files) and executed by a [[Java Virtual Machine]]. +Most modern JVMs further compile the bytecode into your processor's native machine code during execution. +This native code translation is mostly done via a [[Just-In-Time|JIT]] compiler that is built in the JVM. Some Java compilers (such as [[GCJ]]) can compile Java code to native machine code ahead-of-time rather than just-in-time. The primary benefits of Java are: * Cross-[[platform]] (Write Once, Run Anywhere (if all of the libraries are ported)) @@ -29,11 +31,16 @@ The primary benefits of Java are: Java is used in a variety of environments including desktop applications, embedded device (PDA and wireless phone) applications, server-side web page serving applications (as [[Java Server Pages|JSP]]), and applets embedded in web pages. -There are a variety of arguments regarding Java's performance compared to other popular languages like [[C++]]. Some come to the conclusion that the programmer's choices make a bigger difference on performance in each language. Most show that each language is better than the other at specific types of operations (e.g. Java for memory allocation, C++ for numerical operations). An extensive summary of comparisons between Java and C++ can be found [[wp:Comparison of Java and C++|on Wikipedia]]. +There are a variety of arguments regarding Java's performance compared to other popular languages like [[C++]]. Some come to the conclusion that the programmer's choices make a bigger difference on performance in each language. Most show that each language is better than the other at specific types of operations (e.g. Java for memory allocation, C++ for numerical operations). +An extensive summary of comparisons between Java and C++ can be found [[wp:Comparison of Java and C++|on Wikipedia]]. According to some [http://www.tiobe.com/tpci.htm sources], Java is currently one of the most popular programming languages in the world. Useful Java links: * [http://www.java.com java.com] * [http://www.java.net java.net] -* [http://openjdk.java.net OpenJDK] \ No newline at end of file +* [http://openjdk.java.net OpenJDK] +* [https://hackr.io/tutorials/learn-java Hackr.io] + +==Todo== +[[Reports:Tasks_not_implemented_in_Java]] \ No newline at end of file diff --git a/Lang/Java/Arithmetic-geometric-mean-Calculate-Pi b/Lang/Java/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..9bda319939 --- /dev/null +++ b/Lang/Java/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/Java \ No newline at end of file diff --git a/Lang/Java/Averages-Mean-time-of-day b/Lang/Java/Averages-Mean-time-of-day new file mode 120000 index 0000000000..bd96d5ed3d --- /dev/null +++ b/Lang/Java/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/Java \ No newline at end of file diff --git a/Lang/Java/Binary-strings b/Lang/Java/Binary-strings new file mode 120000 index 0000000000..feb557c93b --- /dev/null +++ b/Lang/Java/Binary-strings @@ -0,0 +1 @@ +../../Task/Binary-strings/Java \ No newline at end of file diff --git a/Lang/Java/Circles-of-given-radius-through-two-points b/Lang/Java/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..4fcc695ad6 --- /dev/null +++ b/Lang/Java/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/Java \ No newline at end of file diff --git a/Lang/Java/Continued-fraction-Arithmetic-Construct-from-rational-number b/Lang/Java/Continued-fraction-Arithmetic-Construct-from-rational-number new file mode 120000 index 0000000000..eacba13a54 --- /dev/null +++ b/Lang/Java/Continued-fraction-Arithmetic-Construct-from-rational-number @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Java \ No newline at end of file diff --git a/Lang/Java/History-variables b/Lang/Java/History-variables new file mode 120000 index 0000000000..2347fc84d3 --- /dev/null +++ b/Lang/Java/History-variables @@ -0,0 +1 @@ +../../Task/History-variables/Java \ No newline at end of file diff --git a/Lang/Java/Interactive-programming b/Lang/Java/Interactive-programming new file mode 120000 index 0000000000..64b5e2815c --- /dev/null +++ b/Lang/Java/Interactive-programming @@ -0,0 +1 @@ +../../Task/Interactive-programming/Java \ No newline at end of file diff --git a/Lang/Java/List-comprehensions b/Lang/Java/List-comprehensions new file mode 120000 index 0000000000..f50bb6b7e1 --- /dev/null +++ b/Lang/Java/List-comprehensions @@ -0,0 +1 @@ +../../Task/List-comprehensions/Java \ No newline at end of file diff --git a/Lang/Java/Multiplicative-order b/Lang/Java/Multiplicative-order new file mode 120000 index 0000000000..8452f7a32d --- /dev/null +++ b/Lang/Java/Multiplicative-order @@ -0,0 +1 @@ +../../Task/Multiplicative-order/Java \ No newline at end of file diff --git a/Lang/Java/Permutation-test b/Lang/Java/Permutation-test new file mode 120000 index 0000000000..58cc4c180b --- /dev/null +++ b/Lang/Java/Permutation-test @@ -0,0 +1 @@ +../../Task/Permutation-test/Java \ No newline at end of file diff --git a/Lang/Java/Polynomial-long-division b/Lang/Java/Polynomial-long-division new file mode 120000 index 0000000000..d0401bfca4 --- /dev/null +++ b/Lang/Java/Polynomial-long-division @@ -0,0 +1 @@ +../../Task/Polynomial-long-division/Java \ No newline at end of file diff --git a/Lang/Java/Polynomial-regression b/Lang/Java/Polynomial-regression new file mode 120000 index 0000000000..585909db53 --- /dev/null +++ b/Lang/Java/Polynomial-regression @@ -0,0 +1 @@ +../../Task/Polynomial-regression/Java \ No newline at end of file diff --git a/Lang/Java/RSA-code b/Lang/Java/RSA-code new file mode 120000 index 0000000000..a33a8351be --- /dev/null +++ b/Lang/Java/RSA-code @@ -0,0 +1 @@ +../../Task/RSA-code/Java \ No newline at end of file diff --git a/Lang/Java/Resistor-mesh b/Lang/Java/Resistor-mesh new file mode 120000 index 0000000000..f198038d22 --- /dev/null +++ b/Lang/Java/Resistor-mesh @@ -0,0 +1 @@ +../../Task/Resistor-mesh/Java \ No newline at end of file diff --git a/Lang/Java/Runtime-evaluation b/Lang/Java/Runtime-evaluation new file mode 120000 index 0000000000..164bde7c0e --- /dev/null +++ b/Lang/Java/Runtime-evaluation @@ -0,0 +1 @@ +../../Task/Runtime-evaluation/Java \ No newline at end of file diff --git a/Lang/Java/Safe-addition b/Lang/Java/Safe-addition new file mode 120000 index 0000000000..ac7cf8fe8f --- /dev/null +++ b/Lang/Java/Safe-addition @@ -0,0 +1 @@ +../../Task/Safe-addition/Java \ No newline at end of file diff --git a/Lang/Java/Special-variables b/Lang/Java/Special-variables new file mode 120000 index 0000000000..5754fc95f5 --- /dev/null +++ b/Lang/Java/Special-variables @@ -0,0 +1 @@ +../../Task/Special-variables/Java \ No newline at end of file diff --git a/Lang/Java/Vigen-re-cipher-Cryptanalysis b/Lang/Java/Vigen-re-cipher-Cryptanalysis new file mode 120000 index 0000000000..6ebe5e0d12 --- /dev/null +++ b/Lang/Java/Vigen-re-cipher-Cryptanalysis @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher-Cryptanalysis/Java \ No newline at end of file diff --git a/Lang/Java/Zeckendorf-arithmetic b/Lang/Java/Zeckendorf-arithmetic new file mode 120000 index 0000000000..37f438182d --- /dev/null +++ b/Lang/Java/Zeckendorf-arithmetic @@ -0,0 +1 @@ +../../Task/Zeckendorf-arithmetic/Java \ No newline at end of file diff --git a/Lang/JavaScript/Here-document b/Lang/JavaScript/Here-document new file mode 120000 index 0000000000..8a9df8bd4b --- /dev/null +++ b/Lang/JavaScript/Here-document @@ -0,0 +1 @@ +../../Task/Here-document/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/K-means++-clustering b/Lang/JavaScript/K-means++-clustering new file mode 120000 index 0000000000..eb4b0b3be3 --- /dev/null +++ b/Lang/JavaScript/K-means++-clustering @@ -0,0 +1 @@ +../../Task/K-means++-clustering/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Number-names b/Lang/JavaScript/Number-names new file mode 120000 index 0000000000..bcb9af0a05 --- /dev/null +++ b/Lang/JavaScript/Number-names @@ -0,0 +1 @@ +../../Task/Number-names/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Ulam-spiral--for-primes- b/Lang/JavaScript/Ulam-spiral--for-primes- new file mode 120000 index 0000000000..1e756422f4 --- /dev/null +++ b/Lang/JavaScript/Ulam-spiral--for-primes- @@ -0,0 +1 @@ +../../Task/Ulam-spiral--for-primes-/JavaScript \ No newline at end of file diff --git a/Lang/Julia/00DESCRIPTION b/Lang/Julia/00DESCRIPTION index a8e9b8a3ac..1c807ba161 100644 --- a/Lang/Julia/00DESCRIPTION +++ b/Lang/Julia/00DESCRIPTION @@ -6,11 +6,14 @@ |gc=yes |parampass=both |safety=both -|checking=both +|checking=dynamic |strength=strong }} Julia is a high-level, high-performance dynamic programming language for technical computing, with syntax silimar to [[MATLAB]]'s. It provides a sophisticated compiler, distributed parallel execution, numerical accuracy, and an extensive mathematical function library. It is a functional language that uses multiple dispatch as its primary paradigm. -It has first-class types and homoiconic macros. \ No newline at end of file +It has first-class types and homoiconic macros. + +==Todo== +[[Reports:Tasks_not_implemented_in_Julia]] \ No newline at end of file diff --git a/Lang/Julia/Active-object b/Lang/Julia/Active-object new file mode 120000 index 0000000000..6d796b1648 --- /dev/null +++ b/Lang/Julia/Active-object @@ -0,0 +1 @@ +../../Task/Active-object/Julia \ No newline at end of file diff --git a/Lang/Julia/Add-a-variable-to-a-class-instance-at-runtime b/Lang/Julia/Add-a-variable-to-a-class-instance-at-runtime new file mode 120000 index 0000000000..4651507e5e --- /dev/null +++ b/Lang/Julia/Add-a-variable-to-a-class-instance-at-runtime @@ -0,0 +1 @@ +../../Task/Add-a-variable-to-a-class-instance-at-runtime/Julia \ No newline at end of file diff --git a/Lang/Julia/Animate-a-pendulum b/Lang/Julia/Animate-a-pendulum new file mode 120000 index 0000000000..1c0b2b29b1 --- /dev/null +++ b/Lang/Julia/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/Julia \ No newline at end of file diff --git a/Lang/Julia/Animation b/Lang/Julia/Animation new file mode 120000 index 0000000000..57a47ddf8b --- /dev/null +++ b/Lang/Julia/Animation @@ -0,0 +1 @@ +../../Task/Animation/Julia \ No newline at end of file diff --git a/Lang/Julia/Append-a-record-to-the-end-of-a-text-file b/Lang/Julia/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..341cf7fa1c --- /dev/null +++ b/Lang/Julia/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/Julia \ No newline at end of file diff --git a/Lang/Julia/Arena-storage-pool b/Lang/Julia/Arena-storage-pool new file mode 120000 index 0000000000..8139746611 --- /dev/null +++ b/Lang/Julia/Arena-storage-pool @@ -0,0 +1 @@ +../../Task/Arena-storage-pool/Julia \ No newline at end of file diff --git a/Lang/Julia/Atomic-updates b/Lang/Julia/Atomic-updates new file mode 120000 index 0000000000..08997338c7 --- /dev/null +++ b/Lang/Julia/Atomic-updates @@ -0,0 +1 @@ +../../Task/Atomic-updates/Julia \ No newline at end of file diff --git a/Lang/Julia/Averages-Mean-time-of-day b/Lang/Julia/Averages-Mean-time-of-day new file mode 120000 index 0000000000..3d471bfddc --- /dev/null +++ b/Lang/Julia/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/Julia \ No newline at end of file diff --git a/Lang/Julia/Balanced-ternary b/Lang/Julia/Balanced-ternary new file mode 120000 index 0000000000..ff2c96cd67 --- /dev/null +++ b/Lang/Julia/Balanced-ternary @@ -0,0 +1 @@ +../../Task/Balanced-ternary/Julia \ No newline at end of file diff --git a/Lang/Julia/Bitcoin-address-validation b/Lang/Julia/Bitcoin-address-validation new file mode 120000 index 0000000000..f7d8c7e8fb --- /dev/null +++ b/Lang/Julia/Bitcoin-address-validation @@ -0,0 +1 @@ +../../Task/Bitcoin-address-validation/Julia \ No newline at end of file diff --git a/Lang/Julia/Bitcoin-public-point-to-address b/Lang/Julia/Bitcoin-public-point-to-address new file mode 120000 index 0000000000..19dbe90829 --- /dev/null +++ b/Lang/Julia/Bitcoin-public-point-to-address @@ -0,0 +1 @@ +../../Task/Bitcoin-public-point-to-address/Julia \ No newline at end of file diff --git a/Lang/Julia/Bitmap-B-zier-curves-Cubic b/Lang/Julia/Bitmap-B-zier-curves-Cubic new file mode 120000 index 0000000000..90982fc4e9 --- /dev/null +++ b/Lang/Julia/Bitmap-B-zier-curves-Cubic @@ -0,0 +1 @@ +../../Task/Bitmap-B-zier-curves-Cubic/Julia \ No newline at end of file diff --git a/Lang/Julia/Bitmap-Flood-fill b/Lang/Julia/Bitmap-Flood-fill new file mode 120000 index 0000000000..268e743965 --- /dev/null +++ b/Lang/Julia/Bitmap-Flood-fill @@ -0,0 +1 @@ +../../Task/Bitmap-Flood-fill/Julia \ No newline at end of file diff --git a/Lang/Julia/Bitmap-Midpoint-circle-algorithm b/Lang/Julia/Bitmap-Midpoint-circle-algorithm new file mode 120000 index 0000000000..84c157ef80 --- /dev/null +++ b/Lang/Julia/Bitmap-Midpoint-circle-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Midpoint-circle-algorithm/Julia \ No newline at end of file diff --git a/Lang/Julia/Bitmap-PPM-conversion-through-a-pipe b/Lang/Julia/Bitmap-PPM-conversion-through-a-pipe new file mode 120000 index 0000000000..bcea10f350 --- /dev/null +++ b/Lang/Julia/Bitmap-PPM-conversion-through-a-pipe @@ -0,0 +1 @@ +../../Task/Bitmap-PPM-conversion-through-a-pipe/Julia \ No newline at end of file diff --git a/Lang/Julia/Bitmap-Read-an-image-through-a-pipe b/Lang/Julia/Bitmap-Read-an-image-through-a-pipe new file mode 120000 index 0000000000..516ec24324 --- /dev/null +++ b/Lang/Julia/Bitmap-Read-an-image-through-a-pipe @@ -0,0 +1 @@ +../../Task/Bitmap-Read-an-image-through-a-pipe/Julia \ No newline at end of file diff --git a/Lang/Julia/Bulls-and-cows-Player b/Lang/Julia/Bulls-and-cows-Player new file mode 120000 index 0000000000..2445dcbd49 --- /dev/null +++ b/Lang/Julia/Bulls-and-cows-Player @@ -0,0 +1 @@ +../../Task/Bulls-and-cows-Player/Julia \ No newline at end of file diff --git a/Lang/Julia/Call-a-function b/Lang/Julia/Call-a-function new file mode 120000 index 0000000000..7e3526e6df --- /dev/null +++ b/Lang/Julia/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/Julia \ No newline at end of file diff --git a/Lang/Julia/Canny-edge-detector b/Lang/Julia/Canny-edge-detector new file mode 120000 index 0000000000..1a5d37bc27 --- /dev/null +++ b/Lang/Julia/Canny-edge-detector @@ -0,0 +1 @@ +../../Task/Canny-edge-detector/Julia \ No newline at end of file diff --git a/Lang/Julia/Chat-server b/Lang/Julia/Chat-server new file mode 120000 index 0000000000..f3f29f0b6a --- /dev/null +++ b/Lang/Julia/Chat-server @@ -0,0 +1 @@ +../../Task/Chat-server/Julia \ No newline at end of file diff --git a/Lang/Julia/Chinese-remainder-theorem b/Lang/Julia/Chinese-remainder-theorem new file mode 120000 index 0000000000..b32025b325 --- /dev/null +++ b/Lang/Julia/Chinese-remainder-theorem @@ -0,0 +1 @@ +../../Task/Chinese-remainder-theorem/Julia \ No newline at end of file diff --git a/Lang/Julia/Classes b/Lang/Julia/Classes new file mode 120000 index 0000000000..420f31342d --- /dev/null +++ b/Lang/Julia/Classes @@ -0,0 +1 @@ +../../Task/Classes/Julia \ No newline at end of file diff --git a/Lang/Julia/Collections b/Lang/Julia/Collections new file mode 120000 index 0000000000..46c608f05f --- /dev/null +++ b/Lang/Julia/Collections @@ -0,0 +1 @@ +../../Task/Collections/Julia \ No newline at end of file diff --git a/Lang/Julia/Colour-bars-Display b/Lang/Julia/Colour-bars-Display new file mode 120000 index 0000000000..a29126fb7a --- /dev/null +++ b/Lang/Julia/Colour-bars-Display @@ -0,0 +1 @@ +../../Task/Colour-bars-Display/Julia \ No newline at end of file diff --git a/Lang/Julia/Concurrent-computing b/Lang/Julia/Concurrent-computing new file mode 120000 index 0000000000..c175e596db --- /dev/null +++ b/Lang/Julia/Concurrent-computing @@ -0,0 +1 @@ +../../Task/Concurrent-computing/Julia \ No newline at end of file diff --git a/Lang/Julia/Conditional-structures b/Lang/Julia/Conditional-structures new file mode 120000 index 0000000000..c471667cca --- /dev/null +++ b/Lang/Julia/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/Julia \ No newline at end of file diff --git a/Lang/Julia/Constrained-genericity b/Lang/Julia/Constrained-genericity new file mode 120000 index 0000000000..bbbac864b9 --- /dev/null +++ b/Lang/Julia/Constrained-genericity @@ -0,0 +1 @@ +../../Task/Constrained-genericity/Julia \ No newline at end of file diff --git a/Lang/Julia/Create-an-HTML-table b/Lang/Julia/Create-an-HTML-table new file mode 120000 index 0000000000..118768ffca --- /dev/null +++ b/Lang/Julia/Create-an-HTML-table @@ -0,0 +1 @@ +../../Task/Create-an-HTML-table/Julia \ No newline at end of file diff --git a/Lang/Julia/Create-an-object-at-a-given-address b/Lang/Julia/Create-an-object-at-a-given-address new file mode 120000 index 0000000000..bacbf8cbd2 --- /dev/null +++ b/Lang/Julia/Create-an-object-at-a-given-address @@ -0,0 +1 @@ +../../Task/Create-an-object-at-a-given-address/Julia \ No newline at end of file diff --git a/Lang/Julia/Date-manipulation b/Lang/Julia/Date-manipulation new file mode 120000 index 0000000000..c76a23ba05 --- /dev/null +++ b/Lang/Julia/Date-manipulation @@ -0,0 +1 @@ +../../Task/Date-manipulation/Julia \ No newline at end of file diff --git a/Lang/Julia/Deconvolution-1D b/Lang/Julia/Deconvolution-1D new file mode 120000 index 0000000000..4dd48fb370 --- /dev/null +++ b/Lang/Julia/Deconvolution-1D @@ -0,0 +1 @@ +../../Task/Deconvolution-1D/Julia \ No newline at end of file diff --git a/Lang/Julia/Define-a-primitive-data-type b/Lang/Julia/Define-a-primitive-data-type new file mode 120000 index 0000000000..a9a8553406 --- /dev/null +++ b/Lang/Julia/Define-a-primitive-data-type @@ -0,0 +1 @@ +../../Task/Define-a-primitive-data-type/Julia \ No newline at end of file diff --git a/Lang/Julia/Delegates b/Lang/Julia/Delegates new file mode 120000 index 0000000000..a7c94db0fd --- /dev/null +++ b/Lang/Julia/Delegates @@ -0,0 +1 @@ +../../Task/Delegates/Julia \ No newline at end of file diff --git a/Lang/Julia/Dinesmans-multiple-dwelling-problem b/Lang/Julia/Dinesmans-multiple-dwelling-problem new file mode 120000 index 0000000000..45584aba70 --- /dev/null +++ b/Lang/Julia/Dinesmans-multiple-dwelling-problem @@ -0,0 +1 @@ +../../Task/Dinesmans-multiple-dwelling-problem/Julia \ No newline at end of file diff --git a/Lang/Julia/Dining-philosophers b/Lang/Julia/Dining-philosophers new file mode 120000 index 0000000000..e558c061a5 --- /dev/null +++ b/Lang/Julia/Dining-philosophers @@ -0,0 +1 @@ +../../Task/Dining-philosophers/Julia \ No newline at end of file diff --git a/Lang/Julia/Doubly-linked-list-Element-definition b/Lang/Julia/Doubly-linked-list-Element-definition new file mode 120000 index 0000000000..6eb62ee2cf --- /dev/null +++ b/Lang/Julia/Doubly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Element-definition/Julia \ No newline at end of file diff --git a/Lang/Julia/Dragon-curve b/Lang/Julia/Dragon-curve new file mode 120000 index 0000000000..f694960e8e --- /dev/null +++ b/Lang/Julia/Dragon-curve @@ -0,0 +1 @@ +../../Task/Dragon-curve/Julia \ No newline at end of file diff --git a/Lang/Julia/Draw-a-cuboid b/Lang/Julia/Draw-a-cuboid new file mode 120000 index 0000000000..ae560391da --- /dev/null +++ b/Lang/Julia/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/Julia \ No newline at end of file diff --git a/Lang/Julia/Dynamic-variable-names b/Lang/Julia/Dynamic-variable-names new file mode 120000 index 0000000000..b27cfe7955 --- /dev/null +++ b/Lang/Julia/Dynamic-variable-names @@ -0,0 +1 @@ +../../Task/Dynamic-variable-names/Julia \ No newline at end of file diff --git a/Lang/Julia/Enforced-immutability b/Lang/Julia/Enforced-immutability new file mode 120000 index 0000000000..a2c2ce3a53 --- /dev/null +++ b/Lang/Julia/Enforced-immutability @@ -0,0 +1 @@ +../../Task/Enforced-immutability/Julia \ No newline at end of file diff --git a/Lang/Julia/Events b/Lang/Julia/Events new file mode 120000 index 0000000000..9b333dced2 --- /dev/null +++ b/Lang/Julia/Events @@ -0,0 +1 @@ +../../Task/Events/Julia \ No newline at end of file diff --git a/Lang/Julia/Exceptions b/Lang/Julia/Exceptions new file mode 120000 index 0000000000..f24aab2abd --- /dev/null +++ b/Lang/Julia/Exceptions @@ -0,0 +1 @@ +../../Task/Exceptions/Julia \ No newline at end of file diff --git a/Lang/Julia/Exceptions-Catch-an-exception-thrown-in-a-nested-call b/Lang/Julia/Exceptions-Catch-an-exception-thrown-in-a-nested-call new file mode 120000 index 0000000000..3a7f3a9c9f --- /dev/null +++ b/Lang/Julia/Exceptions-Catch-an-exception-thrown-in-a-nested-call @@ -0,0 +1 @@ +../../Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Julia \ No newline at end of file diff --git a/Lang/Julia/Executable-library b/Lang/Julia/Executable-library new file mode 120000 index 0000000000..0f043ffa6b --- /dev/null +++ b/Lang/Julia/Executable-library @@ -0,0 +1 @@ +../../Task/Executable-library/Julia \ No newline at end of file diff --git a/Lang/Julia/Execute-Brain---- b/Lang/Julia/Execute-Brain---- new file mode 120000 index 0000000000..226d632890 --- /dev/null +++ b/Lang/Julia/Execute-Brain---- @@ -0,0 +1 @@ +../../Task/Execute-Brain----/Julia \ No newline at end of file diff --git a/Lang/Julia/Execute-HQ9+ b/Lang/Julia/Execute-HQ9+ new file mode 120000 index 0000000000..d43fc53242 --- /dev/null +++ b/Lang/Julia/Execute-HQ9+ @@ -0,0 +1 @@ +../../Task/Execute-HQ9+/Julia \ No newline at end of file diff --git a/Lang/Julia/Execute-a-Markov-algorithm b/Lang/Julia/Execute-a-Markov-algorithm new file mode 120000 index 0000000000..2f4a215034 --- /dev/null +++ b/Lang/Julia/Execute-a-Markov-algorithm @@ -0,0 +1 @@ +../../Task/Execute-a-Markov-algorithm/Julia \ No newline at end of file diff --git a/Lang/Julia/Extensible-prime-generator b/Lang/Julia/Extensible-prime-generator new file mode 120000 index 0000000000..644ffb9d71 --- /dev/null +++ b/Lang/Julia/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/Julia \ No newline at end of file diff --git a/Lang/Julia/Fibonacci-word-fractal b/Lang/Julia/Fibonacci-word-fractal new file mode 120000 index 0000000000..564b34653f --- /dev/null +++ b/Lang/Julia/Fibonacci-word-fractal @@ -0,0 +1 @@ +../../Task/Fibonacci-word-fractal/Julia \ No newline at end of file diff --git a/Lang/Julia/First-class-functions-Use-numbers-analogously b/Lang/Julia/First-class-functions-Use-numbers-analogously new file mode 120000 index 0000000000..3b21d5419a --- /dev/null +++ b/Lang/Julia/First-class-functions-Use-numbers-analogously @@ -0,0 +1 @@ +../../Task/First-class-functions-Use-numbers-analogously/Julia \ No newline at end of file diff --git a/Lang/Julia/Flipping-bits-game b/Lang/Julia/Flipping-bits-game new file mode 120000 index 0000000000..cb1edd23a9 --- /dev/null +++ b/Lang/Julia/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/Julia \ No newline at end of file diff --git a/Lang/Julia/Flow-control-structures b/Lang/Julia/Flow-control-structures new file mode 120000 index 0000000000..f12bba52d7 --- /dev/null +++ b/Lang/Julia/Flow-control-structures @@ -0,0 +1 @@ +../../Task/Flow-control-structures/Julia \ No newline at end of file diff --git a/Lang/Julia/Formal-power-series b/Lang/Julia/Formal-power-series new file mode 120000 index 0000000000..e7f2413826 --- /dev/null +++ b/Lang/Julia/Formal-power-series @@ -0,0 +1 @@ +../../Task/Formal-power-series/Julia \ No newline at end of file diff --git a/Lang/Julia/Fractran b/Lang/Julia/Fractran new file mode 120000 index 0000000000..03fd350889 --- /dev/null +++ b/Lang/Julia/Fractran @@ -0,0 +1 @@ +../../Task/Fractran/Julia \ No newline at end of file diff --git a/Lang/Julia/Function-frequency b/Lang/Julia/Function-frequency new file mode 120000 index 0000000000..ed2c67f411 --- /dev/null +++ b/Lang/Julia/Function-frequency @@ -0,0 +1 @@ +../../Task/Function-frequency/Julia \ No newline at end of file diff --git a/Lang/Julia/Image-convolution b/Lang/Julia/Image-convolution new file mode 120000 index 0000000000..d226495a6a --- /dev/null +++ b/Lang/Julia/Image-convolution @@ -0,0 +1 @@ +../../Task/Image-convolution/Julia \ No newline at end of file diff --git a/Lang/Julia/Inverted-syntax b/Lang/Julia/Inverted-syntax new file mode 120000 index 0000000000..f7a2ccf68d --- /dev/null +++ b/Lang/Julia/Inverted-syntax @@ -0,0 +1 @@ +../../Task/Inverted-syntax/Julia \ No newline at end of file diff --git a/Lang/Julia/Jump-anywhere b/Lang/Julia/Jump-anywhere new file mode 120000 index 0000000000..b5bbbd2ed6 --- /dev/null +++ b/Lang/Julia/Jump-anywhere @@ -0,0 +1 @@ +../../Task/Jump-anywhere/Julia \ No newline at end of file diff --git a/Lang/Julia/Keyboard-input-Flush-the-keyboard-buffer b/Lang/Julia/Keyboard-input-Flush-the-keyboard-buffer new file mode 120000 index 0000000000..540199f9a3 --- /dev/null +++ b/Lang/Julia/Keyboard-input-Flush-the-keyboard-buffer @@ -0,0 +1 @@ +../../Task/Keyboard-input-Flush-the-keyboard-buffer/Julia \ No newline at end of file diff --git a/Lang/Julia/Keyboard-input-Obtain-a-Y-or-N-response b/Lang/Julia/Keyboard-input-Obtain-a-Y-or-N-response new file mode 120000 index 0000000000..dfd29fd8ca --- /dev/null +++ b/Lang/Julia/Keyboard-input-Obtain-a-Y-or-N-response @@ -0,0 +1 @@ +../../Task/Keyboard-input-Obtain-a-Y-or-N-response/Julia \ No newline at end of file diff --git a/Lang/Julia/Knapsack-problem-Unbounded b/Lang/Julia/Knapsack-problem-Unbounded new file mode 120000 index 0000000000..86ee806338 --- /dev/null +++ b/Lang/Julia/Knapsack-problem-Unbounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Unbounded/Julia \ No newline at end of file diff --git a/Lang/Julia/LZW-compression b/Lang/Julia/LZW-compression new file mode 120000 index 0000000000..e7cb3ba2d3 --- /dev/null +++ b/Lang/Julia/LZW-compression @@ -0,0 +1 @@ +../../Task/LZW-compression/Julia \ No newline at end of file diff --git a/Lang/Julia/Last-letter-first-letter b/Lang/Julia/Last-letter-first-letter new file mode 120000 index 0000000000..4031fbfd8f --- /dev/null +++ b/Lang/Julia/Last-letter-first-letter @@ -0,0 +1 @@ +../../Task/Last-letter-first-letter/Julia \ No newline at end of file diff --git a/Lang/Julia/Literals-Floating-point b/Lang/Julia/Literals-Floating-point new file mode 120000 index 0000000000..bee2ab54e3 --- /dev/null +++ b/Lang/Julia/Literals-Floating-point @@ -0,0 +1 @@ +../../Task/Literals-Floating-point/Julia \ No newline at end of file diff --git a/Lang/Julia/Long-multiplication b/Lang/Julia/Long-multiplication new file mode 120000 index 0000000000..df01cb4354 --- /dev/null +++ b/Lang/Julia/Long-multiplication @@ -0,0 +1 @@ +../../Task/Long-multiplication/Julia \ No newline at end of file diff --git a/Lang/Julia/Longest-increasing-subsequence b/Lang/Julia/Longest-increasing-subsequence new file mode 120000 index 0000000000..859bed3733 --- /dev/null +++ b/Lang/Julia/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Julia \ No newline at end of file diff --git a/Lang/Julia/Longest-string-challenge b/Lang/Julia/Longest-string-challenge new file mode 120000 index 0000000000..17a3444498 --- /dev/null +++ b/Lang/Julia/Longest-string-challenge @@ -0,0 +1 @@ +../../Task/Longest-string-challenge/Julia \ No newline at end of file diff --git a/Lang/Julia/Lucas-Lehmer-test b/Lang/Julia/Lucas-Lehmer-test new file mode 120000 index 0000000000..e196210941 --- /dev/null +++ b/Lang/Julia/Lucas-Lehmer-test @@ -0,0 +1 @@ +../../Task/Lucas-Lehmer-test/Julia \ No newline at end of file diff --git a/Lang/Julia/Mad-Libs b/Lang/Julia/Mad-Libs new file mode 120000 index 0000000000..42772b6193 --- /dev/null +++ b/Lang/Julia/Mad-Libs @@ -0,0 +1 @@ +../../Task/Mad-Libs/Julia \ No newline at end of file diff --git a/Lang/Julia/Main-step-of-GOST-28147-89 b/Lang/Julia/Main-step-of-GOST-28147-89 new file mode 120000 index 0000000000..1105a013d9 --- /dev/null +++ b/Lang/Julia/Main-step-of-GOST-28147-89 @@ -0,0 +1 @@ +../../Task/Main-step-of-GOST-28147-89/Julia \ No newline at end of file diff --git a/Lang/Julia/Make-directory-path b/Lang/Julia/Make-directory-path new file mode 120000 index 0000000000..60703e57b0 --- /dev/null +++ b/Lang/Julia/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/Julia \ No newline at end of file diff --git a/Lang/Julia/Maximum-triangle-path-sum b/Lang/Julia/Maximum-triangle-path-sum new file mode 120000 index 0000000000..d4727411fa --- /dev/null +++ b/Lang/Julia/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/Julia \ No newline at end of file diff --git a/Lang/Julia/Maze-solving b/Lang/Julia/Maze-solving new file mode 120000 index 0000000000..68bec88c9d --- /dev/null +++ b/Lang/Julia/Maze-solving @@ -0,0 +1 @@ +../../Task/Maze-solving/Julia \ No newline at end of file diff --git a/Lang/Julia/Median-filter b/Lang/Julia/Median-filter new file mode 120000 index 0000000000..96394b4ee7 --- /dev/null +++ b/Lang/Julia/Median-filter @@ -0,0 +1 @@ +../../Task/Median-filter/Julia \ No newline at end of file diff --git a/Lang/Julia/Memory-allocation b/Lang/Julia/Memory-allocation new file mode 120000 index 0000000000..08fc39d9a5 --- /dev/null +++ b/Lang/Julia/Memory-allocation @@ -0,0 +1 @@ +../../Task/Memory-allocation/Julia \ No newline at end of file diff --git a/Lang/Julia/Memory-layout-of-a-data-structure b/Lang/Julia/Memory-layout-of-a-data-structure new file mode 120000 index 0000000000..dd7fdd508d --- /dev/null +++ b/Lang/Julia/Memory-layout-of-a-data-structure @@ -0,0 +1 @@ +../../Task/Memory-layout-of-a-data-structure/Julia \ No newline at end of file diff --git a/Lang/Julia/Menu b/Lang/Julia/Menu new file mode 120000 index 0000000000..0ec9868df7 --- /dev/null +++ b/Lang/Julia/Menu @@ -0,0 +1 @@ +../../Task/Menu/Julia \ No newline at end of file diff --git a/Lang/Julia/Metronome b/Lang/Julia/Metronome new file mode 120000 index 0000000000..50a2dc5dc7 --- /dev/null +++ b/Lang/Julia/Metronome @@ -0,0 +1 @@ +../../Task/Metronome/Julia \ No newline at end of file diff --git a/Lang/Julia/Move-to-front-algorithm b/Lang/Julia/Move-to-front-algorithm new file mode 120000 index 0000000000..d71f5fbe93 --- /dev/null +++ b/Lang/Julia/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Julia \ No newline at end of file diff --git a/Lang/Julia/Multiple-distinct-objects b/Lang/Julia/Multiple-distinct-objects new file mode 120000 index 0000000000..948bd34e76 --- /dev/null +++ b/Lang/Julia/Multiple-distinct-objects @@ -0,0 +1 @@ +../../Task/Multiple-distinct-objects/Julia \ No newline at end of file diff --git a/Lang/Julia/Narcissist b/Lang/Julia/Narcissist new file mode 120000 index 0000000000..2b9099a1c3 --- /dev/null +++ b/Lang/Julia/Narcissist @@ -0,0 +1 @@ +../../Task/Narcissist/Julia \ No newline at end of file diff --git a/Lang/Julia/Object-serialization b/Lang/Julia/Object-serialization new file mode 120000 index 0000000000..3dc5e7241c --- /dev/null +++ b/Lang/Julia/Object-serialization @@ -0,0 +1 @@ +../../Task/Object-serialization/Julia \ No newline at end of file diff --git a/Lang/Julia/Odd-word-problem b/Lang/Julia/Odd-word-problem new file mode 120000 index 0000000000..7abd05bdaa --- /dev/null +++ b/Lang/Julia/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/Julia \ No newline at end of file diff --git a/Lang/Julia/Old-lady-swallowed-a-fly b/Lang/Julia/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..6a9934f733 --- /dev/null +++ b/Lang/Julia/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Julia \ No newline at end of file diff --git a/Lang/Julia/Ordered-Partitions b/Lang/Julia/Ordered-Partitions new file mode 120000 index 0000000000..89c301a3ad --- /dev/null +++ b/Lang/Julia/Ordered-Partitions @@ -0,0 +1 @@ +../../Task/Ordered-Partitions/Julia \ No newline at end of file diff --git a/Lang/Julia/Parallel-calculations b/Lang/Julia/Parallel-calculations new file mode 120000 index 0000000000..429d43fc73 --- /dev/null +++ b/Lang/Julia/Parallel-calculations @@ -0,0 +1 @@ +../../Task/Parallel-calculations/Julia \ No newline at end of file diff --git a/Lang/Julia/Parametric-polymorphism b/Lang/Julia/Parametric-polymorphism new file mode 120000 index 0000000000..11e3884832 --- /dev/null +++ b/Lang/Julia/Parametric-polymorphism @@ -0,0 +1 @@ +../../Task/Parametric-polymorphism/Julia \ No newline at end of file diff --git a/Lang/Julia/Parametrized-SQL-statement b/Lang/Julia/Parametrized-SQL-statement new file mode 120000 index 0000000000..5b282f61bc --- /dev/null +++ b/Lang/Julia/Parametrized-SQL-statement @@ -0,0 +1 @@ +../../Task/Parametrized-SQL-statement/Julia \ No newline at end of file diff --git a/Lang/Julia/Parse-an-IP-Address b/Lang/Julia/Parse-an-IP-Address new file mode 120000 index 0000000000..6b361dce48 --- /dev/null +++ b/Lang/Julia/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Julia \ No newline at end of file diff --git a/Lang/Julia/Parsing-RPN-to-infix-conversion b/Lang/Julia/Parsing-RPN-to-infix-conversion new file mode 120000 index 0000000000..5bffafa265 --- /dev/null +++ b/Lang/Julia/Parsing-RPN-to-infix-conversion @@ -0,0 +1 @@ +../../Task/Parsing-RPN-to-infix-conversion/Julia \ No newline at end of file diff --git a/Lang/Julia/Parsing-Shunting-yard-algorithm b/Lang/Julia/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..0724446740 --- /dev/null +++ b/Lang/Julia/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/Julia \ No newline at end of file diff --git a/Lang/Julia/Partial-function-application b/Lang/Julia/Partial-function-application new file mode 120000 index 0000000000..bd1aeb60aa --- /dev/null +++ b/Lang/Julia/Partial-function-application @@ -0,0 +1 @@ +../../Task/Partial-function-application/Julia \ No newline at end of file diff --git a/Lang/Julia/Pascals-triangle-Puzzle b/Lang/Julia/Pascals-triangle-Puzzle new file mode 120000 index 0000000000..a7726939a4 --- /dev/null +++ b/Lang/Julia/Pascals-triangle-Puzzle @@ -0,0 +1 @@ +../../Task/Pascals-triangle-Puzzle/Julia \ No newline at end of file diff --git a/Lang/Julia/Percentage-difference-between-images b/Lang/Julia/Percentage-difference-between-images new file mode 120000 index 0000000000..dfcb206301 --- /dev/null +++ b/Lang/Julia/Percentage-difference-between-images @@ -0,0 +1 @@ +../../Task/Percentage-difference-between-images/Julia \ No newline at end of file diff --git a/Lang/Julia/Percolation-Bond-percolation b/Lang/Julia/Percolation-Bond-percolation new file mode 120000 index 0000000000..f5350b67b4 --- /dev/null +++ b/Lang/Julia/Percolation-Bond-percolation @@ -0,0 +1 @@ +../../Task/Percolation-Bond-percolation/Julia \ No newline at end of file diff --git a/Lang/Julia/Percolation-Mean-cluster-density b/Lang/Julia/Percolation-Mean-cluster-density new file mode 120000 index 0000000000..dfb470839a --- /dev/null +++ b/Lang/Julia/Percolation-Mean-cluster-density @@ -0,0 +1 @@ +../../Task/Percolation-Mean-cluster-density/Julia \ No newline at end of file diff --git a/Lang/Julia/Percolation-Mean-run-density b/Lang/Julia/Percolation-Mean-run-density new file mode 120000 index 0000000000..4d83d47564 --- /dev/null +++ b/Lang/Julia/Percolation-Mean-run-density @@ -0,0 +1 @@ +../../Task/Percolation-Mean-run-density/Julia \ No newline at end of file diff --git a/Lang/Julia/Percolation-Site-percolation b/Lang/Julia/Percolation-Site-percolation new file mode 120000 index 0000000000..b90f44478b --- /dev/null +++ b/Lang/Julia/Percolation-Site-percolation @@ -0,0 +1 @@ +../../Task/Percolation-Site-percolation/Julia \ No newline at end of file diff --git a/Lang/Julia/Permutations-by-swapping b/Lang/Julia/Permutations-by-swapping new file mode 120000 index 0000000000..955cef299f --- /dev/null +++ b/Lang/Julia/Permutations-by-swapping @@ -0,0 +1 @@ +../../Task/Permutations-by-swapping/Julia \ No newline at end of file diff --git a/Lang/Julia/Pinstripe-Display b/Lang/Julia/Pinstripe-Display new file mode 120000 index 0000000000..15b29978ee --- /dev/null +++ b/Lang/Julia/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/Julia \ No newline at end of file diff --git a/Lang/Julia/Program-termination b/Lang/Julia/Program-termination new file mode 120000 index 0000000000..df06ed63fc --- /dev/null +++ b/Lang/Julia/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/Julia \ No newline at end of file diff --git a/Lang/Julia/Queue-Usage b/Lang/Julia/Queue-Usage new file mode 120000 index 0000000000..a31dc5aa1e --- /dev/null +++ b/Lang/Julia/Queue-Usage @@ -0,0 +1 @@ +../../Task/Queue-Usage/Julia \ No newline at end of file diff --git a/Lang/Julia/Quickselect-algorithm b/Lang/Julia/Quickselect-algorithm new file mode 120000 index 0000000000..938636ea2e --- /dev/null +++ b/Lang/Julia/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/Julia \ No newline at end of file diff --git a/Lang/Julia/RSA-code b/Lang/Julia/RSA-code new file mode 120000 index 0000000000..274037fd69 --- /dev/null +++ b/Lang/Julia/RSA-code @@ -0,0 +1 @@ +../../Task/RSA-code/Julia \ No newline at end of file diff --git a/Lang/Julia/Ray-casting-algorithm b/Lang/Julia/Ray-casting-algorithm new file mode 120000 index 0000000000..e12276fb15 --- /dev/null +++ b/Lang/Julia/Ray-casting-algorithm @@ -0,0 +1 @@ +../../Task/Ray-casting-algorithm/Julia \ No newline at end of file diff --git a/Lang/Julia/Read-a-configuration-file b/Lang/Julia/Read-a-configuration-file new file mode 120000 index 0000000000..a7395d64b5 --- /dev/null +++ b/Lang/Julia/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/Julia \ No newline at end of file diff --git a/Lang/Julia/Record-sound b/Lang/Julia/Record-sound new file mode 120000 index 0000000000..08da83a2bf --- /dev/null +++ b/Lang/Julia/Record-sound @@ -0,0 +1 @@ +../../Task/Record-sound/Julia \ No newline at end of file diff --git a/Lang/Julia/Respond-to-an-unknown-method-call b/Lang/Julia/Respond-to-an-unknown-method-call new file mode 120000 index 0000000000..0a7f78518e --- /dev/null +++ b/Lang/Julia/Respond-to-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Respond-to-an-unknown-method-call/Julia \ No newline at end of file diff --git a/Lang/Julia/Run-length-encoding b/Lang/Julia/Run-length-encoding new file mode 120000 index 0000000000..709fce2a23 --- /dev/null +++ b/Lang/Julia/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/Julia \ No newline at end of file diff --git a/Lang/Julia/Runtime-evaluation b/Lang/Julia/Runtime-evaluation new file mode 120000 index 0000000000..89d9b4f6ef --- /dev/null +++ b/Lang/Julia/Runtime-evaluation @@ -0,0 +1 @@ +../../Task/Runtime-evaluation/Julia \ No newline at end of file diff --git a/Lang/Julia/Runtime-evaluation-In-an-environment b/Lang/Julia/Runtime-evaluation-In-an-environment new file mode 120000 index 0000000000..4f959b2e55 --- /dev/null +++ b/Lang/Julia/Runtime-evaluation-In-an-environment @@ -0,0 +1 @@ +../../Task/Runtime-evaluation-In-an-environment/Julia \ No newline at end of file diff --git a/Lang/Julia/S-Expressions b/Lang/Julia/S-Expressions new file mode 120000 index 0000000000..0396ea94d3 --- /dev/null +++ b/Lang/Julia/S-Expressions @@ -0,0 +1 @@ +../../Task/S-Expressions/Julia \ No newline at end of file diff --git a/Lang/Julia/SEDOLs b/Lang/Julia/SEDOLs new file mode 120000 index 0000000000..409981c7d5 --- /dev/null +++ b/Lang/Julia/SEDOLs @@ -0,0 +1 @@ +../../Task/SEDOLs/Julia \ No newline at end of file diff --git a/Lang/Julia/SQL-based-authentication b/Lang/Julia/SQL-based-authentication new file mode 120000 index 0000000000..7e973fc852 --- /dev/null +++ b/Lang/Julia/SQL-based-authentication @@ -0,0 +1 @@ +../../Task/SQL-based-authentication/Julia \ No newline at end of file diff --git a/Lang/Julia/Safe-addition b/Lang/Julia/Safe-addition new file mode 120000 index 0000000000..e2713ee8e3 --- /dev/null +++ b/Lang/Julia/Safe-addition @@ -0,0 +1 @@ +../../Task/Safe-addition/Julia \ No newline at end of file diff --git a/Lang/Julia/Same-Fringe b/Lang/Julia/Same-Fringe new file mode 120000 index 0000000000..2b78f4990e --- /dev/null +++ b/Lang/Julia/Same-Fringe @@ -0,0 +1 @@ +../../Task/Same-Fringe/Julia \ No newline at end of file diff --git a/Lang/Julia/Send-an-unknown-method-call b/Lang/Julia/Send-an-unknown-method-call new file mode 120000 index 0000000000..e82a3c89d7 --- /dev/null +++ b/Lang/Julia/Send-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Send-an-unknown-method-call/Julia \ No newline at end of file diff --git a/Lang/Julia/Send-email b/Lang/Julia/Send-email new file mode 120000 index 0000000000..0d4007ae11 --- /dev/null +++ b/Lang/Julia/Send-email @@ -0,0 +1 @@ +../../Task/Send-email/Julia \ No newline at end of file diff --git a/Lang/Julia/Set-of-real-numbers b/Lang/Julia/Set-of-real-numbers new file mode 120000 index 0000000000..41ff55f3a0 --- /dev/null +++ b/Lang/Julia/Set-of-real-numbers @@ -0,0 +1 @@ +../../Task/Set-of-real-numbers/Julia \ No newline at end of file diff --git a/Lang/Julia/Sierpinski-triangle-Graphical b/Lang/Julia/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..c071152812 --- /dev/null +++ b/Lang/Julia/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/Julia \ No newline at end of file diff --git a/Lang/Julia/Simple-windowed-application b/Lang/Julia/Simple-windowed-application new file mode 120000 index 0000000000..23c61bd541 --- /dev/null +++ b/Lang/Julia/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Julia \ No newline at end of file diff --git a/Lang/Julia/Singleton b/Lang/Julia/Singleton new file mode 120000 index 0000000000..e608b40aad --- /dev/null +++ b/Lang/Julia/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Julia \ No newline at end of file diff --git a/Lang/Julia/Singly-linked-list-Element-insertion b/Lang/Julia/Singly-linked-list-Element-insertion new file mode 120000 index 0000000000..ecc8d0a1d3 --- /dev/null +++ b/Lang/Julia/Singly-linked-list-Element-insertion @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-insertion/Julia \ No newline at end of file diff --git a/Lang/Julia/Singly-linked-list-Traversal b/Lang/Julia/Singly-linked-list-Traversal new file mode 120000 index 0000000000..8a1e03f305 --- /dev/null +++ b/Lang/Julia/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Julia \ No newline at end of file diff --git a/Lang/Julia/Soundex b/Lang/Julia/Soundex new file mode 120000 index 0000000000..62d07a402d --- /dev/null +++ b/Lang/Julia/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Julia \ No newline at end of file diff --git a/Lang/Julia/Stable-marriage-problem b/Lang/Julia/Stable-marriage-problem new file mode 120000 index 0000000000..10c9327889 --- /dev/null +++ b/Lang/Julia/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/Julia \ No newline at end of file diff --git a/Lang/Julia/Stack-traces b/Lang/Julia/Stack-traces new file mode 120000 index 0000000000..a588b61919 --- /dev/null +++ b/Lang/Julia/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Julia \ No newline at end of file diff --git a/Lang/Julia/Stair-climbing-puzzle b/Lang/Julia/Stair-climbing-puzzle new file mode 120000 index 0000000000..687645ff98 --- /dev/null +++ b/Lang/Julia/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Julia \ No newline at end of file diff --git a/Lang/Julia/State-name-puzzle b/Lang/Julia/State-name-puzzle new file mode 120000 index 0000000000..ddb9d4b9ee --- /dev/null +++ b/Lang/Julia/State-name-puzzle @@ -0,0 +1 @@ +../../Task/State-name-puzzle/Julia \ No newline at end of file diff --git a/Lang/Julia/Statistics-Basic b/Lang/Julia/Statistics-Basic new file mode 120000 index 0000000000..9f9a44b1d4 --- /dev/null +++ b/Lang/Julia/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/Julia \ No newline at end of file diff --git a/Lang/Julia/Synchronous-concurrency b/Lang/Julia/Synchronous-concurrency new file mode 120000 index 0000000000..8ea54600f1 --- /dev/null +++ b/Lang/Julia/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Julia \ No newline at end of file diff --git a/Lang/Julia/Table-creation-Postal-addresses b/Lang/Julia/Table-creation-Postal-addresses new file mode 120000 index 0000000000..e693e824cf --- /dev/null +++ b/Lang/Julia/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/Julia \ No newline at end of file diff --git a/Lang/Julia/Ternary-logic b/Lang/Julia/Ternary-logic new file mode 120000 index 0000000000..114116d05e --- /dev/null +++ b/Lang/Julia/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Julia \ No newline at end of file diff --git a/Lang/Julia/Test-a-function b/Lang/Julia/Test-a-function new file mode 120000 index 0000000000..959617dce6 --- /dev/null +++ b/Lang/Julia/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Julia \ No newline at end of file diff --git a/Lang/Julia/Text-processing-1 b/Lang/Julia/Text-processing-1 new file mode 120000 index 0000000000..c3ab417614 --- /dev/null +++ b/Lang/Julia/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/Julia \ No newline at end of file diff --git a/Lang/Julia/Text-processing-2 b/Lang/Julia/Text-processing-2 new file mode 120000 index 0000000000..bc7b15fb1a --- /dev/null +++ b/Lang/Julia/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/Julia \ No newline at end of file diff --git a/Lang/Julia/Text-processing-Max-licenses-in-use b/Lang/Julia/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..accd508989 --- /dev/null +++ b/Lang/Julia/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Julia \ No newline at end of file diff --git a/Lang/Julia/The-ISAAC-Cipher b/Lang/Julia/The-ISAAC-Cipher new file mode 120000 index 0000000000..88d28d97bc --- /dev/null +++ b/Lang/Julia/The-ISAAC-Cipher @@ -0,0 +1 @@ +../../Task/The-ISAAC-Cipher/Julia \ No newline at end of file diff --git a/Lang/Julia/Topological-sort b/Lang/Julia/Topological-sort new file mode 120000 index 0000000000..bff2468008 --- /dev/null +++ b/Lang/Julia/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/Julia \ No newline at end of file diff --git a/Lang/Julia/Ulam-spiral--for-primes- b/Lang/Julia/Ulam-spiral--for-primes- new file mode 120000 index 0000000000..62fdc245a3 --- /dev/null +++ b/Lang/Julia/Ulam-spiral--for-primes- @@ -0,0 +1 @@ +../../Task/Ulam-spiral--for-primes-/Julia \ No newline at end of file diff --git a/Lang/Julia/Unbias-a-random-generator b/Lang/Julia/Unbias-a-random-generator new file mode 120000 index 0000000000..71634582b6 --- /dev/null +++ b/Lang/Julia/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/Julia \ No newline at end of file diff --git a/Lang/Julia/Verify-distribution-uniformity-Naive b/Lang/Julia/Verify-distribution-uniformity-Naive new file mode 120000 index 0000000000..4eaaa30c5f --- /dev/null +++ b/Lang/Julia/Verify-distribution-uniformity-Naive @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Naive/Julia \ No newline at end of file diff --git a/Lang/Julia/Voronoi-diagram b/Lang/Julia/Voronoi-diagram new file mode 120000 index 0000000000..0ba58a1f52 --- /dev/null +++ b/Lang/Julia/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/Julia \ No newline at end of file diff --git a/Lang/Julia/Walk-a-directory-Non-recursively b/Lang/Julia/Walk-a-directory-Non-recursively new file mode 120000 index 0000000000..a4ffe8c144 --- /dev/null +++ b/Lang/Julia/Walk-a-directory-Non-recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Non-recursively/Julia \ No newline at end of file diff --git a/Lang/Julia/Walk-a-directory-Recursively b/Lang/Julia/Walk-a-directory-Recursively new file mode 120000 index 0000000000..47b5f75939 --- /dev/null +++ b/Lang/Julia/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Julia \ No newline at end of file diff --git a/Lang/Julia/Window-creation-X11 b/Lang/Julia/Window-creation-X11 new file mode 120000 index 0000000000..fb10283c05 --- /dev/null +++ b/Lang/Julia/Window-creation-X11 @@ -0,0 +1 @@ +../../Task/Window-creation-X11/Julia \ No newline at end of file diff --git a/Lang/Julia/Word-wrap b/Lang/Julia/Word-wrap new file mode 120000 index 0000000000..33c2681ad5 --- /dev/null +++ b/Lang/Julia/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Julia \ No newline at end of file diff --git a/Lang/Julia/XML-Input b/Lang/Julia/XML-Input new file mode 120000 index 0000000000..bd67959f8b --- /dev/null +++ b/Lang/Julia/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/Julia \ No newline at end of file diff --git a/Lang/Julia/Xiaolin-Wus-line-algorithm b/Lang/Julia/Xiaolin-Wus-line-algorithm new file mode 120000 index 0000000000..1f426802f6 --- /dev/null +++ b/Lang/Julia/Xiaolin-Wus-line-algorithm @@ -0,0 +1 @@ +../../Task/Xiaolin-Wus-line-algorithm/Julia \ No newline at end of file diff --git a/Lang/Julia/Yin-and-yang b/Lang/Julia/Yin-and-yang new file mode 120000 index 0000000000..a0b2862811 --- /dev/null +++ b/Lang/Julia/Yin-and-yang @@ -0,0 +1 @@ +../../Task/Yin-and-yang/Julia \ No newline at end of file diff --git a/Lang/Julia/Zebra-puzzle b/Lang/Julia/Zebra-puzzle new file mode 120000 index 0000000000..94a4297896 --- /dev/null +++ b/Lang/Julia/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/Julia \ No newline at end of file diff --git a/Lang/Julia/Zhang-Suen-thinning-algorithm b/Lang/Julia/Zhang-Suen-thinning-algorithm new file mode 120000 index 0000000000..014f60fd7d --- /dev/null +++ b/Lang/Julia/Zhang-Suen-thinning-algorithm @@ -0,0 +1 @@ +../../Task/Zhang-Suen-thinning-algorithm/Julia \ No newline at end of file diff --git a/Lang/K/Dinesmans-multiple-dwelling-problem b/Lang/K/Dinesmans-multiple-dwelling-problem new file mode 120000 index 0000000000..eadcb2fc71 --- /dev/null +++ b/Lang/K/Dinesmans-multiple-dwelling-problem @@ -0,0 +1 @@ +../../Task/Dinesmans-multiple-dwelling-problem/K \ No newline at end of file diff --git a/Lang/Kitten/99-Bottles-of-Beer b/Lang/Kitten/99-Bottles-of-Beer new file mode 120000 index 0000000000..72d9853cfc --- /dev/null +++ b/Lang/Kitten/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Kitten \ No newline at end of file diff --git a/Lang/Kitten/Y-combinator b/Lang/Kitten/Y-combinator new file mode 120000 index 0000000000..3d5016643b --- /dev/null +++ b/Lang/Kitten/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Kitten \ No newline at end of file diff --git a/Lang/Klong/100-doors b/Lang/Klong/100-doors new file mode 120000 index 0000000000..06e5d5b4df --- /dev/null +++ b/Lang/Klong/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Klong \ No newline at end of file diff --git a/Lang/Klong/Ackermann-function b/Lang/Klong/Ackermann-function new file mode 120000 index 0000000000..5274d42c65 --- /dev/null +++ b/Lang/Klong/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Klong \ No newline at end of file diff --git a/Lang/Klong/Anonymous-recursion b/Lang/Klong/Anonymous-recursion new file mode 120000 index 0000000000..942b9c1f77 --- /dev/null +++ b/Lang/Klong/Anonymous-recursion @@ -0,0 +1 @@ +../../Task/Anonymous-recursion/Klong \ No newline at end of file diff --git a/Lang/Klong/Array-concatenation b/Lang/Klong/Array-concatenation new file mode 120000 index 0000000000..655e569a9e --- /dev/null +++ b/Lang/Klong/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/Klong \ No newline at end of file diff --git a/Lang/Klong/Command-line-arguments b/Lang/Klong/Command-line-arguments new file mode 120000 index 0000000000..7643f9f173 --- /dev/null +++ b/Lang/Klong/Command-line-arguments @@ -0,0 +1 @@ +../../Task/Command-line-arguments/Klong \ No newline at end of file diff --git a/Lang/Klong/Gaussian-elimination b/Lang/Klong/Gaussian-elimination new file mode 120000 index 0000000000..a9ae6713c9 --- /dev/null +++ b/Lang/Klong/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/Klong \ No newline at end of file diff --git a/Lang/Klong/Greatest-common-divisor b/Lang/Klong/Greatest-common-divisor new file mode 120000 index 0000000000..30920cd518 --- /dev/null +++ b/Lang/Klong/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/Klong \ No newline at end of file diff --git a/Lang/Klong/Loops-For b/Lang/Klong/Loops-For new file mode 120000 index 0000000000..1fe0d2430b --- /dev/null +++ b/Lang/Klong/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Klong \ No newline at end of file diff --git a/Lang/Klong/Matrix-multiplication b/Lang/Klong/Matrix-multiplication new file mode 120000 index 0000000000..93a7a19c5a --- /dev/null +++ b/Lang/Klong/Matrix-multiplication @@ -0,0 +1 @@ +../../Task/Matrix-multiplication/Klong \ No newline at end of file diff --git a/Lang/Klong/Statistics-Basic b/Lang/Klong/Statistics-Basic new file mode 120000 index 0000000000..a3b65d9537 --- /dev/null +++ b/Lang/Klong/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/Klong \ No newline at end of file diff --git a/Lang/Kotlin/00DESCRIPTION b/Lang/Kotlin/00DESCRIPTION index fa4b4c3306..f2884710b5 100644 --- a/Lang/Kotlin/00DESCRIPTION +++ b/Lang/Kotlin/00DESCRIPTION @@ -1,5 +1,6 @@ {{language |checking=static +|tags=kotlin |site=http://kotlinlang.org}}Kotlin is a statically-typed programming language that runs on the [[JVM]] and can also be compiled to JavaScript. It is being developed by JetBrains with assistance from open source contributors and is intended for industrial use. diff --git a/Lang/Kotlin/Active-object b/Lang/Kotlin/Active-object new file mode 120000 index 0000000000..d76ab7cd9d --- /dev/null +++ b/Lang/Kotlin/Active-object @@ -0,0 +1 @@ +../../Task/Active-object/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Append-a-record-to-the-end-of-a-text-file b/Lang/Kotlin/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..7f5dcddc98 --- /dev/null +++ b/Lang/Kotlin/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Arithmetic-evaluation b/Lang/Kotlin/Arithmetic-evaluation new file mode 120000 index 0000000000..3d00f1b045 --- /dev/null +++ b/Lang/Kotlin/Arithmetic-evaluation @@ -0,0 +1 @@ +../../Task/Arithmetic-evaluation/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Atomic-updates b/Lang/Kotlin/Atomic-updates new file mode 120000 index 0000000000..3d4667714a --- /dev/null +++ b/Lang/Kotlin/Atomic-updates @@ -0,0 +1 @@ +../../Task/Atomic-updates/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Bitmap-B-zier-curves-Cubic b/Lang/Kotlin/Bitmap-B-zier-curves-Cubic new file mode 120000 index 0000000000..6aa1af0ce9 --- /dev/null +++ b/Lang/Kotlin/Bitmap-B-zier-curves-Cubic @@ -0,0 +1 @@ +../../Task/Bitmap-B-zier-curves-Cubic/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Bitmap-B-zier-curves-Quadratic b/Lang/Kotlin/Bitmap-B-zier-curves-Quadratic new file mode 120000 index 0000000000..5b368b88f0 --- /dev/null +++ b/Lang/Kotlin/Bitmap-B-zier-curves-Quadratic @@ -0,0 +1 @@ +../../Task/Bitmap-B-zier-curves-Quadratic/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Bitmap-Histogram b/Lang/Kotlin/Bitmap-Histogram new file mode 120000 index 0000000000..2b04afedfd --- /dev/null +++ b/Lang/Kotlin/Bitmap-Histogram @@ -0,0 +1 @@ +../../Task/Bitmap-Histogram/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Bitmap-PPM-conversion-through-a-pipe b/Lang/Kotlin/Bitmap-PPM-conversion-through-a-pipe new file mode 120000 index 0000000000..119fc64f06 --- /dev/null +++ b/Lang/Kotlin/Bitmap-PPM-conversion-through-a-pipe @@ -0,0 +1 @@ +../../Task/Bitmap-PPM-conversion-through-a-pipe/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Bitmap-Read-a-PPM-file b/Lang/Kotlin/Bitmap-Read-a-PPM-file new file mode 120000 index 0000000000..ddb24ef7fe --- /dev/null +++ b/Lang/Kotlin/Bitmap-Read-a-PPM-file @@ -0,0 +1 @@ +../../Task/Bitmap-Read-a-PPM-file/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Bitmap-Read-an-image-through-a-pipe b/Lang/Kotlin/Bitmap-Read-an-image-through-a-pipe new file mode 120000 index 0000000000..c80b340153 --- /dev/null +++ b/Lang/Kotlin/Bitmap-Read-an-image-through-a-pipe @@ -0,0 +1 @@ +../../Task/Bitmap-Read-an-image-through-a-pipe/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Bitmap-Write-a-PPM-file b/Lang/Kotlin/Bitmap-Write-a-PPM-file new file mode 120000 index 0000000000..132204cbf6 --- /dev/null +++ b/Lang/Kotlin/Bitmap-Write-a-PPM-file @@ -0,0 +1 @@ +../../Task/Bitmap-Write-a-PPM-file/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Bitwise-IO b/Lang/Kotlin/Bitwise-IO new file mode 120000 index 0000000000..ee26ac218b --- /dev/null +++ b/Lang/Kotlin/Bitwise-IO @@ -0,0 +1 @@ +../../Task/Bitwise-IO/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Call-a-function-in-a-shared-library b/Lang/Kotlin/Call-a-function-in-a-shared-library new file mode 120000 index 0000000000..7e010469da --- /dev/null +++ b/Lang/Kotlin/Call-a-function-in-a-shared-library @@ -0,0 +1 @@ +../../Task/Call-a-function-in-a-shared-library/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Checkpoint-synchronization b/Lang/Kotlin/Checkpoint-synchronization new file mode 120000 index 0000000000..93e9280812 --- /dev/null +++ b/Lang/Kotlin/Checkpoint-synchronization @@ -0,0 +1 @@ +../../Task/Checkpoint-synchronization/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Circles-of-given-radius-through-two-points b/Lang/Kotlin/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..72d70223a7 --- /dev/null +++ b/Lang/Kotlin/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Color-quantization b/Lang/Kotlin/Color-quantization new file mode 120000 index 0000000000..f16321e1e8 --- /dev/null +++ b/Lang/Kotlin/Color-quantization @@ -0,0 +1 @@ +../../Task/Color-quantization/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Compare-sorting-algorithms-performance b/Lang/Kotlin/Compare-sorting-algorithms-performance new file mode 120000 index 0000000000..115961db67 --- /dev/null +++ b/Lang/Kotlin/Compare-sorting-algorithms-performance @@ -0,0 +1 @@ +../../Task/Compare-sorting-algorithms-performance/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2- b/Lang/Kotlin/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2- new file mode 120000 index 0000000000..39cb183f59 --- /dev/null +++ b/Lang/Kotlin/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2- @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2-/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Conways-Game-of-Life b/Lang/Kotlin/Conways-Game-of-Life new file mode 120000 index 0000000000..95c3aa6212 --- /dev/null +++ b/Lang/Kotlin/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Deepcopy b/Lang/Kotlin/Deepcopy new file mode 120000 index 0000000000..490747ea91 --- /dev/null +++ b/Lang/Kotlin/Deepcopy @@ -0,0 +1 @@ +../../Task/Deepcopy/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Delegates b/Lang/Kotlin/Delegates new file mode 120000 index 0000000000..97e0b21f59 --- /dev/null +++ b/Lang/Kotlin/Delegates @@ -0,0 +1 @@ +../../Task/Delegates/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Dining-philosophers b/Lang/Kotlin/Dining-philosophers new file mode 120000 index 0000000000..e2386ce380 --- /dev/null +++ b/Lang/Kotlin/Dining-philosophers @@ -0,0 +1 @@ +../../Task/Dining-philosophers/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Documentation b/Lang/Kotlin/Documentation new file mode 120000 index 0000000000..1e9fe48ab4 --- /dev/null +++ b/Lang/Kotlin/Documentation @@ -0,0 +1 @@ +../../Task/Documentation/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Element-wise-operations b/Lang/Kotlin/Element-wise-operations new file mode 120000 index 0000000000..a6f726c795 --- /dev/null +++ b/Lang/Kotlin/Element-wise-operations @@ -0,0 +1 @@ +../../Task/Element-wise-operations/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Execute-a-Markov-algorithm b/Lang/Kotlin/Execute-a-Markov-algorithm new file mode 120000 index 0000000000..5a839d1241 --- /dev/null +++ b/Lang/Kotlin/Execute-a-Markov-algorithm @@ -0,0 +1 @@ +../../Task/Execute-a-Markov-algorithm/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Find-common-directory-path b/Lang/Kotlin/Find-common-directory-path new file mode 120000 index 0000000000..771c20e10a --- /dev/null +++ b/Lang/Kotlin/Find-common-directory-path @@ -0,0 +1 @@ +../../Task/Find-common-directory-path/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Fork b/Lang/Kotlin/Fork new file mode 120000 index 0000000000..f2f8867a19 --- /dev/null +++ b/Lang/Kotlin/Fork @@ -0,0 +1 @@ +../../Task/Fork/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Formal-power-series b/Lang/Kotlin/Formal-power-series new file mode 120000 index 0000000000..f600e27242 --- /dev/null +++ b/Lang/Kotlin/Formal-power-series @@ -0,0 +1 @@ +../../Task/Formal-power-series/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Four-bit-adder b/Lang/Kotlin/Four-bit-adder new file mode 120000 index 0000000000..45db70725d --- /dev/null +++ b/Lang/Kotlin/Four-bit-adder @@ -0,0 +1 @@ +../../Task/Four-bit-adder/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/GUI-enabling-disabling-of-controls b/Lang/Kotlin/GUI-enabling-disabling-of-controls new file mode 120000 index 0000000000..17341af2f0 --- /dev/null +++ b/Lang/Kotlin/GUI-enabling-disabling-of-controls @@ -0,0 +1 @@ +../../Task/GUI-enabling-disabling-of-controls/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Galton-box-animation b/Lang/Kotlin/Galton-box-animation new file mode 120000 index 0000000000..8d7ad8c67a --- /dev/null +++ b/Lang/Kotlin/Galton-box-animation @@ -0,0 +1 @@ +../../Task/Galton-box-animation/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Gaussian-elimination b/Lang/Kotlin/Gaussian-elimination new file mode 120000 index 0000000000..112ca5d76c --- /dev/null +++ b/Lang/Kotlin/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Globally-replace-text-in-several-files b/Lang/Kotlin/Globally-replace-text-in-several-files new file mode 120000 index 0000000000..c72d56dac1 --- /dev/null +++ b/Lang/Kotlin/Globally-replace-text-in-several-files @@ -0,0 +1 @@ +../../Task/Globally-replace-text-in-several-files/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Grayscale-image b/Lang/Kotlin/Grayscale-image new file mode 120000 index 0000000000..020ae71fa0 --- /dev/null +++ b/Lang/Kotlin/Grayscale-image @@ -0,0 +1 @@ +../../Task/Grayscale-image/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/HTTPS-Authenticated b/Lang/Kotlin/HTTPS-Authenticated new file mode 120000 index 0000000000..7f1c02a44c --- /dev/null +++ b/Lang/Kotlin/HTTPS-Authenticated @@ -0,0 +1 @@ +../../Task/HTTPS-Authenticated/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/HTTPS-Client-authenticated b/Lang/Kotlin/HTTPS-Client-authenticated new file mode 120000 index 0000000000..e2f4d3395c --- /dev/null +++ b/Lang/Kotlin/HTTPS-Client-authenticated @@ -0,0 +1 @@ +../../Task/HTTPS-Client-authenticated/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Image-convolution b/Lang/Kotlin/Image-convolution new file mode 120000 index 0000000000..1039b9d03b --- /dev/null +++ b/Lang/Kotlin/Image-convolution @@ -0,0 +1 @@ +../../Task/Image-convolution/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Image-noise b/Lang/Kotlin/Image-noise new file mode 120000 index 0000000000..3c0ba495f4 --- /dev/null +++ b/Lang/Kotlin/Image-noise @@ -0,0 +1 @@ +../../Task/Image-noise/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Inverted-index b/Lang/Kotlin/Inverted-index new file mode 120000 index 0000000000..a4b046e632 --- /dev/null +++ b/Lang/Kotlin/Inverted-index @@ -0,0 +1 @@ +../../Task/Inverted-index/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/JSON b/Lang/Kotlin/JSON new file mode 120000 index 0000000000..8685b50693 --- /dev/null +++ b/Lang/Kotlin/JSON @@ -0,0 +1 @@ +../../Task/JSON/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/K-d-tree b/Lang/Kotlin/K-d-tree new file mode 120000 index 0000000000..cafc343158 --- /dev/null +++ b/Lang/Kotlin/K-d-tree @@ -0,0 +1 @@ +../../Task/K-d-tree/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/K-means++-clustering b/Lang/Kotlin/K-means++-clustering new file mode 120000 index 0000000000..3afafe0de9 --- /dev/null +++ b/Lang/Kotlin/K-means++-clustering @@ -0,0 +1 @@ +../../Task/K-means++-clustering/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Keyboard-macros b/Lang/Kotlin/Keyboard-macros new file mode 120000 index 0000000000..1a0c3cdc2a --- /dev/null +++ b/Lang/Kotlin/Keyboard-macros @@ -0,0 +1 @@ +../../Task/Keyboard-macros/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/LU-decomposition b/Lang/Kotlin/LU-decomposition new file mode 120000 index 0000000000..1757f7a412 --- /dev/null +++ b/Lang/Kotlin/LU-decomposition @@ -0,0 +1 @@ +../../Task/LU-decomposition/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Langtons-ant b/Lang/Kotlin/Langtons-ant new file mode 120000 index 0000000000..4799deb98f --- /dev/null +++ b/Lang/Kotlin/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Main-step-of-GOST-28147-89 b/Lang/Kotlin/Main-step-of-GOST-28147-89 new file mode 120000 index 0000000000..faeeca31fb --- /dev/null +++ b/Lang/Kotlin/Main-step-of-GOST-28147-89 @@ -0,0 +1 @@ +../../Task/Main-step-of-GOST-28147-89/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Maze-solving b/Lang/Kotlin/Maze-solving new file mode 120000 index 0000000000..b6b22a5e26 --- /dev/null +++ b/Lang/Kotlin/Maze-solving @@ -0,0 +1 @@ +../../Task/Maze-solving/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Median-filter b/Lang/Kotlin/Median-filter new file mode 120000 index 0000000000..55af0791c9 --- /dev/null +++ b/Lang/Kotlin/Median-filter @@ -0,0 +1 @@ +../../Task/Median-filter/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Metered-concurrency b/Lang/Kotlin/Metered-concurrency new file mode 120000 index 0000000000..8cc73787c6 --- /dev/null +++ b/Lang/Kotlin/Metered-concurrency @@ -0,0 +1 @@ +../../Task/Metered-concurrency/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Multiple-regression b/Lang/Kotlin/Multiple-regression new file mode 120000 index 0000000000..746dce5a8b --- /dev/null +++ b/Lang/Kotlin/Multiple-regression @@ -0,0 +1 @@ +../../Task/Multiple-regression/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Multiplicative-order b/Lang/Kotlin/Multiplicative-order new file mode 120000 index 0000000000..2c84974cf0 --- /dev/null +++ b/Lang/Kotlin/Multiplicative-order @@ -0,0 +1 @@ +../../Task/Multiplicative-order/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Munching-squares b/Lang/Kotlin/Munching-squares new file mode 120000 index 0000000000..0e56de9506 --- /dev/null +++ b/Lang/Kotlin/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Object-serialization b/Lang/Kotlin/Object-serialization new file mode 120000 index 0000000000..3e0e938a7c --- /dev/null +++ b/Lang/Kotlin/Object-serialization @@ -0,0 +1 @@ +../../Task/Object-serialization/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/One-dimensional-cellular-automata b/Lang/Kotlin/One-dimensional-cellular-automata new file mode 120000 index 0000000000..30fb2e31fc --- /dev/null +++ b/Lang/Kotlin/One-dimensional-cellular-automata @@ -0,0 +1 @@ +../../Task/One-dimensional-cellular-automata/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/One-of-n-lines-in-a-file b/Lang/Kotlin/One-of-n-lines-in-a-file new file mode 120000 index 0000000000..e6b7e5d4b5 --- /dev/null +++ b/Lang/Kotlin/One-of-n-lines-in-a-file @@ -0,0 +1 @@ +../../Task/One-of-n-lines-in-a-file/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Optional-parameters b/Lang/Kotlin/Optional-parameters new file mode 120000 index 0000000000..de7fdbee28 --- /dev/null +++ b/Lang/Kotlin/Optional-parameters @@ -0,0 +1 @@ +../../Task/Optional-parameters/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Parallel-calculations b/Lang/Kotlin/Parallel-calculations new file mode 120000 index 0000000000..38001b057f --- /dev/null +++ b/Lang/Kotlin/Parallel-calculations @@ -0,0 +1 @@ +../../Task/Parallel-calculations/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Parametrized-SQL-statement b/Lang/Kotlin/Parametrized-SQL-statement new file mode 120000 index 0000000000..4978e1ba92 --- /dev/null +++ b/Lang/Kotlin/Parametrized-SQL-statement @@ -0,0 +1 @@ +../../Task/Parametrized-SQL-statement/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Parsing-RPN-to-infix-conversion b/Lang/Kotlin/Parsing-RPN-to-infix-conversion new file mode 120000 index 0000000000..26ea71ded1 --- /dev/null +++ b/Lang/Kotlin/Parsing-RPN-to-infix-conversion @@ -0,0 +1 @@ +../../Task/Parsing-RPN-to-infix-conversion/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Parsing-Shunting-yard-algorithm b/Lang/Kotlin/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..c288a2fa81 --- /dev/null +++ b/Lang/Kotlin/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Pattern-matching b/Lang/Kotlin/Pattern-matching new file mode 120000 index 0000000000..aa45178874 --- /dev/null +++ b/Lang/Kotlin/Pattern-matching @@ -0,0 +1 @@ +../../Task/Pattern-matching/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Penneys-game b/Lang/Kotlin/Penneys-game new file mode 120000 index 0000000000..46c272c789 --- /dev/null +++ b/Lang/Kotlin/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Percentage-difference-between-images b/Lang/Kotlin/Percentage-difference-between-images new file mode 120000 index 0000000000..5cf1e3001a --- /dev/null +++ b/Lang/Kotlin/Percentage-difference-between-images @@ -0,0 +1 @@ +../../Task/Percentage-difference-between-images/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Percolation-Bond-percolation b/Lang/Kotlin/Percolation-Bond-percolation new file mode 120000 index 0000000000..fa256fc9ba --- /dev/null +++ b/Lang/Kotlin/Percolation-Bond-percolation @@ -0,0 +1 @@ +../../Task/Percolation-Bond-percolation/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Percolation-Mean-cluster-density b/Lang/Kotlin/Percolation-Mean-cluster-density new file mode 120000 index 0000000000..a2ab3d8899 --- /dev/null +++ b/Lang/Kotlin/Percolation-Mean-cluster-density @@ -0,0 +1 @@ +../../Task/Percolation-Mean-cluster-density/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Percolation-Mean-run-density b/Lang/Kotlin/Percolation-Mean-run-density new file mode 120000 index 0000000000..e85d9d0568 --- /dev/null +++ b/Lang/Kotlin/Percolation-Mean-run-density @@ -0,0 +1 @@ +../../Task/Percolation-Mean-run-density/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Percolation-Site-percolation b/Lang/Kotlin/Percolation-Site-percolation new file mode 120000 index 0000000000..60c52bf0c3 --- /dev/null +++ b/Lang/Kotlin/Percolation-Site-percolation @@ -0,0 +1 @@ +../../Task/Percolation-Site-percolation/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Plot-coordinate-pairs b/Lang/Kotlin/Plot-coordinate-pairs new file mode 120000 index 0000000000..e0170fbf2c --- /dev/null +++ b/Lang/Kotlin/Plot-coordinate-pairs @@ -0,0 +1 @@ +../../Task/Plot-coordinate-pairs/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Polynomial-long-division b/Lang/Kotlin/Polynomial-long-division new file mode 120000 index 0000000000..936e26ca7a --- /dev/null +++ b/Lang/Kotlin/Polynomial-long-division @@ -0,0 +1 @@ +../../Task/Polynomial-long-division/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Polynomial-regression b/Lang/Kotlin/Polynomial-regression new file mode 120000 index 0000000000..93ac90314c --- /dev/null +++ b/Lang/Kotlin/Polynomial-regression @@ -0,0 +1 @@ +../../Task/Polynomial-regression/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Reduced-row-echelon-form b/Lang/Kotlin/Reduced-row-echelon-form new file mode 120000 index 0000000000..f7be5950f3 --- /dev/null +++ b/Lang/Kotlin/Reduced-row-echelon-form @@ -0,0 +1 @@ +../../Task/Reduced-row-echelon-form/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Rock-paper-scissors b/Lang/Kotlin/Rock-paper-scissors new file mode 120000 index 0000000000..6a03ef7198 --- /dev/null +++ b/Lang/Kotlin/Rock-paper-scissors @@ -0,0 +1 @@ +../../Task/Rock-paper-scissors/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/S-Expressions b/Lang/Kotlin/S-Expressions new file mode 120000 index 0000000000..35667c52f5 --- /dev/null +++ b/Lang/Kotlin/S-Expressions @@ -0,0 +1 @@ +../../Task/S-Expressions/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/SOAP b/Lang/Kotlin/SOAP new file mode 120000 index 0000000000..ec42f74e1f --- /dev/null +++ b/Lang/Kotlin/SOAP @@ -0,0 +1 @@ +../../Task/SOAP/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/SQL-based-authentication b/Lang/Kotlin/SQL-based-authentication new file mode 120000 index 0000000000..fe193d802e --- /dev/null +++ b/Lang/Kotlin/SQL-based-authentication @@ -0,0 +1 @@ +../../Task/SQL-based-authentication/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Simple-database b/Lang/Kotlin/Simple-database new file mode 120000 index 0000000000..ad4daf49aa --- /dev/null +++ b/Lang/Kotlin/Simple-database @@ -0,0 +1 @@ +../../Task/Simple-database/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sockets b/Lang/Kotlin/Sockets new file mode 120000 index 0000000000..8f95e3e114 --- /dev/null +++ b/Lang/Kotlin/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sokoban b/Lang/Kotlin/Sokoban new file mode 120000 index 0000000000..6a048c7f38 --- /dev/null +++ b/Lang/Kotlin/Sokoban @@ -0,0 +1 @@ +../../Task/Sokoban/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Solve-a-Hidato-puzzle b/Lang/Kotlin/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..cafb408e41 --- /dev/null +++ b/Lang/Kotlin/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Solve-a-Hopido-puzzle b/Lang/Kotlin/Solve-a-Hopido-puzzle new file mode 120000 index 0000000000..180731c4e6 --- /dev/null +++ b/Lang/Kotlin/Solve-a-Hopido-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hopido-puzzle/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Solve-a-Numbrix-puzzle b/Lang/Kotlin/Solve-a-Numbrix-puzzle new file mode 120000 index 0000000000..e7074f2d0b --- /dev/null +++ b/Lang/Kotlin/Solve-a-Numbrix-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Numbrix-puzzle/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Solve-the-no-connection-puzzle b/Lang/Kotlin/Solve-the-no-connection-puzzle new file mode 120000 index 0000000000..27a782da4b --- /dev/null +++ b/Lang/Kotlin/Solve-the-no-connection-puzzle @@ -0,0 +1 @@ +../../Task/Solve-the-no-connection-puzzle/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sort-disjoint-sublist b/Lang/Kotlin/Sort-disjoint-sublist new file mode 120000 index 0000000000..d8e0949d94 --- /dev/null +++ b/Lang/Kotlin/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sort-stability b/Lang/Kotlin/Sort-stability new file mode 120000 index 0000000000..08feaa0267 --- /dev/null +++ b/Lang/Kotlin/Sort-stability @@ -0,0 +1 @@ +../../Task/Sort-stability/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sorting-algorithms-Sleep-sort b/Lang/Kotlin/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..804d6ff631 --- /dev/null +++ b/Lang/Kotlin/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Speech-synthesis b/Lang/Kotlin/Speech-synthesis new file mode 120000 index 0000000000..f347451ba3 --- /dev/null +++ b/Lang/Kotlin/Speech-synthesis @@ -0,0 +1 @@ +../../Task/Speech-synthesis/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Stair-climbing-puzzle b/Lang/Kotlin/Stair-climbing-puzzle new file mode 120000 index 0000000000..26e863a888 --- /dev/null +++ b/Lang/Kotlin/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/State-name-puzzle b/Lang/Kotlin/State-name-puzzle new file mode 120000 index 0000000000..4c250265e5 --- /dev/null +++ b/Lang/Kotlin/State-name-puzzle @@ -0,0 +1 @@ +../../Task/State-name-puzzle/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Subtractive-generator b/Lang/Kotlin/Subtractive-generator new file mode 120000 index 0000000000..635e5c08b8 --- /dev/null +++ b/Lang/Kotlin/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Sudoku b/Lang/Kotlin/Sudoku new file mode 120000 index 0000000000..7d9ddccce6 --- /dev/null +++ b/Lang/Kotlin/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Synchronous-concurrency b/Lang/Kotlin/Synchronous-concurrency new file mode 120000 index 0000000000..5babaabc44 --- /dev/null +++ b/Lang/Kotlin/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Table-creation-Postal-addresses b/Lang/Kotlin/Table-creation-Postal-addresses new file mode 120000 index 0000000000..97f76d86cc --- /dev/null +++ b/Lang/Kotlin/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Take-notes-on-the-command-line b/Lang/Kotlin/Take-notes-on-the-command-line new file mode 120000 index 0000000000..103c55fd7e --- /dev/null +++ b/Lang/Kotlin/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Text-processing-1 b/Lang/Kotlin/Text-processing-1 new file mode 120000 index 0000000000..f101a54461 --- /dev/null +++ b/Lang/Kotlin/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Text-processing-2 b/Lang/Kotlin/Text-processing-2 new file mode 120000 index 0000000000..7c12c82777 --- /dev/null +++ b/Lang/Kotlin/Text-processing-2 @@ -0,0 +1 @@ +../../Task/Text-processing-2/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Text-processing-Max-licenses-in-use b/Lang/Kotlin/Text-processing-Max-licenses-in-use new file mode 120000 index 0000000000..8c8b5c30eb --- /dev/null +++ b/Lang/Kotlin/Text-processing-Max-licenses-in-use @@ -0,0 +1 @@ +../../Task/Text-processing-Max-licenses-in-use/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Tic-tac-toe b/Lang/Kotlin/Tic-tac-toe new file mode 120000 index 0000000000..83b2d576d2 --- /dev/null +++ b/Lang/Kotlin/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Topological-sort b/Lang/Kotlin/Topological-sort new file mode 120000 index 0000000000..b831dca26a --- /dev/null +++ b/Lang/Kotlin/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Universal-Turing-machine b/Lang/Kotlin/Universal-Turing-machine new file mode 120000 index 0000000000..52d9e4525e --- /dev/null +++ b/Lang/Kotlin/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Unix-ls b/Lang/Kotlin/Unix-ls new file mode 120000 index 0000000000..51e4c3673d --- /dev/null +++ b/Lang/Kotlin/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Update-a-configuration-file b/Lang/Kotlin/Update-a-configuration-file new file mode 120000 index 0000000000..541a986fb6 --- /dev/null +++ b/Lang/Kotlin/Update-a-configuration-file @@ -0,0 +1 @@ +../../Task/Update-a-configuration-file/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Use-another-language-to-call-a-function b/Lang/Kotlin/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..36bd5899eb --- /dev/null +++ b/Lang/Kotlin/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Verify-distribution-uniformity-Chi-squared-test b/Lang/Kotlin/Verify-distribution-uniformity-Chi-squared-test new file mode 120000 index 0000000000..501f58a817 --- /dev/null +++ b/Lang/Kotlin/Verify-distribution-uniformity-Chi-squared-test @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Chi-squared-test/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Video-display-modes b/Lang/Kotlin/Video-display-modes new file mode 120000 index 0000000000..39c9c4a9e7 --- /dev/null +++ b/Lang/Kotlin/Video-display-modes @@ -0,0 +1 @@ +../../Task/Video-display-modes/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Visualize-a-tree b/Lang/Kotlin/Visualize-a-tree new file mode 120000 index 0000000000..73d46fc15e --- /dev/null +++ b/Lang/Kotlin/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Walk-a-directory-Recursively b/Lang/Kotlin/Walk-a-directory-Recursively new file mode 120000 index 0000000000..d3b936862e --- /dev/null +++ b/Lang/Kotlin/Walk-a-directory-Recursively @@ -0,0 +1 @@ +../../Task/Walk-a-directory-Recursively/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Yahoo--search-interface b/Lang/Kotlin/Yahoo--search-interface new file mode 120000 index 0000000000..cb32e1a0b3 --- /dev/null +++ b/Lang/Kotlin/Yahoo--search-interface @@ -0,0 +1 @@ +../../Task/Yahoo--search-interface/Kotlin \ No newline at end of file diff --git a/Lang/Kotlin/Zeckendorf-arithmetic b/Lang/Kotlin/Zeckendorf-arithmetic new file mode 120000 index 0000000000..7b8d6f1e18 --- /dev/null +++ b/Lang/Kotlin/Zeckendorf-arithmetic @@ -0,0 +1 @@ +../../Task/Zeckendorf-arithmetic/Kotlin \ No newline at end of file diff --git a/Lang/Limbo/00DESCRIPTION b/Lang/Limbo/00DESCRIPTION index cd01609666..32ce456cce 100644 --- a/Lang/Limbo/00DESCRIPTION +++ b/Lang/Limbo/00DESCRIPTION @@ -3,7 +3,7 @@ |gc=yes }} -Limbo is the application programming language for Inferno. Syntactically similar to [[C]], it has several features that make it simpler, safer and yet more powerful and better suited to the development of concurrent, distributed systems. The Limbo compiler generates architecture independent object code which is then interpreted by the Dis Virtual Machine or compiled just before runtime to improve performance. This ensures that Limbo applications are completely portable across all Inferno platforms.[[#Citation|[1]]] +Limbo is the application programming language for Inferno. Syntactically similar to [[C]], and more so its predecessor, [[Go]], it has several features that make it simpler, safer and yet more powerful and better suited to the development of concurrent, distributed systems. The Limbo compiler generates architecture independent object code which is then interpreted by the Dis Virtual Machine or compiled just before runtime to improve performance. This ensures that Limbo applications are completely portable across all Inferno platforms.[[#Citation|[1]]] Limbo's approach to concurrency was inspired by Hoare's Communicating Sequential Processes ([[CSP]]).[[#Citation|[2]]] diff --git a/Lang/Limbo/99-Bottles-of-Beer b/Lang/Limbo/99-Bottles-of-Beer new file mode 120000 index 0000000000..a5caf1d6e8 --- /dev/null +++ b/Lang/Limbo/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Limbo \ No newline at end of file diff --git a/Lang/Limbo/Array-concatenation b/Lang/Limbo/Array-concatenation new file mode 120000 index 0000000000..f51c93d24e --- /dev/null +++ b/Lang/Limbo/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/Limbo \ No newline at end of file diff --git a/Lang/Limbo/Averages-Arithmetic-mean b/Lang/Limbo/Averages-Arithmetic-mean new file mode 120000 index 0000000000..4c73069e57 --- /dev/null +++ b/Lang/Limbo/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Limbo \ No newline at end of file diff --git a/Lang/Limbo/Ethiopian-multiplication b/Lang/Limbo/Ethiopian-multiplication new file mode 120000 index 0000000000..9b2f68ca29 --- /dev/null +++ b/Lang/Limbo/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/Limbo \ No newline at end of file diff --git a/Lang/Limbo/Literals-Integer b/Lang/Limbo/Literals-Integer new file mode 120000 index 0000000000..05d567f22e --- /dev/null +++ b/Lang/Limbo/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/Limbo \ No newline at end of file diff --git a/Lang/Limbo/Sieve-of-Eratosthenes b/Lang/Limbo/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..2c33ff2c84 --- /dev/null +++ b/Lang/Limbo/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Limbo \ No newline at end of file diff --git a/Lang/Limbo/Singly-linked-list-Traversal b/Lang/Limbo/Singly-linked-list-Traversal new file mode 120000 index 0000000000..1691af3090 --- /dev/null +++ b/Lang/Limbo/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/Limbo \ No newline at end of file diff --git a/Lang/Lingo/99-Bottles-of-Beer b/Lang/Lingo/99-Bottles-of-Beer new file mode 120000 index 0000000000..6c28941f58 --- /dev/null +++ b/Lang/Lingo/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/Lingo \ No newline at end of file diff --git a/Lang/Lingo/Active-object b/Lang/Lingo/Active-object new file mode 120000 index 0000000000..caef312e35 --- /dev/null +++ b/Lang/Lingo/Active-object @@ -0,0 +1 @@ +../../Task/Active-object/Lingo \ No newline at end of file diff --git a/Lang/Lingo/Add-a-variable-to-a-class-instance-at-runtime b/Lang/Lingo/Add-a-variable-to-a-class-instance-at-runtime new file mode 120000 index 0000000000..5444bc5820 --- /dev/null +++ b/Lang/Lingo/Add-a-variable-to-a-class-instance-at-runtime @@ -0,0 +1 @@ +../../Task/Add-a-variable-to-a-class-instance-at-runtime/Lingo \ No newline at end of file diff --git a/Lang/Lingo/Animate-a-pendulum b/Lang/Lingo/Animate-a-pendulum new file mode 120000 index 0000000000..567fe7352c --- /dev/null +++ b/Lang/Lingo/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/Lingo \ No newline at end of file diff --git a/Lang/Lingo/Arithmetic-Integer b/Lang/Lingo/Arithmetic-Integer new file mode 120000 index 0000000000..2dc374858f --- /dev/null +++ b/Lang/Lingo/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Lingo \ No newline at end of file diff --git a/Lang/Lingo/Averages-Arithmetic-mean b/Lang/Lingo/Averages-Arithmetic-mean new file mode 120000 index 0000000000..a1d5643c4b --- /dev/null +++ b/Lang/Lingo/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Lingo \ No newline at end of file diff --git a/Lang/Lingo/Averages-Median b/Lang/Lingo/Averages-Median new file mode 120000 index 0000000000..28ccff46aa --- /dev/null +++ b/Lang/Lingo/Averages-Median @@ -0,0 +1 @@ +../../Task/Averages-Median/Lingo \ No newline at end of file diff --git a/Lang/Lingo/Binary-strings b/Lang/Lingo/Binary-strings new file mode 120000 index 0000000000..9c46ccef47 --- /dev/null +++ b/Lang/Lingo/Binary-strings @@ -0,0 +1 @@ +../../Task/Binary-strings/Lingo \ No newline at end of file diff --git a/Lang/Lingo/Extensible-prime-generator b/Lang/Lingo/Extensible-prime-generator new file mode 120000 index 0000000000..2076efe213 --- /dev/null +++ b/Lang/Lingo/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/Lingo \ No newline at end of file diff --git a/Lang/Lingo/Factors-of-a-Mersenne-number b/Lang/Lingo/Factors-of-a-Mersenne-number new file mode 120000 index 0000000000..8ae55b733d --- /dev/null +++ b/Lang/Lingo/Factors-of-a-Mersenne-number @@ -0,0 +1 @@ +../../Task/Factors-of-a-Mersenne-number/Lingo \ No newline at end of file diff --git a/Lang/Lingo/Generator-Exponential b/Lang/Lingo/Generator-Exponential new file mode 120000 index 0000000000..e477af158e --- /dev/null +++ b/Lang/Lingo/Generator-Exponential @@ -0,0 +1 @@ +../../Task/Generator-Exponential/Lingo \ No newline at end of file diff --git a/Lang/Lingo/MD5-Implementation b/Lang/Lingo/MD5-Implementation new file mode 120000 index 0000000000..424daf3cc9 --- /dev/null +++ b/Lang/Lingo/MD5-Implementation @@ -0,0 +1 @@ +../../Task/MD5-Implementation/Lingo \ No newline at end of file diff --git a/Lang/Lingo/OpenGL b/Lang/Lingo/OpenGL new file mode 120000 index 0000000000..d392bd7998 --- /dev/null +++ b/Lang/Lingo/OpenGL @@ -0,0 +1 @@ +../../Task/OpenGL/Lingo \ No newline at end of file diff --git a/Lang/Lingo/Primality-by-trial-division b/Lang/Lingo/Primality-by-trial-division new file mode 120000 index 0000000000..e4f4b4babb --- /dev/null +++ b/Lang/Lingo/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/Lingo \ No newline at end of file diff --git a/Lang/Lingo/Random-numbers b/Lang/Lingo/Random-numbers new file mode 120000 index 0000000000..aef063311f --- /dev/null +++ b/Lang/Lingo/Random-numbers @@ -0,0 +1 @@ +../../Task/Random-numbers/Lingo \ No newline at end of file diff --git a/Lang/Lingo/SHA-1 b/Lang/Lingo/SHA-1 new file mode 120000 index 0000000000..f4a4044281 --- /dev/null +++ b/Lang/Lingo/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Lingo \ No newline at end of file diff --git a/Lang/Lingo/Semiprime b/Lang/Lingo/Semiprime new file mode 120000 index 0000000000..56a6b55403 --- /dev/null +++ b/Lang/Lingo/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Lingo \ No newline at end of file diff --git a/Lang/Lingo/Show-the-epoch b/Lang/Lingo/Show-the-epoch new file mode 120000 index 0000000000..36ec191016 --- /dev/null +++ b/Lang/Lingo/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Lingo \ No newline at end of file diff --git a/Lang/Lingo/Sieve-of-Eratosthenes b/Lang/Lingo/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..755fc91a68 --- /dev/null +++ b/Lang/Lingo/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Lingo \ No newline at end of file diff --git a/Lang/Lingo/Tic-tac-toe b/Lang/Lingo/Tic-tac-toe new file mode 120000 index 0000000000..96cd6ed932 --- /dev/null +++ b/Lang/Lingo/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Lingo \ No newline at end of file diff --git a/Lang/Lingo/URL-decoding b/Lang/Lingo/URL-decoding new file mode 120000 index 0000000000..d670a643dd --- /dev/null +++ b/Lang/Lingo/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Lingo \ No newline at end of file diff --git a/Lang/Lingo/Write-to-Windows-event-log b/Lang/Lingo/Write-to-Windows-event-log new file mode 120000 index 0000000000..43a00465e6 --- /dev/null +++ b/Lang/Lingo/Write-to-Windows-event-log @@ -0,0 +1 @@ +../../Task/Write-to-Windows-event-log/Lingo \ No newline at end of file diff --git a/Lang/Lingo/Zeckendorf-number-representation b/Lang/Lingo/Zeckendorf-number-representation new file mode 120000 index 0000000000..79cacfe8d9 --- /dev/null +++ b/Lang/Lingo/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Lingo \ No newline at end of file diff --git a/Lang/Logo/Catalan-numbers b/Lang/Logo/Catalan-numbers new file mode 120000 index 0000000000..3bd77f1ca6 --- /dev/null +++ b/Lang/Logo/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/Logo \ No newline at end of file diff --git a/Lang/Lua/00DESCRIPTION b/Lang/Lua/00DESCRIPTION index e9733dd4e8..e9b2b8d8e6 100644 --- a/Lang/Lua/00DESCRIPTION +++ b/Lang/Lua/00DESCRIPTION @@ -18,4 +18,345 @@ In general, Lua strives to provide flexible meta-features that can be extended a As a result, the base language is light—in fact, the full reference interpreter is only about 150KB compiled—and easily adaptable to a broad range of applications. ==Citations== -* [[wp:Lua_%28programming_language%29|Wikipedia:Lua (programming language)]] \ No newline at end of file +* [[wp:Lua_%28programming_language%29|Wikipedia:Lua (programming language)]] + +==Unimplemented programming tasks== +Output from [[Find_unimplemented_tasks]] : + +Lua has 334 unimplemented programming tasks: + 15 puzzle solver + 2048 + 4-rings or 4-squares puzzle + 9 billion names of God the integer + AKS test for primes + Active Directory/Connect + Active Directory/Search for a user + Active object + Aliquot sequence classifications + Anagrams/Deranged anagrams + Animation + Append a record to the end of a text file + Apply a digital filter (direct form II transposed) + Arbitrary-precision integers (included) + Archimedean spiral + Arena storage pool + Arithmetic-geometric mean/Calculate Pi + Atomic updates + Average loop length + Babbage problem + Balanced ternary + Bernoulli numbers + Best shuffle + Bitcoin/address validation + Bitcoin/public point to address + Bitmap/Bresenham's line algorithm + Bitmap/Bézier curves/Cubic + Bitmap/Bézier curves/Quadratic + Bitmap/Flood fill + Bitmap/Midpoint circle algorithm + Bitmap/PPM conversion through a pipe + Bitmap/Read an image through a pipe + Bitwise IO + Brace expansion + Break OO privacy + Bulls and cows/Player + CRC-32 + Call a function in a shared library + Canny edge detector + Carmichael 3 strong pseudoprimes + Casting out nines + Catmull–Clark subdivision surface + Chat server + Check Machin-like formulas + Checkpoint synchronization + Chinese remainder theorem + Chinese zodiac + Cholesky decomposition + Circles of given radius through two points + Closest-pair problem + Color of a screen pixel + Color quantization + Colour bars/Display + Colour pinstripe/Display + Colour pinstripe/Printer + Combinations and permutations + Commatizing numbers + Compare sorting algorithms' performance + Compiler/AST interpreter + Compiler/code generator + Compiler/lexical analyzer + Compiler/syntax analyzer + Compiler/virtual machine interpreter + Conjugate transpose + Constrained random points on a circle + Continued fraction + Continued fraction/Arithmetic/Construct from rational number + Convert decimal number to rational + Create a file on magnetic tape + Create an object at a given address + Cut a rectangle + DNS query + Death Star + Deconvolution/2D+ + Define a primitive data type + Delegates + Determine if only one instance is running + Digital root/Multiplicative digital root + Dining philosophers + Discordian date + Distributed programming + Documentation + Doubly-linked list/Definition + Doubly-linked list/Element definition + Doubly-linked list/Element insertion + Doubly-linked list/Traversal + Draw a cuboid + Draw a pixel + Draw a rotating cube + Dutch national flag problem + Eertree + Egyptian division + Egyptian fractions + Element-wise operations + Elementary cellular automaton + Enforced immutability + Equilibrium index + Events + Executable library + Extend your language + Extensible prime generator + FTP + Factors of a Mersenne number + Find common directory path + Find largest left truncatable prime in a given base + Find palindromic numbers in both binary and ternary bases + Floyd-Warshall algorithm + Fractran + Function frequency + GUI/Maximum window dimensions + GUI component interaction + GUI enabling/disabling of controls + Galton box animation + Gaussian elimination + Go Fish + Greyscale bars/Display + HTTPS + HTTPS/Authenticated + HTTPS/Client-authenticated + Handle a signal + Hash join + Hello world/Line printer + Hello world/Web server + Hickerson series of almost integers + Hofstadter-Conway $10,000 sequence + Hofstadter Figure-Figure sequences + Hofstadter Q sequence + Honeycombs + Horizontal sundial calculations + Host introspection + Hough transform + Hunt The Wumpus + Image convolution + Image noise + Inheritance/Single + Integer overflow + Inverted index + Inverted syntax + Jaro distance + Joystick position + Julia set + K-d tree + K-means++ clustering + Kernighans large earthquake problem + Keyboard input/Flush the keyboard buffer + Keyboard input/Keypress check + Keyboard input/Obtain a Y or N response + Keyboard macros + Knapsack problem/0-1 + Knapsack problem/Bounded + Knapsack problem/Continuous + Knuth's algorithm S + Kolakoski sequence + LU decomposition + Last letter-first letter + Long multiplication + Loops/Increment loop index within loop body + Lucas-Lehmer test + Lucky and even lucky numbers + Lychrel numbers + MD5/Implementation + Machine code + Mad Libs + Main step of GOST 28147-89 + Maze solving + Median filter + Memory allocation + Memory layout of a data structure + Metered concurrency + Metronome + Miller–Rabin primality test + Minesweeper game + Modular exponentiation + Modular inverse + Mouse position + Multiple regression + Multiplicative order + Narcissist + Natural sorting + Nautical bell + Negative base numbers + Non-continuous subsequences + Nonoblock + Nonogram solver + Numeric error propagation + OLE Automation + Object serialization + Odd word problem + Old lady swallowed a fly + Paraffins + Parallel Brute Force + Parallel calculations + Parametric polymorphism + Parametrized SQL statement + Parse an IP Address + Parsing/RPN to infix conversion + Parsing/Shunting-yard algorithm + Partition an integer X into N primes + Pascal's triangle/Puzzle + Pathological floating point problems + Pattern matching + Pentagram + Percentage difference between images + Percolation/Bond percolation + Percolation/Mean cluster density + Percolation/Mean run density + Percolation/Site percolation + Permutation test + Permutations/Rank of a permutation + Pig the dice game/Player + Pinstripe/Printer + Play recorded sounds + Plot coordinate pairs + Polymorphic copy + Polynomial long division + Polynomial regression + Pragmatic directives + Primes - allocate descendants to their ancestors + Primorial numbers + Problem of Apollonius + Pythagoras tree + Pythagorean quadruples + Pythagorean triples + QR decomposition + RCRPG + RSA code + Ramer-Douglas-Peucker line simplification + Random number generator (device) + Ranking methods + Rate counter + Ray-casting algorithm + Record sound + Reflection/Get source + Reflection/List methods + Reflection/List properties + Rendezvous + Rep-string + Resistor mesh + Retrieve and search chat history + Rosetta Code/Count examples + Rosetta Code/Find bare lang tags + Rosetta Code/Find unimplemented tasks + Rosetta Code/Rank languages by popularity + Runge-Kutta method + S-Expressions + SEDOLs + SOAP + SQL-based authentication + Safe addition + Sailors, coconuts and a monkey problem + Same Fringe + Scope/Function names and labels + Scope modifiers + Set consolidation + Set of real numbers + Set puzzle + Sierpinski carpet + Sierpinski pentagon + Sierpinski triangle + Simple database + Simulate input/Keyboard + Simulate input/Mouse + Singleton + Singly-linked list/Element definition + Singly-linked list/Element insertion + Singly-linked list/Traversal + Sokoban + Solve a Hidato puzzle + Solve a Hopido puzzle + Solve a Numbrix puzzle + Solve the no connection puzzle + Sorting algorithms/Heapsort + Sorting algorithms/Radix sort + Sorting algorithms/Strand sort + Sparkline in unicode + Speech synthesis + Start from a main routine + State name puzzle + Stream Merge + Subtractive generator + Sum and Product Puzzle + Sum to 100 + Superellipse + Taxicab numbers + Terminal control/Coloured text + Terminal control/Cursor movement + Terminal control/Cursor positioning + Terminal control/Dimensions + Terminal control/Hiding the cursor + Terminal control/Inverse video + Terminal control/Positional read + Terminal control/Preserve screen + Terminal control/Unicode output + Ternary logic + The ISAAC Cipher + The Name Game + Thiele's interpolation formula + Tic-tac-toe + Topic variable + Topological sort + Total circles area + Tree traversal + Truth table + Twelve statements + URL parser + UTF-8 encode and decode + Ulam spiral (for primes) + Unicode strings + Update a configuration file + Use another language to call a function + User input/Graphical + Vampire number + Variable-length quantity + Variable size/Get + Variable size/Set + Verify distribution uniformity/Chi-squared test + Verify distribution uniformity/Naive + Video display modes + Vigenère cipher/Cryptanalysis + Visualize a tree + Vogel's approximation method + Walk a directory/Recursively + Water collected between towers + Window creation/X11 + Window management + Word search + World Cup group stage + Write language name in 3D ASCII + Write to Windows event log + Xiaolin Wu's line algorithm + Yahoo! search interface + Yin and yang + Zebra puzzle + Zeckendorf arithmetic + +See also [[Reports:Tasks_not_implemented_in_Lua]] \ No newline at end of file diff --git a/Lang/Lua/Averages-Mean-time-of-day b/Lang/Lua/Averages-Mean-time-of-day new file mode 120000 index 0000000000..6cea13be50 --- /dev/null +++ b/Lang/Lua/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/Lua \ No newline at end of file diff --git a/Lang/Lua/Dinesmans-multiple-dwelling-problem b/Lang/Lua/Dinesmans-multiple-dwelling-problem new file mode 120000 index 0000000000..01eeec513d --- /dev/null +++ b/Lang/Lua/Dinesmans-multiple-dwelling-problem @@ -0,0 +1 @@ +../../Task/Dinesmans-multiple-dwelling-problem/Lua \ No newline at end of file diff --git a/Lang/Lua/Huffman-coding b/Lang/Lua/Huffman-coding new file mode 120000 index 0000000000..87686d6d3c --- /dev/null +++ b/Lang/Lua/Huffman-coding @@ -0,0 +1 @@ +../../Task/Huffman-coding/Lua \ No newline at end of file diff --git a/Lang/Lua/Make-directory-path b/Lang/Lua/Make-directory-path new file mode 120000 index 0000000000..25d06a774a --- /dev/null +++ b/Lang/Lua/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/Lua \ No newline at end of file diff --git a/Lang/Lua/Soundex b/Lang/Lua/Soundex new file mode 120000 index 0000000000..5669231bdf --- /dev/null +++ b/Lang/Lua/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Lua \ No newline at end of file diff --git a/Lang/Lua/Table-creation-Postal-addresses b/Lang/Lua/Table-creation-Postal-addresses new file mode 120000 index 0000000000..456ac16083 --- /dev/null +++ b/Lang/Lua/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/Lua \ No newline at end of file diff --git a/Lang/MATLAB/Draw-a-sphere b/Lang/MATLAB/Draw-a-sphere new file mode 120000 index 0000000000..6901c6dce1 --- /dev/null +++ b/Lang/MATLAB/Draw-a-sphere @@ -0,0 +1 @@ +../../Task/Draw-a-sphere/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Josephus-problem b/Lang/MATLAB/Josephus-problem new file mode 120000 index 0000000000..42d104c6e8 --- /dev/null +++ b/Lang/MATLAB/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Numerical-integration-Gauss-Legendre-Quadrature b/Lang/MATLAB/Numerical-integration-Gauss-Legendre-Quadrature new file mode 120000 index 0000000000..1ef37a6aac --- /dev/null +++ b/Lang/MATLAB/Numerical-integration-Gauss-Legendre-Quadrature @@ -0,0 +1 @@ +../../Task/Numerical-integration-Gauss-Legendre-Quadrature/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/XML-DOM-serialization b/Lang/MATLAB/XML-DOM-serialization new file mode 120000 index 0000000000..4f633fe13d --- /dev/null +++ b/Lang/MATLAB/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/MATLAB \ No newline at end of file diff --git a/Lang/MIPS-Assembly/Towers-of-Hanoi b/Lang/MIPS-Assembly/Towers-of-Hanoi new file mode 120000 index 0000000000..04bebb1511 --- /dev/null +++ b/Lang/MIPS-Assembly/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/MIPS-Assembly \ No newline at end of file diff --git a/Lang/Maple/Animation b/Lang/Maple/Animation new file mode 120000 index 0000000000..de5db5d7eb --- /dev/null +++ b/Lang/Maple/Animation @@ -0,0 +1 @@ +../../Task/Animation/Maple \ No newline at end of file diff --git a/Lang/Maple/Bitmap b/Lang/Maple/Bitmap new file mode 120000 index 0000000000..4eac31aaca --- /dev/null +++ b/Lang/Maple/Bitmap @@ -0,0 +1 @@ +../../Task/Bitmap/Maple \ No newline at end of file diff --git a/Lang/Maple/CSV-to-HTML-translation b/Lang/Maple/CSV-to-HTML-translation new file mode 120000 index 0000000000..eb7d8464be --- /dev/null +++ b/Lang/Maple/CSV-to-HTML-translation @@ -0,0 +1 @@ +../../Task/CSV-to-HTML-translation/Maple \ No newline at end of file diff --git a/Lang/Maple/Closest-pair-problem b/Lang/Maple/Closest-pair-problem new file mode 120000 index 0000000000..0b4171beb8 --- /dev/null +++ b/Lang/Maple/Closest-pair-problem @@ -0,0 +1 @@ +../../Task/Closest-pair-problem/Maple \ No newline at end of file diff --git a/Lang/Maple/Date-manipulation b/Lang/Maple/Date-manipulation new file mode 120000 index 0000000000..e16f7346b7 --- /dev/null +++ b/Lang/Maple/Date-manipulation @@ -0,0 +1 @@ +../../Task/Date-manipulation/Maple \ No newline at end of file diff --git a/Lang/Maple/Day-of-the-week b/Lang/Maple/Day-of-the-week new file mode 120000 index 0000000000..bbe6c14457 --- /dev/null +++ b/Lang/Maple/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Maple \ No newline at end of file diff --git a/Lang/Maple/Element-wise-operations b/Lang/Maple/Element-wise-operations new file mode 120000 index 0000000000..51af8f5be2 --- /dev/null +++ b/Lang/Maple/Element-wise-operations @@ -0,0 +1 @@ +../../Task/Element-wise-operations/Maple \ No newline at end of file diff --git a/Lang/Maple/Find-largest-left-truncatable-prime-in-a-given-base b/Lang/Maple/Find-largest-left-truncatable-prime-in-a-given-base new file mode 120000 index 0000000000..90c1d6e07c --- /dev/null +++ b/Lang/Maple/Find-largest-left-truncatable-prime-in-a-given-base @@ -0,0 +1 @@ +../../Task/Find-largest-left-truncatable-prime-in-a-given-base/Maple \ No newline at end of file diff --git a/Lang/Maple/Find-the-last-Sunday-of-each-month b/Lang/Maple/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..79250d6429 --- /dev/null +++ b/Lang/Maple/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Maple \ No newline at end of file diff --git a/Lang/Maple/Find-the-missing-permutation b/Lang/Maple/Find-the-missing-permutation new file mode 120000 index 0000000000..f44d12c265 --- /dev/null +++ b/Lang/Maple/Find-the-missing-permutation @@ -0,0 +1 @@ +../../Task/Find-the-missing-permutation/Maple \ No newline at end of file diff --git a/Lang/Maple/Five-weekends b/Lang/Maple/Five-weekends new file mode 120000 index 0000000000..981cf15018 --- /dev/null +++ b/Lang/Maple/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/Maple \ No newline at end of file diff --git a/Lang/Maple/GUI-component-interaction b/Lang/Maple/GUI-component-interaction new file mode 120000 index 0000000000..a6ddaed0d1 --- /dev/null +++ b/Lang/Maple/GUI-component-interaction @@ -0,0 +1 @@ +../../Task/GUI-component-interaction/Maple \ No newline at end of file diff --git a/Lang/Maple/GUI-enabling-disabling-of-controls b/Lang/Maple/GUI-enabling-disabling-of-controls new file mode 120000 index 0000000000..88086548a1 --- /dev/null +++ b/Lang/Maple/GUI-enabling-disabling-of-controls @@ -0,0 +1 @@ +../../Task/GUI-enabling-disabling-of-controls/Maple \ No newline at end of file diff --git a/Lang/Maple/Gamma-function b/Lang/Maple/Gamma-function new file mode 120000 index 0000000000..a093c290c1 --- /dev/null +++ b/Lang/Maple/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/Maple \ No newline at end of file diff --git a/Lang/Maple/Grayscale-image b/Lang/Maple/Grayscale-image new file mode 120000 index 0000000000..71e03777c2 --- /dev/null +++ b/Lang/Maple/Grayscale-image @@ -0,0 +1 @@ +../../Task/Grayscale-image/Maple \ No newline at end of file diff --git a/Lang/Maple/Last-Friday-of-each-month b/Lang/Maple/Last-Friday-of-each-month new file mode 120000 index 0000000000..63bc5b49e3 --- /dev/null +++ b/Lang/Maple/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/Maple \ No newline at end of file diff --git a/Lang/Maple/Mandelbrot-set b/Lang/Maple/Mandelbrot-set new file mode 120000 index 0000000000..fe79f21f99 --- /dev/null +++ b/Lang/Maple/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/Maple \ No newline at end of file diff --git a/Lang/Maple/Map-range b/Lang/Maple/Map-range new file mode 120000 index 0000000000..457f729a7d --- /dev/null +++ b/Lang/Maple/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/Maple \ No newline at end of file diff --git a/Lang/Maple/Multifactorial b/Lang/Maple/Multifactorial new file mode 120000 index 0000000000..ec872fb23c --- /dev/null +++ b/Lang/Maple/Multifactorial @@ -0,0 +1 @@ +../../Task/Multifactorial/Maple \ No newline at end of file diff --git a/Lang/Maple/Mutual-recursion b/Lang/Maple/Mutual-recursion new file mode 120000 index 0000000000..6a31d00e14 --- /dev/null +++ b/Lang/Maple/Mutual-recursion @@ -0,0 +1 @@ +../../Task/Mutual-recursion/Maple \ No newline at end of file diff --git a/Lang/Maple/Narcissistic-decimal-number b/Lang/Maple/Narcissistic-decimal-number new file mode 120000 index 0000000000..c0ffc12109 --- /dev/null +++ b/Lang/Maple/Narcissistic-decimal-number @@ -0,0 +1 @@ +../../Task/Narcissistic-decimal-number/Maple \ No newline at end of file diff --git a/Lang/Maple/Non-decimal-radices-Convert b/Lang/Maple/Non-decimal-radices-Convert new file mode 120000 index 0000000000..d48ee261fb --- /dev/null +++ b/Lang/Maple/Non-decimal-radices-Convert @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Convert/Maple \ No newline at end of file diff --git a/Lang/Maple/Ordered-words b/Lang/Maple/Ordered-words new file mode 120000 index 0000000000..633d1b574d --- /dev/null +++ b/Lang/Maple/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/Maple \ No newline at end of file diff --git a/Lang/Maple/Pangram-checker b/Lang/Maple/Pangram-checker new file mode 120000 index 0000000000..46dac9a42d --- /dev/null +++ b/Lang/Maple/Pangram-checker @@ -0,0 +1 @@ +../../Task/Pangram-checker/Maple \ No newline at end of file diff --git a/Lang/Maple/Quickselect-algorithm b/Lang/Maple/Quickselect-algorithm new file mode 120000 index 0000000000..61840a804e --- /dev/null +++ b/Lang/Maple/Quickselect-algorithm @@ -0,0 +1 @@ +../../Task/Quickselect-algorithm/Maple \ No newline at end of file diff --git a/Lang/Maple/Read-a-file-line-by-line b/Lang/Maple/Read-a-file-line-by-line new file mode 120000 index 0000000000..72ff0011e4 --- /dev/null +++ b/Lang/Maple/Read-a-file-line-by-line @@ -0,0 +1 @@ +../../Task/Read-a-file-line-by-line/Maple \ No newline at end of file diff --git a/Lang/Maple/Regular-expressions b/Lang/Maple/Regular-expressions new file mode 120000 index 0000000000..ff00a57190 --- /dev/null +++ b/Lang/Maple/Regular-expressions @@ -0,0 +1 @@ +../../Task/Regular-expressions/Maple \ No newline at end of file diff --git a/Lang/Maple/Search-a-list b/Lang/Maple/Search-a-list new file mode 120000 index 0000000000..c46bc7cf72 --- /dev/null +++ b/Lang/Maple/Search-a-list @@ -0,0 +1 @@ +../../Task/Search-a-list/Maple \ No newline at end of file diff --git a/Lang/Maple/Sorting-algorithms-Bogosort b/Lang/Maple/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..02a3cadec0 --- /dev/null +++ b/Lang/Maple/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Maple \ No newline at end of file diff --git a/Lang/Maple/Sorting-algorithms-Bubble-sort b/Lang/Maple/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..4f98eae010 --- /dev/null +++ b/Lang/Maple/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Maple \ No newline at end of file diff --git a/Lang/Maple/Sorting-algorithms-Cocktail-sort b/Lang/Maple/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..53fa7de868 --- /dev/null +++ b/Lang/Maple/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Maple \ No newline at end of file diff --git a/Lang/Maple/Sorting-algorithms-Comb-sort b/Lang/Maple/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..601188ee87 --- /dev/null +++ b/Lang/Maple/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Maple \ No newline at end of file diff --git a/Lang/Maple/Sorting-algorithms-Gnome-sort b/Lang/Maple/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..aa4dabd6a5 --- /dev/null +++ b/Lang/Maple/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Maple \ No newline at end of file diff --git a/Lang/Maple/Sorting-algorithms-Heapsort b/Lang/Maple/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..f04cb35991 --- /dev/null +++ b/Lang/Maple/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Maple \ No newline at end of file diff --git a/Lang/Maple/Sorting-algorithms-Insertion-sort b/Lang/Maple/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..e36d99262d --- /dev/null +++ b/Lang/Maple/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Maple \ No newline at end of file diff --git a/Lang/Maple/Sorting-algorithms-Merge-sort b/Lang/Maple/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..73fa7e78fb --- /dev/null +++ b/Lang/Maple/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Maple \ No newline at end of file diff --git a/Lang/Maple/Sorting-algorithms-Permutation-sort b/Lang/Maple/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..d874098bb4 --- /dev/null +++ b/Lang/Maple/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Maple \ No newline at end of file diff --git a/Lang/Maple/Sorting-algorithms-Quicksort b/Lang/Maple/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..e913ed599f --- /dev/null +++ b/Lang/Maple/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Maple \ No newline at end of file diff --git a/Lang/Maple/Sorting-algorithms-Selection-sort b/Lang/Maple/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..c2a545a426 --- /dev/null +++ b/Lang/Maple/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Maple \ No newline at end of file diff --git a/Lang/Maple/Sorting-algorithms-Shell-sort b/Lang/Maple/Sorting-algorithms-Shell-sort new file mode 120000 index 0000000000..5185bb2431 --- /dev/null +++ b/Lang/Maple/Sorting-algorithms-Shell-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Shell-sort/Maple \ No newline at end of file diff --git a/Lang/Maple/Sum-of-a-series b/Lang/Maple/Sum-of-a-series new file mode 120000 index 0000000000..455a4d8af5 --- /dev/null +++ b/Lang/Maple/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Maple \ No newline at end of file diff --git a/Lang/Maple/Tokenize-a-string b/Lang/Maple/Tokenize-a-string new file mode 120000 index 0000000000..c1231145a4 --- /dev/null +++ b/Lang/Maple/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Maple \ No newline at end of file diff --git a/Lang/Maple/Towers-of-Hanoi b/Lang/Maple/Towers-of-Hanoi new file mode 120000 index 0000000000..909d82daa8 --- /dev/null +++ b/Lang/Maple/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Maple \ No newline at end of file diff --git a/Lang/Maple/Trabb-Pardo-Knuth-algorithm b/Lang/Maple/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..66da1eb5c9 --- /dev/null +++ b/Lang/Maple/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Maple \ No newline at end of file diff --git a/Lang/Maple/Truncatable-primes b/Lang/Maple/Truncatable-primes new file mode 120000 index 0000000000..36bc738b7b --- /dev/null +++ b/Lang/Maple/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/Maple \ No newline at end of file diff --git a/Lang/Maple/Web-scraping b/Lang/Maple/Web-scraping new file mode 120000 index 0000000000..2165facbdd --- /dev/null +++ b/Lang/Maple/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/Maple \ No newline at end of file diff --git a/Lang/Mathematica/00DESCRIPTION b/Lang/Mathematica/00DESCRIPTION index 82337908b1..5daf1eef81 100644 --- a/Lang/Mathematica/00DESCRIPTION +++ b/Lang/Mathematica/00DESCRIPTION @@ -4,6 +4,11 @@ |checking=dynamic |gc=yes |LCT=yes}}{{implementation|Wolfram Language}}{{language programming paradigm|Declarative}}{{language programming paradigm|Functional}} -Mathematica is a computational software program developed by [http://wolfram.com Wolfram Research]. It is used in many scientific, engineering, mathematical and computing fields, and is based on symbolic mathematics. [[Wolfram Language]] is the primary programming language of Mathematica. +Mathematica is a computational software program developed by [http://wolfram.com Wolfram Research]. +It is used in many scientific, engineering, mathematical and computing fields, and is based on symbolic mathematics. +[[Wolfram Language]] is the primary programming language of Mathematica. -[[Category:Mathematical programming languages]] \ No newline at end of file +[[Category:Mathematical programming languages]] + +==Todo== +[[Reports:Tasks_not_implemented_in_Mathematica]] \ No newline at end of file diff --git a/Lang/Mathematica/Formal-power-series b/Lang/Mathematica/Formal-power-series new file mode 120000 index 0000000000..3d30778b44 --- /dev/null +++ b/Lang/Mathematica/Formal-power-series @@ -0,0 +1 @@ +../../Task/Formal-power-series/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Nautical-bell b/Lang/Mathematica/Nautical-bell new file mode 120000 index 0000000000..224f617961 --- /dev/null +++ b/Lang/Mathematica/Nautical-bell @@ -0,0 +1 @@ +../../Task/Nautical-bell/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sutherland-Hodgman-polygon-clipping b/Lang/Mathematica/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..db1a21680d --- /dev/null +++ b/Lang/Mathematica/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/Mathematica \ No newline at end of file diff --git a/Lang/Maxima/Parsing-RPN-calculator-algorithm b/Lang/Maxima/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..d0ad55a973 --- /dev/null +++ b/Lang/Maxima/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/Maxima \ No newline at end of file diff --git a/Lang/Metapost/Mandelbrot-set b/Lang/Metapost/Mandelbrot-set new file mode 120000 index 0000000000..e0e8bb169a --- /dev/null +++ b/Lang/Metapost/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/Metapost \ No newline at end of file diff --git a/Lang/Modula-2/Abundant,-deficient-and-perfect-number-classifications b/Lang/Modula-2/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..8a53adfe3f --- /dev/null +++ b/Lang/Modula-2/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Almost-prime b/Lang/Modula-2/Almost-prime new file mode 120000 index 0000000000..ac41674faf --- /dev/null +++ b/Lang/Modula-2/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Averages-Pythagorean-means b/Lang/Modula-2/Averages-Pythagorean-means new file mode 120000 index 0000000000..6abd4fae96 --- /dev/null +++ b/Lang/Modula-2/Averages-Pythagorean-means @@ -0,0 +1 @@ +../../Task/Averages-Pythagorean-means/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Box-the-compass b/Lang/Modula-2/Box-the-compass new file mode 120000 index 0000000000..adf8b80f04 --- /dev/null +++ b/Lang/Modula-2/Box-the-compass @@ -0,0 +1 @@ +../../Task/Box-the-compass/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Caesar-cipher b/Lang/Modula-2/Caesar-cipher new file mode 120000 index 0000000000..e9a3c7a0f6 --- /dev/null +++ b/Lang/Modula-2/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Catalan-numbers b/Lang/Modula-2/Catalan-numbers new file mode 120000 index 0000000000..5611e13e83 --- /dev/null +++ b/Lang/Modula-2/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Circles-of-given-radius-through-two-points b/Lang/Modula-2/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..4e6f8310f4 --- /dev/null +++ b/Lang/Modula-2/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Combinations b/Lang/Modula-2/Combinations new file mode 120000 index 0000000000..12c1802247 --- /dev/null +++ b/Lang/Modula-2/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Continued-fraction-Arithmetic-Construct-from-rational-number b/Lang/Modula-2/Continued-fraction-Arithmetic-Construct-from-rational-number new file mode 120000 index 0000000000..370eed1442 --- /dev/null +++ b/Lang/Modula-2/Continued-fraction-Arithmetic-Construct-from-rational-number @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Digital-root b/Lang/Modula-2/Digital-root new file mode 120000 index 0000000000..450e0fa3e3 --- /dev/null +++ b/Lang/Modula-2/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Dot-product b/Lang/Modula-2/Dot-product new file mode 120000 index 0000000000..17b54fd169 --- /dev/null +++ b/Lang/Modula-2/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Ethiopian-multiplication b/Lang/Modula-2/Ethiopian-multiplication new file mode 120000 index 0000000000..a9f2270d94 --- /dev/null +++ b/Lang/Modula-2/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Even-or-odd b/Lang/Modula-2/Even-or-odd new file mode 120000 index 0000000000..9f98331eaf --- /dev/null +++ b/Lang/Modula-2/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Factorial b/Lang/Modula-2/Factorial new file mode 120000 index 0000000000..230fbd99e9 --- /dev/null +++ b/Lang/Modula-2/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Fibonacci-sequence b/Lang/Modula-2/Fibonacci-sequence new file mode 120000 index 0000000000..410ae7239e --- /dev/null +++ b/Lang/Modula-2/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/FizzBuzz b/Lang/Modula-2/FizzBuzz new file mode 120000 index 0000000000..9bde7e0654 --- /dev/null +++ b/Lang/Modula-2/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Floyds-triangle b/Lang/Modula-2/Floyds-triangle new file mode 120000 index 0000000000..2bdf3a25b1 --- /dev/null +++ b/Lang/Modula-2/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Hello-world-Newline-omission b/Lang/Modula-2/Hello-world-Newline-omission new file mode 120000 index 0000000000..6608eef00a --- /dev/null +++ b/Lang/Modula-2/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Horizontal-sundial-calculations b/Lang/Modula-2/Horizontal-sundial-calculations new file mode 120000 index 0000000000..ac71cb73e4 --- /dev/null +++ b/Lang/Modula-2/Horizontal-sundial-calculations @@ -0,0 +1 @@ +../../Task/Horizontal-sundial-calculations/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Horners-rule-for-polynomial-evaluation b/Lang/Modula-2/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..b7993b5093 --- /dev/null +++ b/Lang/Modula-2/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Integer-sequence b/Lang/Modula-2/Integer-sequence new file mode 120000 index 0000000000..b1902cc274 --- /dev/null +++ b/Lang/Modula-2/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Josephus-problem b/Lang/Modula-2/Josephus-problem new file mode 120000 index 0000000000..f573e8ccc5 --- /dev/null +++ b/Lang/Modula-2/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Kaprekar-numbers b/Lang/Modula-2/Kaprekar-numbers new file mode 120000 index 0000000000..6e11654374 --- /dev/null +++ b/Lang/Modula-2/Kaprekar-numbers @@ -0,0 +1 @@ +../../Task/Kaprekar-numbers/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Leap-year b/Lang/Modula-2/Leap-year new file mode 120000 index 0000000000..7402f63d85 --- /dev/null +++ b/Lang/Modula-2/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Least-common-multiple b/Lang/Modula-2/Least-common-multiple new file mode 120000 index 0000000000..5564289e41 --- /dev/null +++ b/Lang/Modula-2/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Logical-operations b/Lang/Modula-2/Logical-operations new file mode 120000 index 0000000000..fe6b4e64b3 --- /dev/null +++ b/Lang/Modula-2/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Modular-inverse b/Lang/Modula-2/Modular-inverse new file mode 120000 index 0000000000..bb1aa46d5b --- /dev/null +++ b/Lang/Modula-2/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Morse-code b/Lang/Modula-2/Morse-code new file mode 120000 index 0000000000..b01192f6d1 --- /dev/null +++ b/Lang/Modula-2/Morse-code @@ -0,0 +1 @@ +../../Task/Morse-code/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Multiplication-tables b/Lang/Modula-2/Multiplication-tables new file mode 120000 index 0000000000..94483e9e9a --- /dev/null +++ b/Lang/Modula-2/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Nth b/Lang/Modula-2/Nth new file mode 120000 index 0000000000..9e8c69dce5 --- /dev/null +++ b/Lang/Modula-2/Nth @@ -0,0 +1 @@ +../../Task/Nth/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Old-lady-swallowed-a-fly b/Lang/Modula-2/Old-lady-swallowed-a-fly new file mode 120000 index 0000000000..66a5ef3213 --- /dev/null +++ b/Lang/Modula-2/Old-lady-swallowed-a-fly @@ -0,0 +1 @@ +../../Task/Old-lady-swallowed-a-fly/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Palindrome-detection b/Lang/Modula-2/Palindrome-detection new file mode 120000 index 0000000000..98748c9216 --- /dev/null +++ b/Lang/Modula-2/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Pascals-triangle b/Lang/Modula-2/Pascals-triangle new file mode 120000 index 0000000000..dca33b5b08 --- /dev/null +++ b/Lang/Modula-2/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Perfect-numbers b/Lang/Modula-2/Perfect-numbers new file mode 120000 index 0000000000..4ab739bb16 --- /dev/null +++ b/Lang/Modula-2/Perfect-numbers @@ -0,0 +1 @@ +../../Task/Perfect-numbers/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Pernicious-numbers b/Lang/Modula-2/Pernicious-numbers new file mode 120000 index 0000000000..8d3a095a1e --- /dev/null +++ b/Lang/Modula-2/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Polynomial-regression b/Lang/Modula-2/Polynomial-regression new file mode 120000 index 0000000000..b775f8686f --- /dev/null +++ b/Lang/Modula-2/Polynomial-regression @@ -0,0 +1 @@ +../../Task/Polynomial-regression/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Remove-duplicate-elements b/Lang/Modula-2/Remove-duplicate-elements new file mode 120000 index 0000000000..a7c0043d2f --- /dev/null +++ b/Lang/Modula-2/Remove-duplicate-elements @@ -0,0 +1 @@ +../../Task/Remove-duplicate-elements/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Resistor-mesh b/Lang/Modula-2/Resistor-mesh new file mode 120000 index 0000000000..99b8ceb886 --- /dev/null +++ b/Lang/Modula-2/Resistor-mesh @@ -0,0 +1 @@ +../../Task/Resistor-mesh/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Reverse-a-string b/Lang/Modula-2/Reverse-a-string new file mode 120000 index 0000000000..71e30acabf --- /dev/null +++ b/Lang/Modula-2/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Reverse-words-in-a-string b/Lang/Modula-2/Reverse-words-in-a-string new file mode 120000 index 0000000000..c2b96a7bb7 --- /dev/null +++ b/Lang/Modula-2/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Roman-numerals-Encode b/Lang/Modula-2/Roman-numerals-Encode new file mode 120000 index 0000000000..afc1bb1795 --- /dev/null +++ b/Lang/Modula-2/Roman-numerals-Encode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Encode/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Self-describing-numbers b/Lang/Modula-2/Self-describing-numbers new file mode 120000 index 0000000000..05fa41ae61 --- /dev/null +++ b/Lang/Modula-2/Self-describing-numbers @@ -0,0 +1 @@ +../../Task/Self-describing-numbers/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Short-circuit-evaluation b/Lang/Modula-2/Short-circuit-evaluation new file mode 120000 index 0000000000..fa6ba866a5 --- /dev/null +++ b/Lang/Modula-2/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Sum-digits-of-an-integer b/Lang/Modula-2/Sum-digits-of-an-integer new file mode 120000 index 0000000000..455c81fe43 --- /dev/null +++ b/Lang/Modula-2/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/System-time b/Lang/Modula-2/System-time new file mode 120000 index 0000000000..11766b5c74 --- /dev/null +++ b/Lang/Modula-2/System-time @@ -0,0 +1 @@ +../../Task/System-time/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/The-ISAAC-Cipher b/Lang/Modula-2/The-ISAAC-Cipher new file mode 120000 index 0000000000..f9333a2d02 --- /dev/null +++ b/Lang/Modula-2/The-ISAAC-Cipher @@ -0,0 +1 @@ +../../Task/The-ISAAC-Cipher/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Towers-of-Hanoi b/Lang/Modula-2/Towers-of-Hanoi new file mode 120000 index 0000000000..e842998274 --- /dev/null +++ b/Lang/Modula-2/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Trigonometric-functions b/Lang/Modula-2/Trigonometric-functions new file mode 120000 index 0000000000..c16d0312f2 --- /dev/null +++ b/Lang/Modula-2/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Van-der-Corput-sequence b/Lang/Modula-2/Van-der-Corput-sequence new file mode 120000 index 0000000000..860067a3d4 --- /dev/null +++ b/Lang/Modula-2/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Vector-products b/Lang/Modula-2/Vector-products new file mode 120000 index 0000000000..86fc882ebc --- /dev/null +++ b/Lang/Modula-2/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Modula-2 \ No newline at end of file diff --git a/Lang/Modula-2/Write-language-name-in-3D-ASCII b/Lang/Modula-2/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..fc6066731f --- /dev/null +++ b/Lang/Modula-2/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Modula-2 \ No newline at end of file diff --git a/Lang/N-t-roff/00DESCRIPTION b/Lang/N-t-roff/00DESCRIPTION index f66cf163bf..1eda2d0665 100644 --- a/Lang/N-t-roff/00DESCRIPTION +++ b/Lang/N-t-roff/00DESCRIPTION @@ -1 +1,34 @@ -{{language}}{{stub}} \ No newline at end of file +{{language|N/t/roff}} +'''N/t/roff''' or '''/.ROFF/''' (regular expression) is a document formatting language used to instruct an automated typesetter/typewriter (i.e. printer) to set/print a document's text. Its name is an acronym of ''New Runoff'' and ''Typesetter Runoff'' respectively. For document preparation purposes (i.e. its designed use), the rules of how text is laid out is written in a ''/.ROFF/ source file''. /.ROFF/ is a predecessor of TeX, and so its ability is a subset of that of TeX and its core values is indeed very similar to that of TeX. To assist the writer in writing documents, macro packages, such as ''-me'', ''-ms'', ''-mm'', and ''-mom''; typefaces and their fonts, such as ''Avant Garde'', ''Helvetica'', and ''Times Roman''; and preprocessors like ''eqn'', ''pic'', and ''tbl'' are available at the writer's disposal. These macro packages and extensions are similar to what LaTeX provides to plain TeX. + +/.ROFF/ '''are''' also compilers for the /.ROFF/ formatting language. The regular expression /.ROFF/ in this page metaphorically matches ''TROFF'' and ''NROFF'' (but it technically matches more than that). Thus, ''TROFF'' and ''NROFF'' are compilers. +The two compilers understand and parse the same language of /.ROFF/, but their outputs are '''not''' the same. Document output from the ''TROFF'' compiler is better-suited for typesetters: photo-typesetters, laser printers, etc.; whereas output from the ''NROFF'' compiler is better-suited for typewriter-like printers: line printers, daisy wheel printers, or glass teletypes. This holds, even if both compilers get the exact same input verbatim; although all logical flow controls are executed in the same manner. + +A typical ''/.ROFF/ source file'' for documents is a plaintext file with the extensions: *.roff, *.me, *.ms, *.mm, or *.mom. The extension depends on what macro package is used to set the pages of the document, although the /.ROFF/ compiler treats all of them the same way and associates no special meanings thither. Such a /.ROFF/ document contains the document's text itself (i.e. the writer's actual words) ''interspersed'' with some formatting requests that instruct the computer how to set the text on a page. + +The complexity of those such requests, their subtleties, and how they intertwine is what makes up the basic /.ROFF/ formatting language. For more complex formatting work, the language offers logical constructs (if-else's), numerical registers (.nr), macro definitions with formal parameters (.de, akin to function definitions), and recursive macro calls. These features are what make the /.ROFF/ language Turing-complete as well, although tasks easy in most programming languages won't necessarily be easy in /.ROFF/. To quote Professor Brian W. Kernighan, a user of TROFF, in an email about this (November 23, 2017): + +
+Eric Raymond observed that troff was Turing complete +in his book on Unix, back in 2003. I think that's true +even of the original version, because it has recursion +and a conditional; it's probably easier in groff, though +I haven't tried either. +
+ +With the availability of such complex requests in plain /.ROFF/ come the macro packages (sets of pre-written macros) that utilize much of the intrinsic requests. A typical collection of macros or macro packages for /.ROFF/ is known as a ''tmac'' (''t''roff ''mac''ros); these files bear the extensions: *.tmac or tmac.*, although the former is preferred to the classical latter. Since macro definitions are not documents and should only contain the typesetter's logic, it does not generally have any text. Thus, compiling a tmac as a document and printing the output usually results in a blank page. Errors pertaining to any of the macros can appear on Standard Error, but never on the typeset output. + +Therefore, when using /.ROFF/ programmatically to solve problems on Rosettacode, output is most often succinct, as almost the entire source file should contain program logic or comments. When there is output, it is merely to present the final output of the algorithm's execution. + +Since the output is on paper, the left-right margins will generally be set (1 inch on either side), the output will mostly mercilessly be wrapped if its width is longer than the paper-size specified during compile-time (usually US Letter or A4), and long output may be printed onto another page. This default typesetting behaviour can be overridden to mimic more well-behaved outputs by most programming languages, but there generally is no need to do so. All error/warning/debug messages should be output to Standard Error, which likely ends up on the terminal, '''not''' the output paper. + +Since one does not desire their algorithm's output to be exceptionally well-typeset, one need not use any typesetting macro packages (e.g. ''-me'', ''-ms'', ''-mm''), although it can be helpful to write macros that aid in writing more complex algorithms. If you do have such macros and are planning to use them, please mention about that and how to obtain them, when making submissions on Rosettacode. You should import your macros using .so or .mso, so that they can easily be expanded later using soelim prior to your submission to Rosettacode. + +== History == +Classical TROFF from Bell Labs was written in Assembly by the late Joseph F. Ossanna in 1973. It was then rewritten in C in 1975 and received active maintenance until Joseph F. Ossanna died as a consequence of heart disease in 1977. In 1979, Professor Brian W. Kernighan modified classical TROFF so that it could produce output for a variety of output devices and typesetters, not just the Graphic Systems CAT typesetter. Since then until 1989, the internals of TROFF had been modestly revised, though much of the original code that Joseph F. Ossanna had written and the /.ROFF/ formatting language's specification remain intact. +The /.ROFF/ specification and compilers developed during 1973 to 1989 will henceforth be referred to as ''Classical /.ROFF/'', with the regular expression expanded if necessary. + +Then came 1990, James Clark wrote GROFF (GNU TROFF) in C++ as a free and open-source alternative to the then-proprietary classical TROFF compiler. In 1999, Werner Lemberg and Ted Harding took over maintenance of GROFF. GROFF is now part of the GNU suite of utilities and is included in almost all distributions of GNU/Linux and available as a package for various BSDs and other UNIX-like systems. The GROFF compiler also extends the traditional TROFF language. In this way, the features found in the GROFF dialect is a superset of those found in classical TROFF. These features, such as .while, aid in writing algorithms. + +== Implementations == +Given the availability, computational superiority, and free/open-source nature of GROFF, it is one of the best implementations, not only to typeset exceptionally beautiful documents, but also to implement algorithms and solve problems on Rosettacode. Heirloom Troff is also a good candidate as well and works pretty much the same as GROFF when .cp 0 is set. \ No newline at end of file diff --git a/Lang/N-t-roff/99-Bottles-of-Beer b/Lang/N-t-roff/99-Bottles-of-Beer new file mode 120000 index 0000000000..f931bcc60f --- /dev/null +++ b/Lang/N-t-roff/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/N-t-roff \ No newline at end of file diff --git a/Lang/N-t-roff/Binary-search b/Lang/N-t-roff/Binary-search new file mode 120000 index 0000000000..757b5f544e --- /dev/null +++ b/Lang/N-t-roff/Binary-search @@ -0,0 +1 @@ +../../Task/Binary-search/N-t-roff \ No newline at end of file diff --git a/Lang/N-t-roff/Empty-program b/Lang/N-t-roff/Empty-program new file mode 120000 index 0000000000..c4f6751158 --- /dev/null +++ b/Lang/N-t-roff/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/N-t-roff \ No newline at end of file diff --git a/Lang/N-t-roff/Hello-world-Graphical b/Lang/N-t-roff/Hello-world-Graphical new file mode 120000 index 0000000000..df9920077c --- /dev/null +++ b/Lang/N-t-roff/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/N-t-roff \ No newline at end of file diff --git a/Lang/N-t-roff/Hello-world-Line-printer b/Lang/N-t-roff/Hello-world-Line-printer new file mode 120000 index 0000000000..b81fded386 --- /dev/null +++ b/Lang/N-t-roff/Hello-world-Line-printer @@ -0,0 +1 @@ +../../Task/Hello-world-Line-printer/N-t-roff \ No newline at end of file diff --git a/Lang/N-t-roff/Hello-world-Newline-omission b/Lang/N-t-roff/Hello-world-Newline-omission new file mode 120000 index 0000000000..5d805ace56 --- /dev/null +++ b/Lang/N-t-roff/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/N-t-roff \ No newline at end of file diff --git a/Lang/N-t-roff/Hello-world-Standard-error b/Lang/N-t-roff/Hello-world-Standard-error new file mode 120000 index 0000000000..c55440a08f --- /dev/null +++ b/Lang/N-t-roff/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/N-t-roff \ No newline at end of file diff --git a/Lang/N-t-roff/Hello-world-Text b/Lang/N-t-roff/Hello-world-Text new file mode 120000 index 0000000000..dfe90f43e9 --- /dev/null +++ b/Lang/N-t-roff/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/N-t-roff \ No newline at end of file diff --git a/Lang/N-t-roff/Parsing-RPN-calculator-algorithm b/Lang/N-t-roff/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..aa36830225 --- /dev/null +++ b/Lang/N-t-roff/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/N-t-roff \ No newline at end of file diff --git a/Lang/N-t-roff/Sorting-algorithms-Bubble-sort b/Lang/N-t-roff/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..070536ab81 --- /dev/null +++ b/Lang/N-t-roff/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/N-t-roff \ No newline at end of file diff --git a/Lang/N-t-roff/Sorting-algorithms-Insertion-sort b/Lang/N-t-roff/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..8a21c58a2a --- /dev/null +++ b/Lang/N-t-roff/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/N-t-roff \ No newline at end of file diff --git a/Lang/N-t-roff/Sorting-algorithms-Selection-sort b/Lang/N-t-roff/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..31d9c3104a --- /dev/null +++ b/Lang/N-t-roff/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/N-t-roff \ No newline at end of file diff --git a/Lang/NetRexx/Soundex b/Lang/NetRexx/Soundex new file mode 120000 index 0000000000..5640cc1f67 --- /dev/null +++ b/Lang/NetRexx/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/NetRexx \ No newline at end of file diff --git a/Lang/NewLISP/HTTPS b/Lang/NewLISP/HTTPS new file mode 120000 index 0000000000..15ba8541fb --- /dev/null +++ b/Lang/NewLISP/HTTPS @@ -0,0 +1 @@ +../../Task/HTTPS/NewLISP \ No newline at end of file diff --git a/Lang/Nial/100-doors b/Lang/Nial/100-doors new file mode 120000 index 0000000000..60d5c9bda5 --- /dev/null +++ b/Lang/Nial/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Nial \ No newline at end of file diff --git a/Lang/Nial/Reverse-words-in-a-string b/Lang/Nial/Reverse-words-in-a-string new file mode 120000 index 0000000000..4e983e29d4 --- /dev/null +++ b/Lang/Nial/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Nial \ No newline at end of file diff --git a/Lang/Nial/Sort-disjoint-sublist b/Lang/Nial/Sort-disjoint-sublist new file mode 120000 index 0000000000..60a646a7e4 --- /dev/null +++ b/Lang/Nial/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Nial \ No newline at end of file diff --git a/Lang/Nial/Tokenize-a-string b/Lang/Nial/Tokenize-a-string new file mode 120000 index 0000000000..a0a0d25f8a --- /dev/null +++ b/Lang/Nial/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Nial \ No newline at end of file diff --git a/Lang/Nial/Zebra-puzzle b/Lang/Nial/Zebra-puzzle new file mode 120000 index 0000000000..c98297e998 --- /dev/null +++ b/Lang/Nial/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/Nial \ No newline at end of file diff --git a/Lang/Nim/Runge-Kutta-method b/Lang/Nim/Runge-Kutta-method new file mode 120000 index 0000000000..dc5bd052f5 --- /dev/null +++ b/Lang/Nim/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Nim \ No newline at end of file diff --git a/Lang/OCaml/Break-OO-privacy b/Lang/OCaml/Break-OO-privacy new file mode 120000 index 0000000000..a92f8e046c --- /dev/null +++ b/Lang/OCaml/Break-OO-privacy @@ -0,0 +1 @@ +../../Task/Break-OO-privacy/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Catalan-numbers-Pascals-triangle b/Lang/OCaml/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..2f93f6bcc1 --- /dev/null +++ b/Lang/OCaml/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Comma-quibbling b/Lang/OCaml/Comma-quibbling new file mode 120000 index 0000000000..13c822a4aa --- /dev/null +++ b/Lang/OCaml/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Execute-HQ9+ b/Lang/OCaml/Execute-HQ9+ new file mode 120000 index 0000000000..39b13940eb --- /dev/null +++ b/Lang/OCaml/Execute-HQ9+ @@ -0,0 +1 @@ +../../Task/Execute-HQ9+/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Flipping-bits-game b/Lang/OCaml/Flipping-bits-game new file mode 120000 index 0000000000..17cd914065 --- /dev/null +++ b/Lang/OCaml/Flipping-bits-game @@ -0,0 +1 @@ +../../Task/Flipping-bits-game/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Generate-lower-case-ASCII-alphabet b/Lang/OCaml/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..446892001e --- /dev/null +++ b/Lang/OCaml/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/OCaml \ No newline at end of file diff --git a/Lang/Oberon-2/Average-loop-length b/Lang/Oberon-2/Average-loop-length new file mode 120000 index 0000000000..7073925ffa --- /dev/null +++ b/Lang/Oberon-2/Average-loop-length @@ -0,0 +1 @@ +../../Task/Average-loop-length/Oberon-2 \ No newline at end of file diff --git a/Lang/Objeck/DNS-query b/Lang/Objeck/DNS-query new file mode 120000 index 0000000000..de5cd7d414 --- /dev/null +++ b/Lang/Objeck/DNS-query @@ -0,0 +1 @@ +../../Task/DNS-query/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Deal-cards-for-FreeCell b/Lang/Objeck/Deal-cards-for-FreeCell new file mode 120000 index 0000000000..33f639ec12 --- /dev/null +++ b/Lang/Objeck/Deal-cards-for-FreeCell @@ -0,0 +1 @@ +../../Task/Deal-cards-for-FreeCell/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Entropy b/Lang/Objeck/Entropy new file mode 120000 index 0000000000..46b525a5a8 --- /dev/null +++ b/Lang/Objeck/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Equilibrium-index b/Lang/Objeck/Equilibrium-index new file mode 120000 index 0000000000..7be7a9460f --- /dev/null +++ b/Lang/Objeck/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Fibonacci-word b/Lang/Objeck/Fibonacci-word new file mode 120000 index 0000000000..ee7710c16c --- /dev/null +++ b/Lang/Objeck/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Make-directory-path b/Lang/Objeck/Make-directory-path new file mode 120000 index 0000000000..1ff5306b1c --- /dev/null +++ b/Lang/Objeck/Make-directory-path @@ -0,0 +1 @@ +../../Task/Make-directory-path/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Return-multiple-values b/Lang/Objeck/Return-multiple-values new file mode 120000 index 0000000000..fb5867800f --- /dev/null +++ b/Lang/Objeck/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Strip-comments-from-a-string b/Lang/Objeck/Strip-comments-from-a-string new file mode 120000 index 0000000000..8e79baf696 --- /dev/null +++ b/Lang/Objeck/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Sum-multiples-of-3-and-5 b/Lang/Objeck/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..e16ff4641e --- /dev/null +++ b/Lang/Objeck/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Objeck \ No newline at end of file diff --git a/Lang/Octave/Semordnilap b/Lang/Octave/Semordnilap new file mode 120000 index 0000000000..74788b529a --- /dev/null +++ b/Lang/Octave/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/Octave \ No newline at end of file diff --git a/Lang/Octave/Zig-zag-matrix b/Lang/Octave/Zig-zag-matrix new file mode 120000 index 0000000000..c8c891660e --- /dev/null +++ b/Lang/Octave/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Octave \ No newline at end of file diff --git a/Lang/Oforth/Address-of-a-variable b/Lang/Oforth/Address-of-a-variable new file mode 120000 index 0000000000..ec3579c76e --- /dev/null +++ b/Lang/Oforth/Address-of-a-variable @@ -0,0 +1 @@ +../../Task/Address-of-a-variable/Oforth \ No newline at end of file diff --git a/Lang/PARI-GP/00DESCRIPTION b/Lang/PARI-GP/00DESCRIPTION index cf4ba59ba3..573c623854 100644 --- a/Lang/PARI-GP/00DESCRIPTION +++ b/Lang/PARI-GP/00DESCRIPTION @@ -19,16 +19,123 @@ PARI/GP is composed of two parts: a [[C]] library called PARI and an interface, PARI was written by Henri Cohen and others at Université de Bordeaux and is now maintained by Karim Belabas. gp was originally written by Dominique Bernardi, then maintained and enhanced by Karim Belabas and Ilya Zakharevich, and finally rewritten by Bill Allombert. -== Using PARI/GP == -PARI/GP can be downloaded at its official website's [http://pari.math.u-bordeaux.fr/download.html download page]. +== Getting PARI/GP == +PARI/GP can be used in many different operating systems. For other systems, see the [http://pari.math.u-bordeaux.fr/download.html download page] or the [https://pari.math.u-bordeaux.fr/lists-index.html mailing lists]. -Windows precompiled binaries are available: an installer, stand-alone stable and development versions, plus a nightly build with the very latest changes. [http://pari.math.u-bordeaux.fr/pub/pari/mac/snapshots/ Mac snapshots] are also available. Linux users can install PARI/GP with their favorite package manager (RPM, dpkg, apt, etc.) or build it from source. [http://math.crg4.com/software.html#pari Instructions] are available for compiling. - -Android phones and tablets can use [https://code.google.com/p/paridroid/ paridroid] (also [https://github.com/FreeMonad/paridroid on github]). - -While an iPhone/iPad version has not been developed, [https://itunes.apple.com/us/app/sage-math/id496492945?mt=8 sage-math] includes gp. Click the "+" in the top-right to start a new program, then click and hold on "Sage" at the top until the "Select Language" dropdown appears, then choose GP. (You can also use the wrapper function pari in a Sage snippet.) - -Finally, gp can be used online through [http://pari.math.u-bordeaux.fr/gp.html the PARI/GP site] (via Emscripten), [http://www.compileonline.com/execute_pari_online.php compile online] or the [https://cloud.sagemath.com/ SageMath cloud] (see [http://youtu.be/CzB6T7Nvc-s How to use PARI/GP in the SageMathCloud]). +{| class="wikitable" +|- +! Operating system +! Kind +! Type of install +! Link +! How to install +|- +| rowspan="3" | Windows +| various +| installer (stable or development) +| [http://pari.math.u-bordeaux.fr/download.html#windows official site] +| run installer +|- +| XP, Vista, 7, 8, 10 +| standalone binaries (stable or development) +| [http://pari.math.u-bordeaux.fr/download.html#windows official site] +| run +|- +| various +| standalone binaries (daily) +| [http://pari.math.u-bordeaux.fr/pub/pari/windows/snapshots/ official site] +| run +|- +| rowspan="5" | Linux +| Ubuntu/Debian +| package manager +| [https://packages.debian.org/stretch/pari-gp Debian packages] +| sudo apt-get install pari-gp +|- +| Fedora +| package manager +| [https://apps.fedoraproject.org/packages/pari-gp Fedora packages] +| sudo dnf install pari-gp +|- +| RHEL/CentOS +| package manager +| +| sudo yum install pari-gp +|- +| FreeBSD +| package manager +| [https://svnweb.freebsd.org/ports/head/math/pari/ FreeBSD Ports Search] +| sudo pkg install pari-2.9.4,2 +|- +| various +| build from source +| [http://pari.math.u-bordeaux.fr/download.html official site] +| [http://math.crg4.com/software.html#pari Building PARI/GP in Linux] +|- +| rowspan="2" | Mac OS +| at least El Capitan (10.11) +| DMG installer (stable or development) +| [http://pari.math.u-bordeaux.fr/download.html#macos official site] +| Open dmg, drag to Applications (note: window may start minimized) +|- +| at least El Capitan (10.11) +| standalone binary (stable or development) +| [http://pari.math.u-bordeaux.fr/download.html#macos official site] +| run +|- +| rowspan="5" | Android +| various +| package manager +| [https://f-droid.org/packages/fr.ubordeaux.math.paridroid/ f-droid] +| +|- +| various +| package manager +| [https://play.google.com/store/apps/details?id=fr.ubordeaux.math.paridroid&hl=en Google Play] +| +|- +| various +| precompiled binary +| [http://pari.math.u-bordeaux.fr/download.html#paridroid official site] +| +|- +| various +| build from source +| [https://github.com/FreeMonad/paridroid github] +| [https://github.com/FreeMonad/paridroid/wiki/Build-Environment Building] and [https://github.com/FreeMonad/paridroid/wiki/Installation Installing] +|- +| various +| build from source +| [http://pari.math.u-bordeaux.fr/cgi-bin/gitweb.cgi?p=paridroid.git;a=summary official site] +| [https://github.com/FreeMonad/paridroid/wiki/Build-Environment Building] and [https://github.com/FreeMonad/paridroid/wiki/Installation Installing] +|- +| iOS +| iOS 8+ +| package manager +| [https://itunes.apple.com/us/app/sage-math/id496492945?mt=8 sage-math] +| Click the "+" in the top-right to start a new program, then click and hold on "Sage" at the top until the "Select Language" dropdown appears, then choose GP. (You can also use the wrapper function pari in a Sage snippet.) +|- +| rowspan="4" | Online +| Chrome, Firefox, Internet Explorer +| local Javascript +| [http://pari.math.u-bordeaux.fr/gp.html Emscripten] +| +|- +| Chrome, Firefox +| local Javascript +| [http://pari.math.u-bordeaux.fr/gpexpwasm.html WebAssembly] +| +|- +| Chrome, Firefox, Internet Explorer +| client/server +| [http://www.compileonline.com/execute_pari_online.php compile online] +| +|- +| various +| client/server +| [https://cocalc.com/ CoCalc] +| [http://youtu.be/CzB6T7Nvc-s How to use PARI/GP in the SageMathCloud] (SageMathCloud is now CoCalc) +|} == Coding with PARI == The most common way to use PARI is through the gp calculator, using its own scripting language, GP. But there are other interfaces to PARI beside gp: @@ -57,14 +164,15 @@ If you want to program with PARI, many languages are supported: == Resources == === General === +*[http://pari.math.u-bordeaux.fr/faq.html Official FAQ] *[http://www.math.utah.edu/faq/pari/pari.html PARI/GP FAQ] *[http://pari.math.u-bordeaux.fr/ateliers.html Ateliers PARI/GP]: Conference slides and other resources *[http://hyperpolyglot.org/more-computer-algebra Comparison with Magma, GAP, and Singular] === Tutorials === -*[http://pari.math.u-bordeaux.fr/pub/pari/manuals/2.7.0/tutorial.pdf Official tutorial] by The PARI Group (52 pp., 2014) +*[http://pari.math.u-bordeaux.fr/pub/pari/manuals/2.9.0/tutorial.pdf Official tutorial] by The PARI Group (58 pp., 2016) *[http://www.math.u-bordeaux.fr/~ballombe/talks/bordeaux-20150924.pdf Tutorial on Elliptic Curves] by Bill Allombert and Karim Belabas (5 pp., 2016) -*[http://www.math.psu.edu/wdb/467/pariinfo.pdf Beginning PARI Programming for CSE/MATH 467] by W. Dale Brownawell (7 pp., 2014) +*[http://www.personal.psu.edu/bug/467/pariinfo.pdf Beginning PARI Programming for CSE/MATH 467] by W. Dale Brownawell (7 pp., 2014) *[http://www.math.uiuc.edu/~r-ash/GPTutorial.pdf Tutorial] by Robert B. Ash (20 pp., 2007) *[http://people.math.umass.edu/~siman/09.791N/tutorial.pdf Tutorial] by Siman Wong (6 pp., 2009) *[http://www.math.uconn.edu/~kconrad/math5230f08/parihandout.pdf Introduction] by Keith Conrad (7 pp., 2008) @@ -75,12 +183,14 @@ If you want to program with PARI, many languages are supported: *[http://w3.countnumber.de/fischer/res-ZT2007/PariByExample.pdf Erste Schritte mit PARI/GP] by Lars Fischer (13 pp., 2007; German) *[http://www.maths.tcd.ie/~vlasenko/MA2316/ Class notes] including PARI/GP tutorial and sample code by Masha Vlasenko (2013) * Class notes, parts [http://myweb.csuchico.edu/~blevitt/math230/230coursedocs/230notes/230notes_01.pdf 1][http://myweb.csuchico.edu/~blevitt/math230/230coursedocs/230notes/230notes_02.pdf 2][http://myweb.csuchico.edu/~blevitt/math230/230coursedocs/230notes/230notes_03.pdf 3][http://myweb.csuchico.edu/~blevitt/math230/230coursedocs/230notes/230notes_04.pdf 4][http://myweb.csuchico.edu/~blevitt/math230/230coursedocs/230notes/230notes_05.pdf 5][http://myweb.csuchico.edu/~blevitt/math230/230coursedocs/230notes/230notes_sieve.pdf sieve] by Benjamin L. Levitt (41 pp., 2009; now offline?) -*[http://users.aims.ac.za/~richard/faq/index.php Pari/GP Tutorial] by Akinola Richard Olatokunbo +*[http://users.aims.ac.za/~richard/faq/index.php Pari/GP Tutorial] by Akinola Richard Olatokunbo (now offline; [https://web.archive.org/web/20170324230906/http://users.aims.ac.za/~richard/faq/index.php archived version]) *[https://www.youtube.com/watch?v=FeG0BYRrDOE&t=12m Video demo of RSA in PARI/GP] by Maren1955 (2014, 17:39) === Papers on PARI/GP === +* Karim Belabas and Jean-François Jaulent, [https://www.math.u-bordeaux.fr/~jjaulent/Articles/bnflog.ps The logarithmic class group package in PARI/GP], ''Mathematical Publications of Besançon, Algebra and Number Theory'' (2016), pp. 5–18. * Bill Alombert, [http://www.math.u-bordeaux.fr/~allomber/darkpaper.pdf A new interpretor for PARI/GP], ''Journal de Théorie des Nombres de Bordeaux'' '''20''':3 (2008), pp. 531–541. (English) * Paul Zimmermann, [http://www.loria.fr/~zimmerma/talks/henri.pdf The Ups and Downs of PARI/GP in the last 20 years], Explicit Methods in Number Theory, October 15th-19th 2007 * Robert H. Lewis and Michael Wester, [https://home.bway.net/lewis/cacomp.ps Comparison of polynomial-oriented computer algebra systems], ''ACM SIGSAM Bulletin'' '''33''':4 (1999), pp. 5-13. +* Henri Cohen, Computing in algebraic number fields. In P. L. Butzer (ed.) et al., Karl der Grosse und sein Nachwirken. 1200 Jahre Kultur und Wissenschaft in Europa. Band 2: Mathematisches Wissen. Turnhout: Brepols. 505-520 (1998) [[Category:Mathematical programming languages]] \ No newline at end of file diff --git a/Lang/PARI-GP/Hello-world-Graphical b/Lang/PARI-GP/Hello-world-Graphical new file mode 120000 index 0000000000..f3fafc8540 --- /dev/null +++ b/Lang/PARI-GP/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Parsing-RPN-calculator-algorithm b/Lang/PARI-GP/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..9441ec6e1f --- /dev/null +++ b/Lang/PARI-GP/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/PARI-GP \ No newline at end of file diff --git a/Lang/PHP/Rock-paper-scissors b/Lang/PHP/Rock-paper-scissors new file mode 120000 index 0000000000..eb4685bd3b --- /dev/null +++ b/Lang/PHP/Rock-paper-scissors @@ -0,0 +1 @@ +../../Task/Rock-paper-scissors/PHP \ No newline at end of file diff --git a/Lang/PL-M/00DESCRIPTION b/Lang/PL-M/00DESCRIPTION index 842acda5a5..4d879db6f5 100644 --- a/Lang/PL-M/00DESCRIPTION +++ b/Lang/PL-M/00DESCRIPTION @@ -5,7 +5,7 @@ PL/M (Programming Language for Microcomputers) is (as the name suggests) a langu
It is approximately a very small subset of PL/1 (though not a strict subset).
-The following statements were available: +The following statements from PL/1 (with some changes) were available: * assignment * CALL * DECLARE @@ -14,9 +14,10 @@ The following statements were available: * GOTO * PROCEDURE-END * RETURN -Additionally a number of compiler directive statements existed. There are no built-in I/O statements - calls to appropriate routines would be made instead. +Additionally, a HALT statement, interrupt related statements and a number of compiler directive statements existed.
+There are no built-in I/O statements - calls to appropriate routines would be made instead.

-Unlike PL1, PL/M keywords are reserved and so cannot be used as identifiers. +Unlike PL1, PL/M keywords are reserved and so cannot be used as identifiers. The Boolean operators are reserved words: AND, OR and NOT instead of the symbols: &, |, ¬.
Available datatypes (BYTE, WORD, etc.) reflected the available types of the microprocessors.

diff --git a/Lang/PL-M/Hello-world-Text b/Lang/PL-M/Hello-world-Text new file mode 120000 index 0000000000..88952e7f3d --- /dev/null +++ b/Lang/PL-M/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/PL-M \ No newline at end of file diff --git a/Lang/PL-M/Trabb-Pardo-Knuth-algorithm b/Lang/PL-M/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..91b721c5b5 --- /dev/null +++ b/Lang/PL-M/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/PL-M \ No newline at end of file diff --git a/Lang/PL-SQL/00DESCRIPTION b/Lang/PL-SQL/00DESCRIPTION index f26936308b..305428322c 100644 --- a/Lang/PL-SQL/00DESCRIPTION +++ b/Lang/PL-SQL/00DESCRIPTION @@ -1,4 +1,7 @@ {{language|PL/SQL}}{{implementation|SQL}}'''PL/SQL''' (Procedural Language/Structured Query Language) is Oracle Corporation's proprietary server-based procedural extension to the [[SQL]] database language. (Some other SQL database management systems offer languages similar to PL/SQL.) Its syntax strongly resembles that of [[Ada]]. + +IBM [[SQL PL|Db2 LUW]] (for Linux, UNIX and Windows) from version 9.7 supports natively Oracle's PL/SQL. That means, you can create stored procedures in Db2 with PL/SQL language. + ==Citations== * [http://en.wikipedia.org/wiki/PL/SQL Wikipedia:PL/SQL] * [http://docs.oracle.com/database/122/LNPLS/toc.htm Oracle 12.2 PL/SQL Manual] \ No newline at end of file diff --git a/Lang/PL-SQL/Loops-While b/Lang/PL-SQL/Loops-While new file mode 120000 index 0000000000..22bb6e5492 --- /dev/null +++ b/Lang/PL-SQL/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/PL-SQL \ No newline at end of file diff --git a/Lang/Pascal/HTTPS b/Lang/Pascal/HTTPS new file mode 120000 index 0000000000..2b5048e8ce --- /dev/null +++ b/Lang/Pascal/HTTPS @@ -0,0 +1 @@ +../../Task/HTTPS/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Twelve-statements b/Lang/Pascal/Twelve-statements new file mode 120000 index 0000000000..b2f4ab0205 --- /dev/null +++ b/Lang/Pascal/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/Pascal \ No newline at end of file diff --git a/Lang/Perl-6/00DESCRIPTION b/Lang/Perl-6/00DESCRIPTION index aeb9c70e54..741b1e1125 100644 --- a/Lang/Perl-6/00DESCRIPTION +++ b/Lang/Perl-6/00DESCRIPTION @@ -14,15 +14,26 @@ {{language programming paradigm|functional}} {{language programming paradigm|object-oriented}} {{language programming paradigm|generic}} -Perl 6 is the up-and-coming little sister to Perl 5. 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. +Perl 6 is the up-and-coming little sister to Perl 5. +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. Damian Conway described the basic philosophy of Perl 6 as follows: -
The Perl 6 design process is about keeping what works in Perl 5, fixing what doesn't, and adding what's missing. That means there will be a few fundamental changes to the language, a large number of extensions to existing features, and a handful of completely new ideas. These modifications, enhancements, and innovations will work together to make the future Perl even more insanely great -- without, we hope, making it even more greatly insane.
+
The Perl 6 design process is about keeping what works in Perl 5, fixing what doesn't, and adding what's missing. +That means there will be a few fundamental changes to the language, a large number of extensions to existing features, and a handful of completely new ideas. +These modifications, enhancements, and innovations will work together to make the future Perl even more insanely great -- without, we hope, making it even more greatly insane.
Major new features include multiple dispatch, declarative classes, grammars, formal parameters to subroutines, type constraints on variables, lazy evaluation, junctions, meta-operators, and the ability to change Perl's syntax at will. The definition of Perl 6 is specified entirely by a test suite, so we could in theory have multiple implementations. -The current version of the language is 6.c (short for 6.christmas), as defined by the test suite known as "roast" (Repository Of All Spec Tests). Compiler releases have date-based versions, and these are typically used in Rosetta Code entries for the "works with" fields. The only compiler implementing the full test suite, rakudo, currently runs on either MoarVM or JVM. Subsequent language revisions are planned (with provisional names of "Diwali", "Eid", and other such celebrations), but these will only come out once a year or so. In 2016 we are primarily working on performance and documentation of the stable 6.c version. +The current version of the language is 6.c (short for 6.christmas), as defined by the test suite known as "roast" (Repository Of All Spec Tests). +Compiler releases have date-based versions, and these are typically used in Rosetta Code entries for the "works with" fields. +The only compiler implementing the full test suite, rakudo, currently runs on either MoarVM or JVM. +Subsequent language revisions are planned (with provisional names of "Diwali", "Eid", and other such celebrations), but these will only come out once a year or so. +In 2016 we are primarily working on performance and documentation of the stable 6.c version. -
\ No newline at end of file +
+ +==Todo== +[[Reports:Tasks_not_implemented_in_Perl_6]] \ No newline at end of file diff --git a/Lang/Perl-6/Append-a-record-to-the-end-of-a-text-file b/Lang/Perl-6/Append-a-record-to-the-end-of-a-text-file new file mode 120000 index 0000000000..9039b4627b --- /dev/null +++ b/Lang/Perl-6/Append-a-record-to-the-end-of-a-text-file @@ -0,0 +1 @@ +../../Task/Append-a-record-to-the-end-of-a-text-file/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Bitmap-B-zier-curves-Cubic b/Lang/Perl-6/Bitmap-B-zier-curves-Cubic new file mode 120000 index 0000000000..9afcf2f69f --- /dev/null +++ b/Lang/Perl-6/Bitmap-B-zier-curves-Cubic @@ -0,0 +1 @@ +../../Task/Bitmap-B-zier-curves-Cubic/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Bitmap-B-zier-curves-Quadratic b/Lang/Perl-6/Bitmap-B-zier-curves-Quadratic new file mode 120000 index 0000000000..42a3ac6bfd --- /dev/null +++ b/Lang/Perl-6/Bitmap-B-zier-curves-Quadratic @@ -0,0 +1 @@ +../../Task/Bitmap-B-zier-curves-Quadratic/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Bitmap-Histogram b/Lang/Perl-6/Bitmap-Histogram new file mode 120000 index 0000000000..6f5f5afe61 --- /dev/null +++ b/Lang/Perl-6/Bitmap-Histogram @@ -0,0 +1 @@ +../../Task/Bitmap-Histogram/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Bitmap-Read-a-PPM-file b/Lang/Perl-6/Bitmap-Read-a-PPM-file new file mode 120000 index 0000000000..4e7f8118b0 --- /dev/null +++ b/Lang/Perl-6/Bitmap-Read-a-PPM-file @@ -0,0 +1 @@ +../../Task/Bitmap-Read-a-PPM-file/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Bitmap-Read-an-image-through-a-pipe b/Lang/Perl-6/Bitmap-Read-an-image-through-a-pipe new file mode 120000 index 0000000000..8efa5734f0 --- /dev/null +++ b/Lang/Perl-6/Bitmap-Read-an-image-through-a-pipe @@ -0,0 +1 @@ +../../Task/Bitmap-Read-an-image-through-a-pipe/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Distributed-programming b/Lang/Perl-6/Distributed-programming new file mode 120000 index 0000000000..01a609cc8b --- /dev/null +++ b/Lang/Perl-6/Distributed-programming @@ -0,0 +1 @@ +../../Task/Distributed-programming/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/HTTPS b/Lang/Perl-6/HTTPS new file mode 120000 index 0000000000..a07634c64a --- /dev/null +++ b/Lang/Perl-6/HTTPS @@ -0,0 +1 @@ +../../Task/HTTPS/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/HTTPS-Authenticated b/Lang/Perl-6/HTTPS-Authenticated new file mode 120000 index 0000000000..3337c03580 --- /dev/null +++ b/Lang/Perl-6/HTTPS-Authenticated @@ -0,0 +1 @@ +../../Task/HTTPS-Authenticated/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Infinity b/Lang/Perl-6/Infinity new file mode 120000 index 0000000000..2d603d9208 --- /dev/null +++ b/Lang/Perl-6/Infinity @@ -0,0 +1 @@ +../../Task/Infinity/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Secure-temporary-file b/Lang/Perl-6/Secure-temporary-file new file mode 120000 index 0000000000..8cfec0a6c1 --- /dev/null +++ b/Lang/Perl-6/Secure-temporary-file @@ -0,0 +1 @@ +../../Task/Secure-temporary-file/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Simple-database b/Lang/Perl-6/Simple-database new file mode 120000 index 0000000000..db999e0e3d --- /dev/null +++ b/Lang/Perl-6/Simple-database @@ -0,0 +1 @@ +../../Task/Simple-database/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Table-creation-Postal-addresses b/Lang/Perl-6/Table-creation-Postal-addresses new file mode 120000 index 0000000000..23602602e6 --- /dev/null +++ b/Lang/Perl-6/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Video-display-modes b/Lang/Perl-6/Video-display-modes new file mode 120000 index 0000000000..1e59a8521c --- /dev/null +++ b/Lang/Perl-6/Video-display-modes @@ -0,0 +1 @@ +../../Task/Video-display-modes/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Voronoi-diagram b/Lang/Perl-6/Voronoi-diagram new file mode 120000 index 0000000000..ff0994e46e --- /dev/null +++ b/Lang/Perl-6/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/XML-DOM-serialization b/Lang/Perl-6/XML-DOM-serialization new file mode 120000 index 0000000000..38446e3f45 --- /dev/null +++ b/Lang/Perl-6/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/XML-Output b/Lang/Perl-6/XML-Output new file mode 120000 index 0000000000..2163bfb210 --- /dev/null +++ b/Lang/Perl-6/XML-Output @@ -0,0 +1 @@ +../../Task/XML-Output/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/XML-XPath b/Lang/Perl-6/XML-XPath new file mode 120000 index 0000000000..aac059223e --- /dev/null +++ b/Lang/Perl-6/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/Perl-6 \ No newline at end of file diff --git a/Lang/Perl/00DESCRIPTION b/Lang/Perl/00DESCRIPTION index 15dcfd719e..fce0dda81a 100644 --- a/Lang/Perl/00DESCRIPTION +++ b/Lang/Perl/00DESCRIPTION @@ -23,4 +23,7 @@ As a language, it takes the best from other programming languages such as [[deri The implementation known as Perl is available on a wide variety of mostly UNIX-based operating systems. ==Citations== -* [[wp:Perl|Wikipedia:Perl]] \ No newline at end of file +* [[wp:Perl|Wikipedia:Perl]] + +==Todo== +[[Reports:Tasks_not_implemented_in_Perl]] \ No newline at end of file diff --git a/Lang/Perl/Keyboard-input-Keypress-check b/Lang/Perl/Keyboard-input-Keypress-check new file mode 120000 index 0000000000..62d4d34e8f --- /dev/null +++ b/Lang/Perl/Keyboard-input-Keypress-check @@ -0,0 +1 @@ +../../Task/Keyboard-input-Keypress-check/Perl \ No newline at end of file diff --git a/Lang/Perl/Matrix-arithmetic b/Lang/Perl/Matrix-arithmetic new file mode 120000 index 0000000000..f05d2ca50c --- /dev/null +++ b/Lang/Perl/Matrix-arithmetic @@ -0,0 +1 @@ +../../Task/Matrix-arithmetic/Perl \ No newline at end of file diff --git a/Lang/Perl/Parallel-calculations b/Lang/Perl/Parallel-calculations new file mode 120000 index 0000000000..07aea8c932 --- /dev/null +++ b/Lang/Perl/Parallel-calculations @@ -0,0 +1 @@ +../../Task/Parallel-calculations/Perl \ No newline at end of file diff --git a/Lang/Perl/Permutations-Rank-of-a-permutation b/Lang/Perl/Permutations-Rank-of-a-permutation new file mode 120000 index 0000000000..45a21595ea --- /dev/null +++ b/Lang/Perl/Permutations-Rank-of-a-permutation @@ -0,0 +1 @@ +../../Task/Permutations-Rank-of-a-permutation/Perl \ No newline at end of file diff --git a/Lang/Perl/Simple-database b/Lang/Perl/Simple-database new file mode 120000 index 0000000000..a92297d695 --- /dev/null +++ b/Lang/Perl/Simple-database @@ -0,0 +1 @@ +../../Task/Simple-database/Perl \ No newline at end of file diff --git a/Lang/Perl/Terminal-control-Preserve-screen b/Lang/Perl/Terminal-control-Preserve-screen new file mode 120000 index 0000000000..ac8a8f9e5b --- /dev/null +++ b/Lang/Perl/Terminal-control-Preserve-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Preserve-screen/Perl \ No newline at end of file diff --git a/Lang/Perl/Write-to-Windows-event-log b/Lang/Perl/Write-to-Windows-event-log new file mode 120000 index 0000000000..2ad2cdac37 --- /dev/null +++ b/Lang/Perl/Write-to-Windows-event-log @@ -0,0 +1 @@ +../../Task/Write-to-Windows-event-log/Perl \ No newline at end of file diff --git a/Lang/Phix/Text-processing-1 b/Lang/Phix/Text-processing-1 new file mode 120000 index 0000000000..2f8af6cb67 --- /dev/null +++ b/Lang/Phix/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/Phix \ No newline at end of file diff --git a/Lang/PicoLisp/00DESCRIPTION b/Lang/PicoLisp/00DESCRIPTION index ee829afafb..36b61978cb 100644 --- a/Lang/PicoLisp/00DESCRIPTION +++ b/Lang/PicoLisp/00DESCRIPTION @@ -6,18 +6,25 @@ {{implementation|Lisp}} [[Category:Lisp Implementations]] -'''PicoLisp''' is a small and fast interpreted [[Lisp]] dialect. It runs on [[Linux]] and other [[POSIX]]-compliant systems, and - in a reduced version - on [[JVM]]. +'''PicoLisp''' is a small and fast interpreted [[Lisp]] dialect. +It runs on [[Linux]] and other [[POSIX]]-compliant systems, and - in a reduced version - on [[JVM]]. -Its most prominent feature is "simplicity". It is built on top of a single internal data type (the cell), without giving up flexibility and expressive power. On the language level, it supports just three data types (numbers, symbols and lists), constructed from internal cells. +Its most prominent feature is "simplicity". It is built on top of a single internal data type (the cell), without giving up flexibility and expressive power. +On the language level, it supports just three data types (numbers, symbols and lists), constructed from internal cells. -PicoLisp programs are often more succinct - and at the same time faster - than those of other interpreted languages. A special feature is the intrinsic database functionality: Persistent symbols are first-class objects, and applications are written using a class hierarchy of entities and relations. +PicoLisp programs are often more succinct - and at the same time faster - than those of other interpreted languages. +A special feature is the intrinsic database functionality: Persistent symbols are first-class objects, and applications are written using a class hierarchy of entities and relations. Other features include a [[Prolog]] engine for logic programming and database queries, distributed databases, inlining of [[C]]/asm functions and native C/asm function calls, child process management, interprocess communication, Browser GUI, Internationalization and localization. To try the RosettaCode tasks, download [http://software-lab.de/picoLisp.tgz picoLisp.tgz], unpack it, and follow the instructions in README and INSTALL. Unless stated otherwise, the examples assume that the interpreter was started with the command $ pil + : -(i.e. with a '+' for "debug mode", as recommended in the documentation. Note: Do not call just the 'picolisp' binary, this is only the bare kernel of PicoLisp) +(i.e. with a '+' for "debug mode", as recommended in the documentation. +Note: Do not call just the 'picolisp' binary, this is only the bare kernel of PicoLisp) ==See Also== * [http://software-lab.de/doc/ref.html Reference Manual] -* [http://software-lab.de/doc/faq.html Frequently asked questions] \ No newline at end of file +* [http://software-lab.de/doc/faq.html Frequently asked questions] + +==Todo== +[[Reports:Tasks_not_implemented_in_PicoLisp]] \ No newline at end of file diff --git a/Lang/PicoLisp/Extensible-prime-generator b/Lang/PicoLisp/Extensible-prime-generator new file mode 120000 index 0000000000..106471cc69 --- /dev/null +++ b/Lang/PicoLisp/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Harshad-or-Niven-series b/Lang/PicoLisp/Harshad-or-Niven-series new file mode 120000 index 0000000000..a59ce939a2 --- /dev/null +++ b/Lang/PicoLisp/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Josephus-problem b/Lang/PicoLisp/Josephus-problem new file mode 120000 index 0000000000..94283927b0 --- /dev/null +++ b/Lang/PicoLisp/Josephus-problem @@ -0,0 +1 @@ +../../Task/Josephus-problem/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Penneys-game b/Lang/PicoLisp/Penneys-game new file mode 120000 index 0000000000..65ba13b7b7 --- /dev/null +++ b/Lang/PicoLisp/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Stern-Brocot-sequence b/Lang/PicoLisp/Stern-Brocot-sequence new file mode 120000 index 0000000000..28530a50a4 --- /dev/null +++ b/Lang/PicoLisp/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/PicoLisp \ No newline at end of file diff --git a/Lang/Pony/Synchronous-concurrency b/Lang/Pony/Synchronous-concurrency new file mode 120000 index 0000000000..df8bcc1fbb --- /dev/null +++ b/Lang/Pony/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Pony \ No newline at end of file diff --git a/Lang/PowerBASIC/Binary-digits b/Lang/PowerBASIC/Binary-digits new file mode 120000 index 0000000000..c3e41e678d --- /dev/null +++ b/Lang/PowerBASIC/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/PowerBASIC \ No newline at end of file diff --git a/Lang/PowerBASIC/Rot-13 b/Lang/PowerBASIC/Rot-13 new file mode 120000 index 0000000000..e95f5e4a14 --- /dev/null +++ b/Lang/PowerBASIC/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/PowerBASIC \ No newline at end of file diff --git a/Lang/PowerShell/Calendar b/Lang/PowerShell/Calendar new file mode 120000 index 0000000000..8e7f52da8c --- /dev/null +++ b/Lang/PowerShell/Calendar @@ -0,0 +1 @@ +../../Task/Calendar/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Natural-sorting b/Lang/PowerShell/Natural-sorting new file mode 120000 index 0000000000..a11615c6d2 --- /dev/null +++ b/Lang/PowerShell/Natural-sorting @@ -0,0 +1 @@ +../../Task/Natural-sorting/PowerShell \ No newline at end of file diff --git a/Lang/Processing/00DESCRIPTION b/Lang/Processing/00DESCRIPTION index 3e91ceb70a..2a3abe6d39 100644 --- a/Lang/Processing/00DESCRIPTION +++ b/Lang/Processing/00DESCRIPTION @@ -2,4 +2,11 @@ |exec=Virtual Machine |site=http://processing.org/}} -Processing is a programming language for create images, animations, and interactions. \ No newline at end of file +Processing is a flexible software sketchbook and a language for learning how to code within the context of the visual arts. Since 2001, Processing has promoted software literacy within the visual arts and visual literacy within technology. There are tens of thousands of students, artists, designers, researchers, and hobbyists who use Processing for learning and prototyping. + +» Free to download and open source +» Interactive programs with 2D, 3D or PDF output +» OpenGL integration for accelerated 2D and 3D +» For GNU/Linux, Mac OS X, Windows, Android, and ARM +» Over 100 libraries extend the core software +» Well documented, with many books available \ No newline at end of file diff --git a/Lang/Processing/Ackermann-function b/Lang/Processing/Ackermann-function new file mode 120000 index 0000000000..667da347ff --- /dev/null +++ b/Lang/Processing/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Processing \ No newline at end of file diff --git a/Lang/Processing/Classes b/Lang/Processing/Classes new file mode 120000 index 0000000000..2a32832711 --- /dev/null +++ b/Lang/Processing/Classes @@ -0,0 +1 @@ +../../Task/Classes/Processing \ No newline at end of file diff --git a/Lang/Processing/Factorial b/Lang/Processing/Factorial new file mode 120000 index 0000000000..a1ce6d02aa --- /dev/null +++ b/Lang/Processing/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Processing \ No newline at end of file diff --git a/Lang/Processing/Mandelbrot-set b/Lang/Processing/Mandelbrot-set new file mode 120000 index 0000000000..1104ffd756 --- /dev/null +++ b/Lang/Processing/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/Processing \ No newline at end of file diff --git a/Lang/Processing/Palindrome-detection b/Lang/Processing/Palindrome-detection new file mode 120000 index 0000000000..7990429bc0 --- /dev/null +++ b/Lang/Processing/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Processing \ No newline at end of file diff --git a/Lang/Prolog/Arithmetic-geometric-mean b/Lang/Prolog/Arithmetic-geometric-mean new file mode 120000 index 0000000000..d39de1e5fe --- /dev/null +++ b/Lang/Prolog/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Closest-pair-problem b/Lang/Prolog/Closest-pair-problem new file mode 120000 index 0000000000..e0f1655eb4 --- /dev/null +++ b/Lang/Prolog/Closest-pair-problem @@ -0,0 +1 @@ +../../Task/Closest-pair-problem/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Execute-Brain---- b/Lang/Prolog/Execute-Brain---- new file mode 120000 index 0000000000..0a52f33ea1 --- /dev/null +++ b/Lang/Prolog/Execute-Brain---- @@ -0,0 +1 @@ +../../Task/Execute-Brain----/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Spiral-matrix b/Lang/Prolog/Spiral-matrix new file mode 120000 index 0000000000..f8f114fc54 --- /dev/null +++ b/Lang/Prolog/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Prolog \ No newline at end of file diff --git a/Lang/PureBasic/00DESCRIPTION b/Lang/PureBasic/00DESCRIPTION index a75d066904..776587a592 100644 --- a/Lang/PureBasic/00DESCRIPTION +++ b/Lang/PureBasic/00DESCRIPTION @@ -5,36 +5,13 @@ |express=implicit |tags=purebasic |site=http://www.purebasic.com/}} -{{implementation|BASIC}}'''PureBasic''' is a "high-level" programming language based on "BASIC" rules. PureBasic has been created for beginners and experts alike. +{{implementation|BASIC}}'''PureBasic''' is a high-level programming language by Fantaisie Software based on [[:Category:BASIC|BASIC]] rules. PureBasic has been created for beginners and experts alike. -PureBasic is a portable programming language with current up to date implementations on Windows, Linux, and MacOS. The same code can be compiled and run natively on each OS. An older version for the Amiga platform is no longer maintained. - -PureBasic was first released by '''Fantaisie Software''' [http://www.purebasic.com www.purebasic.com] in 2001. Since then the language is being improved and expanded continuously. - -==Features== -* x86, x64, 680x0 and PowerPC support -* Built-in arrays, dynamic linked lists, complex structures, pointers and variable definitions -* Supported types: Byte (8 bits), Word (16 bits), Long (32 bits), Quad (64 bits), Float (32 bits), Double (64 bits) and Characters -* User defined types (structures) -* Built-in string types (characters), including ascii and unicode -* Powerful macro support -* Constants, binary and hexadecimal numbers supported -* Expression reducer by grouping constants and numeric numbers together -* Standard arithmetic support in respect of sign priority and parenthesis: +, -, /, *, and, or, <<, >> -* Extremely fast compilation -* Procedure support for structured programming with local and global variables -* All Standard BASIC keywords: If-Else-EndIf, Repeat-Until, etc -* Specialized libraries to manipulate BMP pictures, windows, gadgets, DirectX, etc -* Specialized libraries are very optimized for maximum speed and compactness -* The Win32 API is fully supported as if they were BASIC keywords -* Inline Assembler -* Precompiled structures with constants files for extra-fast compilation -* Configurable CLI compiler -* High productivity, comprehensive keywords, online help -* System friendly, easy to install and easy to use +PureBasic is a portable programming language with current up-to-date implementations on Windows, Linux, and MacOS. The same code can be compiled and run natively on each OS. An older version for the Amiga platform is also available, but no longer maintained. ==See Also== -* [[wp:PureBasic|Wikipedia: PureBasic]] +* [http://www.purebasic.com PureBasic home page] +* [[wp:PureBasic|PureBasic on Wikipedia]] {{language programming paradigm|procedural}} {{language programming paradigm|imperative}} \ No newline at end of file diff --git a/Lang/PureBasic/Almost-prime b/Lang/PureBasic/Almost-prime new file mode 120000 index 0000000000..cb6e251ac1 --- /dev/null +++ b/Lang/PureBasic/Almost-prime @@ -0,0 +1 @@ +../../Task/Almost-prime/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/Modular-inverse b/Lang/PureBasic/Modular-inverse new file mode 120000 index 0000000000..8aa602ad0c --- /dev/null +++ b/Lang/PureBasic/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/PureBasic \ No newline at end of file diff --git a/Lang/PureBasic/The-Twelve-Days-of-Christmas b/Lang/PureBasic/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..aa61bacb74 --- /dev/null +++ b/Lang/PureBasic/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/PureBasic \ No newline at end of file diff --git a/Lang/Python/00DESCRIPTION b/Lang/Python/00DESCRIPTION index 4f95e5a706..7a8cf26ec6 100644 --- a/Lang/Python/00DESCRIPTION +++ b/Lang/Python/00DESCRIPTION @@ -28,4 +28,7 @@ This style is not a requirement for Python code on RC, but it may be in use and The command line is often used in Python for short pieces of code, and so, again; examples showing such use are not incorrect and may be left. ==See Also== -* [[wp:python_(programming_language)|Wikipedia: Python]] \ No newline at end of file +* [[wp:python_(programming_language)|Wikipedia: Python]] + +==Todo== +[[Reports:Tasks_not_implemented_in_Python]] \ No newline at end of file diff --git a/Lang/Python/Colour-pinstripe-Display b/Lang/Python/Colour-pinstripe-Display new file mode 120000 index 0000000000..042e96547f --- /dev/null +++ b/Lang/Python/Colour-pinstripe-Display @@ -0,0 +1 @@ +../../Task/Colour-pinstripe-Display/Python \ No newline at end of file diff --git a/Lang/Python/Events b/Lang/Python/Events new file mode 120000 index 0000000000..83297f9b16 --- /dev/null +++ b/Lang/Python/Events @@ -0,0 +1 @@ +../../Task/Events/Python \ No newline at end of file diff --git a/Lang/Python/Terminal-control-Hiding-the-cursor b/Lang/Python/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..ab15ce601f --- /dev/null +++ b/Lang/Python/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/Python \ No newline at end of file diff --git a/Lang/Python/Terminal-control-Positional-read b/Lang/Python/Terminal-control-Positional-read new file mode 120000 index 0000000000..a52c506d9d --- /dev/null +++ b/Lang/Python/Terminal-control-Positional-read @@ -0,0 +1 @@ +../../Task/Terminal-control-Positional-read/Python \ No newline at end of file diff --git a/Lang/Python/Variables b/Lang/Python/Variables new file mode 120000 index 0000000000..d9bf93e3a1 --- /dev/null +++ b/Lang/Python/Variables @@ -0,0 +1 @@ +../../Task/Variables/Python \ No newline at end of file diff --git a/Lang/Q/Look-and-say-sequence b/Lang/Q/Look-and-say-sequence new file mode 120000 index 0000000000..ce3ed1e4bd --- /dev/null +++ b/Lang/Q/Look-and-say-sequence @@ -0,0 +1 @@ +../../Task/Look-and-say-sequence/Q \ No newline at end of file diff --git a/Lang/R/AKS-test-for-primes b/Lang/R/AKS-test-for-primes new file mode 120000 index 0000000000..be89c11c1a --- /dev/null +++ b/Lang/R/AKS-test-for-primes @@ -0,0 +1 @@ +../../Task/AKS-test-for-primes/R \ No newline at end of file diff --git a/Lang/R/Amicable-pairs b/Lang/R/Amicable-pairs new file mode 120000 index 0000000000..39d3f89785 --- /dev/null +++ b/Lang/R/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/R \ No newline at end of file diff --git a/Lang/R/Catamorphism b/Lang/R/Catamorphism new file mode 120000 index 0000000000..ddbdf02bab --- /dev/null +++ b/Lang/R/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/R \ No newline at end of file diff --git a/Lang/R/Dinesmans-multiple-dwelling-problem b/Lang/R/Dinesmans-multiple-dwelling-problem new file mode 120000 index 0000000000..05ca39c145 --- /dev/null +++ b/Lang/R/Dinesmans-multiple-dwelling-problem @@ -0,0 +1 @@ +../../Task/Dinesmans-multiple-dwelling-problem/R \ No newline at end of file diff --git a/Lang/R/Knapsack-problem-Bounded b/Lang/R/Knapsack-problem-Bounded new file mode 120000 index 0000000000..c2fce1dd2e --- /dev/null +++ b/Lang/R/Knapsack-problem-Bounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Bounded/R \ No newline at end of file diff --git a/Lang/R/Lucas-Lehmer-test b/Lang/R/Lucas-Lehmer-test new file mode 120000 index 0000000000..3d6d63540f --- /dev/null +++ b/Lang/R/Lucas-Lehmer-test @@ -0,0 +1 @@ +../../Task/Lucas-Lehmer-test/R \ No newline at end of file diff --git a/Lang/R/Non-decimal-radices-Convert b/Lang/R/Non-decimal-radices-Convert new file mode 120000 index 0000000000..0bd0d60e18 --- /dev/null +++ b/Lang/R/Non-decimal-radices-Convert @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Convert/R \ No newline at end of file diff --git a/Lang/R/Reverse-words-in-a-string b/Lang/R/Reverse-words-in-a-string new file mode 120000 index 0000000000..7fc553d59c --- /dev/null +++ b/Lang/R/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/R \ No newline at end of file diff --git a/Lang/R/Statistics-Basic b/Lang/R/Statistics-Basic new file mode 120000 index 0000000000..ad3df853b8 --- /dev/null +++ b/Lang/R/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/R \ No newline at end of file diff --git a/Lang/REXX/00DESCRIPTION b/Lang/REXX/00DESCRIPTION index 7c96a0776a..33d950dd4e 100644 --- a/Lang/REXX/00DESCRIPTION +++ b/Lang/REXX/00DESCRIPTION @@ -59,7 +59,7 @@
[Most of the entries were entered mostly from memory and apologies are offered for not knowing more about what wording should be used; the IBM operating systems or Program Products that run REXX are numerous and varied.   Their complete (official) names would fill a pageful.   Some of the REXXes are no longer sold nor available for downloading or purchase, others are no longer maintained.   Naming of names is being avoided (especially those licensed products for sale), and it is hoped that this is seen that no products nor vendors are being endorsed, appraised, or critiqued.]   -- [[User:Gerard Schildberger|Gerard Schildberger]] 09:28, 1 July 2012 (UTC) ===External Links=== -* [http://sourceforge.net/projects/brexx/ Brexx interpreter] +* [https://github.com/vlachoudis/brexx Brexx interpreter] * [http://www.oorexx.org/ Open Object Rexx - www.oorexx.org] * [http://www.netrexx.org The NetRexx Programming Language - www.netrexx.org] * [http://www.rexxla.org The Rexx Language Association - www.rexxla.org] @@ -72,4 +72,7 @@ * [http://www.kilowattsoftware.com/rooPage.htm ROO, Kilowatt Software] * [http://publib.boulder.ibm.com/cgi-bin/bookmgr_OS390/BOOKS/HCSE2C00/CCONTENTS?SHELF=hcsh2ab0&DN=SC24-6221-00&DT=20090724140455 z/VM V6R1 REXX/VM Reference] * [http://publib.boulder.ibm.com/cgi-bin/bookmgr_OS390/BOOKS/HCSB3C00/CCONTENTS?SHELF=hcsh2ab0&DN=SC24-6222-00&DT=20090724131829 z/VM V6R1 REXX/VM User's Guide] -* [http://www.rexxinfo.org/html/rexxinfo1.html#Rexx-Manuals {many references to REXX manuals}] \ No newline at end of file +* [http://www.rexxinfo.org/html/rexxinfo1.html#Rexx-Manuals {many references to REXX manuals}] + +==Todo== +[[Reports:Tasks_not_implemented_in_REXX]] \ No newline at end of file diff --git a/Lang/REXX/Bitmap-Read-a-PPM-file b/Lang/REXX/Bitmap-Read-a-PPM-file new file mode 120000 index 0000000000..c082031638 --- /dev/null +++ b/Lang/REXX/Bitmap-Read-a-PPM-file @@ -0,0 +1 @@ +../../Task/Bitmap-Read-a-PPM-file/REXX \ No newline at end of file diff --git a/Lang/REXX/Color-of-a-screen-pixel b/Lang/REXX/Color-of-a-screen-pixel new file mode 120000 index 0000000000..ba85f639c3 --- /dev/null +++ b/Lang/REXX/Color-of-a-screen-pixel @@ -0,0 +1 @@ +../../Task/Color-of-a-screen-pixel/REXX \ No newline at end of file diff --git a/Lang/REXX/Deconvolution-1D b/Lang/REXX/Deconvolution-1D new file mode 120000 index 0000000000..ea56a55e68 --- /dev/null +++ b/Lang/REXX/Deconvolution-1D @@ -0,0 +1 @@ +../../Task/Deconvolution-1D/REXX \ No newline at end of file diff --git a/Lang/REXX/Extreme-floating-point-values b/Lang/REXX/Extreme-floating-point-values new file mode 120000 index 0000000000..bc426a9edd --- /dev/null +++ b/Lang/REXX/Extreme-floating-point-values @@ -0,0 +1 @@ +../../Task/Extreme-floating-point-values/REXX \ No newline at end of file diff --git a/Lang/REXX/Munching-squares b/Lang/REXX/Munching-squares new file mode 120000 index 0000000000..5096752949 --- /dev/null +++ b/Lang/REXX/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/REXX \ No newline at end of file diff --git a/Lang/REXX/Pattern-matching b/Lang/REXX/Pattern-matching new file mode 120000 index 0000000000..b6cc278a7b --- /dev/null +++ b/Lang/REXX/Pattern-matching @@ -0,0 +1 @@ +../../Task/Pattern-matching/REXX \ No newline at end of file diff --git a/Lang/REXX/Polynomial-long-division b/Lang/REXX/Polynomial-long-division new file mode 120000 index 0000000000..f78bcb415b --- /dev/null +++ b/Lang/REXX/Polynomial-long-division @@ -0,0 +1 @@ +../../Task/Polynomial-long-division/REXX \ No newline at end of file diff --git a/Lang/Racket/00DESCRIPTION b/Lang/Racket/00DESCRIPTION index 3892842bf8..8f240be31b 100644 --- a/Lang/Racket/00DESCRIPTION +++ b/Lang/Racket/00DESCRIPTION @@ -1,7 +1,11 @@ {{language}} {{implementation|Scheme}} -'''Racket''' (renamed from "PLT Scheme" years ago) is a member of the Lisp and Scheme family of languages. Racket draws freely from the various strands of its lineage. +'''Racket''' (renamed from "PLT Scheme" years ago) is a member of the Lisp and Scheme family of languages. +Racket draws freely from the various strands of its lineage. * [http://racket-lang.org/ Home page] -* [http://en.wikipedia.org/wiki/Racket_(programming_language) Wikipedia] \ No newline at end of file +* [http://en.wikipedia.org/wiki/Racket_(programming_language) Wikipedia] + +==Todo== +[[Reports:Tasks_not_implemented_in_Racket]] \ No newline at end of file diff --git a/Lang/Red/ABC-Problem b/Lang/Red/ABC-Problem new file mode 120000 index 0000000000..2caa88d9b4 --- /dev/null +++ b/Lang/Red/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/Red \ No newline at end of file diff --git a/Lang/Red/Anagrams b/Lang/Red/Anagrams new file mode 120000 index 0000000000..10739e5718 --- /dev/null +++ b/Lang/Red/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/Red \ No newline at end of file diff --git a/Lang/Red/Array-concatenation b/Lang/Red/Array-concatenation new file mode 120000 index 0000000000..c3f54d9c67 --- /dev/null +++ b/Lang/Red/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/Red \ No newline at end of file diff --git a/Lang/Red/Arrays b/Lang/Red/Arrays new file mode 120000 index 0000000000..1509773b43 --- /dev/null +++ b/Lang/Red/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Red \ No newline at end of file diff --git a/Lang/Red/Balanced-brackets b/Lang/Red/Balanced-brackets new file mode 120000 index 0000000000..57f406dab8 --- /dev/null +++ b/Lang/Red/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/Red \ No newline at end of file diff --git a/Lang/Red/Binary-digits b/Lang/Red/Binary-digits new file mode 120000 index 0000000000..42661ec25b --- /dev/null +++ b/Lang/Red/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Red \ No newline at end of file diff --git a/Lang/Red/Binary-strings b/Lang/Red/Binary-strings new file mode 120000 index 0000000000..9d273b3ae9 --- /dev/null +++ b/Lang/Red/Binary-strings @@ -0,0 +1 @@ +../../Task/Binary-strings/Red \ No newline at end of file diff --git a/Lang/Red/CSV-data-manipulation b/Lang/Red/CSV-data-manipulation new file mode 120000 index 0000000000..5a172f2078 --- /dev/null +++ b/Lang/Red/CSV-data-manipulation @@ -0,0 +1 @@ +../../Task/CSV-data-manipulation/Red \ No newline at end of file diff --git a/Lang/Red/CSV-to-HTML-translation b/Lang/Red/CSV-to-HTML-translation new file mode 120000 index 0000000000..62c2c6265b --- /dev/null +++ b/Lang/Red/CSV-to-HTML-translation @@ -0,0 +1 @@ +../../Task/CSV-to-HTML-translation/Red \ No newline at end of file diff --git a/Lang/Red/Character-codes b/Lang/Red/Character-codes new file mode 120000 index 0000000000..0cf4460287 --- /dev/null +++ b/Lang/Red/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/Red \ No newline at end of file diff --git a/Lang/Red/Check-that-file-exists b/Lang/Red/Check-that-file-exists new file mode 120000 index 0000000000..bef6cade13 --- /dev/null +++ b/Lang/Red/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/Red \ No newline at end of file diff --git a/Lang/Red/Closures-Value-capture b/Lang/Red/Closures-Value-capture new file mode 120000 index 0000000000..1d77653a2a --- /dev/null +++ b/Lang/Red/Closures-Value-capture @@ -0,0 +1 @@ +../../Task/Closures-Value-capture/Red \ No newline at end of file diff --git a/Lang/Red/Conditional-structures b/Lang/Red/Conditional-structures new file mode 120000 index 0000000000..2a899ac95f --- /dev/null +++ b/Lang/Red/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/Red \ No newline at end of file diff --git a/Lang/Red/Count-occurrences-of-a-substring b/Lang/Red/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..d17a6796bf --- /dev/null +++ b/Lang/Red/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/Red \ No newline at end of file diff --git a/Lang/Red/Date-manipulation b/Lang/Red/Date-manipulation new file mode 120000 index 0000000000..cb5880337d --- /dev/null +++ b/Lang/Red/Date-manipulation @@ -0,0 +1 @@ +../../Task/Date-manipulation/Red \ No newline at end of file diff --git a/Lang/Red/Day-of-the-week b/Lang/Red/Day-of-the-week new file mode 120000 index 0000000000..331abae141 --- /dev/null +++ b/Lang/Red/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Red \ No newline at end of file diff --git a/Lang/Red/Empty-string b/Lang/Red/Empty-string new file mode 120000 index 0000000000..e1cddefe1e --- /dev/null +++ b/Lang/Red/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Red \ No newline at end of file diff --git a/Lang/Red/Execute-a-system-command b/Lang/Red/Execute-a-system-command new file mode 120000 index 0000000000..f8a3f6091d --- /dev/null +++ b/Lang/Red/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/Red \ No newline at end of file diff --git a/Lang/Red/File-input-output b/Lang/Red/File-input-output new file mode 120000 index 0000000000..20e9b30324 --- /dev/null +++ b/Lang/Red/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/Red \ No newline at end of file diff --git a/Lang/Red/File-size b/Lang/Red/File-size new file mode 120000 index 0000000000..3c7c571a51 --- /dev/null +++ b/Lang/Red/File-size @@ -0,0 +1 @@ +../../Task/File-size/Red \ No newline at end of file diff --git a/Lang/Red/Filter b/Lang/Red/Filter new file mode 120000 index 0000000000..9b8c8c943a --- /dev/null +++ b/Lang/Red/Filter @@ -0,0 +1 @@ +../../Task/Filter/Red \ No newline at end of file diff --git a/Lang/Red/Globally-replace-text-in-several-files b/Lang/Red/Globally-replace-text-in-several-files new file mode 120000 index 0000000000..ac618f4ed4 --- /dev/null +++ b/Lang/Red/Globally-replace-text-in-several-files @@ -0,0 +1 @@ +../../Task/Globally-replace-text-in-several-files/Red \ No newline at end of file diff --git a/Lang/Red/Greatest-element-of-a-list b/Lang/Red/Greatest-element-of-a-list new file mode 120000 index 0000000000..87abd7278d --- /dev/null +++ b/Lang/Red/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Red \ No newline at end of file diff --git a/Lang/Red/Hello-world-Graphical b/Lang/Red/Hello-world-Graphical new file mode 120000 index 0000000000..beb6569d7c --- /dev/null +++ b/Lang/Red/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/Red \ No newline at end of file diff --git a/Lang/Red/Huffman-coding b/Lang/Red/Huffman-coding new file mode 120000 index 0000000000..832dbcd4d4 --- /dev/null +++ b/Lang/Red/Huffman-coding @@ -0,0 +1 @@ +../../Task/Huffman-coding/Red \ No newline at end of file diff --git a/Lang/Red/Loop-over-multiple-arrays-simultaneously b/Lang/Red/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..f5a6c33ace --- /dev/null +++ b/Lang/Red/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/Red \ No newline at end of file diff --git a/Lang/Red/Loops-Continue b/Lang/Red/Loops-Continue new file mode 120000 index 0000000000..922a3a5d08 --- /dev/null +++ b/Lang/Red/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Red \ No newline at end of file diff --git a/Lang/Red/Loops-Do-while b/Lang/Red/Loops-Do-while new file mode 120000 index 0000000000..160407d794 --- /dev/null +++ b/Lang/Red/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Red \ No newline at end of file diff --git a/Lang/Red/Loops-Foreach b/Lang/Red/Loops-Foreach new file mode 120000 index 0000000000..86b9006898 --- /dev/null +++ b/Lang/Red/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Red \ No newline at end of file diff --git a/Lang/Red/Loops-Infinite b/Lang/Red/Loops-Infinite new file mode 120000 index 0000000000..569c453371 --- /dev/null +++ b/Lang/Red/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Red \ No newline at end of file diff --git a/Lang/Red/Morse-code b/Lang/Red/Morse-code new file mode 120000 index 0000000000..bf8d6d338d --- /dev/null +++ b/Lang/Red/Morse-code @@ -0,0 +1 @@ +../../Task/Morse-code/Red \ No newline at end of file diff --git a/Lang/Red/Ordered-words b/Lang/Red/Ordered-words new file mode 120000 index 0000000000..8d1d42ec4e --- /dev/null +++ b/Lang/Red/Ordered-words @@ -0,0 +1 @@ +../../Task/Ordered-words/Red \ No newline at end of file diff --git a/Lang/Red/Pick-random-element b/Lang/Red/Pick-random-element new file mode 120000 index 0000000000..5937b03846 --- /dev/null +++ b/Lang/Red/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/Red \ No newline at end of file diff --git a/Lang/Red/Read-a-specific-line-from-a-file b/Lang/Red/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..59fb4832c1 --- /dev/null +++ b/Lang/Red/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/Red \ No newline at end of file diff --git a/Lang/Red/Remove-duplicate-elements b/Lang/Red/Remove-duplicate-elements new file mode 120000 index 0000000000..79bbc0060e --- /dev/null +++ b/Lang/Red/Remove-duplicate-elements @@ -0,0 +1 @@ +../../Task/Remove-duplicate-elements/Red \ No newline at end of file diff --git a/Lang/Red/Repeat-a-string b/Lang/Red/Repeat-a-string new file mode 120000 index 0000000000..b111ea29c4 --- /dev/null +++ b/Lang/Red/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/Red \ No newline at end of file diff --git a/Lang/Red/Reverse-a-string b/Lang/Red/Reverse-a-string new file mode 120000 index 0000000000..35f56be083 --- /dev/null +++ b/Lang/Red/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Red \ No newline at end of file diff --git a/Lang/Red/Reverse-words-in-a-string b/Lang/Red/Reverse-words-in-a-string new file mode 120000 index 0000000000..9575e316fc --- /dev/null +++ b/Lang/Red/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/Red \ No newline at end of file diff --git a/Lang/Red/Self-describing-numbers b/Lang/Red/Self-describing-numbers new file mode 120000 index 0000000000..e5cdf857d4 --- /dev/null +++ b/Lang/Red/Self-describing-numbers @@ -0,0 +1 @@ +../../Task/Self-describing-numbers/Red \ No newline at end of file diff --git a/Lang/Red/Sleep b/Lang/Red/Sleep new file mode 120000 index 0000000000..b6eb29f33f --- /dev/null +++ b/Lang/Red/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/Red \ No newline at end of file diff --git a/Lang/Red/Sort-an-integer-array b/Lang/Red/Sort-an-integer-array new file mode 120000 index 0000000000..9aa86bb8fb --- /dev/null +++ b/Lang/Red/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Red \ No newline at end of file diff --git a/Lang/Red/String-case b/Lang/Red/String-case new file mode 120000 index 0000000000..970e1faee7 --- /dev/null +++ b/Lang/Red/String-case @@ -0,0 +1 @@ +../../Task/String-case/Red \ No newline at end of file diff --git a/Lang/Red/String-concatenation b/Lang/Red/String-concatenation new file mode 120000 index 0000000000..3dd6f00f0a --- /dev/null +++ b/Lang/Red/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Red \ No newline at end of file diff --git a/Lang/Red/String-prepend b/Lang/Red/String-prepend new file mode 120000 index 0000000000..b081aadf55 --- /dev/null +++ b/Lang/Red/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Red \ No newline at end of file diff --git a/Lang/Red/Strip-a-set-of-characters-from-a-string b/Lang/Red/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..46d57022ac --- /dev/null +++ b/Lang/Red/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Red \ No newline at end of file diff --git a/Lang/Red/Strip-comments-from-a-string b/Lang/Red/Strip-comments-from-a-string new file mode 120000 index 0000000000..90abc848c3 --- /dev/null +++ b/Lang/Red/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Red \ No newline at end of file diff --git a/Lang/Red/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Red/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..488dad9033 --- /dev/null +++ b/Lang/Red/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Red \ No newline at end of file diff --git a/Lang/Red/Sum-of-a-series b/Lang/Red/Sum-of-a-series new file mode 120000 index 0000000000..30a3182607 --- /dev/null +++ b/Lang/Red/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Red \ No newline at end of file diff --git a/Lang/Red/Tokenize-a-string b/Lang/Red/Tokenize-a-string new file mode 120000 index 0000000000..a88925aab3 --- /dev/null +++ b/Lang/Red/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Red \ No newline at end of file diff --git a/Lang/Red/User-input-Text b/Lang/Red/User-input-Text new file mode 120000 index 0000000000..a8bcf8c94e --- /dev/null +++ b/Lang/Red/User-input-Text @@ -0,0 +1 @@ +../../Task/User-input-Text/Red \ No newline at end of file diff --git a/Lang/Red/Vigen-re-cipher b/Lang/Red/Vigen-re-cipher new file mode 120000 index 0000000000..6558ae0eb4 --- /dev/null +++ b/Lang/Red/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Red \ No newline at end of file diff --git a/Lang/Red/Window-creation b/Lang/Red/Window-creation new file mode 120000 index 0000000000..65b366a3aa --- /dev/null +++ b/Lang/Red/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Red \ No newline at end of file diff --git a/Lang/Ring/24-game b/Lang/Ring/24-game new file mode 120000 index 0000000000..b635f10053 --- /dev/null +++ b/Lang/Ring/24-game @@ -0,0 +1 @@ +../../Task/24-game/Ring \ No newline at end of file diff --git a/Lang/Ring/Aliquot-sequence-classifications b/Lang/Ring/Aliquot-sequence-classifications new file mode 120000 index 0000000000..2a7250eca5 --- /dev/null +++ b/Lang/Ring/Aliquot-sequence-classifications @@ -0,0 +1 @@ +../../Task/Aliquot-sequence-classifications/Ring \ No newline at end of file diff --git a/Lang/Ring/Anagrams b/Lang/Ring/Anagrams new file mode 120000 index 0000000000..e0f165de10 --- /dev/null +++ b/Lang/Ring/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/Ring \ No newline at end of file diff --git a/Lang/Ring/Anagrams-Deranged-anagrams b/Lang/Ring/Anagrams-Deranged-anagrams new file mode 120000 index 0000000000..55f5a92d02 --- /dev/null +++ b/Lang/Ring/Anagrams-Deranged-anagrams @@ -0,0 +1 @@ +../../Task/Anagrams-Deranged-anagrams/Ring \ No newline at end of file diff --git a/Lang/Ring/Animate-a-pendulum b/Lang/Ring/Animate-a-pendulum new file mode 120000 index 0000000000..82da9263cd --- /dev/null +++ b/Lang/Ring/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/Ring \ No newline at end of file diff --git a/Lang/Ring/Animation b/Lang/Ring/Animation new file mode 120000 index 0000000000..326d447565 --- /dev/null +++ b/Lang/Ring/Animation @@ -0,0 +1 @@ +../../Task/Animation/Ring \ No newline at end of file diff --git a/Lang/Ring/Anonymous-recursion b/Lang/Ring/Anonymous-recursion new file mode 120000 index 0000000000..3988c51247 --- /dev/null +++ b/Lang/Ring/Anonymous-recursion @@ -0,0 +1 @@ +../../Task/Anonymous-recursion/Ring \ No newline at end of file diff --git a/Lang/Ring/Associative-array-Creation b/Lang/Ring/Associative-array-Creation new file mode 120000 index 0000000000..c2be7a500e --- /dev/null +++ b/Lang/Ring/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Ring \ No newline at end of file diff --git a/Lang/Ring/Associative-array-Iteration b/Lang/Ring/Associative-array-Iteration new file mode 120000 index 0000000000..3367c5d8d2 --- /dev/null +++ b/Lang/Ring/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Ring \ No newline at end of file diff --git a/Lang/Ring/Atomic-updates b/Lang/Ring/Atomic-updates new file mode 120000 index 0000000000..0ae113f840 --- /dev/null +++ b/Lang/Ring/Atomic-updates @@ -0,0 +1 @@ +../../Task/Atomic-updates/Ring \ No newline at end of file diff --git a/Lang/Ring/Averages-Mean-angle b/Lang/Ring/Averages-Mean-angle new file mode 120000 index 0000000000..df55aed53e --- /dev/null +++ b/Lang/Ring/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/Ring \ No newline at end of file diff --git a/Lang/Ring/Averages-Mode b/Lang/Ring/Averages-Mode new file mode 120000 index 0000000000..aab38dbb43 --- /dev/null +++ b/Lang/Ring/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Ring \ No newline at end of file diff --git a/Lang/Ring/Benfords-law b/Lang/Ring/Benfords-law new file mode 120000 index 0000000000..2078a31505 --- /dev/null +++ b/Lang/Ring/Benfords-law @@ -0,0 +1 @@ +../../Task/Benfords-law/Ring \ No newline at end of file diff --git a/Lang/Ring/Best-shuffle b/Lang/Ring/Best-shuffle new file mode 120000 index 0000000000..7c96d9155d --- /dev/null +++ b/Lang/Ring/Best-shuffle @@ -0,0 +1 @@ +../../Task/Best-shuffle/Ring \ No newline at end of file diff --git a/Lang/Ring/Box-the-compass b/Lang/Ring/Box-the-compass new file mode 120000 index 0000000000..766a916cd4 --- /dev/null +++ b/Lang/Ring/Box-the-compass @@ -0,0 +1 @@ +../../Task/Box-the-compass/Ring \ No newline at end of file diff --git a/Lang/Ring/Brownian-tree b/Lang/Ring/Brownian-tree new file mode 120000 index 0000000000..dcedd71d0e --- /dev/null +++ b/Lang/Ring/Brownian-tree @@ -0,0 +1 @@ +../../Task/Brownian-tree/Ring \ No newline at end of file diff --git a/Lang/Ring/Bulls-and-cows b/Lang/Ring/Bulls-and-cows new file mode 120000 index 0000000000..21afa483e6 --- /dev/null +++ b/Lang/Ring/Bulls-and-cows @@ -0,0 +1 @@ +../../Task/Bulls-and-cows/Ring \ No newline at end of file diff --git a/Lang/Ring/Bulls-and-cows-Player b/Lang/Ring/Bulls-and-cows-Player new file mode 120000 index 0000000000..e178d39243 --- /dev/null +++ b/Lang/Ring/Bulls-and-cows-Player @@ -0,0 +1 @@ +../../Task/Bulls-and-cows-Player/Ring \ No newline at end of file diff --git a/Lang/Ring/Caesar-cipher b/Lang/Ring/Caesar-cipher new file mode 120000 index 0000000000..b6dca9144f --- /dev/null +++ b/Lang/Ring/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Ring \ No newline at end of file diff --git a/Lang/Ring/Calendar b/Lang/Ring/Calendar new file mode 120000 index 0000000000..040f15574a --- /dev/null +++ b/Lang/Ring/Calendar @@ -0,0 +1 @@ +../../Task/Calendar/Ring \ No newline at end of file diff --git a/Lang/Ring/Carmichael-3-strong-pseudoprimes b/Lang/Ring/Carmichael-3-strong-pseudoprimes new file mode 120000 index 0000000000..e05687f7e7 --- /dev/null +++ b/Lang/Ring/Carmichael-3-strong-pseudoprimes @@ -0,0 +1 @@ +../../Task/Carmichael-3-strong-pseudoprimes/Ring \ No newline at end of file diff --git a/Lang/Ring/Casting-out-nines b/Lang/Ring/Casting-out-nines new file mode 120000 index 0000000000..dfe9fb646e --- /dev/null +++ b/Lang/Ring/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/Ring \ No newline at end of file diff --git a/Lang/Ring/Cholesky-decomposition b/Lang/Ring/Cholesky-decomposition new file mode 120000 index 0000000000..63332743f3 --- /dev/null +++ b/Lang/Ring/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/Ring \ No newline at end of file diff --git a/Lang/Ring/Circles-of-given-radius-through-two-points b/Lang/Ring/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..afcbba75d6 --- /dev/null +++ b/Lang/Ring/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/Ring \ No newline at end of file diff --git a/Lang/Ring/Colour-pinstripe-Display b/Lang/Ring/Colour-pinstripe-Display new file mode 120000 index 0000000000..1fef0cc703 --- /dev/null +++ b/Lang/Ring/Colour-pinstripe-Display @@ -0,0 +1 @@ +../../Task/Colour-pinstripe-Display/Ring \ No newline at end of file diff --git a/Lang/Ring/Combinations b/Lang/Ring/Combinations new file mode 120000 index 0000000000..09f8477177 --- /dev/null +++ b/Lang/Ring/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/Ring \ No newline at end of file diff --git a/Lang/Ring/Combinations-with-repetitions b/Lang/Ring/Combinations-with-repetitions new file mode 120000 index 0000000000..ccf69ec03e --- /dev/null +++ b/Lang/Ring/Combinations-with-repetitions @@ -0,0 +1 @@ +../../Task/Combinations-with-repetitions/Ring \ No newline at end of file diff --git a/Lang/Ring/Comma-quibbling b/Lang/Ring/Comma-quibbling new file mode 120000 index 0000000000..8995ef931d --- /dev/null +++ b/Lang/Ring/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/Ring \ No newline at end of file diff --git a/Lang/Ring/Continued-fraction b/Lang/Ring/Continued-fraction new file mode 120000 index 0000000000..5f3155c526 --- /dev/null +++ b/Lang/Ring/Continued-fraction @@ -0,0 +1 @@ +../../Task/Continued-fraction/Ring \ No newline at end of file diff --git a/Lang/Ring/Create-a-file-on-magnetic-tape b/Lang/Ring/Create-a-file-on-magnetic-tape new file mode 120000 index 0000000000..20bf6693b1 --- /dev/null +++ b/Lang/Ring/Create-a-file-on-magnetic-tape @@ -0,0 +1 @@ +../../Task/Create-a-file-on-magnetic-tape/Ring \ No newline at end of file diff --git a/Lang/Ring/Date-manipulation b/Lang/Ring/Date-manipulation new file mode 120000 index 0000000000..dc2d08c2c2 --- /dev/null +++ b/Lang/Ring/Date-manipulation @@ -0,0 +1 @@ +../../Task/Date-manipulation/Ring \ No newline at end of file diff --git a/Lang/Ring/Digital-root-Multiplicative-digital-root b/Lang/Ring/Digital-root-Multiplicative-digital-root new file mode 120000 index 0000000000..b52fd66d11 --- /dev/null +++ b/Lang/Ring/Digital-root-Multiplicative-digital-root @@ -0,0 +1 @@ +../../Task/Digital-root-Multiplicative-digital-root/Ring \ No newline at end of file diff --git a/Lang/Ring/Doubly-linked-list-Definition b/Lang/Ring/Doubly-linked-list-Definition new file mode 120000 index 0000000000..9be7f21fec --- /dev/null +++ b/Lang/Ring/Doubly-linked-list-Definition @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Definition/Ring \ No newline at end of file diff --git a/Lang/Ring/Doubly-linked-list-Traversal b/Lang/Ring/Doubly-linked-list-Traversal new file mode 120000 index 0000000000..54c6b7eaca --- /dev/null +++ b/Lang/Ring/Doubly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Doubly-linked-list-Traversal/Ring \ No newline at end of file diff --git a/Lang/Ring/Draw-a-cuboid b/Lang/Ring/Draw-a-cuboid new file mode 120000 index 0000000000..a42b9ec755 --- /dev/null +++ b/Lang/Ring/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/Ring \ No newline at end of file diff --git a/Lang/Ring/Dutch-national-flag-problem b/Lang/Ring/Dutch-national-flag-problem new file mode 120000 index 0000000000..f751b3f1b0 --- /dev/null +++ b/Lang/Ring/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/Ring \ No newline at end of file diff --git a/Lang/Ring/Enforced-immutability b/Lang/Ring/Enforced-immutability new file mode 120000 index 0000000000..034e473178 --- /dev/null +++ b/Lang/Ring/Enforced-immutability @@ -0,0 +1 @@ +../../Task/Enforced-immutability/Ring \ No newline at end of file diff --git a/Lang/Ring/Evolutionary-algorithm b/Lang/Ring/Evolutionary-algorithm new file mode 120000 index 0000000000..6170a9d96d --- /dev/null +++ b/Lang/Ring/Evolutionary-algorithm @@ -0,0 +1 @@ +../../Task/Evolutionary-algorithm/Ring \ No newline at end of file diff --git a/Lang/Ring/Extend-your-language b/Lang/Ring/Extend-your-language new file mode 120000 index 0000000000..db61934d7e --- /dev/null +++ b/Lang/Ring/Extend-your-language @@ -0,0 +1 @@ +../../Task/Extend-your-language/Ring \ No newline at end of file diff --git a/Lang/Ring/Factors-of-a-Mersenne-number b/Lang/Ring/Factors-of-a-Mersenne-number new file mode 120000 index 0000000000..d50569b528 --- /dev/null +++ b/Lang/Ring/Factors-of-a-Mersenne-number @@ -0,0 +1 @@ +../../Task/Factors-of-a-Mersenne-number/Ring \ No newline at end of file diff --git a/Lang/Ring/Fibonacci-n-step-number-sequences b/Lang/Ring/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..a76266205b --- /dev/null +++ b/Lang/Ring/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/Ring \ No newline at end of file diff --git a/Lang/Ring/Fibonacci-word b/Lang/Ring/Fibonacci-word new file mode 120000 index 0000000000..085c3bc1ff --- /dev/null +++ b/Lang/Ring/Fibonacci-word @@ -0,0 +1 @@ +../../Task/Fibonacci-word/Ring \ No newline at end of file diff --git a/Lang/Ring/Forest-fire b/Lang/Ring/Forest-fire new file mode 120000 index 0000000000..d383ffd499 --- /dev/null +++ b/Lang/Ring/Forest-fire @@ -0,0 +1 @@ +../../Task/Forest-fire/Ring \ No newline at end of file diff --git a/Lang/Ring/Forward-difference b/Lang/Ring/Forward-difference new file mode 120000 index 0000000000..ea130eece9 --- /dev/null +++ b/Lang/Ring/Forward-difference @@ -0,0 +1 @@ +../../Task/Forward-difference/Ring \ No newline at end of file diff --git a/Lang/Ring/Four-bit-adder b/Lang/Ring/Four-bit-adder new file mode 120000 index 0000000000..eeef340d84 --- /dev/null +++ b/Lang/Ring/Four-bit-adder @@ -0,0 +1 @@ +../../Task/Four-bit-adder/Ring \ No newline at end of file diff --git a/Lang/Ring/Gray-code b/Lang/Ring/Gray-code new file mode 120000 index 0000000000..895d79097f --- /dev/null +++ b/Lang/Ring/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/Ring \ No newline at end of file diff --git a/Lang/Ring/Greatest-subsequential-sum b/Lang/Ring/Greatest-subsequential-sum new file mode 120000 index 0000000000..9b792ff333 --- /dev/null +++ b/Lang/Ring/Greatest-subsequential-sum @@ -0,0 +1 @@ +../../Task/Greatest-subsequential-sum/Ring \ No newline at end of file diff --git a/Lang/Ring/Greyscale-bars-Display b/Lang/Ring/Greyscale-bars-Display new file mode 120000 index 0000000000..8e80fe8a98 --- /dev/null +++ b/Lang/Ring/Greyscale-bars-Display @@ -0,0 +1 @@ +../../Task/Greyscale-bars-Display/Ring \ No newline at end of file diff --git a/Lang/Ring/Hash-from-two-arrays b/Lang/Ring/Hash-from-two-arrays new file mode 120000 index 0000000000..8baf29d2cc --- /dev/null +++ b/Lang/Ring/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/Ring \ No newline at end of file diff --git a/Lang/Ring/Heronian-triangles b/Lang/Ring/Heronian-triangles new file mode 120000 index 0000000000..1c13dd5c7a --- /dev/null +++ b/Lang/Ring/Heronian-triangles @@ -0,0 +1 @@ +../../Task/Heronian-triangles/Ring \ No newline at end of file diff --git a/Lang/Ring/Higher-order-functions b/Lang/Ring/Higher-order-functions new file mode 120000 index 0000000000..3ad8eb7eb1 --- /dev/null +++ b/Lang/Ring/Higher-order-functions @@ -0,0 +1 @@ +../../Task/Higher-order-functions/Ring \ No newline at end of file diff --git a/Lang/Ring/Hofstadter-Figure-Figure-sequences b/Lang/Ring/Hofstadter-Figure-Figure-sequences new file mode 120000 index 0000000000..37b81a82c7 --- /dev/null +++ b/Lang/Ring/Hofstadter-Figure-Figure-sequences @@ -0,0 +1 @@ +../../Task/Hofstadter-Figure-Figure-sequences/Ring \ No newline at end of file diff --git a/Lang/Ring/Horizontal-sundial-calculations b/Lang/Ring/Horizontal-sundial-calculations new file mode 120000 index 0000000000..9d3da775b8 --- /dev/null +++ b/Lang/Ring/Horizontal-sundial-calculations @@ -0,0 +1 @@ +../../Task/Horizontal-sundial-calculations/Ring \ No newline at end of file diff --git a/Lang/Ring/I-before-E-except-after-C b/Lang/Ring/I-before-E-except-after-C new file mode 120000 index 0000000000..6f6085317c --- /dev/null +++ b/Lang/Ring/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Ring \ No newline at end of file diff --git a/Lang/Ring/IBAN b/Lang/Ring/IBAN new file mode 120000 index 0000000000..011d5e0917 --- /dev/null +++ b/Lang/Ring/IBAN @@ -0,0 +1 @@ +../../Task/IBAN/Ring \ No newline at end of file diff --git a/Lang/Ring/Jensens-Device b/Lang/Ring/Jensens-Device new file mode 120000 index 0000000000..cd5b17c608 --- /dev/null +++ b/Lang/Ring/Jensens-Device @@ -0,0 +1 @@ +../../Task/Jensens-Device/Ring \ No newline at end of file diff --git a/Lang/Ring/Knapsack-problem-0-1 b/Lang/Ring/Knapsack-problem-0-1 new file mode 120000 index 0000000000..28e8ea9e62 --- /dev/null +++ b/Lang/Ring/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/Ring \ No newline at end of file diff --git a/Lang/Ring/LZW-compression b/Lang/Ring/LZW-compression new file mode 120000 index 0000000000..a9f058ce1e --- /dev/null +++ b/Lang/Ring/LZW-compression @@ -0,0 +1 @@ +../../Task/LZW-compression/Ring \ No newline at end of file diff --git a/Lang/Ring/Last-letter-first-letter b/Lang/Ring/Last-letter-first-letter new file mode 120000 index 0000000000..d73a652054 --- /dev/null +++ b/Lang/Ring/Last-letter-first-letter @@ -0,0 +1 @@ +../../Task/Last-letter-first-letter/Ring \ No newline at end of file diff --git a/Lang/Ring/Levenshtein-distance b/Lang/Ring/Levenshtein-distance new file mode 120000 index 0000000000..77e8a8825c --- /dev/null +++ b/Lang/Ring/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Ring \ No newline at end of file diff --git a/Lang/Ring/Longest-increasing-subsequence b/Lang/Ring/Longest-increasing-subsequence new file mode 120000 index 0000000000..7c3a0fe6ce --- /dev/null +++ b/Lang/Ring/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Ring \ No newline at end of file diff --git a/Lang/Ring/Longest-string-challenge b/Lang/Ring/Longest-string-challenge new file mode 120000 index 0000000000..c4c196fbd9 --- /dev/null +++ b/Lang/Ring/Longest-string-challenge @@ -0,0 +1 @@ +../../Task/Longest-string-challenge/Ring \ No newline at end of file diff --git a/Lang/Ring/Ludic-numbers b/Lang/Ring/Ludic-numbers new file mode 120000 index 0000000000..22d9a2b788 --- /dev/null +++ b/Lang/Ring/Ludic-numbers @@ -0,0 +1 @@ +../../Task/Ludic-numbers/Ring \ No newline at end of file diff --git a/Lang/Ring/Maximum-triangle-path-sum b/Lang/Ring/Maximum-triangle-path-sum new file mode 120000 index 0000000000..3de5658634 --- /dev/null +++ b/Lang/Ring/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/Ring \ No newline at end of file diff --git a/Lang/Ring/Morse-code b/Lang/Ring/Morse-code new file mode 120000 index 0000000000..f008e739ca --- /dev/null +++ b/Lang/Ring/Morse-code @@ -0,0 +1 @@ +../../Task/Morse-code/Ring \ No newline at end of file diff --git a/Lang/Ring/Move-to-front-algorithm b/Lang/Ring/Move-to-front-algorithm new file mode 120000 index 0000000000..612577b46d --- /dev/null +++ b/Lang/Ring/Move-to-front-algorithm @@ -0,0 +1 @@ +../../Task/Move-to-front-algorithm/Ring \ No newline at end of file diff --git a/Lang/Ring/Multisplit b/Lang/Ring/Multisplit new file mode 120000 index 0000000000..75756ffed8 --- /dev/null +++ b/Lang/Ring/Multisplit @@ -0,0 +1 @@ +../../Task/Multisplit/Ring \ No newline at end of file diff --git a/Lang/Ring/Munching-squares b/Lang/Ring/Munching-squares new file mode 120000 index 0000000000..da6715d415 --- /dev/null +++ b/Lang/Ring/Munching-squares @@ -0,0 +1 @@ +../../Task/Munching-squares/Ring \ No newline at end of file diff --git a/Lang/Ring/Nautical-bell b/Lang/Ring/Nautical-bell new file mode 120000 index 0000000000..afc200d5eb --- /dev/null +++ b/Lang/Ring/Nautical-bell @@ -0,0 +1 @@ +../../Task/Nautical-bell/Ring \ No newline at end of file diff --git a/Lang/Ring/Non-continuous-subsequences b/Lang/Ring/Non-continuous-subsequences new file mode 120000 index 0000000000..5ed952e64d --- /dev/null +++ b/Lang/Ring/Non-continuous-subsequences @@ -0,0 +1 @@ +../../Task/Non-continuous-subsequences/Ring \ No newline at end of file diff --git a/Lang/Ring/Non-decimal-radices-Convert b/Lang/Ring/Non-decimal-radices-Convert new file mode 120000 index 0000000000..31b4e0786f --- /dev/null +++ b/Lang/Ring/Non-decimal-radices-Convert @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Convert/Ring \ No newline at end of file diff --git a/Lang/Ring/Number-reversal-game b/Lang/Ring/Number-reversal-game new file mode 120000 index 0000000000..72bd929610 --- /dev/null +++ b/Lang/Ring/Number-reversal-game @@ -0,0 +1 @@ +../../Task/Number-reversal-game/Ring \ No newline at end of file diff --git a/Lang/Ring/Numerical-integration b/Lang/Ring/Numerical-integration new file mode 120000 index 0000000000..efbab805b6 --- /dev/null +++ b/Lang/Ring/Numerical-integration @@ -0,0 +1 @@ +../../Task/Numerical-integration/Ring \ No newline at end of file diff --git a/Lang/Ring/Odd-word-problem b/Lang/Ring/Odd-word-problem new file mode 120000 index 0000000000..45181a0e83 --- /dev/null +++ b/Lang/Ring/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/Ring \ No newline at end of file diff --git a/Lang/Ring/One-dimensional-cellular-automata b/Lang/Ring/One-dimensional-cellular-automata new file mode 120000 index 0000000000..dde545b5b6 --- /dev/null +++ b/Lang/Ring/One-dimensional-cellular-automata @@ -0,0 +1 @@ +../../Task/One-dimensional-cellular-automata/Ring \ No newline at end of file diff --git a/Lang/Ring/OpenGL b/Lang/Ring/OpenGL new file mode 120000 index 0000000000..dcffa97891 --- /dev/null +++ b/Lang/Ring/OpenGL @@ -0,0 +1 @@ +../../Task/OpenGL/Ring \ No newline at end of file diff --git a/Lang/Ring/Permutations-Rank-of-a-permutation b/Lang/Ring/Permutations-Rank-of-a-permutation new file mode 120000 index 0000000000..8c73430598 --- /dev/null +++ b/Lang/Ring/Permutations-Rank-of-a-permutation @@ -0,0 +1 @@ +../../Task/Permutations-Rank-of-a-permutation/Ring \ No newline at end of file diff --git a/Lang/Ring/Pernicious-numbers b/Lang/Ring/Pernicious-numbers new file mode 120000 index 0000000000..9d8173fd87 --- /dev/null +++ b/Lang/Ring/Pernicious-numbers @@ -0,0 +1 @@ +../../Task/Pernicious-numbers/Ring \ No newline at end of file diff --git a/Lang/Ring/Pig-the-dice-game b/Lang/Ring/Pig-the-dice-game new file mode 120000 index 0000000000..1e02a481d6 --- /dev/null +++ b/Lang/Ring/Pig-the-dice-game @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game/Ring \ No newline at end of file diff --git a/Lang/Ring/Pinstripe-Display b/Lang/Ring/Pinstripe-Display new file mode 120000 index 0000000000..0866639003 --- /dev/null +++ b/Lang/Ring/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/Ring \ No newline at end of file diff --git a/Lang/Ring/Plot-coordinate-pairs b/Lang/Ring/Plot-coordinate-pairs new file mode 120000 index 0000000000..912e5c624b --- /dev/null +++ b/Lang/Ring/Plot-coordinate-pairs @@ -0,0 +1 @@ +../../Task/Plot-coordinate-pairs/Ring \ No newline at end of file diff --git a/Lang/Ring/Power-set b/Lang/Ring/Power-set new file mode 120000 index 0000000000..70dcbc9bae --- /dev/null +++ b/Lang/Ring/Power-set @@ -0,0 +1 @@ +../../Task/Power-set/Ring \ No newline at end of file diff --git a/Lang/Ring/Probabilistic-choice b/Lang/Ring/Probabilistic-choice new file mode 120000 index 0000000000..8636ca9913 --- /dev/null +++ b/Lang/Ring/Probabilistic-choice @@ -0,0 +1 @@ +../../Task/Probabilistic-choice/Ring \ No newline at end of file diff --git a/Lang/Ring/Range-expansion b/Lang/Ring/Range-expansion new file mode 120000 index 0000000000..f2d6d06d03 --- /dev/null +++ b/Lang/Ring/Range-expansion @@ -0,0 +1 @@ +../../Task/Range-expansion/Ring \ No newline at end of file diff --git a/Lang/Ring/Range-extraction b/Lang/Ring/Range-extraction new file mode 120000 index 0000000000..22a133eff8 --- /dev/null +++ b/Lang/Ring/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/Ring \ No newline at end of file diff --git a/Lang/Ring/Reduced-row-echelon-form b/Lang/Ring/Reduced-row-echelon-form new file mode 120000 index 0000000000..1a12cacfd2 --- /dev/null +++ b/Lang/Ring/Reduced-row-echelon-form @@ -0,0 +1 @@ +../../Task/Reduced-row-echelon-form/Ring \ No newline at end of file diff --git a/Lang/Ring/Regular-expressions b/Lang/Ring/Regular-expressions new file mode 120000 index 0000000000..44a111bab2 --- /dev/null +++ b/Lang/Ring/Regular-expressions @@ -0,0 +1 @@ +../../Task/Regular-expressions/Ring \ No newline at end of file diff --git a/Lang/Ring/Rep-string b/Lang/Ring/Rep-string new file mode 120000 index 0000000000..5b6d33ab60 --- /dev/null +++ b/Lang/Ring/Rep-string @@ -0,0 +1 @@ +../../Task/Rep-string/Ring \ No newline at end of file diff --git a/Lang/Ring/Rock-paper-scissors b/Lang/Ring/Rock-paper-scissors new file mode 120000 index 0000000000..0bf5d6c876 --- /dev/null +++ b/Lang/Ring/Rock-paper-scissors @@ -0,0 +1 @@ +../../Task/Rock-paper-scissors/Ring \ No newline at end of file diff --git a/Lang/Ring/Run-length-encoding b/Lang/Ring/Run-length-encoding new file mode 120000 index 0000000000..b47c67f315 --- /dev/null +++ b/Lang/Ring/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/Ring \ No newline at end of file diff --git a/Lang/Ring/SHA-1 b/Lang/Ring/SHA-1 new file mode 120000 index 0000000000..bba777fc74 --- /dev/null +++ b/Lang/Ring/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Ring \ No newline at end of file diff --git a/Lang/Ring/SHA-256 b/Lang/Ring/SHA-256 new file mode 120000 index 0000000000..cf2fd3506a --- /dev/null +++ b/Lang/Ring/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Ring \ No newline at end of file diff --git a/Lang/Ring/Scope-Function-names-and-labels b/Lang/Ring/Scope-Function-names-and-labels new file mode 120000 index 0000000000..190ef03f79 --- /dev/null +++ b/Lang/Ring/Scope-Function-names-and-labels @@ -0,0 +1 @@ +../../Task/Scope-Function-names-and-labels/Ring \ No newline at end of file diff --git a/Lang/Ring/Self-describing-numbers b/Lang/Ring/Self-describing-numbers new file mode 120000 index 0000000000..3f353e1cd8 --- /dev/null +++ b/Lang/Ring/Self-describing-numbers @@ -0,0 +1 @@ +../../Task/Self-describing-numbers/Ring \ No newline at end of file diff --git a/Lang/Ring/Set b/Lang/Ring/Set new file mode 120000 index 0000000000..fc5998a995 --- /dev/null +++ b/Lang/Ring/Set @@ -0,0 +1 @@ +../../Task/Set/Ring \ No newline at end of file diff --git a/Lang/Ring/Set-consolidation b/Lang/Ring/Set-consolidation new file mode 120000 index 0000000000..8e0850ce7b --- /dev/null +++ b/Lang/Ring/Set-consolidation @@ -0,0 +1 @@ +../../Task/Set-consolidation/Ring \ No newline at end of file diff --git a/Lang/Ring/Seven-sided-dice-from-five-sided-dice b/Lang/Ring/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..dcf20789c4 --- /dev/null +++ b/Lang/Ring/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/Ring \ No newline at end of file diff --git a/Lang/Ring/Short-circuit-evaluation b/Lang/Ring/Short-circuit-evaluation new file mode 120000 index 0000000000..55ad1aba4d --- /dev/null +++ b/Lang/Ring/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Ring \ No newline at end of file diff --git a/Lang/Ring/Simulate-input-Mouse b/Lang/Ring/Simulate-input-Mouse new file mode 120000 index 0000000000..0d86e8283f --- /dev/null +++ b/Lang/Ring/Simulate-input-Mouse @@ -0,0 +1 @@ +../../Task/Simulate-input-Mouse/Ring \ No newline at end of file diff --git a/Lang/Ring/Sorting-algorithms-Bogosort b/Lang/Ring/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..76d97b1cf7 --- /dev/null +++ b/Lang/Ring/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Ring \ No newline at end of file diff --git a/Lang/Ring/Sorting-algorithms-Heapsort b/Lang/Ring/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..f883f95064 --- /dev/null +++ b/Lang/Ring/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Ring \ No newline at end of file diff --git a/Lang/Ring/Sorting-algorithms-Permutation-sort b/Lang/Ring/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..ad5391df3d --- /dev/null +++ b/Lang/Ring/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/Ring \ No newline at end of file diff --git a/Lang/Ring/Sorting-algorithms-Quicksort b/Lang/Ring/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..2894bde69a --- /dev/null +++ b/Lang/Ring/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Ring \ No newline at end of file diff --git a/Lang/Ring/Sorting-algorithms-Strand-sort b/Lang/Ring/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..1c40748761 --- /dev/null +++ b/Lang/Ring/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/Ring \ No newline at end of file diff --git a/Lang/Ring/Soundex b/Lang/Ring/Soundex new file mode 120000 index 0000000000..e81228453c --- /dev/null +++ b/Lang/Ring/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Ring \ No newline at end of file diff --git a/Lang/Ring/Spiral-matrix b/Lang/Ring/Spiral-matrix new file mode 120000 index 0000000000..18b74cbaae --- /dev/null +++ b/Lang/Ring/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Ring \ No newline at end of file diff --git a/Lang/Ring/Statistics-Basic b/Lang/Ring/Statistics-Basic new file mode 120000 index 0000000000..7d2b33158b --- /dev/null +++ b/Lang/Ring/Statistics-Basic @@ -0,0 +1 @@ +../../Task/Statistics-Basic/Ring \ No newline at end of file diff --git a/Lang/Ring/Stem-and-leaf-plot b/Lang/Ring/Stem-and-leaf-plot new file mode 120000 index 0000000000..a7f6972396 --- /dev/null +++ b/Lang/Ring/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Ring \ No newline at end of file diff --git a/Lang/Ring/Stern-Brocot-sequence b/Lang/Ring/Stern-Brocot-sequence new file mode 120000 index 0000000000..fc533a41c8 --- /dev/null +++ b/Lang/Ring/Stern-Brocot-sequence @@ -0,0 +1 @@ +../../Task/Stern-Brocot-sequence/Ring \ No newline at end of file diff --git a/Lang/Ring/Table-creation-Postal-addresses b/Lang/Ring/Table-creation-Postal-addresses new file mode 120000 index 0000000000..c8b15a569e --- /dev/null +++ b/Lang/Ring/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/Ring \ No newline at end of file diff --git a/Lang/Ring/Terminal-control-Coloured-text b/Lang/Ring/Terminal-control-Coloured-text new file mode 120000 index 0000000000..9b235ca022 --- /dev/null +++ b/Lang/Ring/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/Ring \ No newline at end of file diff --git a/Lang/Ring/Terminal-control-Cursor-positioning b/Lang/Ring/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..5811164d9a --- /dev/null +++ b/Lang/Ring/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/Ring \ No newline at end of file diff --git a/Lang/Ring/Terminal-control-Display-an-extended-character b/Lang/Ring/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..1df4b86f3b --- /dev/null +++ b/Lang/Ring/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/Ring \ No newline at end of file diff --git a/Lang/Ring/The-Twelve-Days-of-Christmas b/Lang/Ring/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..8f088d0c3e --- /dev/null +++ b/Lang/Ring/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/Ring \ No newline at end of file diff --git a/Lang/Ring/Top-rank-per-group b/Lang/Ring/Top-rank-per-group new file mode 120000 index 0000000000..a0caf17dd7 --- /dev/null +++ b/Lang/Ring/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Ring \ No newline at end of file diff --git a/Lang/Ring/Truncatable-primes b/Lang/Ring/Truncatable-primes new file mode 120000 index 0000000000..d3aefb077d --- /dev/null +++ b/Lang/Ring/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/Ring \ No newline at end of file diff --git a/Lang/Ring/Ulam-spiral--for-primes- b/Lang/Ring/Ulam-spiral--for-primes- new file mode 120000 index 0000000000..3bbe0aa9a1 --- /dev/null +++ b/Lang/Ring/Ulam-spiral--for-primes- @@ -0,0 +1 @@ +../../Task/Ulam-spiral--for-primes-/Ring \ No newline at end of file diff --git a/Lang/Ring/Undefined-values b/Lang/Ring/Undefined-values new file mode 120000 index 0000000000..c1af1b88c3 --- /dev/null +++ b/Lang/Ring/Undefined-values @@ -0,0 +1 @@ +../../Task/Undefined-values/Ring \ No newline at end of file diff --git a/Lang/Ring/Vampire-number b/Lang/Ring/Vampire-number new file mode 120000 index 0000000000..f195bac087 --- /dev/null +++ b/Lang/Ring/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/Ring \ No newline at end of file diff --git a/Lang/Ring/Variadic-function b/Lang/Ring/Variadic-function new file mode 120000 index 0000000000..4c637dd582 --- /dev/null +++ b/Lang/Ring/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/Ring \ No newline at end of file diff --git a/Lang/Ring/Vigen-re-cipher b/Lang/Ring/Vigen-re-cipher new file mode 120000 index 0000000000..f6cbbab775 --- /dev/null +++ b/Lang/Ring/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/Ring \ No newline at end of file diff --git a/Lang/Ring/Voronoi-diagram b/Lang/Ring/Voronoi-diagram new file mode 120000 index 0000000000..025a837b4e --- /dev/null +++ b/Lang/Ring/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/Ring \ No newline at end of file diff --git a/Lang/Ring/Word-wrap b/Lang/Ring/Word-wrap new file mode 120000 index 0000000000..b7d7602ce7 --- /dev/null +++ b/Lang/Ring/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Ring \ No newline at end of file diff --git a/Lang/Ring/Write-float-arrays-to-a-text-file b/Lang/Ring/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..e93dc85fec --- /dev/null +++ b/Lang/Ring/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Ring \ No newline at end of file diff --git a/Lang/Ring/Zeckendorf-number-representation b/Lang/Ring/Zeckendorf-number-representation new file mode 120000 index 0000000000..f8878e7bd6 --- /dev/null +++ b/Lang/Ring/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/Ring \ No newline at end of file diff --git a/Lang/Ring/Zig-zag-matrix b/Lang/Ring/Zig-zag-matrix new file mode 120000 index 0000000000..4e99bc3748 --- /dev/null +++ b/Lang/Ring/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Ring \ No newline at end of file diff --git a/Lang/Ruby/00DESCRIPTION b/Lang/Ruby/00DESCRIPTION index 6636144f09..dd566e398f 100644 --- a/Lang/Ruby/00DESCRIPTION +++ b/Lang/Ruby/00DESCRIPTION @@ -28,4 +28,7 @@ He has often said that he is “trying to make Ruby natural, not simple,” in a Since its public release in 1995, Ruby has drawn devoted coders worldwide. In 2006, Ruby achieved mass acceptance. The [http://www.tiobe.com/tpci.htm TIOBE] index, which measures the growth of programming languages, ranks Ruby as #11 among programming languages worldwide. Much of the growth is attributed to the popularity of software written in Ruby, particularly the Rails web framework. -An interactive tutorial is available in the form of an [http://tryruby.org/ Interactive Console] inside of your Web Browser. \ No newline at end of file +An interactive tutorial is available in the form of an [http://tryruby.org/ Interactive Console] inside of your Web Browser. + +==Todo== +[[Reports:Tasks_not_implemented_in_Ruby]] \ No newline at end of file diff --git a/Lang/Run-BASIC/00DESCRIPTION b/Lang/Run-BASIC/00DESCRIPTION index 5c9241833c..0e8ecf50da 100644 --- a/Lang/Run-BASIC/00DESCRIPTION +++ b/Lang/Run-BASIC/00DESCRIPTION @@ -12,4 +12,7 @@ Database capability is included via the [[:Category:SQLite|SQLite]] database eng ==See also== *[http://www.runbasic.com/ Run BASIC homepage] *[[wp:Run BASIC|Run BASIC on Wikipedia]] -*[http://runbasichosting.com/ The Run BASIC Hosting Service] -- "a reliable, hassle-free way to publish your Run BASIC web applications" \ No newline at end of file +*[http://runbasichosting.com/ The Run BASIC Hosting Service] -- "a reliable, hassle-free way to publish your Run BASIC web applications" + +[[Category:BASIC Implementations]] +[[Category:Web Application]] \ No newline at end of file diff --git a/Lang/Rust/Amb b/Lang/Rust/Amb new file mode 120000 index 0000000000..ae5ee7dd80 --- /dev/null +++ b/Lang/Rust/Amb @@ -0,0 +1 @@ +../../Task/Amb/Rust \ No newline at end of file diff --git a/Lang/Rust/Constrained-random-points-on-a-circle b/Lang/Rust/Constrained-random-points-on-a-circle new file mode 120000 index 0000000000..29a64d9178 --- /dev/null +++ b/Lang/Rust/Constrained-random-points-on-a-circle @@ -0,0 +1 @@ +../../Task/Constrained-random-points-on-a-circle/Rust \ No newline at end of file diff --git a/Lang/Rust/Convert-decimal-number-to-rational b/Lang/Rust/Convert-decimal-number-to-rational new file mode 120000 index 0000000000..c90504cb5a --- /dev/null +++ b/Lang/Rust/Convert-decimal-number-to-rational @@ -0,0 +1 @@ +../../Task/Convert-decimal-number-to-rational/Rust \ No newline at end of file diff --git a/Lang/Rust/Day-of-the-week b/Lang/Rust/Day-of-the-week new file mode 120000 index 0000000000..bc6bb5a637 --- /dev/null +++ b/Lang/Rust/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Rust \ No newline at end of file diff --git a/Lang/Rust/Detect-division-by-zero b/Lang/Rust/Detect-division-by-zero new file mode 120000 index 0000000000..7b86045735 --- /dev/null +++ b/Lang/Rust/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/Rust \ No newline at end of file diff --git a/Lang/Rust/Discordian-date b/Lang/Rust/Discordian-date new file mode 120000 index 0000000000..2da680eed7 --- /dev/null +++ b/Lang/Rust/Discordian-date @@ -0,0 +1 @@ +../../Task/Discordian-date/Rust \ No newline at end of file diff --git a/Lang/Rust/Empty-directory b/Lang/Rust/Empty-directory new file mode 120000 index 0000000000..8bd6628fc7 --- /dev/null +++ b/Lang/Rust/Empty-directory @@ -0,0 +1 @@ +../../Task/Empty-directory/Rust \ No newline at end of file diff --git a/Lang/Rust/Evolutionary-algorithm b/Lang/Rust/Evolutionary-algorithm new file mode 120000 index 0000000000..5e3f65c954 --- /dev/null +++ b/Lang/Rust/Evolutionary-algorithm @@ -0,0 +1 @@ +../../Task/Evolutionary-algorithm/Rust \ No newline at end of file diff --git a/Lang/Rust/Fractal-tree b/Lang/Rust/Fractal-tree new file mode 120000 index 0000000000..91b5434e24 --- /dev/null +++ b/Lang/Rust/Fractal-tree @@ -0,0 +1 @@ +../../Task/Fractal-tree/Rust \ No newline at end of file diff --git a/Lang/Rust/Harshad-or-Niven-series b/Lang/Rust/Harshad-or-Niven-series new file mode 120000 index 0000000000..b119c905fd --- /dev/null +++ b/Lang/Rust/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/Rust \ No newline at end of file diff --git a/Lang/Rust/Identity-matrix b/Lang/Rust/Identity-matrix new file mode 120000 index 0000000000..bbddbe21f9 --- /dev/null +++ b/Lang/Rust/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/Rust \ No newline at end of file diff --git a/Lang/Rust/Knuths-algorithm-S b/Lang/Rust/Knuths-algorithm-S new file mode 120000 index 0000000000..83d3e2910c --- /dev/null +++ b/Lang/Rust/Knuths-algorithm-S @@ -0,0 +1 @@ +../../Task/Knuths-algorithm-S/Rust \ No newline at end of file diff --git a/Lang/Rust/Linear-congruential-generator b/Lang/Rust/Linear-congruential-generator new file mode 120000 index 0000000000..539d70e154 --- /dev/null +++ b/Lang/Rust/Linear-congruential-generator @@ -0,0 +1 @@ +../../Task/Linear-congruential-generator/Rust \ No newline at end of file diff --git a/Lang/Rust/Longest-increasing-subsequence b/Lang/Rust/Longest-increasing-subsequence new file mode 120000 index 0000000000..e1feb172cf --- /dev/null +++ b/Lang/Rust/Longest-increasing-subsequence @@ -0,0 +1 @@ +../../Task/Longest-increasing-subsequence/Rust \ No newline at end of file diff --git a/Lang/Rust/Lucas-Lehmer-test b/Lang/Rust/Lucas-Lehmer-test new file mode 120000 index 0000000000..2ab70e931a --- /dev/null +++ b/Lang/Rust/Lucas-Lehmer-test @@ -0,0 +1 @@ +../../Task/Lucas-Lehmer-test/Rust \ No newline at end of file diff --git a/Lang/Rust/Man-or-boy-test b/Lang/Rust/Man-or-boy-test new file mode 120000 index 0000000000..70ba25d004 --- /dev/null +++ b/Lang/Rust/Man-or-boy-test @@ -0,0 +1 @@ +../../Task/Man-or-boy-test/Rust \ No newline at end of file diff --git a/Lang/Rust/Mandelbrot-set b/Lang/Rust/Mandelbrot-set new file mode 120000 index 0000000000..1493db1e8f --- /dev/null +++ b/Lang/Rust/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/Rust \ No newline at end of file diff --git a/Lang/Rust/Menu b/Lang/Rust/Menu new file mode 120000 index 0000000000..47bfe0be0f --- /dev/null +++ b/Lang/Rust/Menu @@ -0,0 +1 @@ +../../Task/Menu/Rust \ No newline at end of file diff --git a/Lang/Rust/Minesweeper-game b/Lang/Rust/Minesweeper-game new file mode 120000 index 0000000000..f13e764461 --- /dev/null +++ b/Lang/Rust/Minesweeper-game @@ -0,0 +1 @@ +../../Task/Minesweeper-game/Rust \ No newline at end of file diff --git a/Lang/Rust/Monte-Carlo-methods b/Lang/Rust/Monte-Carlo-methods new file mode 120000 index 0000000000..899d64a7c4 --- /dev/null +++ b/Lang/Rust/Monte-Carlo-methods @@ -0,0 +1 @@ +../../Task/Monte-Carlo-methods/Rust \ No newline at end of file diff --git a/Lang/Rust/Parsing-Shunting-yard-algorithm b/Lang/Rust/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..43e527ad29 --- /dev/null +++ b/Lang/Rust/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/Rust \ No newline at end of file diff --git a/Lang/Rust/Pascals-triangle b/Lang/Rust/Pascals-triangle new file mode 120000 index 0000000000..efb0acdb26 --- /dev/null +++ b/Lang/Rust/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/Rust \ No newline at end of file diff --git a/Lang/Rust/Probabilistic-choice b/Lang/Rust/Probabilistic-choice new file mode 120000 index 0000000000..3d8f9aeb84 --- /dev/null +++ b/Lang/Rust/Probabilistic-choice @@ -0,0 +1 @@ +../../Task/Probabilistic-choice/Rust \ No newline at end of file diff --git a/Lang/Rust/Pythagorean-triples b/Lang/Rust/Pythagorean-triples new file mode 120000 index 0000000000..eb5ca09270 --- /dev/null +++ b/Lang/Rust/Pythagorean-triples @@ -0,0 +1 @@ +../../Task/Pythagorean-triples/Rust \ No newline at end of file diff --git a/Lang/Rust/Quaternion-type b/Lang/Rust/Quaternion-type new file mode 120000 index 0000000000..92c25b946f --- /dev/null +++ b/Lang/Rust/Quaternion-type @@ -0,0 +1 @@ +../../Task/Quaternion-type/Rust \ No newline at end of file diff --git a/Lang/Rust/Read-a-configuration-file b/Lang/Rust/Read-a-configuration-file new file mode 120000 index 0000000000..2b0ef1b8d7 --- /dev/null +++ b/Lang/Rust/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/Rust \ No newline at end of file diff --git a/Lang/Rust/Read-a-specific-line-from-a-file b/Lang/Rust/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..24465d400b --- /dev/null +++ b/Lang/Rust/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/Rust \ No newline at end of file diff --git a/Lang/Rust/Rock-paper-scissors b/Lang/Rust/Rock-paper-scissors new file mode 120000 index 0000000000..39e855e9da --- /dev/null +++ b/Lang/Rust/Rock-paper-scissors @@ -0,0 +1 @@ +../../Task/Rock-paper-scissors/Rust \ No newline at end of file diff --git a/Lang/Rust/Self-describing-numbers b/Lang/Rust/Self-describing-numbers new file mode 120000 index 0000000000..7d6814a46f --- /dev/null +++ b/Lang/Rust/Self-describing-numbers @@ -0,0 +1 @@ +../../Task/Self-describing-numbers/Rust \ No newline at end of file diff --git a/Lang/Rust/Semiprime b/Lang/Rust/Semiprime new file mode 120000 index 0000000000..06e2aa03cb --- /dev/null +++ b/Lang/Rust/Semiprime @@ -0,0 +1 @@ +../../Task/Semiprime/Rust \ No newline at end of file diff --git a/Lang/Rust/Short-circuit-evaluation b/Lang/Rust/Short-circuit-evaluation new file mode 120000 index 0000000000..efaaf2270b --- /dev/null +++ b/Lang/Rust/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Rust \ No newline at end of file diff --git a/Lang/Rust/Simulate-input-Keyboard b/Lang/Rust/Simulate-input-Keyboard new file mode 120000 index 0000000000..b54554b9b9 --- /dev/null +++ b/Lang/Rust/Simulate-input-Keyboard @@ -0,0 +1 @@ +../../Task/Simulate-input-Keyboard/Rust \ No newline at end of file diff --git a/Lang/Rust/Simulate-input-Mouse b/Lang/Rust/Simulate-input-Mouse new file mode 120000 index 0000000000..ccbe79d651 --- /dev/null +++ b/Lang/Rust/Simulate-input-Mouse @@ -0,0 +1 @@ +../../Task/Simulate-input-Mouse/Rust \ No newline at end of file diff --git a/Lang/Rust/Sorting-algorithms-Counting-sort b/Lang/Rust/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..7684625128 --- /dev/null +++ b/Lang/Rust/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Rust \ No newline at end of file diff --git a/Lang/Rust/Sorting-algorithms-Pancake-sort b/Lang/Rust/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..5983415e9a --- /dev/null +++ b/Lang/Rust/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Rust \ No newline at end of file diff --git a/Lang/Rust/String-prepend b/Lang/Rust/String-prepend new file mode 120000 index 0000000000..af5f00bb46 --- /dev/null +++ b/Lang/Rust/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Rust \ No newline at end of file diff --git a/Lang/Rust/Strip-a-set-of-characters-from-a-string b/Lang/Rust/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..6a75654888 --- /dev/null +++ b/Lang/Rust/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Rust \ No newline at end of file diff --git a/Lang/Rust/Substring b/Lang/Rust/Substring new file mode 120000 index 0000000000..74d6ba336b --- /dev/null +++ b/Lang/Rust/Substring @@ -0,0 +1 @@ +../../Task/Substring/Rust \ No newline at end of file diff --git a/Lang/Rust/Sum-multiples-of-3-and-5 b/Lang/Rust/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..74d44e13d2 --- /dev/null +++ b/Lang/Rust/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Rust \ No newline at end of file diff --git a/Lang/Rust/Take-notes-on-the-command-line b/Lang/Rust/Take-notes-on-the-command-line new file mode 120000 index 0000000000..1b6aa50c02 --- /dev/null +++ b/Lang/Rust/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Rust \ No newline at end of file diff --git a/Lang/Rust/Unbias-a-random-generator b/Lang/Rust/Unbias-a-random-generator new file mode 120000 index 0000000000..dbf441e948 --- /dev/null +++ b/Lang/Rust/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/Rust \ No newline at end of file diff --git a/Lang/Rust/Voronoi-diagram b/Lang/Rust/Voronoi-diagram new file mode 120000 index 0000000000..c3d4889a26 --- /dev/null +++ b/Lang/Rust/Voronoi-diagram @@ -0,0 +1 @@ +../../Task/Voronoi-diagram/Rust \ No newline at end of file diff --git a/Lang/SAS/Sieve-of-Eratosthenes b/Lang/SAS/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..9358efc930 --- /dev/null +++ b/Lang/SAS/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/SAS \ No newline at end of file diff --git a/Lang/SETL/Roman-numerals-Encode b/Lang/SETL/Roman-numerals-Encode new file mode 120000 index 0000000000..1ee3e3e32d --- /dev/null +++ b/Lang/SETL/Roman-numerals-Encode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Encode/SETL \ No newline at end of file diff --git a/Lang/Scala/00DESCRIPTION b/Lang/Scala/00DESCRIPTION index 5560f22b58..3535ecf235 100644 --- a/Lang/Scala/00DESCRIPTION +++ b/Lang/Scala/00DESCRIPTION @@ -13,4 +13,8 @@ The language is most focused on the results of the program, therefor the [http://en.wikipedia.org/wiki/Considered_harmful considered harmful] technical computer oriented concepts like threads, semaphore, pointers, coercion, casting, goto- and break statements to struggle with are not there. For parallel processing (that very simple can archived) these concept are present but not visible to the programmer. -Lots of RC tasks addresses technical "features" of goto's, break, continue, side effects, pointers, type-casting, weak-typing and so on and are deliberately not Scala's cup of tea. \ No newline at end of file +Lots of RC tasks addresses technical "features" of goto's, break, continue, side effects, pointers, type-casting, weak-typing and so on and are deliberately not Scala's cup of tea. + +Compiled strongly-typed languages, where more defects can be caught at compile time, are less prone to runtime failures than interpreted or weakly-typed languages. +==Todo== +[[Reports:Tasks_not_implemented_in_Scala]] \ No newline at end of file diff --git a/Lang/Scala/Active-Directory-Connect b/Lang/Scala/Active-Directory-Connect new file mode 120000 index 0000000000..78124321e7 --- /dev/null +++ b/Lang/Scala/Active-Directory-Connect @@ -0,0 +1 @@ +../../Task/Active-Directory-Connect/Scala \ No newline at end of file diff --git a/Lang/Scala/Arithmetic-geometric-mean-Calculate-Pi b/Lang/Scala/Arithmetic-geometric-mean-Calculate-Pi new file mode 120000 index 0000000000..ef2bb73405 --- /dev/null +++ b/Lang/Scala/Arithmetic-geometric-mean-Calculate-Pi @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean-Calculate-Pi/Scala \ No newline at end of file diff --git a/Lang/Scala/Bitcoin-address-validation b/Lang/Scala/Bitcoin-address-validation new file mode 120000 index 0000000000..bbd0f50efb --- /dev/null +++ b/Lang/Scala/Bitcoin-address-validation @@ -0,0 +1 @@ +../../Task/Bitcoin-address-validation/Scala \ No newline at end of file diff --git a/Lang/Scala/Call-a-foreign-language-function b/Lang/Scala/Call-a-foreign-language-function new file mode 120000 index 0000000000..5cb09e1aca --- /dev/null +++ b/Lang/Scala/Call-a-foreign-language-function @@ -0,0 +1 @@ +../../Task/Call-a-foreign-language-function/Scala \ No newline at end of file diff --git a/Lang/Scala/Catalan-numbers-Pascals-triangle b/Lang/Scala/Catalan-numbers-Pascals-triangle new file mode 120000 index 0000000000..a405066ea1 --- /dev/null +++ b/Lang/Scala/Catalan-numbers-Pascals-triangle @@ -0,0 +1 @@ +../../Task/Catalan-numbers-Pascals-triangle/Scala \ No newline at end of file diff --git a/Lang/Scala/Catamorphism b/Lang/Scala/Catamorphism new file mode 120000 index 0000000000..034db436d0 --- /dev/null +++ b/Lang/Scala/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Scala \ No newline at end of file diff --git a/Lang/Scala/Compile-time-calculation b/Lang/Scala/Compile-time-calculation new file mode 120000 index 0000000000..2b91dfb2bb --- /dev/null +++ b/Lang/Scala/Compile-time-calculation @@ -0,0 +1 @@ +../../Task/Compile-time-calculation/Scala \ No newline at end of file diff --git a/Lang/Scala/Draw-a-sphere b/Lang/Scala/Draw-a-sphere new file mode 120000 index 0000000000..274fea795e --- /dev/null +++ b/Lang/Scala/Draw-a-sphere @@ -0,0 +1 @@ +../../Task/Draw-a-sphere/Scala \ No newline at end of file diff --git a/Lang/Scala/Echo-server b/Lang/Scala/Echo-server new file mode 120000 index 0000000000..5d5c229403 --- /dev/null +++ b/Lang/Scala/Echo-server @@ -0,0 +1 @@ +../../Task/Echo-server/Scala \ No newline at end of file diff --git a/Lang/Scala/GUI-Maximum-window-dimensions b/Lang/Scala/GUI-Maximum-window-dimensions new file mode 120000 index 0000000000..1e6544b42f --- /dev/null +++ b/Lang/Scala/GUI-Maximum-window-dimensions @@ -0,0 +1 @@ +../../Task/GUI-Maximum-window-dimensions/Scala \ No newline at end of file diff --git a/Lang/Scala/Globally-replace-text-in-several-files b/Lang/Scala/Globally-replace-text-in-several-files new file mode 120000 index 0000000000..3f6ca89497 --- /dev/null +++ b/Lang/Scala/Globally-replace-text-in-several-files @@ -0,0 +1 @@ +../../Task/Globally-replace-text-in-several-files/Scala \ No newline at end of file diff --git a/Lang/Scala/Guess-the-number-With-feedback b/Lang/Scala/Guess-the-number-With-feedback new file mode 120000 index 0000000000..30fd7d169e --- /dev/null +++ b/Lang/Scala/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/Scala \ No newline at end of file diff --git a/Lang/Scala/HTTPS-Authenticated b/Lang/Scala/HTTPS-Authenticated new file mode 120000 index 0000000000..b34e84c9f2 --- /dev/null +++ b/Lang/Scala/HTTPS-Authenticated @@ -0,0 +1 @@ +../../Task/HTTPS-Authenticated/Scala \ No newline at end of file diff --git a/Lang/Scala/HTTPS-Client-authenticated b/Lang/Scala/HTTPS-Client-authenticated new file mode 120000 index 0000000000..dcbe682843 --- /dev/null +++ b/Lang/Scala/HTTPS-Client-authenticated @@ -0,0 +1 @@ +../../Task/HTTPS-Client-authenticated/Scala \ No newline at end of file diff --git a/Lang/Scala/Hickerson-series-of-almost-integers b/Lang/Scala/Hickerson-series-of-almost-integers new file mode 120000 index 0000000000..383a4487e1 --- /dev/null +++ b/Lang/Scala/Hickerson-series-of-almost-integers @@ -0,0 +1 @@ +../../Task/Hickerson-series-of-almost-integers/Scala \ No newline at end of file diff --git a/Lang/Scala/Inverted-syntax b/Lang/Scala/Inverted-syntax new file mode 120000 index 0000000000..22df5f83fc --- /dev/null +++ b/Lang/Scala/Inverted-syntax @@ -0,0 +1 @@ +../../Task/Inverted-syntax/Scala \ No newline at end of file diff --git a/Lang/Scala/Keyboard-input-Keypress-check b/Lang/Scala/Keyboard-input-Keypress-check new file mode 120000 index 0000000000..23355ed50c --- /dev/null +++ b/Lang/Scala/Keyboard-input-Keypress-check @@ -0,0 +1 @@ +../../Task/Keyboard-input-Keypress-check/Scala \ No newline at end of file diff --git a/Lang/Scala/Knapsack-problem-Continuous b/Lang/Scala/Knapsack-problem-Continuous new file mode 120000 index 0000000000..ed6f430747 --- /dev/null +++ b/Lang/Scala/Knapsack-problem-Continuous @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Continuous/Scala \ No newline at end of file diff --git a/Lang/Scala/Knuths-algorithm-S b/Lang/Scala/Knuths-algorithm-S new file mode 120000 index 0000000000..525fb7ed15 --- /dev/null +++ b/Lang/Scala/Knuths-algorithm-S @@ -0,0 +1 @@ +../../Task/Knuths-algorithm-S/Scala \ No newline at end of file diff --git a/Lang/Scala/MD5-Implementation b/Lang/Scala/MD5-Implementation new file mode 120000 index 0000000000..7fdb8ff00c --- /dev/null +++ b/Lang/Scala/MD5-Implementation @@ -0,0 +1 @@ +../../Task/MD5-Implementation/Scala \ No newline at end of file diff --git a/Lang/Scala/Memory-layout-of-a-data-structure b/Lang/Scala/Memory-layout-of-a-data-structure new file mode 120000 index 0000000000..098b69dd37 --- /dev/null +++ b/Lang/Scala/Memory-layout-of-a-data-structure @@ -0,0 +1 @@ +../../Task/Memory-layout-of-a-data-structure/Scala \ No newline at end of file diff --git a/Lang/Scala/Menu b/Lang/Scala/Menu new file mode 120000 index 0000000000..a29e2a2656 --- /dev/null +++ b/Lang/Scala/Menu @@ -0,0 +1 @@ +../../Task/Menu/Scala \ No newline at end of file diff --git a/Lang/Scala/Metaprogramming b/Lang/Scala/Metaprogramming new file mode 120000 index 0000000000..d1b3466ff8 --- /dev/null +++ b/Lang/Scala/Metaprogramming @@ -0,0 +1 @@ +../../Task/Metaprogramming/Scala \ No newline at end of file diff --git a/Lang/Scala/Metered-concurrency b/Lang/Scala/Metered-concurrency new file mode 120000 index 0000000000..d9dc8b5c36 --- /dev/null +++ b/Lang/Scala/Metered-concurrency @@ -0,0 +1 @@ +../../Task/Metered-concurrency/Scala \ No newline at end of file diff --git a/Lang/Scala/Metronome b/Lang/Scala/Metronome new file mode 120000 index 0000000000..24e6c69b73 --- /dev/null +++ b/Lang/Scala/Metronome @@ -0,0 +1 @@ +../../Task/Metronome/Scala \ No newline at end of file diff --git a/Lang/Scala/Narcissist b/Lang/Scala/Narcissist new file mode 120000 index 0000000000..585c21c962 --- /dev/null +++ b/Lang/Scala/Narcissist @@ -0,0 +1 @@ +../../Task/Narcissist/Scala \ No newline at end of file diff --git a/Lang/Scala/Non-decimal-radices-Convert b/Lang/Scala/Non-decimal-radices-Convert new file mode 120000 index 0000000000..6e5304f5bd --- /dev/null +++ b/Lang/Scala/Non-decimal-radices-Convert @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Convert/Scala \ No newline at end of file diff --git a/Lang/Scala/Non-decimal-radices-Input b/Lang/Scala/Non-decimal-radices-Input new file mode 120000 index 0000000000..242d13c6de --- /dev/null +++ b/Lang/Scala/Non-decimal-radices-Input @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Input/Scala \ No newline at end of file diff --git a/Lang/Scala/Non-decimal-radices-Output b/Lang/Scala/Non-decimal-radices-Output new file mode 120000 index 0000000000..d06b2beae3 --- /dev/null +++ b/Lang/Scala/Non-decimal-radices-Output @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Output/Scala \ No newline at end of file diff --git a/Lang/Scala/Paraffins b/Lang/Scala/Paraffins new file mode 120000 index 0000000000..3f223bb123 --- /dev/null +++ b/Lang/Scala/Paraffins @@ -0,0 +1 @@ +../../Task/Paraffins/Scala \ No newline at end of file diff --git a/Lang/Scala/Parse-an-IP-Address b/Lang/Scala/Parse-an-IP-Address new file mode 120000 index 0000000000..fb04406469 --- /dev/null +++ b/Lang/Scala/Parse-an-IP-Address @@ -0,0 +1 @@ +../../Task/Parse-an-IP-Address/Scala \ No newline at end of file diff --git a/Lang/Scala/Pascals-triangle-Puzzle b/Lang/Scala/Pascals-triangle-Puzzle new file mode 120000 index 0000000000..3031357d42 --- /dev/null +++ b/Lang/Scala/Pascals-triangle-Puzzle @@ -0,0 +1 @@ +../../Task/Pascals-triangle-Puzzle/Scala \ No newline at end of file diff --git a/Lang/Scala/Permutations-by-swapping b/Lang/Scala/Permutations-by-swapping new file mode 120000 index 0000000000..f6cd0f6fae --- /dev/null +++ b/Lang/Scala/Permutations-by-swapping @@ -0,0 +1 @@ +../../Task/Permutations-by-swapping/Scala \ No newline at end of file diff --git a/Lang/Scala/Polymorphic-copy b/Lang/Scala/Polymorphic-copy new file mode 120000 index 0000000000..161834390b --- /dev/null +++ b/Lang/Scala/Polymorphic-copy @@ -0,0 +1 @@ +../../Task/Polymorphic-copy/Scala \ No newline at end of file diff --git a/Lang/Scala/Pragmatic-directives b/Lang/Scala/Pragmatic-directives new file mode 120000 index 0000000000..7675dd25f5 --- /dev/null +++ b/Lang/Scala/Pragmatic-directives @@ -0,0 +1 @@ +../../Task/Pragmatic-directives/Scala \ No newline at end of file diff --git a/Lang/Scala/Random-number-generator--device- b/Lang/Scala/Random-number-generator--device- new file mode 120000 index 0000000000..aa61a0276d --- /dev/null +++ b/Lang/Scala/Random-number-generator--device- @@ -0,0 +1 @@ +../../Task/Random-number-generator--device-/Scala \ No newline at end of file diff --git a/Lang/Scala/Real-constants-and-functions b/Lang/Scala/Real-constants-and-functions new file mode 120000 index 0000000000..afa72d1a25 --- /dev/null +++ b/Lang/Scala/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/Scala \ No newline at end of file diff --git a/Lang/Scala/Runtime-evaluation-In-an-environment b/Lang/Scala/Runtime-evaluation-In-an-environment new file mode 120000 index 0000000000..709a696565 --- /dev/null +++ b/Lang/Scala/Runtime-evaluation-In-an-environment @@ -0,0 +1 @@ +../../Task/Runtime-evaluation-In-an-environment/Scala \ No newline at end of file diff --git a/Lang/Scala/Safe-addition b/Lang/Scala/Safe-addition new file mode 120000 index 0000000000..5d4a343daa --- /dev/null +++ b/Lang/Scala/Safe-addition @@ -0,0 +1 @@ +../../Task/Safe-addition/Scala \ No newline at end of file diff --git a/Lang/Scala/Scope-Function-names-and-labels b/Lang/Scala/Scope-Function-names-and-labels new file mode 120000 index 0000000000..5676a62ce6 --- /dev/null +++ b/Lang/Scala/Scope-Function-names-and-labels @@ -0,0 +1 @@ +../../Task/Scope-Function-names-and-labels/Scala \ No newline at end of file diff --git a/Lang/Scala/Self-describing-numbers b/Lang/Scala/Self-describing-numbers new file mode 120000 index 0000000000..0a295297f2 --- /dev/null +++ b/Lang/Scala/Self-describing-numbers @@ -0,0 +1 @@ +../../Task/Self-describing-numbers/Scala \ No newline at end of file diff --git a/Lang/Scala/Sorting-algorithms-Comb-sort b/Lang/Scala/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..1d82878916 --- /dev/null +++ b/Lang/Scala/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Scala \ No newline at end of file diff --git a/Lang/Scala/Sorting-algorithms-Stooge-sort b/Lang/Scala/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..3180b80912 --- /dev/null +++ b/Lang/Scala/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Scala \ No newline at end of file diff --git a/Lang/Scala/Terminal-control-Coloured-text b/Lang/Scala/Terminal-control-Coloured-text new file mode 120000 index 0000000000..ba6bad2b0b --- /dev/null +++ b/Lang/Scala/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/Scala \ No newline at end of file diff --git a/Lang/Scala/Terminal-control-Cursor-movement b/Lang/Scala/Terminal-control-Cursor-movement new file mode 120000 index 0000000000..b8ee3682ef --- /dev/null +++ b/Lang/Scala/Terminal-control-Cursor-movement @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-movement/Scala \ No newline at end of file diff --git a/Lang/Scala/Terminal-control-Cursor-positioning b/Lang/Scala/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..7af13def1b --- /dev/null +++ b/Lang/Scala/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/Scala \ No newline at end of file diff --git a/Lang/Scala/Terminal-control-Dimensions b/Lang/Scala/Terminal-control-Dimensions new file mode 120000 index 0000000000..701d108e90 --- /dev/null +++ b/Lang/Scala/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/Scala \ No newline at end of file diff --git a/Lang/Scala/Terminal-control-Hiding-the-cursor b/Lang/Scala/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..a6b9ef20a9 --- /dev/null +++ b/Lang/Scala/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/Scala \ No newline at end of file diff --git a/Lang/Scala/Terminal-control-Inverse-video b/Lang/Scala/Terminal-control-Inverse-video new file mode 120000 index 0000000000..145df44090 --- /dev/null +++ b/Lang/Scala/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/Scala \ No newline at end of file diff --git a/Lang/Scala/Topic-variable b/Lang/Scala/Topic-variable new file mode 120000 index 0000000000..18f33defa4 --- /dev/null +++ b/Lang/Scala/Topic-variable @@ -0,0 +1 @@ +../../Task/Topic-variable/Scala \ No newline at end of file diff --git a/Lang/Scala/Twelve-statements b/Lang/Scala/Twelve-statements new file mode 120000 index 0000000000..b373177cd0 --- /dev/null +++ b/Lang/Scala/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/Scala \ No newline at end of file diff --git a/Lang/Scala/Use-another-language-to-call-a-function b/Lang/Scala/Use-another-language-to-call-a-function new file mode 120000 index 0000000000..388eec1af8 --- /dev/null +++ b/Lang/Scala/Use-another-language-to-call-a-function @@ -0,0 +1 @@ +../../Task/Use-another-language-to-call-a-function/Scala \ No newline at end of file diff --git a/Lang/Scala/Variable-size-Set b/Lang/Scala/Variable-size-Set new file mode 120000 index 0000000000..094a7926be --- /dev/null +++ b/Lang/Scala/Variable-size-Set @@ -0,0 +1 @@ +../../Task/Variable-size-Set/Scala \ No newline at end of file diff --git a/Lang/Scala/Video-display-modes b/Lang/Scala/Video-display-modes new file mode 120000 index 0000000000..8604d9b200 --- /dev/null +++ b/Lang/Scala/Video-display-modes @@ -0,0 +1 @@ +../../Task/Video-display-modes/Scala \ No newline at end of file diff --git a/Lang/Scala/Write-to-Windows-event-log b/Lang/Scala/Write-to-Windows-event-log new file mode 120000 index 0000000000..6f6b9d3c63 --- /dev/null +++ b/Lang/Scala/Write-to-Windows-event-log @@ -0,0 +1 @@ +../../Task/Write-to-Windows-event-log/Scala \ No newline at end of file diff --git a/Lang/Scheme/24-game-Solve b/Lang/Scheme/24-game-Solve new file mode 120000 index 0000000000..427c5a2730 --- /dev/null +++ b/Lang/Scheme/24-game-Solve @@ -0,0 +1 @@ +../../Task/24-game-Solve/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Continued-fraction b/Lang/Scheme/Continued-fraction new file mode 120000 index 0000000000..9be0f1fe02 --- /dev/null +++ b/Lang/Scheme/Continued-fraction @@ -0,0 +1 @@ +../../Task/Continued-fraction/Scheme \ No newline at end of file diff --git a/Lang/Scilab/Cholesky-decomposition b/Lang/Scilab/Cholesky-decomposition new file mode 120000 index 0000000000..f6e07da9e2 --- /dev/null +++ b/Lang/Scilab/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Zig-zag-matrix b/Lang/Scilab/Zig-zag-matrix new file mode 120000 index 0000000000..78982c58cf --- /dev/null +++ b/Lang/Scilab/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Scilab \ No newline at end of file diff --git a/Lang/Scratch/00DESCRIPTION b/Lang/Scratch/00DESCRIPTION index e154630a25..dc11375da9 100644 --- a/Lang/Scratch/00DESCRIPTION +++ b/Lang/Scratch/00DESCRIPTION @@ -5,4 +5,5 @@ |site=http://scratch.mit.edu/}} {{language programming paradigm|object-oriented}} {{Wikipedia|Scratch (programming language)}} -Scratch is an educational programming language that allows people of any experience background and age to experiment with the concepts of fully versatile computer programming by using an alterable GUI. It is developed by the Lifelong Kindergarten group at the MIT Media Lab by a team led by Mitchel Resnick and first appeared in the summer of 2007. Scratch can be installed and freely redistributed on any Windows, Mac OS X or Linux computer. The source code is made available under a license that allows modifications for non-commercial uses. \ No newline at end of file +'''Scratch''' is an educational programming language that allows people of any experience background and age to experiment with the concepts of fully versatile computer programming by using an alterable GUI. It is developed by the Lifelong Kindergarten group at the MIT Media Lab by a team led by Mitchel Resnick and first appeared in the summer of 2007. Scratch can be installed and freely redistributed on any Windows, Mac OS X or Linux computer. The source code is made available under a license that allows modifications for non-commercial uses. +[[Category:Web Application]] \ No newline at end of file diff --git a/Lang/SheerPower-4GL/100-doors b/Lang/SheerPower-4GL/100-doors new file mode 120000 index 0000000000..514627f38f --- /dev/null +++ b/Lang/SheerPower-4GL/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/SheerPower-4GL \ No newline at end of file diff --git a/Lang/Shen/Averages-Root-mean-square b/Lang/Shen/Averages-Root-mean-square new file mode 120000 index 0000000000..fe83c34215 --- /dev/null +++ b/Lang/Shen/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/Shen \ No newline at end of file diff --git a/Lang/Shen/Enumerations b/Lang/Shen/Enumerations new file mode 120000 index 0000000000..d1504c9ff5 --- /dev/null +++ b/Lang/Shen/Enumerations @@ -0,0 +1 @@ +../../Task/Enumerations/Shen \ No newline at end of file diff --git a/Lang/Shen/Sorting-algorithms-Bubble-sort b/Lang/Shen/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..d23245f8a4 --- /dev/null +++ b/Lang/Shen/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Shen \ No newline at end of file diff --git a/Lang/Sidef/00DESCRIPTION b/Lang/Sidef/00DESCRIPTION index 26ba2cc083..1c5a0597f3 100644 --- a/Lang/Sidef/00DESCRIPTION +++ b/Lang/Sidef/00DESCRIPTION @@ -22,4 +22,7 @@ The language is mostly used as a research programming language. For more details, see: * Gitbook: [http://trizen.gitbooks.io/sidef-lang/content/ http://trizen.gitbooks.io/sidef-lang/content/] * Tutorial: [https://github.com/trizen/sidef/wiki https://github.com/trizen/sidef/wiki] -* Development page: [https://github.com/trizen/sidef https://github.com/trizen/sidef] \ No newline at end of file +* Development page: [https://github.com/trizen/sidef https://github.com/trizen/sidef] + +==Todo== +[[Reports:Tasks_not_implemented_in_Sidef]] \ No newline at end of file diff --git a/Lang/Sidef/Arithmetic-Rational b/Lang/Sidef/Arithmetic-Rational new file mode 120000 index 0000000000..843ef7234d --- /dev/null +++ b/Lang/Sidef/Arithmetic-Rational @@ -0,0 +1 @@ +../../Task/Arithmetic-Rational/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Brownian-tree b/Lang/Sidef/Brownian-tree new file mode 120000 index 0000000000..8d207420cb --- /dev/null +++ b/Lang/Sidef/Brownian-tree @@ -0,0 +1 @@ +../../Task/Brownian-tree/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Casting-out-nines b/Lang/Sidef/Casting-out-nines new file mode 120000 index 0000000000..35710c7398 --- /dev/null +++ b/Lang/Sidef/Casting-out-nines @@ -0,0 +1 @@ +../../Task/Casting-out-nines/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Circles-of-given-radius-through-two-points b/Lang/Sidef/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..3aeddbfe94 --- /dev/null +++ b/Lang/Sidef/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Color-quantization b/Lang/Sidef/Color-quantization new file mode 120000 index 0000000000..6ac3ded95f --- /dev/null +++ b/Lang/Sidef/Color-quantization @@ -0,0 +1 @@ +../../Task/Color-quantization/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Colour-pinstripe-Display b/Lang/Sidef/Colour-pinstripe-Display new file mode 120000 index 0000000000..b10088819c --- /dev/null +++ b/Lang/Sidef/Colour-pinstripe-Display @@ -0,0 +1 @@ +../../Task/Colour-pinstripe-Display/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Delegates b/Lang/Sidef/Delegates new file mode 120000 index 0000000000..b9bd16c9c8 --- /dev/null +++ b/Lang/Sidef/Delegates @@ -0,0 +1 @@ +../../Task/Delegates/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Element-wise-operations b/Lang/Sidef/Element-wise-operations new file mode 120000 index 0000000000..d14a49e775 --- /dev/null +++ b/Lang/Sidef/Element-wise-operations @@ -0,0 +1 @@ +../../Task/Element-wise-operations/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Matrix-arithmetic b/Lang/Sidef/Matrix-arithmetic new file mode 120000 index 0000000000..7f13c4f5e5 --- /dev/null +++ b/Lang/Sidef/Matrix-arithmetic @@ -0,0 +1 @@ +../../Task/Matrix-arithmetic/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Matrix-exponentiation-operator b/Lang/Sidef/Matrix-exponentiation-operator new file mode 120000 index 0000000000..988eb75b62 --- /dev/null +++ b/Lang/Sidef/Matrix-exponentiation-operator @@ -0,0 +1 @@ +../../Task/Matrix-exponentiation-operator/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Multiplicative-order b/Lang/Sidef/Multiplicative-order new file mode 120000 index 0000000000..79849a2327 --- /dev/null +++ b/Lang/Sidef/Multiplicative-order @@ -0,0 +1 @@ +../../Task/Multiplicative-order/Sidef \ No newline at end of file diff --git a/Lang/Sidef/N-queens-problem b/Lang/Sidef/N-queens-problem new file mode 120000 index 0000000000..c43f04b2be --- /dev/null +++ b/Lang/Sidef/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Vampire-number b/Lang/Sidef/Vampire-number new file mode 120000 index 0000000000..081a5fcc68 --- /dev/null +++ b/Lang/Sidef/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/Sidef \ No newline at end of file diff --git a/Lang/Sidef/Vogels-approximation-method b/Lang/Sidef/Vogels-approximation-method new file mode 120000 index 0000000000..2026628efa --- /dev/null +++ b/Lang/Sidef/Vogels-approximation-method @@ -0,0 +1 @@ +../../Task/Vogels-approximation-method/Sidef \ No newline at end of file diff --git a/Lang/Simula/Ackermann-function b/Lang/Simula/Ackermann-function new file mode 120000 index 0000000000..8eb024b67a --- /dev/null +++ b/Lang/Simula/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Simula \ No newline at end of file diff --git a/Lang/Simula/Greatest-common-divisor b/Lang/Simula/Greatest-common-divisor new file mode 120000 index 0000000000..c3a762caa7 --- /dev/null +++ b/Lang/Simula/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/Simula \ No newline at end of file diff --git a/Lang/Simula/Program-termination b/Lang/Simula/Program-termination new file mode 120000 index 0000000000..ae3a4ac2f4 --- /dev/null +++ b/Lang/Simula/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/Simula \ No newline at end of file diff --git a/Lang/Simula/String-case b/Lang/Simula/String-case new file mode 120000 index 0000000000..07d50fdb01 --- /dev/null +++ b/Lang/Simula/String-case @@ -0,0 +1 @@ +../../Task/String-case/Simula \ No newline at end of file diff --git a/Lang/Simula/String-concatenation b/Lang/Simula/String-concatenation new file mode 120000 index 0000000000..ee2730b34c --- /dev/null +++ b/Lang/Simula/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Simula \ No newline at end of file diff --git a/Lang/Simula/Sum-multiples-of-3-and-5 b/Lang/Simula/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..0b9c47c332 --- /dev/null +++ b/Lang/Simula/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/Simula \ No newline at end of file diff --git a/Lang/Sinclair-ZX81-BASIC/00DESCRIPTION b/Lang/Sinclair-ZX81-BASIC/00DESCRIPTION index f60b6b4138..c7e628155f 100644 --- a/Lang/Sinclair-ZX81-BASIC/00DESCRIPTION +++ b/Lang/Sinclair-ZX81-BASIC/00DESCRIPTION @@ -1,13 +1,13 @@ {{language|Sinclair ZX81 BASIC}} {{implementation|BASIC}} -Sinclair ZX81 BASIC is the dialect of BASIC resident in ROM on the ZX81 home computer (1981) and compatibles (Timex Sinclair 1000, Lambda 8300, and many others). It was developed by John Grant and Steve Vickers. Today, ZX81 emulators exist for a wide range of platforms and operating systems. +Sinclair ZX81 BASIC is the dialect of BASIC resident in ROM on the ZX81 home computer (1981) and compatibles (Timex Sinclair 1000, Lambda 8300, and many others). It was developed by John Grant and Steve Vickers. Around 1.5 million ZX81s and 'official' compatibles were sold, together with a substantial number of clones (unofficial compatibles) manufactured in Brazil, Hong Kong, and elsewhere. Today, ZX81 emulators exist for a wide range of platforms and operating systems. ZX81 BASIC is almost a subset of [[ZX Spectrum Basic]], but not quite: the exponentiation operator is spelled ** rather than (mapped to ASCII ^), the jump and subroutine call keywords are spelled GOTO and GOSUB rather than GO TO and GO SUB, etc. Note also that the ZX81 uses an idiosyncratic (non-ASCII) character set, so that the CODE and CHR$ functions do not return the same values as they would on the Spectrum. Floating point operations, some string handling, and low-resolution graphics are supported; colour, sound, user-defined functions, the READ, DATA, and RESTORE keywords, and assorted other features are not. -The ZX81 has no moving parts and only four microchips: the 3.25MHz Z80 CPU, an 8k ROM chip containing the operating system and BASIC, a 1k RAM chip, and an uncommitted logic array. Since there is no separate video chip, the CPU spends about 75% of its time driving the display and only 25% doing everything else. This can, however, be controlled under BASIC using the FAST and SLOW commands: FAST blanks the screen and allows the processor to operate at full speed, and SLOW reverts to the default behaviour. Even FAST mode can be slower than some other BASIC dialects running on comparable hardware, because ZX81 BASIC has no integer type: all numeric operations have to be done on 40-bit floats using software floating-point routines. +The ZX81 has no moving parts and only four microchips: the 3.25MHz Z80 CPU, an 8k ROM chip containing the operating system and BASIC, a 1k RAM chip, and an uncommitted logic array. Since there is no separate video chip, the CPU spends about 75% of its time driving the display and only 25% doing everything else. This can, however, be controlled under BASIC using the FAST and SLOW commands: FAST blanks the screen and allows the processor to operate at full speed, and SLOW reverts to the default behaviour. Even FAST mode can be slower than some other BASIC dialects running on comparable hardware, because ZX81 BASIC has no integer type: all numeric operations have to be done on 40-bit floats using software floating-point routines. If you are used to other popular 8-bit computers, you should expect the ZX81 to feel noticeably slower. -The original machine's 1k of RAM was shared between the display, the system variables and stack, and the user's program and variables. The Timex-branded model marketed in the United States had a minimum of 2k, as did many clones; an expansion pack was available from Sinclair to increase the RAM to 16k, and expansions of other sizes were produced by third parties. Most ZX81 BASIC programs on Rosetta Code will work with the 1k configuration, but unfortunately some of them require 2k. The minimum RAM requirement is usually stated in a note to the program: where it is omitted, it can be assumed to be 1k. +The original machine's 1k of RAM was shared between the display, the system variables and stack, and the user's program and variables. An expansion pack from Sinclair increased the RAM to 16k; other sizes were available from third parties, allowing the ZX81 to be expanded to a theoretical maximum of 56k. The Timex-branded models marketed in North America came with either 2k or 16k, as did many of the clones. Most ZX81 BASIC programs on Rosetta Code will work with the 1k configuration, but unfortunately some of them do require more. The minimum RAM requirement is usually stated in a note to the program: where it is omitted, it can generally be assumed to be 1k. A PDF version of the manual, ZX81 BASIC Programming by Steve Vickers, is available [http://zxnext.narod.ru/manuals/ZX81_Manual.pdf here]. diff --git a/Lang/Sinclair-ZX81-BASIC/Create-a-two-dimensional-array-at-runtime b/Lang/Sinclair-ZX81-BASIC/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..abe9655852 --- /dev/null +++ b/Lang/Sinclair-ZX81-BASIC/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/Sinclair-ZX81-BASIC \ No newline at end of file diff --git a/Lang/Sinclair-ZX81-BASIC/Pinstripe-Display b/Lang/Sinclair-ZX81-BASIC/Pinstripe-Display new file mode 120000 index 0000000000..bdf2be42ea --- /dev/null +++ b/Lang/Sinclair-ZX81-BASIC/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/Sinclair-ZX81-BASIC \ No newline at end of file diff --git a/Lang/Standard-ML/Left-factorials b/Lang/Standard-ML/Left-factorials new file mode 120000 index 0000000000..479a0ffdc0 --- /dev/null +++ b/Lang/Standard-ML/Left-factorials @@ -0,0 +1 @@ +../../Task/Left-factorials/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Unix-ls b/Lang/Standard-ML/Unix-ls new file mode 120000 index 0000000000..6566cf1e69 --- /dev/null +++ b/Lang/Standard-ML/Unix-ls @@ -0,0 +1 @@ +../../Task/Unix-ls/Standard-ML \ No newline at end of file diff --git a/Lang/Stata/00DESCRIPTION b/Lang/Stata/00DESCRIPTION index d96c2c6e51..19ee115061 100644 --- a/Lang/Stata/00DESCRIPTION +++ b/Lang/Stata/00DESCRIPTION @@ -1,3 +1,3 @@ {{stub}}{{language|Stata|site=http://www.stata.com/}} -Stata is a statistical software package created in 1985. It includes a macro language and a matrix language called Mata. \ No newline at end of file +[[:wp:Stata|Stata]] is a statistical software package created in 1985 and developed by StataCorp, located in College Station, Texas. Stata includes a command-based macro language (informally called "Ado") and a matrix language called Mata. A large part of Stata is itself written in Ado and Mata, with source code available. \ No newline at end of file diff --git a/Lang/Stata/9-billion-names-of-God-the-integer b/Lang/Stata/9-billion-names-of-God-the-integer new file mode 120000 index 0000000000..ba7d182d9f --- /dev/null +++ b/Lang/Stata/9-billion-names-of-God-the-integer @@ -0,0 +1 @@ +../../Task/9-billion-names-of-God-the-integer/Stata \ No newline at end of file diff --git a/Lang/Stata/Address-of-a-variable b/Lang/Stata/Address-of-a-variable new file mode 120000 index 0000000000..9b09ee428e --- /dev/null +++ b/Lang/Stata/Address-of-a-variable @@ -0,0 +1 @@ +../../Task/Address-of-a-variable/Stata \ No newline at end of file diff --git a/Lang/Stata/Anagrams b/Lang/Stata/Anagrams new file mode 120000 index 0000000000..68b0c3c4c0 --- /dev/null +++ b/Lang/Stata/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/Stata \ No newline at end of file diff --git a/Lang/Stata/Apply-a-callback-to-an-array b/Lang/Stata/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..bf4fa1278b --- /dev/null +++ b/Lang/Stata/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/Stata \ No newline at end of file diff --git a/Lang/Stata/Averages-Root-mean-square b/Lang/Stata/Averages-Root-mean-square new file mode 120000 index 0000000000..baffe48dce --- /dev/null +++ b/Lang/Stata/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/Stata \ No newline at end of file diff --git a/Lang/Stata/Balanced-brackets b/Lang/Stata/Balanced-brackets new file mode 120000 index 0000000000..9336f03f3a --- /dev/null +++ b/Lang/Stata/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/Stata \ No newline at end of file diff --git a/Lang/Stata/Caesar-cipher b/Lang/Stata/Caesar-cipher new file mode 120000 index 0000000000..36dff5b5f9 --- /dev/null +++ b/Lang/Stata/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Stata \ No newline at end of file diff --git a/Lang/Stata/Catalan-numbers b/Lang/Stata/Catalan-numbers new file mode 120000 index 0000000000..f30b2c9ca6 --- /dev/null +++ b/Lang/Stata/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/Stata \ No newline at end of file diff --git a/Lang/Stata/Character-codes b/Lang/Stata/Character-codes new file mode 120000 index 0000000000..79c3ebaa21 --- /dev/null +++ b/Lang/Stata/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/Stata \ No newline at end of file diff --git a/Lang/Stata/Circles-of-given-radius-through-two-points b/Lang/Stata/Circles-of-given-radius-through-two-points new file mode 120000 index 0000000000..2f2af6de0f --- /dev/null +++ b/Lang/Stata/Circles-of-given-radius-through-two-points @@ -0,0 +1 @@ +../../Task/Circles-of-given-radius-through-two-points/Stata \ No newline at end of file diff --git a/Lang/Stata/Combinations-and-permutations b/Lang/Stata/Combinations-and-permutations new file mode 120000 index 0000000000..e2a29ddde5 --- /dev/null +++ b/Lang/Stata/Combinations-and-permutations @@ -0,0 +1 @@ +../../Task/Combinations-and-permutations/Stata \ No newline at end of file diff --git a/Lang/Stata/Combinations-with-repetitions b/Lang/Stata/Combinations-with-repetitions new file mode 120000 index 0000000000..cc9a7960d0 --- /dev/null +++ b/Lang/Stata/Combinations-with-repetitions @@ -0,0 +1 @@ +../../Task/Combinations-with-repetitions/Stata \ No newline at end of file diff --git a/Lang/Stata/Conditional-structures b/Lang/Stata/Conditional-structures new file mode 120000 index 0000000000..78da3f9c67 --- /dev/null +++ b/Lang/Stata/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/Stata \ No newline at end of file diff --git a/Lang/Stata/Count-occurrences-of-a-substring b/Lang/Stata/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..761f8b93e5 --- /dev/null +++ b/Lang/Stata/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/Stata \ No newline at end of file diff --git a/Lang/Stata/Documentation b/Lang/Stata/Documentation new file mode 120000 index 0000000000..b26092f6ab --- /dev/null +++ b/Lang/Stata/Documentation @@ -0,0 +1 @@ +../../Task/Documentation/Stata \ No newline at end of file diff --git a/Lang/Stata/Element-wise-operations b/Lang/Stata/Element-wise-operations new file mode 120000 index 0000000000..ecd76281ad --- /dev/null +++ b/Lang/Stata/Element-wise-operations @@ -0,0 +1 @@ +../../Task/Element-wise-operations/Stata \ No newline at end of file diff --git a/Lang/Stata/Even-or-odd b/Lang/Stata/Even-or-odd new file mode 120000 index 0000000000..f3946df4c9 --- /dev/null +++ b/Lang/Stata/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Stata \ No newline at end of file diff --git a/Lang/Stata/Exponentiation-operator b/Lang/Stata/Exponentiation-operator new file mode 120000 index 0000000000..0b14570e64 --- /dev/null +++ b/Lang/Stata/Exponentiation-operator @@ -0,0 +1 @@ +../../Task/Exponentiation-operator/Stata \ No newline at end of file diff --git a/Lang/Stata/Find-the-last-Sunday-of-each-month b/Lang/Stata/Find-the-last-Sunday-of-each-month new file mode 120000 index 0000000000..33d89ec411 --- /dev/null +++ b/Lang/Stata/Find-the-last-Sunday-of-each-month @@ -0,0 +1 @@ +../../Task/Find-the-last-Sunday-of-each-month/Stata \ No newline at end of file diff --git a/Lang/Stata/Five-weekends b/Lang/Stata/Five-weekends new file mode 120000 index 0000000000..7b68fcd6ff --- /dev/null +++ b/Lang/Stata/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/Stata \ No newline at end of file diff --git a/Lang/Stata/FizzBuzz b/Lang/Stata/FizzBuzz new file mode 120000 index 0000000000..7ceb9e202c --- /dev/null +++ b/Lang/Stata/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Stata \ No newline at end of file diff --git a/Lang/Stata/Function-definition b/Lang/Stata/Function-definition new file mode 120000 index 0000000000..275d0ad2c0 --- /dev/null +++ b/Lang/Stata/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Stata \ No newline at end of file diff --git a/Lang/Stata/Gamma-function b/Lang/Stata/Gamma-function new file mode 120000 index 0000000000..a1789b4c7c --- /dev/null +++ b/Lang/Stata/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/Stata \ No newline at end of file diff --git a/Lang/Stata/Gaussian-elimination b/Lang/Stata/Gaussian-elimination new file mode 120000 index 0000000000..f1016017cf --- /dev/null +++ b/Lang/Stata/Gaussian-elimination @@ -0,0 +1 @@ +../../Task/Gaussian-elimination/Stata \ No newline at end of file diff --git a/Lang/Stata/Greatest-common-divisor b/Lang/Stata/Greatest-common-divisor new file mode 120000 index 0000000000..e8e2e50ee6 --- /dev/null +++ b/Lang/Stata/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/Stata \ No newline at end of file diff --git a/Lang/Stata/Greatest-element-of-a-list b/Lang/Stata/Greatest-element-of-a-list new file mode 120000 index 0000000000..46e29eb67d --- /dev/null +++ b/Lang/Stata/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Stata \ No newline at end of file diff --git a/Lang/Stata/Identity-matrix b/Lang/Stata/Identity-matrix new file mode 120000 index 0000000000..e9e37db4cb --- /dev/null +++ b/Lang/Stata/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/Stata \ No newline at end of file diff --git a/Lang/Stata/Knuth-shuffle b/Lang/Stata/Knuth-shuffle new file mode 120000 index 0000000000..d0fa8c5783 --- /dev/null +++ b/Lang/Stata/Knuth-shuffle @@ -0,0 +1 @@ +../../Task/Knuth-shuffle/Stata \ No newline at end of file diff --git a/Lang/Stata/Last-Friday-of-each-month b/Lang/Stata/Last-Friday-of-each-month new file mode 120000 index 0000000000..494d6fe8da --- /dev/null +++ b/Lang/Stata/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/Stata \ No newline at end of file diff --git a/Lang/Stata/Linear-congruential-generator b/Lang/Stata/Linear-congruential-generator new file mode 120000 index 0000000000..6176398951 --- /dev/null +++ b/Lang/Stata/Linear-congruential-generator @@ -0,0 +1 @@ +../../Task/Linear-congruential-generator/Stata \ No newline at end of file diff --git a/Lang/Stata/List-comprehensions b/Lang/Stata/List-comprehensions new file mode 120000 index 0000000000..18427a287c --- /dev/null +++ b/Lang/Stata/List-comprehensions @@ -0,0 +1 @@ +../../Task/List-comprehensions/Stata \ No newline at end of file diff --git a/Lang/Stata/Literals-Floating-point b/Lang/Stata/Literals-Floating-point new file mode 120000 index 0000000000..1ba036c1e6 --- /dev/null +++ b/Lang/Stata/Literals-Floating-point @@ -0,0 +1 @@ +../../Task/Literals-Floating-point/Stata \ No newline at end of file diff --git a/Lang/Stata/Map-range b/Lang/Stata/Map-range new file mode 120000 index 0000000000..ed217153cb --- /dev/null +++ b/Lang/Stata/Map-range @@ -0,0 +1 @@ +../../Task/Map-range/Stata \ No newline at end of file diff --git a/Lang/Stata/Matrix-arithmetic b/Lang/Stata/Matrix-arithmetic new file mode 120000 index 0000000000..65acccc465 --- /dev/null +++ b/Lang/Stata/Matrix-arithmetic @@ -0,0 +1 @@ +../../Task/Matrix-arithmetic/Stata \ No newline at end of file diff --git a/Lang/Stata/Matrix-exponentiation-operator b/Lang/Stata/Matrix-exponentiation-operator new file mode 120000 index 0000000000..b0e81b07e8 --- /dev/null +++ b/Lang/Stata/Matrix-exponentiation-operator @@ -0,0 +1 @@ +../../Task/Matrix-exponentiation-operator/Stata \ No newline at end of file diff --git a/Lang/Stata/Matrix-multiplication b/Lang/Stata/Matrix-multiplication new file mode 120000 index 0000000000..419cc38e1b --- /dev/null +++ b/Lang/Stata/Matrix-multiplication @@ -0,0 +1 @@ +../../Task/Matrix-multiplication/Stata \ No newline at end of file diff --git a/Lang/Stata/Matrix-transposition b/Lang/Stata/Matrix-transposition new file mode 120000 index 0000000000..8d906a4ad2 --- /dev/null +++ b/Lang/Stata/Matrix-transposition @@ -0,0 +1 @@ +../../Task/Matrix-transposition/Stata \ No newline at end of file diff --git a/Lang/Stata/Maximum-triangle-path-sum b/Lang/Stata/Maximum-triangle-path-sum new file mode 120000 index 0000000000..12d1b6319d --- /dev/null +++ b/Lang/Stata/Maximum-triangle-path-sum @@ -0,0 +1 @@ +../../Task/Maximum-triangle-path-sum/Stata \ No newline at end of file diff --git a/Lang/Stata/Multiple-regression b/Lang/Stata/Multiple-regression new file mode 120000 index 0000000000..3804b33eca --- /dev/null +++ b/Lang/Stata/Multiple-regression @@ -0,0 +1 @@ +../../Task/Multiple-regression/Stata \ No newline at end of file diff --git a/Lang/Stata/Nth b/Lang/Stata/Nth new file mode 120000 index 0000000000..1a2043a56b --- /dev/null +++ b/Lang/Stata/Nth @@ -0,0 +1 @@ +../../Task/Nth/Stata \ No newline at end of file diff --git a/Lang/Stata/Numerical-integration b/Lang/Stata/Numerical-integration new file mode 120000 index 0000000000..bbf0dd1a3d --- /dev/null +++ b/Lang/Stata/Numerical-integration @@ -0,0 +1 @@ +../../Task/Numerical-integration/Stata \ No newline at end of file diff --git a/Lang/Stata/Pascals-triangle b/Lang/Stata/Pascals-triangle new file mode 120000 index 0000000000..9cd4a32487 --- /dev/null +++ b/Lang/Stata/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/Stata \ No newline at end of file diff --git a/Lang/Stata/Prime-decomposition b/Lang/Stata/Prime-decomposition new file mode 120000 index 0000000000..41016e3abb --- /dev/null +++ b/Lang/Stata/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/Stata \ No newline at end of file diff --git a/Lang/Stata/Probabilistic-choice b/Lang/Stata/Probabilistic-choice new file mode 120000 index 0000000000..d461db8100 --- /dev/null +++ b/Lang/Stata/Probabilistic-choice @@ -0,0 +1 @@ +../../Task/Probabilistic-choice/Stata \ No newline at end of file diff --git a/Lang/Stata/Roots-of-unity b/Lang/Stata/Roots-of-unity new file mode 120000 index 0000000000..e8123e6deb --- /dev/null +++ b/Lang/Stata/Roots-of-unity @@ -0,0 +1 @@ +../../Task/Roots-of-unity/Stata \ No newline at end of file diff --git a/Lang/Stata/Rot-13 b/Lang/Stata/Rot-13 new file mode 120000 index 0000000000..5f61596be3 --- /dev/null +++ b/Lang/Stata/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/Stata \ No newline at end of file diff --git a/Lang/Stata/Runge-Kutta-method b/Lang/Stata/Runge-Kutta-method new file mode 120000 index 0000000000..086ce2f9f0 --- /dev/null +++ b/Lang/Stata/Runge-Kutta-method @@ -0,0 +1 @@ +../../Task/Runge-Kutta-method/Stata \ No newline at end of file diff --git a/Lang/Stata/Semordnilap b/Lang/Stata/Semordnilap new file mode 120000 index 0000000000..b5a398025e --- /dev/null +++ b/Lang/Stata/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/Stata \ No newline at end of file diff --git a/Lang/Stata/Short-circuit-evaluation b/Lang/Stata/Short-circuit-evaluation new file mode 120000 index 0000000000..992eaf5b1d --- /dev/null +++ b/Lang/Stata/Short-circuit-evaluation @@ -0,0 +1 @@ +../../Task/Short-circuit-evaluation/Stata \ No newline at end of file diff --git a/Lang/Stata/Show-the-epoch b/Lang/Stata/Show-the-epoch new file mode 120000 index 0000000000..b50f5cd9c0 --- /dev/null +++ b/Lang/Stata/Show-the-epoch @@ -0,0 +1 @@ +../../Task/Show-the-epoch/Stata \ No newline at end of file diff --git a/Lang/Stata/Singly-linked-list-Element-definition b/Lang/Stata/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..34ccca3f97 --- /dev/null +++ b/Lang/Stata/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Stata \ No newline at end of file diff --git a/Lang/Stata/Sorting-algorithms-Insertion-sort b/Lang/Stata/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..57c0e2534e --- /dev/null +++ b/Lang/Stata/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/Stata \ No newline at end of file diff --git a/Lang/Stata/Sorting-algorithms-Selection-sort b/Lang/Stata/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..260274a787 --- /dev/null +++ b/Lang/Stata/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Stata \ No newline at end of file diff --git a/Lang/Stata/Spiral-matrix b/Lang/Stata/Spiral-matrix new file mode 120000 index 0000000000..339beedcee --- /dev/null +++ b/Lang/Stata/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Stata \ No newline at end of file diff --git a/Lang/Stata/String-append b/Lang/Stata/String-append new file mode 120000 index 0000000000..f67baa1243 --- /dev/null +++ b/Lang/Stata/String-append @@ -0,0 +1 @@ +../../Task/String-append/Stata \ No newline at end of file diff --git a/Lang/Stata/String-concatenation b/Lang/Stata/String-concatenation new file mode 120000 index 0000000000..231e34ae12 --- /dev/null +++ b/Lang/Stata/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Stata \ No newline at end of file diff --git a/Lang/Stata/String-interpolation--included- b/Lang/Stata/String-interpolation--included- new file mode 120000 index 0000000000..1691937ae0 --- /dev/null +++ b/Lang/Stata/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Stata \ No newline at end of file diff --git a/Lang/Stata/String-prepend b/Lang/Stata/String-prepend new file mode 120000 index 0000000000..b11796d90e --- /dev/null +++ b/Lang/Stata/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/Stata \ No newline at end of file diff --git a/Lang/Stata/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Stata/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..508a992fec --- /dev/null +++ b/Lang/Stata/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Stata \ No newline at end of file diff --git a/Lang/Stata/Substring b/Lang/Stata/Substring new file mode 120000 index 0000000000..4a3ab5f9fb --- /dev/null +++ b/Lang/Stata/Substring @@ -0,0 +1 @@ +../../Task/Substring/Stata \ No newline at end of file diff --git a/Lang/Stata/Sudoku b/Lang/Stata/Sudoku new file mode 120000 index 0000000000..cae6efcba1 --- /dev/null +++ b/Lang/Stata/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/Stata \ No newline at end of file diff --git a/Lang/Stata/Sum-and-product-of-an-array b/Lang/Stata/Sum-and-product-of-an-array new file mode 120000 index 0000000000..2ddcc123e5 --- /dev/null +++ b/Lang/Stata/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Stata \ No newline at end of file diff --git a/Lang/Stata/Sum-digits-of-an-integer b/Lang/Stata/Sum-digits-of-an-integer new file mode 120000 index 0000000000..7ff94e9456 --- /dev/null +++ b/Lang/Stata/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Stata \ No newline at end of file diff --git a/Lang/Stata/Sum-of-a-series b/Lang/Stata/Sum-of-a-series new file mode 120000 index 0000000000..4b6132a5f6 --- /dev/null +++ b/Lang/Stata/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Stata \ No newline at end of file diff --git a/Lang/Stata/Sum-of-squares b/Lang/Stata/Sum-of-squares new file mode 120000 index 0000000000..06816036a1 --- /dev/null +++ b/Lang/Stata/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Stata \ No newline at end of file diff --git a/Lang/Stata/System-time b/Lang/Stata/System-time new file mode 120000 index 0000000000..e193259a3b --- /dev/null +++ b/Lang/Stata/System-time @@ -0,0 +1 @@ +../../Task/System-time/Stata \ No newline at end of file diff --git a/Lang/Stata/Table-creation-Postal-addresses b/Lang/Stata/Table-creation-Postal-addresses new file mode 120000 index 0000000000..9bb660d501 --- /dev/null +++ b/Lang/Stata/Table-creation-Postal-addresses @@ -0,0 +1 @@ +../../Task/Table-creation-Postal-addresses/Stata \ No newline at end of file diff --git a/Lang/Stata/Towers-of-Hanoi b/Lang/Stata/Towers-of-Hanoi new file mode 120000 index 0000000000..d17c46cf9c --- /dev/null +++ b/Lang/Stata/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Stata \ No newline at end of file diff --git a/Lang/Stata/Unicode-variable-names b/Lang/Stata/Unicode-variable-names new file mode 120000 index 0000000000..4742411c15 --- /dev/null +++ b/Lang/Stata/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Stata \ No newline at end of file diff --git a/Lang/Stata/Zig-zag-matrix b/Lang/Stata/Zig-zag-matrix new file mode 120000 index 0000000000..b8a21450c5 --- /dev/null +++ b/Lang/Stata/Zig-zag-matrix @@ -0,0 +1 @@ +../../Task/Zig-zag-matrix/Stata \ No newline at end of file diff --git a/Lang/Swift/Catamorphism b/Lang/Swift/Catamorphism new file mode 120000 index 0000000000..264a528a31 --- /dev/null +++ b/Lang/Swift/Catamorphism @@ -0,0 +1 @@ +../../Task/Catamorphism/Swift \ No newline at end of file diff --git a/Lang/Swift/Find-limit-of-recursion b/Lang/Swift/Find-limit-of-recursion new file mode 120000 index 0000000000..d7e6272066 --- /dev/null +++ b/Lang/Swift/Find-limit-of-recursion @@ -0,0 +1 @@ +../../Task/Find-limit-of-recursion/Swift \ No newline at end of file diff --git a/Lang/Swift/Power-set b/Lang/Swift/Power-set new file mode 120000 index 0000000000..7c91969e71 --- /dev/null +++ b/Lang/Swift/Power-set @@ -0,0 +1 @@ +../../Task/Power-set/Swift \ No newline at end of file diff --git a/Lang/SystemVerilog/Fast-Fourier-transform b/Lang/SystemVerilog/Fast-Fourier-transform new file mode 120000 index 0000000000..4fdfac556a --- /dev/null +++ b/Lang/SystemVerilog/Fast-Fourier-transform @@ -0,0 +1 @@ +../../Task/Fast-Fourier-transform/SystemVerilog \ No newline at end of file diff --git a/Lang/Tcl/00DESCRIPTION b/Lang/Tcl/00DESCRIPTION index 5ad88d1a46..1930bff61c 100644 --- a/Lang/Tcl/00DESCRIPTION +++ b/Lang/Tcl/00DESCRIPTION @@ -157,4 +157,7 @@ Note that all variables can hold values of ''any'' type; the language does not i *[http://www.tcl.tk/man/ Tcl Documentation] *[http://wiki.tcl.tk Tcl Wiki] *[http://en.wikipedia.org/wiki/Tcl Wikipedia article] -*[http://en.wikibooks.org/wiki/Programming:Tcl Wikibook] \ No newline at end of file +*[http://en.wikibooks.org/wiki/Programming:Tcl Wikibook] + +==Todo== +[[Reports:Tasks_not_implemented_in_Tcl]] \ No newline at end of file diff --git a/Lang/TechBASIC/00DESCRIPTION b/Lang/TechBASIC/00DESCRIPTION index 9783def5cf..1c10f07295 100644 --- a/Lang/TechBASIC/00DESCRIPTION +++ b/Lang/TechBASIC/00DESCRIPTION @@ -1,5 +1,5 @@ -=={{header|TechBASIC}}== -{{language|TechBASIC +==techBASIC== +{{language|techBASIC |exec=interpreted/compiled |site=http://www.byteworks.us/Byte_Works/techBASIC.html |parampass=both @@ -9,99 +9,6 @@ {{language programming paradigm|Object-oriented}} {{implementation|BASIC}} -

Write Scientific and Educational Programs on the iPhone/iPad

+'''techBASIC''' is an implementation of [[:Category:BASIC|BASIC]] intended for development of [[wp:iOS|iOS]] apps ([[wp:iPhone|iPhone]] and [[wp:iPad|iPad]]). -== '''Overview''' == - -techBASIC has been around since 2011 and is a comprehensive software development and technical computing environment for programming, data collection, displaying sophisticated interactive graphics and analyzing data. - -techBASIC is a powerful matrix-rich version of the famously easy to use BASIC programming language. Their built-in help system, reference manual and web-based tutorials make it easy to start using techBASIC for real problems in programming, education and in the professional lab right away. - -And once you finish your app in techBASIC, compile it with techBASIC App Builder and XCode on your Macintosh to create a stand-alone app. You can share that app with others using Ad Hoc distribution or publish it on Apple’s App Store. - - -== '''Building iPhone & iPad Electronic Projects''' == - -Buy ready-built or DIY electronic kits, design, invent your own sensors, data collectors, a comprehensive scientific development environment right on your mobile device. Connect to internal and external sensors using techBASIC’s built-in commands. - -techBASIC brings the power of a desktop computer to your iPhone/iPad for programming, collecting and analyzing data, and visualizing and manipulating stunning 3D graphics. It’s a robust implementation of the famously easy to use BASIC Programming Language with specialized array and matrix commands. - -Scientists and engineers can collect and analyze complex data easily and accurately with techBASIC. The built-in floating-point libraries insure calculations are precise. Special classes make it easy to perform complex array and matrix calculations. The graphing capabilities allow you to display and interact with your data in new and amazing ways. And, data can be moved easily to and from your desktop computer. - -A new book from O’Reilly features techBASIC, showing how to access real-world Arduino, sensor and Bluetooth Low Energy apps in techBASIC. The book is available in print and ebook format.
 -Key Features: - - -== Collecting/Analyzing Data == -
    -
  • Send and receive data from Bluetooth LE devices (only on hardware that supports Bluetooth LE)--control the Internet of Things right from your iPhone or iPadCollect, analyze and display data right on your iPhone/iPad
    -
  • Use Bluetooth LE or WiFi to connect to Arduino using the Red Bear Arduino BLE Bridge or Roving Networks WiFly
    -
  • Collect data from outside sensors using HiJack
    -
  • Access to the accelerometer, magnetometer and gyroscope
    -
  • Get the current location and heading
    -
  • Analyze photos and images pixel-by-pixel
    -
  • Supports TCP/IP, HTTP and FTP for accessing information via WiFi connections

    -
  • Numeric integration for calculus
    -
  • Fit curves to data with polynomial and linear regression
    -
  • Solve simultaneous equations with matrix operations like LU decomposition
    -
  • Special functions for statistics -
-

- -== BASIC Programming == -
    -
  • Array and matrix commands like matrix inversion, determinants, matrix arithmetic and more.
    -
  • Step and trace debugger
    -
  • Set breakpoints with a tap
    -
  • See current variables, both local and global
    -
  • See everything in a variable, even large matrices
    -
  • 43 statements, 41 functions
    -
  • 35 classes with 362 methods, including GUI, graphics, sensor data collection and matrices -
-

- -== Create Stunning GUIs and Use all standard iOS controls == -
    -
  • Activity indicators
    -
  • Buttons
    -
  • Date pickers
    -
  • Images
    -
  • Labels
    -
  • Map views
    -
  • Pickers
    -
  • Progress bars
    -
  • Segmented controls
    -
  • Sliders
    -
  • Steppers
    -
  • Switches
    -
  • Tables
    -
  • Text fields
    -
  • Text views
    -
  • Web pages
    -
  • Add alerts
    -
  • Send emails
    -
  • Take photos or grab pictures from the photo library
 -
-

- -== Graphing/Plotting Capabilities == -
    -
  • Create a plot with only a few lines of code
    -
  • Pan and zoom plots with swipes and pinches
    -
  • Rotate 3D plots along an arbitrary axis
    -
  • Supports 2D or 3D Cartesian axis
    -
  • Polar, spherical and cylindrical axis
    -
  • Plot general surfaces
    -
  • Create error bars in 2 or 3 dimensions
    -
  • 2D and 3D vector plots
    -
  • Add custom callouts
 -
-

- -Apps for people who think.™ -

-
'''techBASIC''' initially introduced to Rosetta Code on January 29, 2017 by [http://rosettacode.org/wiki/User:George_McGinn]
techBASIC and the techBASIC logo are owned by Byte Works, Inc. -Text owned and copyrighted ©2017 by Byte Works, Inc. All Rights Reserved ----- -
- \ No newline at end of file +The homepage is located [http://www.byteworks.us/Byte_Works/techBASIC.html here.] \ No newline at end of file diff --git a/Lang/TypeScript/Sorting-algorithms-Quicksort b/Lang/TypeScript/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..4daf637794 --- /dev/null +++ b/Lang/TypeScript/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/TypeScript \ No newline at end of file diff --git a/Lang/UNIX-Shell/Calendar---for-REAL-programmers b/Lang/UNIX-Shell/Calendar---for-REAL-programmers new file mode 120000 index 0000000000..7fe33a203d --- /dev/null +++ b/Lang/UNIX-Shell/Calendar---for-REAL-programmers @@ -0,0 +1 @@ +../../Task/Calendar---for-REAL-programmers/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Digital-root b/Lang/UNIX-Shell/Digital-root new file mode 120000 index 0000000000..e371ef4e3c --- /dev/null +++ b/Lang/UNIX-Shell/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Dynamic-variable-names b/Lang/UNIX-Shell/Dynamic-variable-names new file mode 120000 index 0000000000..9a9f808450 --- /dev/null +++ b/Lang/UNIX-Shell/Dynamic-variable-names @@ -0,0 +1 @@ +../../Task/Dynamic-variable-names/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Even-or-odd b/Lang/UNIX-Shell/Even-or-odd new file mode 120000 index 0000000000..474a7a2347 --- /dev/null +++ b/Lang/UNIX-Shell/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Palindrome-detection b/Lang/UNIX-Shell/Palindrome-detection new file mode 120000 index 0000000000..c0d653c881 --- /dev/null +++ b/Lang/UNIX-Shell/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Parsing-RPN-calculator-algorithm b/Lang/UNIX-Shell/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..ea3e666010 --- /dev/null +++ b/Lang/UNIX-Shell/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Parsing-Shunting-yard-algorithm b/Lang/UNIX-Shell/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..88858b3ac0 --- /dev/null +++ b/Lang/UNIX-Shell/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Temperature-conversion b/Lang/UNIX-Shell/Temperature-conversion new file mode 120000 index 0000000000..9f63852053 --- /dev/null +++ b/Lang/UNIX-Shell/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/UNIX-Shell \ No newline at end of file diff --git a/Lang/Ursa/Sockets b/Lang/Ursa/Sockets new file mode 120000 index 0000000000..7f94dec1f6 --- /dev/null +++ b/Lang/Ursa/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Ursa \ No newline at end of file diff --git a/Lang/Ursala/00DESCRIPTION b/Lang/Ursala/00DESCRIPTION index aed2a4878f..96f14c4325 100644 --- a/Lang/Ursala/00DESCRIPTION +++ b/Lang/Ursala/00DESCRIPTION @@ -1,5 +1,4 @@ {{language|Ursala -|site= http://www.basis.netii.net/ursala |LCT=no }} {{language programming paradigm|Functional}} diff --git a/Lang/VBA/ABC-Problem b/Lang/VBA/ABC-Problem new file mode 120000 index 0000000000..462cd0eaeb --- /dev/null +++ b/Lang/VBA/ABC-Problem @@ -0,0 +1 @@ +../../Task/ABC-Problem/VBA \ No newline at end of file diff --git a/Lang/VBA/Abundant,-deficient-and-perfect-number-classifications b/Lang/VBA/Abundant,-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..01c5670319 --- /dev/null +++ b/Lang/VBA/Abundant,-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant,-deficient-and-perfect-number-classifications/VBA \ No newline at end of file diff --git a/Lang/VBA/Amicable-pairs b/Lang/VBA/Amicable-pairs new file mode 120000 index 0000000000..5fac6a0715 --- /dev/null +++ b/Lang/VBA/Amicable-pairs @@ -0,0 +1 @@ +../../Task/Amicable-pairs/VBA \ No newline at end of file diff --git a/Lang/VBA/Anagrams b/Lang/VBA/Anagrams new file mode 120000 index 0000000000..9829685561 --- /dev/null +++ b/Lang/VBA/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/VBA \ No newline at end of file diff --git a/Lang/VBA/Anonymous-recursion b/Lang/VBA/Anonymous-recursion new file mode 120000 index 0000000000..fcc5fada4e --- /dev/null +++ b/Lang/VBA/Anonymous-recursion @@ -0,0 +1 @@ +../../Task/Anonymous-recursion/VBA \ No newline at end of file diff --git a/Lang/VBA/Apply-a-callback-to-an-array b/Lang/VBA/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..bb846caf43 --- /dev/null +++ b/Lang/VBA/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/VBA \ No newline at end of file diff --git a/Lang/VBA/Array-concatenation b/Lang/VBA/Array-concatenation new file mode 120000 index 0000000000..f00815e6d4 --- /dev/null +++ b/Lang/VBA/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/VBA \ No newline at end of file diff --git a/Lang/VBA/Best-shuffle b/Lang/VBA/Best-shuffle new file mode 120000 index 0000000000..d00982ba9a --- /dev/null +++ b/Lang/VBA/Best-shuffle @@ -0,0 +1 @@ +../../Task/Best-shuffle/VBA \ No newline at end of file diff --git a/Lang/VBA/Binary-digits b/Lang/VBA/Binary-digits new file mode 120000 index 0000000000..49d17fbef3 --- /dev/null +++ b/Lang/VBA/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/VBA \ No newline at end of file diff --git a/Lang/VBA/Binary-strings b/Lang/VBA/Binary-strings new file mode 120000 index 0000000000..27061c6d67 --- /dev/null +++ b/Lang/VBA/Binary-strings @@ -0,0 +1 @@ +../../Task/Binary-strings/VBA \ No newline at end of file diff --git a/Lang/VBA/Bulls-and-cows b/Lang/VBA/Bulls-and-cows new file mode 120000 index 0000000000..7a940eae93 --- /dev/null +++ b/Lang/VBA/Bulls-and-cows @@ -0,0 +1 @@ +../../Task/Bulls-and-cows/VBA \ No newline at end of file diff --git a/Lang/VBA/Bulls-and-cows-Player b/Lang/VBA/Bulls-and-cows-Player new file mode 120000 index 0000000000..f32e0a0254 --- /dev/null +++ b/Lang/VBA/Bulls-and-cows-Player @@ -0,0 +1 @@ +../../Task/Bulls-and-cows-Player/VBA \ No newline at end of file diff --git a/Lang/VBA/Caesar-cipher b/Lang/VBA/Caesar-cipher new file mode 120000 index 0000000000..c4aa14b8d6 --- /dev/null +++ b/Lang/VBA/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/VBA \ No newline at end of file diff --git a/Lang/VBA/Call-an-object-method b/Lang/VBA/Call-an-object-method new file mode 120000 index 0000000000..51878525b3 --- /dev/null +++ b/Lang/VBA/Call-an-object-method @@ -0,0 +1 @@ +../../Task/Call-an-object-method/VBA \ No newline at end of file diff --git a/Lang/VBA/Check-that-file-exists b/Lang/VBA/Check-that-file-exists new file mode 120000 index 0000000000..143d841c75 --- /dev/null +++ b/Lang/VBA/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/VBA \ No newline at end of file diff --git a/Lang/VBA/Closest-pair-problem b/Lang/VBA/Closest-pair-problem new file mode 120000 index 0000000000..e501f60d58 --- /dev/null +++ b/Lang/VBA/Closest-pair-problem @@ -0,0 +1 @@ +../../Task/Closest-pair-problem/VBA \ No newline at end of file diff --git a/Lang/VBA/Color-of-a-screen-pixel b/Lang/VBA/Color-of-a-screen-pixel new file mode 120000 index 0000000000..4abfa19b99 --- /dev/null +++ b/Lang/VBA/Color-of-a-screen-pixel @@ -0,0 +1 @@ +../../Task/Color-of-a-screen-pixel/VBA \ No newline at end of file diff --git a/Lang/VBA/Combinations b/Lang/VBA/Combinations new file mode 120000 index 0000000000..24f75f768f --- /dev/null +++ b/Lang/VBA/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/VBA \ No newline at end of file diff --git a/Lang/VBA/Comma-quibbling b/Lang/VBA/Comma-quibbling new file mode 120000 index 0000000000..321365eae1 --- /dev/null +++ b/Lang/VBA/Comma-quibbling @@ -0,0 +1 @@ +../../Task/Comma-quibbling/VBA \ No newline at end of file diff --git a/Lang/VBA/Conditional-structures b/Lang/VBA/Conditional-structures new file mode 120000 index 0000000000..7b5eb87ba5 --- /dev/null +++ b/Lang/VBA/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/VBA \ No newline at end of file diff --git a/Lang/VBA/Create-a-two-dimensional-array-at-runtime b/Lang/VBA/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..3e2dce2d1a --- /dev/null +++ b/Lang/VBA/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/VBA \ No newline at end of file diff --git a/Lang/VBA/Day-of-the-week b/Lang/VBA/Day-of-the-week new file mode 120000 index 0000000000..576bae4906 --- /dev/null +++ b/Lang/VBA/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/VBA \ No newline at end of file diff --git a/Lang/VBA/Delete-a-file b/Lang/VBA/Delete-a-file new file mode 120000 index 0000000000..d7675231c3 --- /dev/null +++ b/Lang/VBA/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/VBA \ No newline at end of file diff --git a/Lang/VBA/Detect-division-by-zero b/Lang/VBA/Detect-division-by-zero new file mode 120000 index 0000000000..2376221a3d --- /dev/null +++ b/Lang/VBA/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/VBA \ No newline at end of file diff --git a/Lang/VBA/Determine-if-a-string-is-numeric b/Lang/VBA/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..0e47e1fea2 --- /dev/null +++ b/Lang/VBA/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/VBA \ No newline at end of file diff --git a/Lang/VBA/Empty-directory b/Lang/VBA/Empty-directory new file mode 120000 index 0000000000..1d2eec5b15 --- /dev/null +++ b/Lang/VBA/Empty-directory @@ -0,0 +1 @@ +../../Task/Empty-directory/VBA \ No newline at end of file diff --git a/Lang/VBA/Empty-program b/Lang/VBA/Empty-program new file mode 120000 index 0000000000..7e5c69e290 --- /dev/null +++ b/Lang/VBA/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/VBA \ No newline at end of file diff --git a/Lang/VBA/Ethiopian-multiplication b/Lang/VBA/Ethiopian-multiplication new file mode 120000 index 0000000000..41cef96302 --- /dev/null +++ b/Lang/VBA/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/VBA \ No newline at end of file diff --git a/Lang/VBA/Even-or-odd b/Lang/VBA/Even-or-odd new file mode 120000 index 0000000000..e2d9675b68 --- /dev/null +++ b/Lang/VBA/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/VBA \ No newline at end of file diff --git a/Lang/VBA/Exceptions b/Lang/VBA/Exceptions new file mode 120000 index 0000000000..7df38be353 --- /dev/null +++ b/Lang/VBA/Exceptions @@ -0,0 +1 @@ +../../Task/Exceptions/VBA \ No newline at end of file diff --git a/Lang/VBA/Extensible-prime-generator b/Lang/VBA/Extensible-prime-generator new file mode 120000 index 0000000000..bf5cf88847 --- /dev/null +++ b/Lang/VBA/Extensible-prime-generator @@ -0,0 +1 @@ +../../Task/Extensible-prime-generator/VBA \ No newline at end of file diff --git a/Lang/VBA/Factorial b/Lang/VBA/Factorial new file mode 120000 index 0000000000..82581749ca --- /dev/null +++ b/Lang/VBA/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/VBA \ No newline at end of file diff --git a/Lang/VBA/Fibonacci-n-step-number-sequences b/Lang/VBA/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..ec1a03acc2 --- /dev/null +++ b/Lang/VBA/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/VBA \ No newline at end of file diff --git a/Lang/VBA/File-input-output b/Lang/VBA/File-input-output new file mode 120000 index 0000000000..e5e7326d2c --- /dev/null +++ b/Lang/VBA/File-input-output @@ -0,0 +1 @@ +../../Task/File-input-output/VBA \ No newline at end of file diff --git a/Lang/VBA/Filter b/Lang/VBA/Filter new file mode 120000 index 0000000000..014f0cc0b7 --- /dev/null +++ b/Lang/VBA/Filter @@ -0,0 +1 @@ +../../Task/Filter/VBA \ No newline at end of file diff --git a/Lang/VBA/Find-limit-of-recursion b/Lang/VBA/Find-limit-of-recursion new file mode 120000 index 0000000000..2adf3f1a5f --- /dev/null +++ b/Lang/VBA/Find-limit-of-recursion @@ -0,0 +1 @@ +../../Task/Find-limit-of-recursion/VBA \ No newline at end of file diff --git a/Lang/VBA/Five-weekends b/Lang/VBA/Five-weekends new file mode 120000 index 0000000000..dea485a05a --- /dev/null +++ b/Lang/VBA/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/VBA \ No newline at end of file diff --git a/Lang/VBA/FizzBuzz b/Lang/VBA/FizzBuzz new file mode 120000 index 0000000000..84e206d58a --- /dev/null +++ b/Lang/VBA/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/VBA \ No newline at end of file diff --git a/Lang/VBA/Function-definition b/Lang/VBA/Function-definition new file mode 120000 index 0000000000..39bf2ae72c --- /dev/null +++ b/Lang/VBA/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/VBA \ No newline at end of file diff --git a/Lang/VBA/Generate-lower-case-ASCII-alphabet b/Lang/VBA/Generate-lower-case-ASCII-alphabet new file mode 120000 index 0000000000..a01f872184 --- /dev/null +++ b/Lang/VBA/Generate-lower-case-ASCII-alphabet @@ -0,0 +1 @@ +../../Task/Generate-lower-case-ASCII-alphabet/VBA \ No newline at end of file diff --git a/Lang/VBA/Guess-the-number b/Lang/VBA/Guess-the-number new file mode 120000 index 0000000000..127d0290a0 --- /dev/null +++ b/Lang/VBA/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/VBA \ No newline at end of file diff --git a/Lang/VBA/Happy-numbers b/Lang/VBA/Happy-numbers new file mode 120000 index 0000000000..acbd362bc5 --- /dev/null +++ b/Lang/VBA/Happy-numbers @@ -0,0 +1 @@ +../../Task/Happy-numbers/VBA \ No newline at end of file diff --git a/Lang/VBA/Langtons-ant b/Lang/VBA/Langtons-ant new file mode 120000 index 0000000000..61aa4c4e6e --- /dev/null +++ b/Lang/VBA/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/VBA \ No newline at end of file diff --git a/Lang/VBA/Luhn-test-of-credit-card-numbers b/Lang/VBA/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..4b76c1f96d --- /dev/null +++ b/Lang/VBA/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/VBA \ No newline at end of file diff --git a/Lang/VBA/Middle-three-digits b/Lang/VBA/Middle-three-digits new file mode 120000 index 0000000000..37947d5e0e --- /dev/null +++ b/Lang/VBA/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/VBA \ No newline at end of file diff --git a/Lang/VBA/Minesweeper-game b/Lang/VBA/Minesweeper-game new file mode 120000 index 0000000000..6f425ae663 --- /dev/null +++ b/Lang/VBA/Minesweeper-game @@ -0,0 +1 @@ +../../Task/Minesweeper-game/VBA \ No newline at end of file diff --git a/Lang/VBA/Morse-code b/Lang/VBA/Morse-code new file mode 120000 index 0000000000..ecd6368e50 --- /dev/null +++ b/Lang/VBA/Morse-code @@ -0,0 +1 @@ +../../Task/Morse-code/VBA \ No newline at end of file diff --git a/Lang/VBA/Multiplication-tables b/Lang/VBA/Multiplication-tables new file mode 120000 index 0000000000..77920949af --- /dev/null +++ b/Lang/VBA/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/VBA \ No newline at end of file diff --git a/Lang/VBA/Odd-word-problem b/Lang/VBA/Odd-word-problem new file mode 120000 index 0000000000..396d42f35d --- /dev/null +++ b/Lang/VBA/Odd-word-problem @@ -0,0 +1 @@ +../../Task/Odd-word-problem/VBA \ No newline at end of file diff --git a/Lang/VBA/Penneys-game b/Lang/VBA/Penneys-game new file mode 120000 index 0000000000..bb23b66900 --- /dev/null +++ b/Lang/VBA/Penneys-game @@ -0,0 +1 @@ +../../Task/Penneys-game/VBA \ No newline at end of file diff --git a/Lang/VBA/Phrase-reversals b/Lang/VBA/Phrase-reversals new file mode 120000 index 0000000000..56845e1fd0 --- /dev/null +++ b/Lang/VBA/Phrase-reversals @@ -0,0 +1 @@ +../../Task/Phrase-reversals/VBA \ No newline at end of file diff --git a/Lang/VBA/Pick-random-element b/Lang/VBA/Pick-random-element new file mode 120000 index 0000000000..682859dda8 --- /dev/null +++ b/Lang/VBA/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/VBA \ No newline at end of file diff --git a/Lang/VBA/Pig-the-dice-game b/Lang/VBA/Pig-the-dice-game new file mode 120000 index 0000000000..7c5885eebb --- /dev/null +++ b/Lang/VBA/Pig-the-dice-game @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game/VBA \ No newline at end of file diff --git a/Lang/VBA/Price-fraction b/Lang/VBA/Price-fraction new file mode 120000 index 0000000000..3dbcc8f49b --- /dev/null +++ b/Lang/VBA/Price-fraction @@ -0,0 +1 @@ +../../Task/Price-fraction/VBA \ No newline at end of file diff --git a/Lang/VBA/Primality-by-trial-division b/Lang/VBA/Primality-by-trial-division new file mode 120000 index 0000000000..086622daeb --- /dev/null +++ b/Lang/VBA/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/VBA \ No newline at end of file diff --git a/Lang/VBA/Remove-duplicate-elements b/Lang/VBA/Remove-duplicate-elements new file mode 120000 index 0000000000..fd1b6b355e --- /dev/null +++ b/Lang/VBA/Remove-duplicate-elements @@ -0,0 +1 @@ +../../Task/Remove-duplicate-elements/VBA \ No newline at end of file diff --git a/Lang/VBA/Remove-lines-from-a-file b/Lang/VBA/Remove-lines-from-a-file new file mode 120000 index 0000000000..5b798755cf --- /dev/null +++ b/Lang/VBA/Remove-lines-from-a-file @@ -0,0 +1 @@ +../../Task/Remove-lines-from-a-file/VBA \ No newline at end of file diff --git a/Lang/VBA/Return-multiple-values b/Lang/VBA/Return-multiple-values new file mode 120000 index 0000000000..59aa99ab62 --- /dev/null +++ b/Lang/VBA/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/VBA \ No newline at end of file diff --git a/Lang/VBA/Reverse-words-in-a-string b/Lang/VBA/Reverse-words-in-a-string new file mode 120000 index 0000000000..11288ae4ca --- /dev/null +++ b/Lang/VBA/Reverse-words-in-a-string @@ -0,0 +1 @@ +../../Task/Reverse-words-in-a-string/VBA \ No newline at end of file diff --git a/Lang/VBA/Roman-numerals-Decode b/Lang/VBA/Roman-numerals-Decode new file mode 120000 index 0000000000..1ee9fd6518 --- /dev/null +++ b/Lang/VBA/Roman-numerals-Decode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Decode/VBA \ No newline at end of file diff --git a/Lang/VBA/Run-length-encoding b/Lang/VBA/Run-length-encoding new file mode 120000 index 0000000000..5b1f7c24e5 --- /dev/null +++ b/Lang/VBA/Run-length-encoding @@ -0,0 +1 @@ +../../Task/Run-length-encoding/VBA \ No newline at end of file diff --git a/Lang/VBA/Sequence-of-non-squares b/Lang/VBA/Sequence-of-non-squares new file mode 120000 index 0000000000..e46ce644e4 --- /dev/null +++ b/Lang/VBA/Sequence-of-non-squares @@ -0,0 +1 @@ +../../Task/Sequence-of-non-squares/VBA \ No newline at end of file diff --git a/Lang/VBA/String-concatenation b/Lang/VBA/String-concatenation new file mode 120000 index 0000000000..4319458b98 --- /dev/null +++ b/Lang/VBA/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/VBA \ No newline at end of file diff --git a/Lang/VBA/Sum-multiples-of-3-and-5 b/Lang/VBA/Sum-multiples-of-3-and-5 new file mode 120000 index 0000000000..2f47cbbb2d --- /dev/null +++ b/Lang/VBA/Sum-multiples-of-3-and-5 @@ -0,0 +1 @@ +../../Task/Sum-multiples-of-3-and-5/VBA \ No newline at end of file diff --git a/Lang/VBA/Temperature-conversion b/Lang/VBA/Temperature-conversion new file mode 120000 index 0000000000..809ce2f678 --- /dev/null +++ b/Lang/VBA/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/VBA \ No newline at end of file diff --git a/Lang/VBA/Test-a-function b/Lang/VBA/Test-a-function new file mode 120000 index 0000000000..bf5520ae01 --- /dev/null +++ b/Lang/VBA/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/VBA \ No newline at end of file diff --git a/Lang/VBA/The-Twelve-Days-of-Christmas b/Lang/VBA/The-Twelve-Days-of-Christmas new file mode 120000 index 0000000000..7515624815 --- /dev/null +++ b/Lang/VBA/The-Twelve-Days-of-Christmas @@ -0,0 +1 @@ +../../Task/The-Twelve-Days-of-Christmas/VBA \ No newline at end of file diff --git a/Lang/VBA/Tic-tac-toe b/Lang/VBA/Tic-tac-toe new file mode 120000 index 0000000000..327a3d4392 --- /dev/null +++ b/Lang/VBA/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/VBA \ No newline at end of file diff --git a/Lang/VBA/Tokenize-a-string b/Lang/VBA/Tokenize-a-string new file mode 120000 index 0000000000..eac06d5257 --- /dev/null +++ b/Lang/VBA/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/VBA \ No newline at end of file diff --git a/Lang/VBA/Vigen-re-cipher b/Lang/VBA/Vigen-re-cipher new file mode 120000 index 0000000000..94e27ff942 --- /dev/null +++ b/Lang/VBA/Vigen-re-cipher @@ -0,0 +1 @@ +../../Task/Vigen-re-cipher/VBA \ No newline at end of file diff --git a/Lang/VBA/Web-scraping b/Lang/VBA/Web-scraping new file mode 120000 index 0000000000..6bd4ded962 --- /dev/null +++ b/Lang/VBA/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/VBA \ No newline at end of file diff --git a/Lang/VBA/Window-creation b/Lang/VBA/Window-creation new file mode 120000 index 0000000000..5e4960d376 --- /dev/null +++ b/Lang/VBA/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/VBA \ No newline at end of file diff --git a/Lang/VBA/XML-Input b/Lang/VBA/XML-Input new file mode 120000 index 0000000000..1fb829a97d --- /dev/null +++ b/Lang/VBA/XML-Input @@ -0,0 +1 @@ +../../Task/XML-Input/VBA \ No newline at end of file diff --git a/Lang/VBScript/Guess-the-number-With-feedback b/Lang/VBScript/Guess-the-number-With-feedback new file mode 120000 index 0000000000..1d3ce681e3 --- /dev/null +++ b/Lang/VBScript/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/VBScript \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Balanced-brackets b/Lang/Visual-Basic-.NET/Balanced-brackets new file mode 120000 index 0000000000..87933fc913 --- /dev/null +++ b/Lang/Visual-Basic-.NET/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Hello-world-Text b/Lang/Visual-Basic-.NET/Hello-world-Text new file mode 120000 index 0000000000..84a700bd1f --- /dev/null +++ b/Lang/Visual-Basic-.NET/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Ray-casting-algorithm b/Lang/Visual-Basic-.NET/Ray-casting-algorithm new file mode 120000 index 0000000000..e260aac393 --- /dev/null +++ b/Lang/Visual-Basic-.NET/Ray-casting-algorithm @@ -0,0 +1 @@ +../../Task/Ray-casting-algorithm/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/String-interpolation--included- b/Lang/Visual-Basic-.NET/String-interpolation--included- new file mode 120000 index 0000000000..fbdaabb756 --- /dev/null +++ b/Lang/Visual-Basic-.NET/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Variables b/Lang/Visual-Basic-.NET/Variables new file mode 120000 index 0000000000..70e204ad02 --- /dev/null +++ b/Lang/Visual-Basic-.NET/Variables @@ -0,0 +1 @@ +../../Task/Variables/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic/100-doors b/Lang/Visual-Basic/100-doors new file mode 120000 index 0000000000..e927facd96 --- /dev/null +++ b/Lang/Visual-Basic/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/Binary-digits b/Lang/Visual-Basic/Binary-digits new file mode 120000 index 0000000000..03251c3c39 --- /dev/null +++ b/Lang/Visual-Basic/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/Check-that-file-exists b/Lang/Visual-Basic/Check-that-file-exists new file mode 120000 index 0000000000..e8ad930fe4 --- /dev/null +++ b/Lang/Visual-Basic/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/Conditional-structures b/Lang/Visual-Basic/Conditional-structures new file mode 120000 index 0000000000..d17c6a8ab4 --- /dev/null +++ b/Lang/Visual-Basic/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/Formatted-numeric-output b/Lang/Visual-Basic/Formatted-numeric-output new file mode 120000 index 0000000000..039819eb34 --- /dev/null +++ b/Lang/Visual-Basic/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/Leap-year b/Lang/Visual-Basic/Leap-year new file mode 120000 index 0000000000..52a83c9514 --- /dev/null +++ b/Lang/Visual-Basic/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/Null-object b/Lang/Visual-Basic/Null-object new file mode 120000 index 0000000000..40fb804ab8 --- /dev/null +++ b/Lang/Visual-Basic/Null-object @@ -0,0 +1 @@ +../../Task/Null-object/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/Rot-13 b/Lang/Visual-Basic/Rot-13 new file mode 120000 index 0000000000..70f0da2e82 --- /dev/null +++ b/Lang/Visual-Basic/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/Visual-Basic \ No newline at end of file diff --git a/Lang/Wart/00DESCRIPTION b/Lang/Wart/00DESCRIPTION index 3150915b1b..345fa160fe 100644 --- a/Lang/Wart/00DESCRIPTION +++ b/Lang/Wart/00DESCRIPTION @@ -37,7 +37,7 @@ subtract 3 :from 4 These are all hard open questions, not expected to be definitively answered anytime soon. Wart is an experiment, and looking for feedback from people unafraid to bounce between language and implementation. If that's you, check it out: http://github.com/akkartik/wart#readme -To run the following examples: +To run the following examples in most places (but not Windows): $ git clone http://github.com/akkartik/wart $ cd wart diff --git a/Lang/Wart/N-queens-problem b/Lang/Wart/N-queens-problem new file mode 120000 index 0000000000..a5d1163855 --- /dev/null +++ b/Lang/Wart/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Wart \ No newline at end of file diff --git a/Lang/X86-Assembly/Balanced-brackets b/Lang/X86-Assembly/Balanced-brackets new file mode 120000 index 0000000000..490a53532c --- /dev/null +++ b/Lang/X86-Assembly/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Echo-server b/Lang/X86-Assembly/Echo-server new file mode 120000 index 0000000000..6f8bf4654f --- /dev/null +++ b/Lang/X86-Assembly/Echo-server @@ -0,0 +1 @@ +../../Task/Echo-server/X86-Assembly \ No newline at end of file diff --git a/Lang/X86-Assembly/Loops-While b/Lang/X86-Assembly/Loops-While new file mode 120000 index 0000000000..abc3dba44a --- /dev/null +++ b/Lang/X86-Assembly/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/X86-Assembly \ No newline at end of file diff --git a/Lang/XLISP/Accumulator-factory b/Lang/XLISP/Accumulator-factory new file mode 120000 index 0000000000..3de57e6b6f --- /dev/null +++ b/Lang/XLISP/Accumulator-factory @@ -0,0 +1 @@ +../../Task/Accumulator-factory/XLISP \ No newline at end of file diff --git a/Lang/XLISP/Address-of-a-variable b/Lang/XLISP/Address-of-a-variable new file mode 120000 index 0000000000..39887ec482 --- /dev/null +++ b/Lang/XLISP/Address-of-a-variable @@ -0,0 +1 @@ +../../Task/Address-of-a-variable/XLISP \ No newline at end of file diff --git a/Lang/XLISP/Greatest-common-divisor b/Lang/XLISP/Greatest-common-divisor new file mode 120000 index 0000000000..4b65d7188b --- /dev/null +++ b/Lang/XLISP/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/XLISP \ No newline at end of file diff --git a/Lang/XLISP/Priority-queue b/Lang/XLISP/Priority-queue new file mode 120000 index 0000000000..73ae652fd8 --- /dev/null +++ b/Lang/XLISP/Priority-queue @@ -0,0 +1 @@ +../../Task/Priority-queue/XLISP \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/Execute-Brain---- b/Lang/ZX-Spectrum-Basic/Execute-Brain---- new file mode 120000 index 0000000000..4deac5017a --- /dev/null +++ b/Lang/ZX-Spectrum-Basic/Execute-Brain---- @@ -0,0 +1 @@ +../../Task/Execute-Brain----/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/Infinity b/Lang/ZX-Spectrum-Basic/Infinity new file mode 120000 index 0000000000..6a8a886445 --- /dev/null +++ b/Lang/ZX-Spectrum-Basic/Infinity @@ -0,0 +1 @@ +../../Task/Infinity/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/Joystick-position b/Lang/ZX-Spectrum-Basic/Joystick-position new file mode 120000 index 0000000000..b21eb80927 --- /dev/null +++ b/Lang/ZX-Spectrum-Basic/Joystick-position @@ -0,0 +1 @@ +../../Task/Joystick-position/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Lang/ZX-Spectrum-Basic/Pascals-triangle b/Lang/ZX-Spectrum-Basic/Pascals-triangle new file mode 120000 index 0000000000..f561a8c668 --- /dev/null +++ b/Lang/ZX-Spectrum-Basic/Pascals-triangle @@ -0,0 +1 @@ +../../Task/Pascals-triangle/ZX-Spectrum-Basic \ No newline at end of file diff --git a/Lang/Zkl/00DESCRIPTION b/Lang/Zkl/00DESCRIPTION index 42aae14b69..760e7b5d44 100644 --- a/Lang/Zkl/00DESCRIPTION +++ b/Lang/Zkl/00DESCRIPTION @@ -10,10 +10,17 @@ |hopl=no |tags=zkl }} -zkl is a general purpose object oriented programming language. It is imperative but borrows concepts from many programming paradigms, including functional and prototype based. It is curly-bracketed, dynamic, reflective, and threaded. It has built in garbage collection, strings, lists, dictionaries, threads, fibers (continuations and co-routines) and more. The syntax strongly resembles the C programming language while the data model is closer to that of Python and Smalltalk. +zkl is a general purpose object oriented programming language. +It is imperative but borrows concepts from many programming paradigms, including functional and prototype based. +It is curly-bracketed, dynamic, reflective, and threaded. +It has built in garbage collection, strings, lists, dictionaries, threads, fibers (continuations and co-routines) and more. +The syntax strongly resembles the C programming language while the data model is closer to that of Python and Smalltalk. The goals of the language are rapid prototyping and programmer productivity. Program speed and the the constraints of production oriented programming are not high on the "needs" list. -It is open source and free. Download, compile and play with it. The VM is written in C, it compiles with clang, GCC or VisualStudio (makefiles, project files included) on Linux/FreeBSD/MS Windows. Running it is old school: command line or REPL, no IDE or GUI. Will work with emacs or vi! I use c mode. +It is open source and free. Download, compile and play with it. +The VM is written in C, it compiles with clang, GCC or VisualStudio (makefiles, project files included) on Linux/FreeBSD/MS Windows. +Running it is old school: command line or REPL, no IDE or GUI. +Will work with emacs or vi! I use c mode. == External Links and References == === Web Pages === @@ -21,4 +28,7 @@ It is open source and free. Download, compile and play with it. The VM is writte * [http://www.zenkinetic.com/zklDownloads.html zkl downloads page] === Books === -* [http://www.zenkinetic.com/Documents/zklManual.pdf The zkl programming language and reference manual (PDF)] \ No newline at end of file +* [http://www.zenkinetic.com/Documents/zklManual.pdf The zkl programming language and reference manual (PDF)] + +==Todo== +[[Reports:Tasks_not_implemented_in_Zkl]] \ No newline at end of file diff --git a/Task/100-doors/Astro/100-doors.astro b/Task/100-doors/Astro/100-doors.astro index fd1782d362..1ef6705711 100644 --- a/Task/100-doors/Astro/100-doors.astro +++ b/Task/100-doors/Astro/100-doors.astro @@ -1,4 +1,5 @@ -var doors = falses 100 -for a in [:101]: - for b in [a:a:101]: doors[b] = !doors[b] - print "Door $a is $('open.' if doors[a] else 'closed.')" +var doors = falses(100) +for a in 1..100: for b in a..a..100: + doors[b] = not doors[b] +for a in 1..100: + print "Door $a is $((doors[a]) ? 'open.': 'closed.')" diff --git a/Task/100-doors/BASIC/100-doors-1.basic b/Task/100-doors/BASIC/100-doors-1.basic index dd92311c2f..75aba4f22e 100644 --- a/Task/100-doors/BASIC/100-doors-1.basic +++ b/Task/100-doors/BASIC/100-doors-1.basic @@ -1,22 +1,11 @@ -REM "100 Doors" program for QB64 BASIC (http://www.qb64.net/), a QuickBASIC-like compiler. -REM Author: G. A. Tippery -REM Date: 12-Feb-2014 -REM -REM Unoptimized (naive) version, per specifications at http://rosettacode.org/wiki/100_doors - -DEFINT A-Z -CONST N = 100 -DIM door(N) - -FOR stride = 1 TO N - FOR index = stride TO N STEP stride - LET door(index) = NOT (door(index)) - NEXT index -NEXT stride - -PRINT "Open doors:" -FOR index = 1 TO N - IF door(index) THEN PRINT index -NEXT index - -END + 100 : + 110 REM 100 DOORS PROBLEM + 120 : + 130 DIM D(100) + 140 FOR P = 1 TO 100 + 150 FOR T = P TO 100 STEP P + 160 D(T) = NOT D(T): NEXT T + 170 NEXT P + 180 FOR I = 1 TO 100 + 190 IF D(I) THEN PRINT I;" "; + 200 NEXT I diff --git a/Task/100-doors/BASIC/100-doors-2.basic b/Task/100-doors/BASIC/100-doors-2.basic index f2179f24e0..b5630f49ac 100644 --- a/Task/100-doors/BASIC/100-doors-2.basic +++ b/Task/100-doors/BASIC/100-doors-2.basic @@ -1,16 +1,34 @@ -DIM doors(0 TO 99) -FOR pass = 0 TO 99 - FOR door = pass TO 99 STEP pass + 1 - PRINT doors(door) - PRINT NOT doors(door) - doors(door) = NOT doors(door) - NEXT door -NEXT pass -FOR i = 0 TO 99 - PRINT "Door #"; i + 1; " is "; - IF NOT doors(i) THEN - PRINT "closed" - ELSE - PRINT "open" - END IF -NEXT i +# 100 doors problem +dim d(100) + +# simple solution +print "simple solution" +gosub initialize +for t = 1 to 100 + for j = t to 100 step t + d[j-1] = not d[j-1] + next j +next t +gosub showopen + +# more optimized solution +print "more optimized solution" +gosub initialize +for t = 1 to 10 + d[t^2-1] = true +next t +gosub showopen +end + +initialize: +for t = 1 to d[?] + d[t-1] = false # closed +next t +return + +showopen: +for t = 1 to d[?] + print d[t-1]+ " "; + if t%10 = 0 then print +next t +return diff --git a/Task/100-doors/BASIC/100-doors-3.basic b/Task/100-doors/BASIC/100-doors-3.basic index ddaffaa2c1..4aa6f409d4 100644 --- a/Task/100-doors/BASIC/100-doors-3.basic +++ b/Task/100-doors/BASIC/100-doors-3.basic @@ -1,12 +1,9 @@ -DIM doors(0 TO 99) -FOR door = 0 TO 99 - IF INT(SQR(door)) = SQR(door) THEN doors(door) = -1 -NEXT door -FOR i = 0 TO 99 - PRINT "Door #"; i + 1; " is "; - IF NOT doors(i) THEN - PRINT "closed" - ELSE - PRINT "open" - END IF -NEXT i +10 DIM D(100) +20 FOR I=1 TO 100 +30 FOR J=I TO 100 STEP I +40 D(J) = NOT D(J) +50 NEXT J +60 NEXT I +70 FOR I=1 TO 100 +80 IF D(I) THEN PRINT I, +90 NEXT I diff --git a/Task/100-doors/BASIC/100-doors-4.basic b/Task/100-doors/BASIC/100-doors-4.basic index 14a02c2b80..dd92311c2f 100644 --- a/Task/100-doors/BASIC/100-doors-4.basic +++ b/Task/100-doors/BASIC/100-doors-4.basic @@ -1,10 +1,22 @@ -'lrcvs 04.11.12 -cls -x = 1 : y = 3 : z = 0 -print x + " Open" -do -z = x + y -print z + " Open" -x = z : y = y + 2 -until z >= 100 -end +REM "100 Doors" program for QB64 BASIC (http://www.qb64.net/), a QuickBASIC-like compiler. +REM Author: G. A. Tippery +REM Date: 12-Feb-2014 +REM +REM Unoptimized (naive) version, per specifications at http://rosettacode.org/wiki/100_doors + +DEFINT A-Z +CONST N = 100 +DIM door(N) + +FOR stride = 1 TO N + FOR index = stride TO N STEP stride + LET door(index) = NOT (door(index)) + NEXT index +NEXT stride + +PRINT "Open doors:" +FOR index = 1 TO N + IF door(index) THEN PRINT index +NEXT index + +END diff --git a/Task/100-doors/BASIC/100-doors-5.basic b/Task/100-doors/BASIC/100-doors-5.basic index 4229d9c86a..f2179f24e0 100644 --- a/Task/100-doors/BASIC/100-doors-5.basic +++ b/Task/100-doors/BASIC/100-doors-5.basic @@ -1,9 +1,16 @@ -10 DIM D(100) -20 FOR I=1 TO 100 -30 FOR J=I TO 100 STEP I -40 LET D(J)=NOT D(J) -50 NEXT J -60 NEXT I -70 FOR I=1 TO 100 -80 IF D(I) THEN PRINT I, -90 NEXT I +DIM doors(0 TO 99) +FOR pass = 0 TO 99 + FOR door = pass TO 99 STEP pass + 1 + PRINT doors(door) + PRINT NOT doors(door) + doors(door) = NOT doors(door) + NEXT door +NEXT pass +FOR i = 0 TO 99 + PRINT "Door #"; i + 1; " is "; + IF NOT doors(i) THEN + PRINT "closed" + ELSE + PRINT "open" + END IF +NEXT i diff --git a/Task/100-doors/BASIC/100-doors-6.basic b/Task/100-doors/BASIC/100-doors-6.basic index b5630f49ac..ddaffaa2c1 100644 --- a/Task/100-doors/BASIC/100-doors-6.basic +++ b/Task/100-doors/BASIC/100-doors-6.basic @@ -1,34 +1,12 @@ -# 100 doors problem -dim d(100) - -# simple solution -print "simple solution" -gosub initialize -for t = 1 to 100 - for j = t to 100 step t - d[j-1] = not d[j-1] - next j -next t -gosub showopen - -# more optimized solution -print "more optimized solution" -gosub initialize -for t = 1 to 10 - d[t^2-1] = true -next t -gosub showopen -end - -initialize: -for t = 1 to d[?] - d[t-1] = false # closed -next t -return - -showopen: -for t = 1 to d[?] - print d[t-1]+ " "; - if t%10 = 0 then print -next t -return +DIM doors(0 TO 99) +FOR door = 0 TO 99 + IF INT(SQR(door)) = SQR(door) THEN doors(door) = -1 +NEXT door +FOR i = 0 TO 99 + PRINT "Door #"; i + 1; " is "; + IF NOT doors(i) THEN + PRINT "closed" + ELSE + PRINT "open" + END IF +NEXT i diff --git a/Task/100-doors/BASIC/100-doors-7.basic b/Task/100-doors/BASIC/100-doors-7.basic index 4aa6f409d4..14a02c2b80 100644 --- a/Task/100-doors/BASIC/100-doors-7.basic +++ b/Task/100-doors/BASIC/100-doors-7.basic @@ -1,9 +1,10 @@ -10 DIM D(100) -20 FOR I=1 TO 100 -30 FOR J=I TO 100 STEP I -40 D(J) = NOT D(J) -50 NEXT J -60 NEXT I -70 FOR I=1 TO 100 -80 IF D(I) THEN PRINT I, -90 NEXT I +'lrcvs 04.11.12 +cls +x = 1 : y = 3 : z = 0 +print x + " Open" +do +z = x + y +print z + " Open" +x = z : y = y + 2 +until z >= 100 +end diff --git a/Task/100-doors/BASIC/100-doors-8.basic b/Task/100-doors/BASIC/100-doors-8.basic new file mode 100644 index 0000000000..4229d9c86a --- /dev/null +++ b/Task/100-doors/BASIC/100-doors-8.basic @@ -0,0 +1,9 @@ +10 DIM D(100) +20 FOR I=1 TO 100 +30 FOR J=I TO 100 STEP I +40 LET D(J)=NOT D(J) +50 NEXT J +60 NEXT I +70 FOR I=1 TO 100 +80 IF D(I) THEN PRINT I, +90 NEXT I diff --git a/Task/100-doors/C-sharp/100-doors-2.cs b/Task/100-doors/C-sharp/100-doors-2.cs index eb6c4248a1..1b18af4e1d 100644 --- a/Task/100-doors/C-sharp/100-doors-2.cs +++ b/Task/100-doors/C-sharp/100-doors-2.cs @@ -7,9 +7,10 @@ namespace ConsoleApplication1 { //The o variable stores the number of the next OPEN door. int o = 1; - - //The n variable is used to help calculate the next value of the o variable. - int n = 0; + int f = 1; + int l = 5; + Random r = new Random(); + o = r.Next(f, l); //The d variable determines the door to be output next. for (int d = 1; d <= 100; d++) @@ -18,8 +19,9 @@ namespace ConsoleApplication1 if (d == o) { Console.WriteLine("Open"); - n++; - o += 2 * n + 1; + f = f + 5; + l = l + 5; + o = r.Next(f, l); } else Console.WriteLine("Closed"); diff --git a/Task/100-doors/Common-Lisp/100-doors-3.lisp b/Task/100-doors/Common-Lisp/100-doors-3.lisp index 7d2e52d87e..2fe09ee83f 100644 --- a/Task/100-doors/Common-Lisp/100-doors-3.lisp +++ b/Task/100-doors/Common-Lisp/100-doors-3.lisp @@ -1,10 +1,10 @@ +(defun doors (z &optional (w (make-list z)) (n 1)) + (if (> n z) w (doors z (toggle w n z) (1+ n)))) + (defun toggle (w m z) (loop for a in w for n from 1 to z collect (if (zerop (mod n m)) (not a) a))) -(defun doors (z &optional (w (make-list z)) (n 1)) - (if (> n z) w (doors z (toggle w n z) (1+ n)))) - > (doors 100) (T NIL NIL T NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL diff --git a/Task/100-doors/Common-Lisp/100-doors-4.lisp b/Task/100-doors/Common-Lisp/100-doors-4.lisp index e10efb7d66..f0e2d0503c 100644 --- a/Task/100-doors/Common-Lisp/100-doors-4.lisp +++ b/Task/100-doors/Common-Lisp/100-doors-4.lisp @@ -1,6 +1,10 @@ -(defun 100-doors () - (let ((doors (make-array 100))) - (dotimes (i 10) - (setf (svref doors (* i i)) t)) - (dotimes (i 100) - (format t "door ~a: ~:[closed~;open~]~%" (1+ i) (svref doors i))))) +(defun doors (n) + (loop for a from 1 to n collect + (if (zerop (mod (sqrt a) 1)) t nil))) + +> (doors 100) +(T NIL NIL T NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL + NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL + NIL NIL NIL NIL NIL NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL + NIL NIL T NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T + NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL NIL T) diff --git a/Task/100-doors/Common-Lisp/100-doors-5.lisp b/Task/100-doors/Common-Lisp/100-doors-5.lisp index dfec970db4..e10efb7d66 100644 --- a/Task/100-doors/Common-Lisp/100-doors-5.lisp +++ b/Task/100-doors/Common-Lisp/100-doors-5.lisp @@ -1,23 +1,6 @@ -(defun perfect-square-list (n) - "Generates a list of perfect squares from 0 up to n" - (loop for i from 1 to (isqrt n) collect (expt i 2))) - -(defun print-doors (doors) - "Pretty prints the doors list" - (format T "~{~A ~A ~A ~A ~A ~A ~A ~A ~A ~A~%~}~%" doors)) - -(defun open-door (doors num open) - "Sets door at num to open" - (setf (nth (- num 1) doors) open)) - -(defun visit-all (doors vlist open) - "Visits and opens all the doors indicated in vlist" - (dolist (dn vlist doors) - (open-door doors dn open))) - -(defun start2 (&optional (size 100)) - "Start the program" - (print-doors - (visit-all (make-list size :initial-element '\#) - (perfect-square-list size) - '_))) +(defun 100-doors () + (let ((doors (make-array 100))) + (dotimes (i 10) + (setf (svref doors (* i i)) t)) + (dotimes (i 100) + (format t "door ~a: ~:[closed~;open~]~%" (1+ i) (svref doors i))))) diff --git a/Task/100-doors/Common-Lisp/100-doors-6.lisp b/Task/100-doors/Common-Lisp/100-doors-6.lisp index b791c006f2..dfec970db4 100644 --- a/Task/100-doors/Common-Lisp/100-doors-6.lisp +++ b/Task/100-doors/Common-Lisp/100-doors-6.lisp @@ -1,5 +1,23 @@ -(let ((i 0)) - (mapcar (lambda (x) - (if (zerop (mod (sqrt (incf i)) 1)) - "_" "#")) - (make-list 100))) +(defun perfect-square-list (n) + "Generates a list of perfect squares from 0 up to n" + (loop for i from 1 to (isqrt n) collect (expt i 2))) + +(defun print-doors (doors) + "Pretty prints the doors list" + (format T "~{~A ~A ~A ~A ~A ~A ~A ~A ~A ~A~%~}~%" doors)) + +(defun open-door (doors num open) + "Sets door at num to open" + (setf (nth (- num 1) doors) open)) + +(defun visit-all (doors vlist open) + "Visits and opens all the doors indicated in vlist" + (dolist (dn vlist doors) + (open-door doors dn open))) + +(defun start2 (&optional (size 100)) + "Start the program" + (print-doors + (visit-all (make-list size :initial-element '\#) + (perfect-square-list size) + '_))) diff --git a/Task/100-doors/Common-Lisp/100-doors-7.lisp b/Task/100-doors/Common-Lisp/100-doors-7.lisp new file mode 100644 index 0000000000..b791c006f2 --- /dev/null +++ b/Task/100-doors/Common-Lisp/100-doors-7.lisp @@ -0,0 +1,5 @@ +(let ((i 0)) + (mapcar (lambda (x) + (if (zerop (mod (sqrt (incf i)) 1)) + "_" "#")) + (make-list 100))) diff --git a/Task/100-doors/Elena/100-doors.elena b/Task/100-doors/Elena/100-doors.elena index 5b19be4a90..24d125de68 100644 --- a/Task/100-doors/Elena/100-doors.elena +++ b/Task/100-doors/Elena/100-doors.elena @@ -1,7 +1,7 @@ import system'routines. import extensions. -program = +public program = [ var Doors := Array new:100; populate(:n)( false ). diff --git a/Task/100-doors/Excel/100-doors-1.excel b/Task/100-doors/Excel/100-doors-1.excel new file mode 100644 index 0000000000..960cfebd6c --- /dev/null +++ b/Task/100-doors/Excel/100-doors-1.excel @@ -0,0 +1 @@ +=IF($A2/C$1=INT($A2/C$1),IF(B2=0,1,IF(B2=1,0)),B2) diff --git a/Task/100-doors/Excel/100-doors-2.excel b/Task/100-doors/Excel/100-doors-2.excel new file mode 100644 index 0000000000..f3b725eca7 --- /dev/null +++ b/Task/100-doors/Excel/100-doors-2.excel @@ -0,0 +1 @@ +=IF($A3/C$1=INT($A3/C$1),IF(B3=0,1,IF(B3=1,0)),B3) diff --git a/Task/100-doors/Excel/100-doors-3.excel b/Task/100-doors/Excel/100-doors-3.excel new file mode 100644 index 0000000000..93e10a5352 --- /dev/null +++ b/Task/100-doors/Excel/100-doors-3.excel @@ -0,0 +1 @@ +=IF($A2/D$1=INT($A2/D$1),IF(C2=0,1,IF(C2=1,0)),C2) diff --git a/Task/100-doors/HolyC/100-doors.holyc b/Task/100-doors/HolyC/100-doors.holyc new file mode 100644 index 0000000000..81a3643ea6 --- /dev/null +++ b/Task/100-doors/HolyC/100-doors.holyc @@ -0,0 +1,14 @@ +U8 is_open[100]; +U8 pass = 0, door = 0; + +/* do the 100 passes */ +for (pass = 0; pass < 100; ++pass) + for (door = pass; door < 100; door += pass + 1) + is_open[door] = !is_open[door]; + +/* output the result */ +for (door = 0; door < 100; ++door) + if (is_open[door]) + Print("Door #%d is open.\n", door + 1); + else + Print("Door #%d is closed.\n", door + 1); diff --git a/Task/100-doors/Julia/100-doors-1.julia b/Task/100-doors/Julia/100-doors-1.julia index 6a4b4a18ee..c71eb94e89 100644 --- a/Task/100-doors/Julia/100-doors-1.julia +++ b/Task/100-doors/Julia/100-doors-1.julia @@ -1,5 +1,5 @@ doors = falses(100) -for a = 1:100, b in a:a:100 +for a in 1:100, b in a:a:100 doors[b] = !doors[b] end for a = 1:100 diff --git a/Task/100-doors/Julia/100-doors-2.julia b/Task/100-doors/Julia/100-doors-2.julia index c0aa20d831..fde2304646 100644 --- a/Task/100-doors/Julia/100-doors-2.julia +++ b/Task/100-doors/Julia/100-doors-2.julia @@ -1 +1 @@ -for i = 1:10 println("Door $(i^2) is open.") end +for i in 1:10 println("Door $(i^2) is open.") end diff --git a/Task/100-doors/Klong/100-doors-1.klong b/Task/100-doors/Klong/100-doors-1.klong new file mode 100644 index 0000000000..f9585288dc --- /dev/null +++ b/Task/100-doors/Klong/100-doors-1.klong @@ -0,0 +1,2 @@ +flip::{,/{(1-*x),1_x}'x:#y} +i::0;(100{i::i+1;flip(i;x)}:*100:^0)?1 diff --git a/Task/100-doors/Klong/100-doors-2.klong b/Task/100-doors/Klong/100-doors-2.klong new file mode 100644 index 0000000000..21a1aa595e --- /dev/null +++ b/Task/100-doors/Klong/100-doors-2.klong @@ -0,0 +1 @@ +(1+!9)^2 diff --git a/Task/100-doors/Nial/100-doors-1.nial b/Task/100-doors/Nial/100-doors-1.nial new file mode 100644 index 0000000000..ee64664c54 --- /dev/null +++ b/Task/100-doors/Nial/100-doors-1.nial @@ -0,0 +1,4 @@ + n:=100;reduce xor (count n eachright mod count n eachall<1) +looloooolooooooloooooooolooooooooooloooooooooooolooooooooooooooloooooooooooooooo + +looooooooooooooooool diff --git a/Task/100-doors/Nial/100-doors-2.nial b/Task/100-doors/Nial/100-doors-2.nial new file mode 100644 index 0000000000..4da2874b46 --- /dev/null +++ b/Task/100-doors/Nial/100-doors-2.nial @@ -0,0 +1,2 @@ + true findall (n:=100;reduce xor (count n eachright mod count n eachall<1))+1 +1 4 9 16 25 36 49 64 81 100 diff --git a/Task/100-doors/Nial/100-doors-3.nial b/Task/100-doors/Nial/100-doors-3.nial new file mode 100644 index 0000000000..702650107e --- /dev/null +++ b/Task/100-doors/Nial/100-doors-3.nial @@ -0,0 +1,2 @@ + count 10 power 2 +1 4 9 16 25 36 49 64 81 100 diff --git a/Task/100-doors/Oforth/100-doors.oforth b/Task/100-doors/Oforth/100-doors.oforth index 4697e15ac4..34534cf445 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 | - ListBuffer initValue(100, false) ->l + 100 #[ false ] Array init dup ->l 100 loop: i [ i 100 i step: j [ l put(j, l at(j) not) ] ] - l println ; + l . ; diff --git a/Task/100-doors/R/100-doors-4.r b/Task/100-doors/R/100-doors-4.r new file mode 100644 index 0000000000..fefc4ade84 --- /dev/null +++ b/Task/100-doors/R/100-doors-4.r @@ -0,0 +1,3 @@ +H=100 +f=rep(F,H) +which(Reduce(function(d,n) xor(replace(f,seq(n,H,n),T),d), 1:H, f)) diff --git a/Task/100-doors/Rust/100-doors-1.rust b/Task/100-doors/Rust/100-doors-1.rust index b224a24b57..58876fa83f 100644 --- a/Task/100-doors/Rust/100-doors-1.rust +++ b/Task/100-doors/Rust/100-doors-1.rust @@ -1,8 +1,6 @@ -#![feature(inclusive_range_syntax)] - fn main() { let mut door_open = [false; 100]; - for pass in 1...100 { + for pass in 1..100 { let mut door = pass; while door <= 100 { door_open[door - 1] = !door_open[door - 1]; @@ -13,3 +11,4 @@ fn main() { println!("Door {} is {}.", i + 1, if is_open {"open"} else {"closed"}); } } +} diff --git a/Task/100-doors/Rust/100-doors-2.rust b/Task/100-doors/Rust/100-doors-2.rust index fe4d9e1f42..8bbbc0bb75 100644 --- a/Task/100-doors/Rust/100-doors-2.rust +++ b/Task/100-doors/Rust/100-doors-2.rust @@ -1,8 +1,6 @@ -#![feature(inclusive_range_syntax)] - fn main() { let doors = vec![false; 100].iter_mut().enumerate() - .map(|(door, door_state)| (1...100).into_iter() + .map(|(door, door_state)| (1..100).into_iter() .filter(|pass| door % pass == 0) .map(|_| { *door_state = !*door_state; *door_state }) .last().unwrap()).collect::>(); diff --git a/Task/100-doors/Rust/100-doors-3.rust b/Task/100-doors/Rust/100-doors-3.rust index 25610e11b3..560a4ddd58 100644 --- a/Task/100-doors/Rust/100-doors-3.rust +++ b/Task/100-doors/Rust/100-doors-3.rust @@ -1,10 +1,8 @@ -#![feature(inclusive_range_syntax)] - fn main() { - let squares: Vec<_> = (1...10).map(|n| n*n).collect(); + let squares: Vec<_> = (1..10).map(|n| n*n).collect(); let is_square = |num| squares.binary_search(&num).is_ok(); - for i in 1...100 { + for i in 1..100 { let state = if is_square(i) {"open"} else {"closed"}; println!("Door {} is {}", i, state); } diff --git a/Task/100-doors/Rust/100-doors-4.rust b/Task/100-doors/Rust/100-doors-4.rust index 6ae27a5ded..4d187e933f 100644 --- a/Task/100-doors/Rust/100-doors-4.rust +++ b/Task/100-doors/Rust/100-doors-4.rust @@ -1,7 +1,5 @@ -#![feature(inclusive_range_syntax)] - fn main() { - for i in 1u32...10u32{ + for i in 1u32..10u32{ println!("Door {} is open", i.pow(2)); } } diff --git a/Task/100-doors/SheerPower-4GL/100-doors.4gl b/Task/100-doors/SheerPower-4GL/100-doors.4gl new file mode 100644 index 0000000000..ffd3fbfee4 --- /dev/null +++ b/Task/100-doors/SheerPower-4GL/100-doors.4gl @@ -0,0 +1,43 @@ +!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +! I n i t i a l i z a t i o n +!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +doors% = 100 + +dim doorArray?(doors%) + +!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +! M a i n L o g i c A r e a +!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +// Initialize Array +for index% = 1 to doors% + doorArray?(index%) = false +next index% + +// Execute routine +toggle_doors + +// Print results +for index% = 1 to doors% + if doorArray?(index%) = true then print index%, ' is open' +next index% + + +stop + + +!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +! R o u t i n e s +!%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +routine toggle_doors + for index_outer% = 1 to doors% + for index_inner% = 1 to doors% + if mod(index_inner%, index_outer%) = 0 then + doorArray?(index_inner%) = not doorArray?(index_inner%) + end if + next index_inner% + next index_outer% +end routine + + +end diff --git a/Task/100-doors/Simula/100-doors.simula b/Task/100-doors/Simula/100-doors.simula index d10c6d58f2..104a3661b4 100644 --- a/Task/100-doors/Simula/100-doors.simula +++ b/Task/100-doors/Simula/100-doors.simula @@ -1,16 +1,16 @@ BEGIN - INTEGER I, PASS; - BOOLEAN ARRAY DOORS(1:100); + INTEGER LIMIT = 100, door, stride; + BOOLEAN ARRAY DOORS(1:LIMIT); + TEXT intro; - FOR I := 1 STEP 1 UNTIL 100 DO - DOORS(I) := FALSE; - - FOR PASS := 1 STEP 1 UNTIL 100 DO - FOR I := PASS STEP PASS UNTIL 100 DO - DOORS(I) := NOT DOORS(I); - - FOR I := 1 STEP 1 UNTIL 100 DO - IF DOORS(I) - THEN BEGIN OUTTEXT("DOOR "); OUTINT(I,0); OUTTEXT(" IS OPEN"); OUTIMAGE END + FOR stride := 1 STEP 1 UNTIL LIMIT DO + FOR door := stride STEP stride UNTIL LIMIT DO + DOORS(door) := NOT DOORS(door); + intro :- "All doors closed but "; + FOR door := 1 STEP 1 UNTIL LIMIT DO + IF DOORS(door) THEN BEGIN + OUTTEXT(intro); OUTINT(door, 0); intro :- ", " + END; + OUTIMAGE END. diff --git a/Task/100-doors/Stata/100-doors.stata b/Task/100-doors/Stata/100-doors.stata index 05f4aeb261..35173a27fa 100644 --- a/Task/100-doors/Stata/100-doors.stata +++ b/Task/100-doors/Stata/100-doors.stata @@ -1,24 +1,22 @@ -clear all +clear set obs 100 gen doors=0 gen index=_n forvalues i=1/100 { quietly replace doors=1-doors if mod(_n,`i')==0 } -list index if doors +list index if doors, noobs noheader - +-------+ - | index | - |-------| - 1. | 1 | - 4. | 4 | - 9. | 9 | - 16. | 16 | - 25. | 25 | - |-------| - 36. | 36 | - 49. | 49 | - 64. | 64 | - 81. | 81 | -100. | 100 | - +-------+ + +-------+ + | 1 | + | 4 | + | 9 | + | 16 | + | 25 | + |-------| + | 36 | + | 49 | + | 64 | + | 81 | + | 100 | + +-------+ diff --git a/Task/100-doors/Visual-Basic/100-doors.vb b/Task/100-doors/Visual-Basic/100-doors.vb new file mode 100644 index 0000000000..ea784a1ede --- /dev/null +++ b/Task/100-doors/Visual-Basic/100-doors.vb @@ -0,0 +1,17 @@ +Public Sub Doors100() + ' the state of a door is represented by the data type boolean (false = door closed, true = door opened) + Dim doorstate(1 To 100) As Boolean ' the doorstate()-array is initialized by VB with value 'false' + Dim i As Long, j As Long + + For i = 1 To 100 + For j = i To 100 Step i + doorstate(j) = Not doorstate(j) + Next j + Next i + + Debug.Print "The following doors are open:" + For i = 1 To 100 + ' print number if door is openend + If doorstate(i) Then Debug.Print CStr(i) + Next i +End Sub diff --git a/Task/24-game-Solve/Factor/24-game-solve.factor b/Task/24-game-Solve/Factor/24-game-solve.factor new file mode 100644 index 0000000000..cd9498b05e --- /dev/null +++ b/Task/24-game-Solve/Factor/24-game-solve.factor @@ -0,0 +1,18 @@ +USING: continuations grouping io kernel math math.combinatorics +prettyprint quotations random sequences sequences.deep ; +IN: rosetta-code.24-game + +: 4digits ( -- seq ) 4 9 random-integers [ 1 + ] map ; + +: expressions ( digits -- exprs ) + all-permutations [ [ + - * / ] 3 selections + [ append ] with map ] map flatten 7 group ; + +: 24= ( exprs -- ) + >quotation dup call( -- x ) 24 = [ . ] [ drop ] if ; + +: 24-game ( -- ) + 4digits dup "The numbers: " write . "The solutions: " + print expressions [ [ 24= ] [ 2drop ] recover ] each ; + +24-game diff --git a/Task/24-game-Solve/Mathematica/24-game-solve-3.math b/Task/24-game-Solve/Mathematica/24-game-solve-3.math new file mode 100644 index 0000000000..8eb7511525 --- /dev/null +++ b/Task/24-game-Solve/Mathematica/24-game-solve-3.math @@ -0,0 +1,35 @@ +evaluate[HoldForm[op_[l_, r_]]] := op[evaluate[l], evaluate[r]]; +evaluate[x_] := x; +combine[l_, r_ /; evaluate[r] != 0] := {HoldForm[Plus[l, r]], + HoldForm[Subtract[l, r]], HoldForm[Times[l, r]], + HoldForm[Divide[l, r]] }; +combine[l_, r_] := {HoldForm[Plus[l, r]], HoldForm[Subtract[l, r]], + HoldForm[Times[l, r]]}; +split[items_] := + Table[{items[[1 ;; i]], items[[i + 1 ;; Length[items]]]}, {i, 1, + Length[items] - 1}]; +expressions[{x_}] := {x}; +expressions[items_] := + Flatten[Table[ + Flatten[Table[ + combine[l, r], {l, expressions[sp[[1]]]}, {r, + expressions[sp[[2]]]}], 2], {sp, split[items]}]]; + +(* Must use all atoms in given order. *) +solveMaintainOrder[goal_, items_] := + Select[expressions[items], (evaluate[#] == goal) &]; +(* Must use all atoms, but can permute them. *) +solveCanPermute[goal_, items_] := + Flatten[Table[ + solveMaintainOrder[goal, pitems], {pitems, + Permutations[items]}]]; +(* Can use any subset of atoms. *) +solveSubsets[goal_, items_] := + Flatten[Table[ + solveCanPermute[goal, is], {is, + Subsets[items, {1, Length[items]}]}], 2]; + +(* Demonstration to find all the ways to create 1/5 from {2, 3, 4, 5}. *) +solveMaintainOrder[1/5, Range[2, 5]] +solveCanPermute[1/5, Range[2, 5]] +solveSubsets[1/5, Range[2, 5]] diff --git a/Task/24-game-Solve/Python/24-game-solve.py b/Task/24-game-Solve/Python/24-game-solve-1.py similarity index 100% rename from Task/24-game-Solve/Python/24-game-solve.py rename to Task/24-game-Solve/Python/24-game-solve-1.py diff --git a/Task/24-game-Solve/Python/24-game-solve-2.py b/Task/24-game-Solve/Python/24-game-solve-2.py new file mode 100644 index 0000000000..03fcb20bc4 --- /dev/null +++ b/Task/24-game-Solve/Python/24-game-solve-2.py @@ -0,0 +1,39 @@ +# -*- coding: utf-8 -*- +import operator +from itertools import product, permutations + +def mydiv(n, d): + return n / d if d != 0 else 9999999 + +syms = [operator.add, operator.sub, operator.mul, mydiv] +op = {sym: ch for sym, ch in zip(syms, '+-*/')} + +def solve24(nums): + for x, y, z in product(syms, repeat=3): + for a, b, c, d in permutations(nums): + if round(x(y(a,b),z(c,d)),5) == 24: + return f"({a} {op[y]} {b}) {op[x]} ({c} {op[z]} {d})" + elif round(x(a,y(b,z(c,d))),5) == 24: + return f"{a} {op[x]} ({b} {op[y]} ({c} {op[z]} {d}))" + elif round(x(y(z(c,d),b),a),5) == 24: + return f"(({c} {op[z]} {d}) {op[y]} {b}) {op[x]} {a}" + elif round(x(y(b,z(c,d)),a),5) == 24: + return f"({b} {op[y]} ({c} {op[z]} {d})) {op[x]} {a}" + return '--Not Found--' + +if __name__ == '__main__': + #nums = eval(input('Four integers in the range 1:9 inclusive, separated by commas: ')) + for nums in [ + [9,4,4,5], + [1,7,2,7], + [5,7,5,4], + [1,4,6,6], + [2,3,7,3], + [8,7,9,7], + [1,6,2,6], + [7,9,4,1], + [6,4,2,2], + [5,7,9,7], + [3,3,8,8], # Difficult case requiring precise division + ]: + print(f"solve24({nums}) -> {solve24(nums)}") diff --git a/Task/24-game-Solve/Python/24-game-solve-3.py b/Task/24-game-Solve/Python/24-game-solve-3.py new file mode 100644 index 0000000000..3d96555131 --- /dev/null +++ b/Task/24-game-Solve/Python/24-game-solve-3.py @@ -0,0 +1,44 @@ +# -*- coding: utf-8 -*- +# Python 3 +from operator import mul, sub, add + + +def div(a, b): + if b == 0: + return 999999.0 + return a / b + +ops = {mul: '*', div: '/', sub: '-', add: '+'} + +def solve24(num, how, target): + if len(num) == 1: + if round(num[0], 5) == round(target, 5): + yield str(how[0]).replace(',', '').replace("'", '') + else: + for i, n1 in enumerate(num): + for j, n2 in enumerate(num): + if i != j: + for op in ops: + new_num = [n for k, n in enumerate(num) if k != i and k != j] + [op(n1, n2)] + new_how = [h for k, h in enumerate(how) if k != i and k != j] + [(how[i], ops[op], how[j])] + yield from solve24(new_num, new_how, target) + +tests = [ + [1, 7, 2, 7], + [5, 7, 5, 4], + [1, 4, 6, 6], + [2, 3, 7, 3], + [1, 6, 2, 6], + [7, 9, 4, 1], + [6, 4, 2, 2], + [5, 7, 9, 7], + [3, 3, 8, 8], # Difficult case requiring precise division + [8, 7, 9, 7], # No solution + [9, 4, 4, 5], # No solution + ] +for nums in tests: + print(nums, end=' : ') + try: + print(next(solve24(nums, nums, 24))) + except StopIteration: + print("No solution found") diff --git a/Task/24-game-Solve/Scheme/24-game-solve-1.ss b/Task/24-game-Solve/Scheme/24-game-solve-1.ss new file mode 100644 index 0000000000..3905a71796 --- /dev/null +++ b/Task/24-game-Solve/Scheme/24-game-solve-1.ss @@ -0,0 +1,46 @@ +#!r6rs + +(import (rnrs) + (rnrs eval) + (only (srfi :1 lists) append-map delete-duplicates iota)) + +(define (map* fn . lis) + (if (null? lis) + (list (fn)) + (append-map (lambda (x) + (apply map* + (lambda xs (apply fn x xs)) + (cdr lis))) + (car lis)))) + +(define (insert x li n) + (if (= n 0) + (cons x li) + (cons (car li) (insert x (cdr li) (- n 1))))) + +(define (permutations li) + (if (null? li) + (list ()) + (map* insert (list (car li)) (permutations (cdr li)) (iota (length li))))) + +(define (evaluates-to-24 expr) + (guard (e ((assertion-violation? e) #f)) + (= 24 (eval expr (environment '(rnrs base)))))) + +(define (tree n o0 o1 o2 xs) + (list-ref + (list + `(,o0 (,o1 (,o2 ,(car xs) ,(cadr xs)) ,(caddr xs)) ,(cadddr xs)) + `(,o0 (,o1 (,o2 ,(car xs) ,(cadr xs)) ,(caddr xs)) ,(cadddr xs)) + `(,o0 (,o1 ,(car xs) (,o2 ,(cadr xs) ,(caddr xs))) ,(cadddr xs)) + `(,o0 (,o1 ,(car xs) ,(cadr xs)) (,o2 ,(caddr xs) ,(cadddr xs))) + `(,o0 ,(car xs) (,o1 (,o2 ,(cadr xs) ,(caddr xs)) ,(cadddr xs))) + `(,o0 ,(car xs) (,o1 ,(cadr xs) (,o2 ,(caddr xs) ,(cadddr xs))))) + n)) + +(define (solve a b c d) + (define ops '(+ - * /)) + (define perms (delete-duplicates (permutations (list a b c d)))) + (delete-duplicates + (filter evaluates-to-24 + (map* tree (iota 6) ops ops ops perms)))) diff --git a/Task/24-game-Solve/Scheme/24-game-solve-2.ss b/Task/24-game-Solve/Scheme/24-game-solve-2.ss new file mode 100644 index 0000000000..67063f0e05 --- /dev/null +++ b/Task/24-game-Solve/Scheme/24-game-solve-2.ss @@ -0,0 +1,13 @@ +> (solve 1 3 5 7) +((* (+ 1 5) (- 7 3)) + (* (+ 5 1) (- 7 3)) + (* (+ 5 7) (- 3 1)) + (* (+ 7 5) (- 3 1)) + (* (- 3 1) (+ 5 7)) + (* (- 3 1) (+ 7 5)) + (* (- 7 3) (+ 1 5)) + (* (- 7 3) (+ 5 1))) +> (solve 3 3 8 8) +((/ 8 (- 3 (/ 8 3)))) +> (solve 3 4 9 10) +() diff --git a/Task/24-game/Befunge/24-game.bf b/Task/24-game/Befunge/24-game.bf new file mode 100644 index 0000000000..d7be792232 --- /dev/null +++ b/Task/24-game/Befunge/24-game.bf @@ -0,0 +1,25 @@ +v > > >> v +2 2 1234 +4 ^1?3^4 +>8*00p10p> >? ?5> 68*+00g10gpv + v9?7v6 0 + 8 0 + > > >> ^ g + ^p00 _v# `\*49:+1 < +_>"rorrE",,,,,$ >~:67*-!#v_:167*+-!#v_:95*-!#v_:295*+-!#v_:586*+\`#v_:97*2--!#v + $ $ $ $ : $ + * + - / 1 : + ^ < < < < 8 . + 6 6 + * 4 + + * + \ - + ` > v_v + " + ^ < _v e + ^ _^#+*28:p2\*84\-*86g2:-+*441< s + o + L + > 1 |-*49"#< + | -*84gg01g0000g:1+00p66*`#^_ "niW">:#,_@ diff --git a/Task/24-game/Elena/24-game.elena b/Task/24-game/Elena/24-game.elena index 4a5af756b7..a02c7fb7ad 100644 --- a/Task/24-game/Elena/24-game.elena +++ b/Task/24-game/Elena/24-game.elena @@ -9,40 +9,43 @@ class ExpressionTree constructor new : aLiteral [ - var aLevel := Integer new:0. + auto aLevel := Integer new:0. aLiteral forEach(:ch) [ var node := DynamicStruct new. ch => - $43 [ node set level(aLevel + 1); set operation:%add ]; // + - $45 [ node set level(aLevel + 1); set operation:%subtract ]; // - - $42 [ node set level(aLevel + 2); set operation:%multiply ]; // * - $47 [ node set level(aLevel + 2); set operation:%divide ]; // / - $40 [ aLevel append int:10. ^ $self ]; // ( - $41 [ aLevel reduce int:10. ^ $self ]; // ) + $43 [ node level := aLevel + 1. node operation := %add ]; // + + $45 [ node level := aLevel + 1. node operation := %subtract ]; // - + $42 [ node level := aLevel + 2. node operation := %multiply ]; // * + $47 [ node level := aLevel + 2. node operation := %divide ]; // / + $40 [ aLevel append(10). ^ self ]; // ( + $41 [ aLevel reduce(10). ^ self ]; // ) ! [ - node set leaf(ch literal; toReal); set level(aLevel + 3). + node leaf := ch literal; toReal. + node level := aLevel + 3. ]. - if ($nil == theTree) + if (nil == theTree) [ theTree := node ]; [ if (theTree level >= node level) [ - node set left:theTree; set right:$nil. + node left := theTree. + node right := nilValue. theTree := node ]; [ var aTop := theTree. - while (($nil != aTop right)and:$(aTop right; level < node level)) + while ((nilValue != aTop right)&&(aTop right; level < node level)) [ aTop := aTop right ]. - node set left(aTop right); set right:$nil. + node left := aTop right. + node right := nilValue. - aTop set right:node + aTop right := node ] ] ] @@ -53,8 +56,8 @@ class ExpressionTree if (aNode containsProperty:%leaf) [ ^ aNode leaf ]; [ - var aLeft := $self eval:(aNode left). - var aRight := $self eval:(aNode right). + var aLeft := self eval:(aNode left). + var aRight := self eval:(aNode right). ^ aLeft~(aNode operation) eval:aRight ] @@ -65,14 +68,14 @@ class ExpressionTree readLeaves : aList at:aNode [ - if ($nil == aNode) + if (nil == aNode) [ InvalidArgumentException new; raise ]. if (aNode containsProperty:%leaf) [ aList append(aNode leaf) ]; [ - $self readLeaves:aList at(aNode left). - $self readLeaves:aList at(aNode right). + self readLeaves:aList at(aNode left). + self readLeaves:aList at(aNode right). ]. ] @@ -86,7 +89,7 @@ class TwentyFourGame constructor new [ - $self newPuzzle. + self newPuzzle. ] newPuzzle @@ -129,14 +132,14 @@ class TwentyFourGame exp readLeaves:Leaves. ifnot (Leaves ascendant; sequenceEqual(theNumbers ascendant)) - [ console printLine:"Invalid input. Enter an equation using all of those four digits. Try again.". ^ $self ]. + [ console printLine:"Invalid input. Enter an equation using all of those four digits. Try again.". ^ self ]. var aResult := exp value. if (aResult == 24) [ console printLine("Good work. ",aLine,"=",aResult). - $self newPuzzle. + self newPuzzle. ]; [ console printLine("Incorrect. ",aLine,"=",aResult) ] ] @@ -159,13 +162,12 @@ extension gameOp ] } ]. - ^ true ]. ] } -program = +public program = [ var aGame := TwentyFourGame new; help. diff --git a/Task/24-game/Oforth/24-game.oforth b/Task/24-game/Oforth/24-game.oforth index 260af55ccf..f52e5fd24c 100644 --- a/Task/24-game/Oforth/24-game.oforth +++ b/Task/24-game/Oforth/24-game.oforth @@ -1,19 +1,22 @@ -: 24game +import: mapping + +: game | l expr w n i | - ListBuffer init(4, #[ 9 rand ]) ->l + 4 #[ 9 rand ] Array init ->l System.Out "Digits : " << l << " --> RPN Expression for 24 : " << drop - System.Console askln ->expr + System.Console accept ->expr expr words forEach: w [ w "+" == ifTrue: [ + continue ] w "-" == ifTrue: [ - continue ] w "*" == ifTrue: [ * continue ] - w "/" == ifTrue: [ asFloat / continue ] + w "/" == ifTrue: [ >float / continue ] - w asInteger dup ->n ifNull: [ System.Out "Word " << w << " not allowed " << cr break ] - l indexOf(n) dup ->i ifNull: [ System.Out "Integer " << n << " is wrong " << cr break ] + w >integer dup ->n ifNull: [ System.Out "Word " << w << " not allowed " << cr break ] + n l indexOf dup ->i ifNull: [ System.Out "Integer " << n << " is wrong " << cr break ] n l put(i, null) ] - l conform(#isNull) ifFalse: [ "Sorry, all numbers must be used..." println return ] - 24 == ifTrue: [ "You won !" ] else: [ "You loose..." ] println ; + #null? l conform? ifFalse: [ "Sorry, all numbers must be used..." . return ] + 24 if=: [ "You won !" ] else: [ "You loose..." ] . +; diff --git a/Task/24-game/Ring/24-game.ring b/Task/24-game/Ring/24-game.ring new file mode 100644 index 0000000000..a77bd070f6 --- /dev/null +++ b/Task/24-game/Ring/24-game.ring @@ -0,0 +1,63 @@ +# Project : 24 game +# Date : 2018/02/21 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +load "stdlib.ring" +digits = list(4) +check = list(4) +for choice = 1 to 4 + digits[choice] = random(9) +next + +see "enter an equation (using all of, and only, the single digits " + nl +for index = 1 to 4 + see digits[index] + if index != 4 + see " " + ok +next +see ")" +see " which evaluates to exactly 24. only multiplication (*), division (/)," + nl +see "addition (+) & subtraction (-) operations and parentheses are allowed:" + nl +see "24 = " +give equation +see "equation = " + equation + nl + +while true + for char = 1 to len(equation) + digit = substr("0123456789", equation[char]) - 1 + if digit >= 0 + for index = 1 to 4 + if digit = digits[index] + if not check[index] + check[index] = 1 + exit + ok + ok + next + if index > 4 + see "sorry, you used the illegal digit " + digit + nl + exit 2 + ok + ok + next + for index = 1 to 4 + if check[index] = 0 + see "sorry, you failed to use the digit " + digits[index] + nl + exit 2 + ok + next + for pair = 11 to 99 + if substr(equation, string(pair)) + see "sorry, you may not use a pair of digits " + pair + nl + ok + next + eval("result = " + equation) + if result = 24 + see "congratulations, you succeeded in the task!" + nl + exit + else + see "sorry, your equation evaluated to " + result + " rather than 24!" + nl + ok +end diff --git a/Task/9-billion-names-of-God-the-integer/Go/9-billion-names-of-god-the-integer.go b/Task/9-billion-names-of-God-the-integer/Go/9-billion-names-of-god-the-integer.go new file mode 100644 index 0000000000..a932733ef3 --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Go/9-billion-names-of-god-the-integer.go @@ -0,0 +1,45 @@ +package main + +import ( + f "fmt" + "math" + m "math/big" +) + +func main() { + var cache = make([][]m.Int, 0) + cache = append(cache, append([]m.Int{}, *m.NewInt(1))) + + cumu := func(n int) []m.Int { + for l := len(cache); l <= n; l++ { + r := make([]m.Int, 0) + r = append(r, *m.NewInt(0)) + for x := 1; x <= l; x++ { + cacheValue := &cache[l-x][int(math.Min(float64(x), float64(l-x)))] + r = append(r, *m.NewInt(0).Add(&r[len(r)-1], cacheValue)) + } + cache = append(cache, r) + } + return cache[n] + } + + row := func(n int) { + e := cumu(n) + for i := 0; i < n; i++ { + f.Printf(" %v ", (*m.NewInt(0).Sub(&e[i+1], &e[i])).Text(10)) + } + f.Print("\n") + } + + f.Print("rows:\n") + for x := 1; x < 11; x++ { + row(x) + } + f.Print("\n sums:\n") + nums := []int{23, 123, 1234,12345} + for _, num := range nums { + r := cumu(num) + f.Printf("%d %v \n", num, r[len(r)-1].Text(10)) + } + +} diff --git a/Task/9-billion-names-of-God-the-integer/Stata/9-billion-names-of-god-the-integer.stata b/Task/9-billion-names-of-God-the-integer/Stata/9-billion-names-of-god-the-integer.stata new file mode 100644 index 0000000000..28518f5fec --- /dev/null +++ b/Task/9-billion-names-of-God-the-integer/Stata/9-billion-names-of-god-the-integer.stata @@ -0,0 +1,10 @@ +mata +function part(n) { + a = J(n,n,.) + for (i=1;i<=n;i++) a[i,1] = a[i,i] = 1 + for (i=3;i<=n;i++) { + for (j=2;j @@ -24,9 +24,16 @@ Grammatical support for "1 bottle of beer" is optional. As with any puzzle, try to do it in as creative/concise/comical a way as possible (simple, obvious solutions allowed, too). + +;Related tasks: +*   [[The Twelve Days of Christmas]] +*   [[Old_lady_swallowed_a_fly]] +*   [[Mad Libs]] + + ;See also: -* http://99-bottles-of-beer.net/ -* [[:Category:99_Bottles_of_Beer]] -* [[:Category:Programming language families]] -* [https://en.wikipedia.org/wiki/99_Bottles_of_Beer Wikipedia 99 bottles of beer] +*   http://99-bottles-of-beer.net/ +*   [[:Category:99_Bottles_of_Beer]] +*   [[:Category:Programming language families]] +*   [https://en.wikipedia.org/wiki/99_Bottles_of_Beer Wikipedia 99 bottles of beer]

diff --git a/Task/99-Bottles-of-Beer/Astro/99-bottles-of-beer.astro b/Task/99-Bottles-of-Beer/Astro/99-bottles-of-beer.astro index 13dcf7a1b7..634e60e7ae 100644 --- a/Task/99-Bottles-of-Beer/Astro/99-bottles-of-beer.astro +++ b/Task/99-Bottles-of-Beer/Astro/99-bottles-of-beer.astro @@ -1,9 +1,9 @@ fun bottles(n): - | 0 -> "No more bottles" - | 1 -> "1 bottle" - | _ -> "$n bottles" + | 0 => "No more bottles" + | 1 => "1 bottle" + | _ => "$n bottles" -for n in [100:1]: +for n in !99..1: print """ $(bottles n) of beer on the wall $(bottles n) of beer diff --git a/Task/99-Bottles-of-Beer/Crystal/99-bottles-of-beer.crystal b/Task/99-Bottles-of-Beer/Crystal/99-bottles-of-beer.crystal new file mode 100644 index 0000000000..84e3c595eb --- /dev/null +++ b/Task/99-Bottles-of-Beer/Crystal/99-bottles-of-beer.crystal @@ -0,0 +1,7 @@ +99.downto(1) do |n| + puts "#{n} bottle#{n > 1 ? "s" : ""} of beer on the wall" + puts "#{n} bottle#{n > 1 ? "s" : ""} of beer" + puts "Take one down, pass it around" + puts "#{n-1} bottle#{n > 2 ? "s" : ""} of beer on the wall\n\n" if n > 1 +end +puts "No more bottles of beer on the wall" 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 301a6bee0e..cdd9d6bb39 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 @@ -1,4 +1,3 @@ -import system'dynamic. import system'routines. import extensions. import extensions'routines. @@ -9,22 +8,26 @@ extension bottleOp bottleDescription = self literal + (self != 1) iif(" bottles"," bottle"). - bottleEnumerator = Variable new:self; doWith(:target) + bottleEnumerator = Variable new:self; doWith(:n) [ ^ Enumerator:: { - next = target > 0. + bool next = n > 0. get = StringWriter new; - printLine(target bottleDescription," of beer on the wall"); - printLine(target bottleDescription," of beer"); + printLine(n bottleDescription," of beer on the wall"); + printLine(n bottleDescription," of beer"); printLine("Take one down, pass it around"); - printLine((target reduce:1) bottleDescription," of beer on the wall"). + printLine((n reduce:1) bottleDescription," of beer on the wall"). + + reset [] + + enumerable = target. } ]. } -program = +public program = [ var bottles := 99. diff --git a/Task/99-Bottles-of-Beer/Kitten/99-bottles-of-beer.kitten b/Task/99-Bottles-of-Beer/Kitten/99-bottles-of-beer.kitten new file mode 100644 index 0000000000..dd2d10e0c6 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Kitten/99-bottles-of-beer.kitten @@ -0,0 +1,32 @@ +99 bottles_of_beer_on_the_wall + +define bottles_of_beer_on_the_wall (Int32 -> +IO): + -> n; + n th_verse + if (n > 1): (n - 1) bottles_of_beer_on_the_wall + +define th_verse (Int32 -> +IO): + -> n; + n bottles_of_beer on_the_wall say + n bottles_of_beer say + take_one_down_pass_it_around say + (n - 1) bottles_of_beer on_the_wall say + newline + +define bottles_of_beer (Int32 -> List): + bottles " of beer" cat + +define on_the_wall (List -> List): + " on the wall" cat + +define take_one_down_pass_it_around (-> List): + "take one down, pass it around" + +define bottles (Int32 -> List): + -> n; + if (n = 0): + "no more bottles" + elif (n = 1): + "one bottle" + else: + n show " bottles" cat diff --git a/Task/99-Bottles-of-Beer/Limbo/99-bottles-of-beer.limbo b/Task/99-Bottles-of-Beer/Limbo/99-bottles-of-beer.limbo new file mode 100644 index 0000000000..84edf4fdf7 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Limbo/99-bottles-of-beer.limbo @@ -0,0 +1,26 @@ +implement Beer; + +include "sys.m"; +include "draw.m"; + +sys: Sys; + +Beer : module +{ + init : fn(ctxt : ref Draw->Context, args : list of string); +}; + +init (ctxt: ref Draw->Context, args: list of string) +{ + sys = load Sys Sys->PATH; + beers := 99; + for (; beers > 1; --beers) { + sys->print("%d bottles of beer on the wall\n", beers); + sys->print("%d bottles of beer\n", beers); + sys->print("Take one down, pass it around,\n"); + sys->print("%d bottles of beer on the wall\n\n", beers-1); + }; + sys->print("1 bottle of beer on the wall\n1 bottle of beer\n"); + sys->print("Take it down, pass it around\nand nothing is left!\n\n"); + +} diff --git a/Task/99-Bottles-of-Beer/Lingo/99-bottles-of-beer.lingo b/Task/99-Bottles-of-Beer/Lingo/99-bottles-of-beer.lingo new file mode 100644 index 0000000000..f61f8af7fb --- /dev/null +++ b/Task/99-Bottles-of-Beer/Lingo/99-bottles-of-beer.lingo @@ -0,0 +1,18 @@ +repeat with i = 99 down to 2 + put i & " bottles of beer on the wall" + put i & " bottles of beer" + put "Take one down, pass it around" + put (i-1) & " bottles of beer on the wall" + put +end repeat + +put "1 bottle of beer on the wall" +put "1 bottle of beer" +put "Take one down, pass it around" +put "No more bottles of beer on the wall" +put + +put "No more bottles of beer on the wall" +put "No more bottles of beer" +put "Go to the store and buy some more" +put "99 bottles of beer on the wall" diff --git a/Task/99-Bottles-of-Beer/Lua/99-bottles-of-beer-3.lua b/Task/99-Bottles-of-Beer/Lua/99-bottles-of-beer-3.lua new file mode 100644 index 0000000000..157bf1b79a --- /dev/null +++ b/Task/99-Bottles-of-Beer/Lua/99-bottles-of-beer-3.lua @@ -0,0 +1,11 @@ +function bottles(i) + local s = i == 1 and "1 bottle of beer" or + i == 0 and "no more bottles of beer" or + tostring(i) .. " bottles of beer" + return s, s +end + +for i = 99, 1, -1 do + print( string.format("%s on the wall,\n%s,\ntake one down, pass it around,", bottles(i)), + string.format("\n%s on the wall.\n", bottles(i-1)) ) +end diff --git a/Task/99-Bottles-of-Beer/N-t-roff/99-bottles-of-beer-1.n b/Task/99-Bottles-of-Beer/N-t-roff/99-bottles-of-beer-1.n new file mode 100644 index 0000000000..ad7ee7e67d --- /dev/null +++ b/Task/99-Bottles-of-Beer/N-t-roff/99-bottles-of-beer-1.n @@ -0,0 +1,18 @@ +.nr BS 99 1 +.de L1 +.ie \\n(BS>1 \{ \ +\\n(BS bottles of beer on the wall, +\\n(BS bottles of beer.\c +\} +.el \{ \ +\\n(BS bottle of beer on the wall, +\\n(BS bottle of beer.\c +\} +Take one down, pass it around, +\\n-(BS bottles of beer on the wall. + +.if \\n(BS>0 .L1 +.. +.nf +.L1 +.fi diff --git a/Task/99-Bottles-of-Beer/N-t-roff/99-bottles-of-beer-2.n b/Task/99-Bottles-of-Beer/N-t-roff/99-bottles-of-beer-2.n new file mode 100644 index 0000000000..bb1c3544a0 --- /dev/null +++ b/Task/99-Bottles-of-Beer/N-t-roff/99-bottles-of-beer-2.n @@ -0,0 +1,15 @@ +.nr beers 99 1 +.nf +.while \n[beers]>0 \{ \ +.ie \n[beers]>1 \{ \ +\n[beers] bottles of beer on the wall, +\n[beers] bottles of beer.\c +\} \" ie \n[beers]>1 +.el \{ \ +\n[beers] bottle of beer on the wall, +\n[beers] bottle of beer.\c +\} \" el +Take one down, pass it around, +\n-[beers] bottles of beer on the wall. +\} \" while \n[beers]>0 +.fi diff --git a/Task/99-Bottles-of-Beer/Oforth/99-bottles-of-beer.oforth b/Task/99-Bottles-of-Beer/Oforth/99-bottles-of-beer.oforth index bc51776a8a..b4d90af114 100644 --- a/Task/99-Bottles-of-Beer/Oforth/99-bottles-of-beer.oforth +++ b/Task/99-Bottles-of-Beer/Oforth/99-bottles-of-beer.oforth @@ -1,4 +1,4 @@ "bottles of beer on the wall\n" const: B "bottles of beer\nTake one down, pass it around\n" const: T -: beer #[ dup . B print dup . T print 1- . B .cr ] 100 seq applyr ; +#[ 100 swap - dup . B print dup . T print 1- . B .cr ] 99 each diff --git a/Task/99-Bottles-of-Beer/REXX/99-bottles-of-beer.rexx b/Task/99-Bottles-of-Beer/REXX/99-bottles-of-beer.rexx index 71b7768580..9a5f8c3c94 100644 --- a/Task/99-Bottles-of-Beer/REXX/99-bottles-of-beer.rexx +++ b/Task/99-Bottles-of-Beer/REXX/99-bottles-of-beer.rexx @@ -1,20 +1,20 @@ -/*REXX program displays lyrics to the song "99 Bottles of Beer on the Wall". */ -parse arg N .; if N=='' | N=="," then N=99 /*let number of bottles be given. */ - - do j=N by -1 to 1 /*start the countdown and singdown*/ - say j 'bottle's(j) "of beer on the wall," /*sing the number bottles of beer.*/ - say j 'bottle's(j) "of beer." /* ··· and the song's refrain.*/ - say 'Take one down, pass it around,' /*take a beer bottle and share it.*/ - m=j-1 /*M: number of bottles we have now*/ - if m==0 then m='no' /*use "no" instead of numeric 0.*/ - say m 'bottle's(m) "of beer on the wall." /*sing the beer bottle inventory. */ - say /*a blank line between the verses.*/ - end /*j*/ - /*Not quite tanked? Then sing it.*/ -say 'No more bottles of beer on the wall,' /*Finally! The last verse. */ -say 'no more bottles of beer.' /*this is so forlorn ··· */ -say 'Go to the store and buy some more,' /*obtain replenishment of the beer*/ -say N 'bottles of beer on the wall.' /*all is well in the ole tavern. */ -exit /*we're all done and also sloshed.*/ +/*REXX program displays lyrics to the infamous song "99 Bottles of Beer on the Wall". */ +parse arg N .; if N=='' | N=="," then N=99 /*allow number of bottles be specified.*/ + /* [↓] downward count of beer bottles.*/ + do #=N by -1 for N /*start the countdown and singdown. */ + say # 'bottle's(#) "of beer on the wall," /*sing the number bottles of beer. */ + say # 'bottle's(#) "of beer." /* ··· and also the song's refrain.*/ + say 'Take one down, pass it around,' /*take a beer bottle ─── and share it.*/ + m= # - 1 /*M: the number of bottles we have now*/ + if m==0 then m= 'no' /*use word "no" instead of numeric 0.*/ + say m 'bottle's(m) "of beer on the wall." /*sing the beer bottle inventory. */ + say /*show a blank line between the verses.*/ + end /*#*/ /*PSA: Please drink responsibly. */ + /*Not quite tanked? Then sing it. */ +say 'No more bottles of beer on the wall,' /*Finally! The last verse. */ +say 'no more bottles of beer.' /*this is sooooooo sad and forlorn ··· */ +say 'Go to the store and buy some more,' /*obtain replenishment of the beer. */ +say N 'bottles of beer on the wall.' /*all is well in the ole town tavern. */ +exit /*we're all done, and also sloshed !. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -s: if arg(1)=1 then return ''; return 's' /*a simple pluralizer function. */ +s: if arg(1)=1 then return ''; return 's' /*simple pluralizer for gooder English.*/ diff --git a/Task/99-Bottles-of-Beer/Xojo/99-bottles-of-beer.xojo b/Task/99-Bottles-of-Beer/Xojo/99-bottles-of-beer.xojo index 42597d0947..dea756ef27 100644 --- a/Task/99-Bottles-of-Beer/Xojo/99-bottles-of-beer.xojo +++ b/Task/99-Bottles-of-Beer/Xojo/99-bottles-of-beer.xojo @@ -1,6 +1,6 @@ Dim bottles As Integer = 99 While bottles > 0 - Print(bottles.ToText) + " bottles of beer on the wall,") + Print(bottles.ToText + " bottles of beer on the wall,") Print(bottles.ToText + " bottles of beer.") Print("Take one down, pass it around.") bottles = bottles - 1 diff --git a/Task/A+B/BASIC/a+b-11.basic b/Task/A+B/BASIC/a+b-11.basic index a8f00895d3..564d38244c 100644 --- a/Task/A+B/BASIC/a+b-11.basic +++ b/Task/A+B/BASIC/a+b-11.basic @@ -1,8 +1,6 @@ -! RosettaCode: A+B -! True BASIC v6.007 -PROGRAM APLUSB - INPUT PROMPT "Enter A:":A - INPUT PROMPT "Enter B:":B - PRINT "A + B =";(A+B) - GET KEY done -END +10 INPUT A$ +20 LET I=1 +30 IF A$(I)=" " THEN GOTO 60 +40 LET I=I+1 +50 GOTO 30 +60 PRINT VAL A$( TO I-1)+VAL A$(I+1 TO ) diff --git a/Task/A+B/Ceylon/a+b.ceylon b/Task/A+B/Ceylon/a+b.ceylon index 6b8bba821c..d27c2cd5e6 100644 --- a/Task/A+B/Ceylon/a+b.ceylon +++ b/Task/A+B/Ceylon/a+b.ceylon @@ -1,23 +1,25 @@ shared void run() { - while(true) { - print("please enter two numbers for me to add"); - value input = process.readLine(); - if(exists input) { - value tokens = input.split(); - value numbers = tokens.map(parseInteger); - if(numbers.any((Integer? element) => element is Null)) { - print("numbers only, please"); - } else if(numbers.size != 2) { - print("two numbers, please"); - } else if(!numbers.coalesced.every((Integer element) => -1k <= element <= 1k)) { - print("only numbers between -1000 and 1000, please"); - } else if(exists a = numbers.first, exists b = numbers.last) { - print(a + b); - } else { - print("something went wrong"); - } - } else { - break; - } - } + + print("please enter two numbers for me to add"); + value input = process.readLine(); + if (exists input) { + value tokens = input.split().map(Integer.parse); + if (tokens.any((element) => element is ParseException)) { + print("numbers only, please"); + return; + } + value numbers = tokens.narrow(); + if (numbers.size != 2) { + print("two numbers, please"); + } + else if (!numbers.every((Integer element) => -1k <= element <= 1k)) { + print("only numbers between -1000 and 1000, please"); + } + else if (exists a = numbers.first, exists b = numbers.last) { + print(a + b); + } + else { + print("something went wrong"); + } + } } diff --git a/Task/A+B/Elena/a+b-1.elena b/Task/A+B/Elena/a+b-1.elena index 7b5270398e..96e82bd3dd 100644 --- a/Task/A+B/Elena/a+b-1.elena +++ b/Task/A+B/Elena/a+b-1.elena @@ -1,6 +1,6 @@ import extensions. -program = +public program = [ var A := Integer new. var B := Integer new. diff --git a/Task/A+B/Elena/a+b-2.elena b/Task/A+B/Elena/a+b-2.elena index 27967047a4..1f1ab29612 100644 --- a/Task/A+B/Elena/a+b-2.elena +++ b/Task/A+B/Elena/a+b-2.elena @@ -1,7 +1,7 @@ import system'routines. import extensions. -program = +public program = [ console writeLine(console readLine; split; diff --git a/Task/A+B/Oforth/a+b.oforth b/Task/A+B/Oforth/a+b.oforth index 1392dd6796..38c060bde0 100644 --- a/Task/A+B/Oforth/a+b.oforth +++ b/Task/A+B/Oforth/a+b.oforth @@ -1 +1,3 @@ -System.Console askln words map(#asInteger) sum . +import: mapping + +System.Console accept words map( #>integer) reduce( #+ ) printcr . diff --git a/Task/ABC-Problem/Astro/abc-problem.astro b/Task/ABC-Problem/Astro/abc-problem.astro index 9844a0f97a..7420d9f430 100644 --- a/Task/ABC-Problem/Astro/abc-problem.astro +++ b/Task/ABC-Problem/Astro/abc-problem.astro @@ -1,12 +1,12 @@ -fun abc(s, list): - return true if s.empty - for i in [:list.size]: - return any([abc(s[:!1], delete(val list, i))]) ... - if s[!0] in list[i] else true +fun abc(str, list): + if list.isEmpty: return true + for i in indices(list) where s[!1] in list[i]: + return abc(str[:!2], remove(val list, i)) false let test = ["A", "BARK","BOOK","TREAT","COMMON","SQUAD","CONFUSE"] -let list = ["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS","JW", -"HU","VI","AN","OB","ER","FS","LY","PC","ZM"] -for s in test: - print "$:.-8(s) | $(abc(s, list))" +let list = ["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS", +"JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"] + +for str in test: + print "$:>8(s) | $(abc(s, list))" diff --git a/Task/ABC-Problem/Elena/abc-problem.elena b/Task/ABC-Problem/Elena/abc-problem.elena index d23e1ea99a..b6773ec09c 100644 --- a/Task/ABC-Problem/Elena/abc-problem.elena +++ b/Task/ABC-Problem/Elena/abc-problem.elena @@ -9,19 +9,19 @@ extension op [ var list := ArrayList new:blocks. - ^ $nil == self literal; upperCase; seekEach(:ch) + ^ nil == self literal; upperCase; seekEach(:ch) [ var index := list indexOfElement ((:word)(word indexOf:ch at:0 != -1) asComparator). if (index>=0) - [ list remove at:index. ^ false ]; + [ list removeAt:index. ^ false ]; [ ^ true ] ] ] } -program = +public program = [ var blocks := ("BO", "XK", "DQ", "CP", "NA", "GT", "RE", "TG", "QD", "FS", diff --git a/Task/ABC-Problem/Julia/abc-problem.julia b/Task/ABC-Problem/Julia/abc-problem.julia index 5a920d21b3..52bf08a809 100644 --- a/Task/ABC-Problem/Julia/abc-problem.julia +++ b/Task/ABC-Problem/Julia/abc-problem.julia @@ -1,9 +1,17 @@ -function abc (str, list) - isempty(str) && return true - for i = eachindex(list) - str[end] in list[i] && - any([abc(str[1:end-1], deleteat!(copy(list), i))]) && - return true - end - false +function abc(str::AbstractString, list) + isempty(str) && return true + for i in eachindex(list) + str[end] in list[i] && + any([abc(str[1:end-1], deleteat!(copy(list), i))]) && + return true + end + return false +end + +let test = ["A", "BARK","BOOK","TREAT","COMMON","SQUAD","CONFUSE"], + list = ["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS", + "JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"] + for str in test + @printf("%-8s | %s\n", str, abc(str, list)) + end end diff --git a/Task/ABC-Problem/Maple/abc-problem.maple b/Task/ABC-Problem/Maple/abc-problem.maple index bffeca4f00..98312bccce 100644 --- a/Task/ABC-Problem/Maple/abc-problem.maple +++ b/Task/ABC-Problem/Maple/abc-problem.maple @@ -1,14 +1,15 @@ canSpell := proc(w) local blocks, i, j, word, letterFound; - blocks := [["B", "O"], ["X", "K"], ["D", "Q"], ["C", "P"], ["N", "A"], ["G", "T"], ["R", "E"], ["T", "G"], ["Q", "D"], ["F", "S"], - ["J", "W"], ["H", "U"], ["V", "I"], ["A", "N"], ["O", "B"], ["E", "R"], ["F", "S"], ["L", "Y"], ["P", "C"], ["Z", "M"]]; + blocks := Array([["B", "O"], ["X", "K"], ["D", "Q"], ["C", "P"], ["N", "A"], ["G", "T"], ["R", "E"], ["T", "G"], + ["Q", "D"], ["F", "S"], ["J", "W"], ["H", "U"], ["V", "I"], ["A", "N"], ["O", "B"], ["E", "R"], + ["F", "S"], ["L", "Y"], ["P", "C"], ["Z", "M"]]); word := StringTools[UpperCase](convert(w, string)); for i to length(word) do letterFound := false; - for j to numelems(blocks) do - if not letterFound and (substring(word, i) = blocks[j][1] or substring(word, i) = blocks[j][2]) then - blocks[j][1] := undefined; - blocks[j][2] := undefined; + for j to numelems(blocks)/2 do + if not letterFound and (substring(word, i) = blocks[j,1] or substring(word, i) = blocks[j,2]) then + blocks[j,1] := undefined; + blocks[j,2] := undefined; letterFound := true; end if; end do; diff --git a/Task/ABC-Problem/Oforth/abc-problem.oforth b/Task/ABC-Problem/Oforth/abc-problem.oforth index 6689704078..21bb247b9a 100644 --- a/Task/ABC-Problem/Oforth/abc-problem.oforth +++ b/Task/ABC-Problem/Oforth/abc-problem.oforth @@ -1,10 +1,14 @@ -["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS","JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"] const: ABCBlocks +import: mapping + +["BO","XK","DQ","CP","NA","GT","RE","TG","QD","FS","JW","HU","VI","AN","OB","ER","FS","LY","PC","ZM"] +const: ABCBlocks : canMakeWord(w, blocks) | i | - w isEmpty ifTrue: [ true return ] + w empty? ifTrue: [ true return ] blocks size loop: i [ - blocks at(i) include(w first toUpper) ifFalse: [ continue ] - canMakeWord(w right(w size 1 -), blocks del(i, i)) ifTrue: [ true return ] + w first >upper blocks at(i) include? ifFalse: [ continue ] + canMakeWord( w right( w size 1- ), blocks del(i, i) ) ifTrue: [ true return ] ] - false ; + false +; diff --git a/Task/ABC-Problem/Red/abc-problem.red b/Task/ABC-Problem/Red/abc-problem.red new file mode 100644 index 0000000000..0b3235f9d3 --- /dev/null +++ b/Task/ABC-Problem/Red/abc-problem.red @@ -0,0 +1,16 @@ +Red [] +test: func [ s][ +p: copy "BOXKDQCPNAGTRETGQDFSJWHUVIANOBERFSLYPCZM" +forever [ + if 0 = length? s [ return 'true ] ;; if string cleared, all chars found/removed + if tail? p [ return 'false ] ;; if at end of search block - not found + rule: reduce [ first p '| second p] ;; construct parse rule from string + either parse s [ to rule remove rule to end ] [ ;; remove found char from string + remove/part p 2 ;;character found , remove block + p: head p ;;start from remaining string at beginning aka head + ] [ p: skip p 2 ] ;; else move to next block +] +] +foreach word split {A bark book TrEAT COmMoN SQUAD conFUsE} space [ + print reduce [ pad copy word 8 ":" test word] + ] diff --git a/Task/ABC-Problem/VBA/abc-problem.vba b/Task/ABC-Problem/VBA/abc-problem.vba new file mode 100644 index 0000000000..a51ab492a0 --- /dev/null +++ b/Task/ABC-Problem/VBA/abc-problem.vba @@ -0,0 +1,34 @@ +Option Explicit + +Sub Main_ABC() +Dim Arr, i As Long + + Arr = Array("A", "BARK", "BOOK", "TREAT", "COMMON", "SQUAD", "CONFUSE") + For i = 0 To 6 + Debug.Print ">>> can_make_word " & Arr(i) & " => " & ABC(CStr(Arr(i))) + Next i +End Sub + +Function ABC(myWord As String) As Boolean +Dim myColl As New Collection +Dim NbLoop As Long, NbInit As Long +Dim b As Byte, i As Byte +Const BLOCKS As String = "B,O;X,K;D,Q;C,P;N,A;G,T;R,E;T,G;Q,D;F,S;J,W;H,U;V,I;A,N;O,B;E,R;F,S;L,Y;P,C;Z,M" + + For b = 0 To 19 + myColl.Add Split(BLOCKS, ";")(b), Split(BLOCKS, ";")(b) & b + Next b + NbInit = myColl.Count + NbLoop = NbInit + For b = 1 To Len(myWord) + For i = 1 To NbLoop + If i > NbLoop Then Exit For + If InStr(myColl(i), Mid(myWord, b, 1)) <> 0 Then + myColl.Remove (i) + NbLoop = NbLoop - 1 + Exit For + End If + Next + Next b + ABC = (NbInit = (myColl.Count + Len(myWord))) +End Function diff --git a/Task/AKS-test-for-primes/8th/aks-test-for-primes.8th b/Task/AKS-test-for-primes/8th/aks-test-for-primes.8th new file mode 100644 index 0000000000..b4a4571fd5 --- /dev/null +++ b/Task/AKS-test-for-primes/8th/aks-test-for-primes.8th @@ -0,0 +1,56 @@ +with: a + +: nextrow \ a -- a + len + [ ( drop [1] ), + ( drop [1,1] ), + ( ' n:+ y 1 slide 1 push ) ] + swap 2 min caseof ; + +;with + +with: n + +: .x \ n -- + dup + [ ( drop ), + ( drop "x" . ), + ( "x^" . . ) ] + swap 2 min caseof space ; + +: .term \ coef exp -- ; omit coef for 1x^n when n > 0 + over 1 = over 0 > and if nip .x else swap . .x then ; + +: .sgn \ +/-1 -- + [ "-", null, "+" ] + swap 1+ caseof . space ; + +: .lhs \ n -- + "(x-1)^" . . ; + +: .rhs \ a -- a + a:len 1- >r + 1 swap ( third .sgn r@ rot - .term -1 * ) a:each + nip rdrop ; + +: .eqn \ a -- a + a:len 1- .lhs " = " . .rhs ; + +: .binomials \ -- + [] ( nextrow .eqn cr ) 8 times drop ; + +: primerow? \ a -- a ? + a:len 3 < if false ;then + 1 a:@ >r \ 2nd position is the number to check for primality + true swap ( nip dup 1 = swap r@ mod 0 = or and ) a:each swap + rdrop ; + +: .primes-via-aks \ -- + [] ( nextrow primerow? if 1 a:@ . space then ) 50 times drop ; + +;with + +.binomials cr +"The primes upto 50 are (via AKS): " . .primes-via-aks cr + +bye diff --git a/Task/AKS-test-for-primes/Elena/aks-test-for-primes.elena b/Task/AKS-test-for-primes/Elena/aks-test-for-primes.elena new file mode 100644 index 0000000000..1e3297daff --- /dev/null +++ b/Task/AKS-test-for-primes/Elena/aks-test-for-primes.elena @@ -0,0 +1,82 @@ +import extensions. + +singleton AksTest +{ + static Array c := V(100). + + coef(int n) + [ + int i := 0. + int j := 0. + + if ((n < 0) || (n > 63)) [ AbortException new; raise ]. // gracefully deal with range issue + + c[i] := 1l. + while(i < n) + [ + j := i. + c[1 + j] := 1l. + while (j > 0) + [ + c[j] := c[j - 1] - c[j]. + + j -= 1 + ]. + + c[0] := c[0] negative. + i += 1 + ]. + + var t := c. + ] + + bool is_prime(int n) + [ + int i := n. + + self coef(n). + (c[0]) += 1. + (c[i]) -= 1. + + i -= 1. + while ((i + 1 != 0) && (c[i+1] mod(n) == 0)) + [ + i -= 1 + ]. + + ^ i < 0 + ] + + show(int n) + [ + int i := n. + i += 1. + while(i != 0) + [ + i -= 1. + console print("+",c[i],"x^",i). + ] + ] +} + +public program = +[ + 0 till:10 do(:n) + [ + AksTest coef(n). + + console print("(x-1)^",n," = "). + AksTest show(n). + console printLine. + ]. + console print("Primes:"). + 1 to(63) do(:n) + [ + if (AksTest is_prime(n)) + [ + console print(n," "). + ] + ]. + + console printLine; readLine +]. diff --git a/Task/AKS-test-for-primes/Oforth/aks-test-for-primes.oforth b/Task/AKS-test-for-primes/Oforth/aks-test-for-primes.oforth index 709c0c889d..bd2b05f760 100644 --- a/Task/AKS-test-for-primes/Oforth/aks-test-for-primes.oforth +++ b/Task/AKS-test-for-primes/Oforth/aks-test-for-primes.oforth @@ -1,13 +1,20 @@ -: nextCoef(prev) -| i | - ListBuffer new dup add(0) - prev size 1- loop: i [ dup add(prev at(i) prev at(i 1+) - ) ] - dup add(0) ; +import: mapping -: coefs(n) [ 0, 1, 0 ] #nextCoef times(n) extract(2, n 2 + ) ; -: isPrime(n) coefs(n) extract(2, n) conform(#[n mod 0 == ]) ; +: nextCoef( prev -- [] ) +| i | + Array new 0 over dup + prev size 1- loop: i [ prev at(i) prev at(i 1+) - over add ] + 0 over add +; + +: coefs( n -- [] ) + [ 0, 1, 0 ] #nextCoef times(n) extract(2, n 2 + ) ; + +: prime?( n -- b) + coefs( n ) extract(2, n) conform?( #[n mod 0 == ] ) ; : aks | i | - 0 10 for: i [ System.Out "(x-1)^" << i << " = " << coefs(i) << cr ] - 50 seq filter(#isPrime) apply(#[ print " " print ]) printcr ; + 0 10 for: i [ System.Out "(x-1)^" << i << " = " << coefs( i ) << cr ] + 50 seq filter( #prime? ) apply(#.) printcr +; diff --git a/Task/AKS-test-for-primes/Perl-6/aks-test-for-primes.pl6 b/Task/AKS-test-for-primes/Perl-6/aks-test-for-primes.pl6 new file mode 100644 index 0000000000..73a468d6a6 --- /dev/null +++ b/Task/AKS-test-for-primes/Perl-6/aks-test-for-primes.pl6 @@ -0,0 +1,31 @@ +constant expansions = [1], [1,-1], -> @prior { [|@prior,0 Z- 0,|@prior] } ... *; + +sub polyprime($p where 2..*) { so expansions[$p].[1 ..^ */2].all %% $p } + +# Showing the expansions: + +say ' p: (x-1)ᵖ'; +say '-----------'; + +sub super ($n) { + $n.trans: '0123456789' + => '⁰¹²³⁴⁵⁶⁷⁸⁹'; +} + +for ^13 -> $d { + say $d.fmt('%2i: '), ( + expansions[$d].kv.map: -> $i, $n { + my $p = $d - $i; + [~] gather { + take < + - >[$n < 0] ~ ' ' unless $p == $d; + take $n.abs unless $p == $d > 0; + take 'x' if $p > 0; + take super $p - $i if $p > 1; + } + } + ) +} + +# And testing the function: + +print "\nPrimes up to 100:\n { grep &polyprime, 2..100 }\n"; diff --git a/Task/AKS-test-for-primes/R/aks-test-for-primes.r b/Task/AKS-test-for-primes/R/aks-test-for-primes.r new file mode 100644 index 0000000000..924afc479a --- /dev/null +++ b/Task/AKS-test-for-primes/R/aks-test-for-primes.r @@ -0,0 +1,9 @@ +AKS<-function(p){ + i<-2:p-1 + l<-unique(factorial(p) / (factorial(p-i) * factorial(i))) + if(all(l%%p==0)){ + print(noquote("It is prime.")) + }else{ + print(noquote("It isn't prime.")) + } +} diff --git a/Task/AKS-test-for-primes/REXX/aks-test-for-primes-2.rexx b/Task/AKS-test-for-primes/REXX/aks-test-for-primes-2.rexx index 2371997158..a74f05877c 100644 --- a/Task/AKS-test-for-primes/REXX/aks-test-for-primes-2.rexx +++ b/Task/AKS-test-for-primes/REXX/aks-test-for-primes-2.rexx @@ -1,41 +1,42 @@ /*REXX program calculates primes via the Agrawal─Kayal─Saxena (AKS) primality test.*/ -parse arg Z .; if Z=='' then Z=200 /*Z not specified? Then use default.*/ -OZ=Z; tell= Z<0; Z=abs(Z) /*Is Z negative? Then show expression.*/ -numeric digits max(9, Z%3) /*define a dynamic # of decimal digits.*/ -$.0='-'; $.1="+"; @.=1 /*$.x: sign char; default coefficients.*/ -#= /*define list of prime numbers (so far)*/ - do p=3 for Z; pm=p-1; pp=p+1 /*PM & PP: used as a coding convenience*/ - do m=2 for pp%2-1; mm=m-1 /*calculate coefficients for a power. */ - @.p.m=@.pm.mm + @.pm.m; h=pp-m /*calculate left side of coefficients*/ - @.p.h=@.p.m /* " right " " " */ - end /*m*/ /* [↑] The M DO loop creates both */ - end /*p*/ /* sides in the same loop, saving */ - /* a bunch of execution time. */ -if tell then say '(x-1)^0: 1' /*possibly display the first expression*/ - /* [↓] test for primality by division.*/ - do n=2 for Z; nh=n%2; d=n-1 /*create expressions; find the primes.*/ - do k=3 to nh while @.n.k//d==0 /*are coefficients divisible by N-1 ? */ - end /*k*/ /* [↑] skip the 1st & 2nd coefficients*/ - /* [↓] multiple THEN─IF faster than &s*/ - if k>nh then if d\==1 then if d\==4 then #=# d /*add a number to prime list.*/ - if \tell then iterate /*Don't tell? Don't show expressions.*/ - y='(x-1)^'d": " /*define the 1st part of the expression*/ - s=1 /*S: is the sign indicator (-1│+1).*/ - do j=n for n-1 by -1; jm=j-1 /*create the higher powers first. */ - if j==2 then xp='x' /*if power=1, then don't show the power*/ - else xp='x^'jm /* ··· else show power with ^ */ - if j==n then y=y xp /*no sign (+│-) for the 1st expression.*/ - else y=y $.s || @.n.j'∙'xp /*build the expression with sign (+|-).*/ - s=\s /*flip the sign for the next expression*/ - end /*j*/ /* [↑] the sign (now) is either 0 │ 1,*/ - /* and is displayed either - │ + */ - say y $.s || 1 /*just show the first N expressions, */ - end /*n*/ /* [↑] ··· but only for negative Z. */ -say /* [↓] Has Z a leading + ? Then show.*/ -if Z==word(. #, words(#)+1) then is= 'is' /*the number is a prime. */ - else is= "isn't" /* " " isn't " " */ -if left(OZ, 1)=='+' then say Z is 'prime.' /*display if OZ has a + (plus sign).*/ - else say 'primes:' # /*display the prime number list. */ -say /* [↓] the digit length of a big coef.*/ -say 'Found ' words(#) " primes and the largest coefficient has " length(@.pm.h), - " decimal digits." /*stick a fork in it, we're all done. */ +parse arg Z .; if Z=='' | Z=="," then Z=200 /*Z not specified? Then use default.*/ +OZ=Z; tell= Z<0; Z=abs(Z) /*Is Z negative? Then show expression.*/ +numeric digits max(9, Z % 3) /*define a dynamic # of decimal digits.*/ +call AKS /*invoke the AKS funtion for coef. bld.*/ +if left(OZ,1)=='+' then do; say Z isAksp(); exit /*display if Z is or isn't a prime.*/ + end /* [↑] call isAKSp if Z has leading +.*/ +say; say "primes found:" # /*display the prime number list. */ +say; if \datatype(#, 'W') then exit /* [↓] the digit length of a big coef.*/ +say 'Found ' words(#) " primes and the largest coefficient has " length(@.pm.h) @dd +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +isAKSp: if z==word(#,words(#)) then return ' is a prime.'; else return " isn't a prime." +/*──────────────────────────────────────────────────────────────────────────────────────*/ +AKS: $.0= '-'; $.1= "+"; @.=1 /*$.x: sign char; default coefficients.*/ + q.=1; q.1=0; q.4=0 /*sparse array for faster comparisons. */ + #=; L= length(Z) /*define list of prime numbers (so far)*/ + do p=3 for Z; pm=p - 1; pp=p + 1 /*PM & PP: used as a coding convenience*/ + do m=2 for pp % 2 - 1; mm=m - 1 /*calculate coefficients for a power. */ + @.p.m= @.pm.mm + @.pm.m; h=pp - m /*calculate left side of coefficients*/ + @.p.h= @.p.m /* " right " " " */ + end /*m*/ /* [↑] The M DO loop creates both */ + end /*p*/ /* sides in the same loop. */ + if tell then say '(x-1)^'right(0, L)": 1" /*possibly display the first expression*/ + @dd= 'decimal digits.' /* [↓] test for primality by division.*/ + do n=2 for Z; nh=n % 2; d=n - 1 /*create expressions; find the primes.*/ + do k=3 to nh while @.n.k//d==0 /*are coefficients divisible by N-1 ? */ + end /*k*/ /* [↑] skip the 1st & 2nd coefficients*/ + if k>nh then if q.d then #=# d /*add a number to the prime list. */ + if \tell then iterate /*Don't tell? Don't show expressions.*/ + y='(x-1)^'right(d, L)": " /*define the 1st part of the expression*/ + s=1 /*S: is the sign indicator (-1│+1).*/ + do j=n for n-1 by -1 /*create the higher powers first. */ + if j==2 then xp= 'x' /*if power=1, then don't show the power*/ + else xp= 'x^' || (j-1) /* ··· else show power with ^ */ + if j==n then y=y xp /*no sign (+│-) for the 1st expression.*/ + else y=y $.s || @.n.j'∙'xp /*build the expression with sign (+|-).*/ + s= \s /*flip the sign for the next expression*/ + end /*j*/ /* [↑] the sign (now) is either 0 │ 1,*/ + say y $.s'1' /*just show the first N expressions, */ + end /*n*/ /* [↑] ··· but only for negative Z. */ + if #=='' then #='none'; return # /*if null, return "none"; else return #*/ diff --git a/Task/Abstract-type/Julia/abstract-type-1.julia b/Task/Abstract-type/Julia/abstract-type-1.julia index a27849a327..46342ee217 100644 --- a/Task/Abstract-type/Julia/abstract-type-1.julia +++ b/Task/Abstract-type/Julia/abstract-type-1.julia @@ -1,2 +1,2 @@ -abstract «name» -abstract «name» <: «supertype» +abstract type «name» end +abstract type «name» <: «supertype» end diff --git a/Task/Abstract-type/Julia/abstract-type-2.julia b/Task/Abstract-type/Julia/abstract-type-2.julia index 70af29b407..1ec517793a 100644 --- a/Task/Abstract-type/Julia/abstract-type-2.julia +++ b/Task/Abstract-type/Julia/abstract-type-2.julia @@ -1,6 +1,6 @@ -abstract Number -abstract Real <: Number -abstract FloatingPoint <: Real -abstract Integer <: Real -abstract Signed <: Integer -abstract Unsigned <: Integer +abstract type Number end +abstract type Real <: Number end +abstract type FloatingPoint <: Real end +abstract type Integer <: Real end +abstract type Signed <: Integer end +abstract type Unsigned <: Integer end diff --git a/Task/Abstract-type/Oforth/abstract-type-1.oforth b/Task/Abstract-type/Oforth/abstract-type-1.oforth index c1d9d05864..bb39e73293 100644 --- a/Task/Abstract-type/Oforth/abstract-type-1.oforth +++ b/Task/Abstract-type/Oforth/abstract-type-1.oforth @@ -1,8 +1,8 @@ Property new: Spherical(r) Spherical method: radius @r ; Spherical method: setRadius := r ; -Spherical method: perimeter @r 2 * Pi * ; -Spherical method: surface @r sq Pi * 4 * ; +Spherical method: perimeter @r 2 * PI * ; +Spherical method: surface @r sq PI * 4 * ; Object Class new: Ballon(color) Ballon is: Spherical diff --git a/Task/Abstract-type/Oforth/abstract-type-2.oforth b/Task/Abstract-type/Oforth/abstract-type-2.oforth index fb880a83e5..8a677c8c7c 100644 --- a/Task/Abstract-type/Oforth/abstract-type-2.oforth +++ b/Task/Abstract-type/Oforth/abstract-type-2.oforth @@ -8,4 +8,5 @@ Planete new("Earth", 6371000.0) ->p System.Out "Earth radius is : " << p radius << cr System.Out "Earth perimeter is : " << p perimeter << cr - System.Out "Earth surface is : " << p surface << cr ; + System.Out "Earth surface is : " << p surface << cr +; diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Elena/abundant,-deficient-and-perfect-number-classifications.elena b/Task/Abundant,-deficient-and-perfect-number-classifications/Elena/abundant,-deficient-and-perfect-number-classifications.elena new file mode 100644 index 0000000000..4fa19b9994 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Elena/abundant,-deficient-and-perfect-number-classifications.elena @@ -0,0 +1,41 @@ +import extensions. + +classifyNumbers = +{ + eval(int bound, ref abundant, ref deficient, ref perfect) + [ + int a := 0. + int d := 0. + int p := 0. + Array sum := V(bound + 1). + + 1 to(bound / 2) do(:divisor) + [ + (divisor + divisor) to:bound by:divisor do(:i) + [ + (sum[i]) += divisor + ]. + ]. + 1 to:bound do(:i) + [ + int t := sum[i]. + + if (sum[i]i) [ a += 1 ]; + [ p += 1 ] + ]. + + abundant value := a. + deficient value := d. + perfect value := p + ] +}. + +public program = +[ + int abundant := 0. + int deficient := 0. + int perfect := 0. + classifyNumbers eval(20000, &abundant, &deficient, &perfect). + console printLine("Abundant: ",abundant,", Deficient: ",deficient,", Perfect: ",perfect). +]. diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Erlang/abundant,-deficient-and-perfect-number-classifications.erl b/Task/Abundant,-deficient-and-perfect-number-classifications/Erlang/abundant,-deficient-and-perfect-number-classifications-1.erl similarity index 100% rename from Task/Abundant,-deficient-and-perfect-number-classifications/Erlang/abundant,-deficient-and-perfect-number-classifications.erl rename to Task/Abundant,-deficient-and-perfect-number-classifications/Erlang/abundant,-deficient-and-perfect-number-classifications-1.erl diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Erlang/abundant,-deficient-and-perfect-number-classifications-2.erl b/Task/Abundant,-deficient-and-perfect-number-classifications/Erlang/abundant,-deficient-and-perfect-number-classifications-2.erl new file mode 100644 index 0000000000..221976e804 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Erlang/abundant,-deficient-and-perfect-number-classifications-2.erl @@ -0,0 +1,29 @@ +-module(proper_divisors). +-export([classify_range/2]). + +classify_range(Start, Stop) -> + lists:foldl(fun (X, A) -> + Class = classify(X), + A#{Class => maps:get(Class, A, 0)+1} end, + #{}, + lists:seq(Start, Stop)). + +classify(N) -> + SumPD = lists:sum(proper_divisors(N)), + if + SumPD < N -> deficient; + SumPD =:= N -> perfect; + SumPD > N -> abundant + end. + +proper_divisors(1) -> []; +proper_divisors(N) when N > 1, is_integer(N) -> + proper_divisors(2, math:sqrt(N), N, [1]). + +proper_divisors(I, L, _, A) when I > L -> lists:sort(A); +proper_divisors(I, L, N, A) when N rem I =/= 0 -> + proper_divisors(I+1, L, N, A); +proper_divisors(I, L, N, A) when I * I =:= N -> + proper_divisors(I+1, L, N, [I|A]); +proper_divisors(I, L, N, A) -> + proper_divisors(I+1, L, N, [N div I, I|A]). diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Factor/abundant,-deficient-and-perfect-number-classifications.factor b/Task/Abundant,-deficient-and-perfect-number-classifications/Factor/abundant,-deficient-and-perfect-number-classifications.factor new file mode 100644 index 0000000000..8bfc4291f3 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Factor/abundant,-deficient-and-perfect-number-classifications.factor @@ -0,0 +1,8 @@ +USING: fry math.primes.factors math.ranges ; +: psum ( n -- m ) divisors but-last sum ; +: pcompare ( n -- <=> ) dup psum swap <=> ; +: classify ( -- seq ) 20,000 [1,b] [ pcompare ] map ; +: pcount ( <=> -- n ) '[ _ = ] count ; +classify [ +lt+ pcount "Deficient: " write . ] + [ +eq+ pcount "Perfect: " write . ] + [ +gt+ pcount "Abundant: " write . ] tri diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Modula-2/abundant,-deficient-and-perfect-number-classifications.mod2 b/Task/Abundant,-deficient-and-perfect-number-classifications/Modula-2/abundant,-deficient-and-perfect-number-classifications.mod2 new file mode 100644 index 0000000000..5b13fd6868 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Modula-2/abundant,-deficient-and-perfect-number-classifications.mod2 @@ -0,0 +1,47 @@ +MODULE ADP; +FROM FormatString IMPORT FormatString; +FROM Terminal IMPORT WriteString,WriteLn,ReadChar; + +PROCEDURE ProperDivisorSum(n : INTEGER) : INTEGER; +VAR i,sum : INTEGER; +BEGIN + sum := 0; + IF n<2 THEN + RETURN 0 + END; + FOR i:=1 TO (n DIV 2) DO + IF n MOD i = 0 THEN + INC(sum,i) + END + END; + RETURN sum +END ProperDivisorSum; + +VAR + buf : ARRAY[0..63] OF CHAR; + n : INTEGER; + d,p,a : INTEGER = 0; + sum : INTEGER; +BEGIN + FOR n:=1 TO 20000 DO + sum := ProperDivisorSum(n); + IF sumn THEN + INC(a) + END + END; + + WriteString("The classification of the numbers from 1 to 20,000 is as follows:"); + WriteLn; + + FormatString("Deficient = %i\n", buf, d); + WriteString(buf); + FormatString("Perfect = %i\n", buf, p); + WriteString(buf); + FormatString("Abundant = %i\n", buf, a); + WriteString(buf); + ReadChar +END ADP. diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Oforth/abundant,-deficient-and-perfect-number-classifications.oforth b/Task/Abundant,-deficient-and-perfect-number-classifications/Oforth/abundant,-deficient-and-perfect-number-classifications.oforth index 5dd5b52817..efe25451d3 100644 --- a/Task/Abundant,-deficient-and-perfect-number-classifications/Oforth/abundant,-deficient-and-perfect-number-classifications.oforth +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Oforth/abundant,-deficient-and-perfect-number-classifications.oforth @@ -1,14 +1,18 @@ -Integer method: properDivs self 2 / seq filter(#[ self swap mod 0 == ]) ; +import: mapping + +Integer method: properDivs -- [] + self 2 / seq filter( #[ self swap mod 0 == ] ) ; : numberClasses | i deficient perfect s | 0 0 ->deficient ->perfect 0 20000 loop: i [ - i properDivs sum ->s + 0 #+ i properDivs apply ->s s i < ifTrue: [ deficient 1+ ->deficient continue ] s i == ifTrue: [ perfect 1+ ->perfect continue ] 1+ ] - "Deficients : " print deficient println - "Perfects : " print perfect println - "Abundant : " print println ; + "Deficients :" . deficient .cr + "Perfects :" . perfect .cr + "Abundant :" . .cr +; diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/Ruby/abundant,-deficient-and-perfect-number-classifications.rb b/Task/Abundant,-deficient-and-perfect-number-classifications/Ruby/abundant,-deficient-and-perfect-number-classifications.rb index 30415fb5b2..b15e4d2508 100644 --- a/Task/Abundant,-deficient-and-perfect-number-classifications/Ruby/abundant,-deficient-and-perfect-number-classifications.rb +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/Ruby/abundant,-deficient-and-perfect-number-classifications.rb @@ -1,3 +1,3 @@ res = Hash.new(0) -(1 .. 20_000).each{|n| res[n.proper_divisors.inject(0, :+) <=> n] += 1} +(1 .. 20_000).each{|n| res[n.proper_divisors.sum <=> n] += 1} puts "Deficient: #{res[-1]} Perfect: #{res[0]} Abundant: #{res[1]}" diff --git a/Task/Abundant,-deficient-and-perfect-number-classifications/VBA/abundant,-deficient-and-perfect-number-classifications.vba b/Task/Abundant,-deficient-and-perfect-number-classifications/VBA/abundant,-deficient-and-perfect-number-classifications.vba new file mode 100644 index 0000000000..7c92a4def3 --- /dev/null +++ b/Task/Abundant,-deficient-and-perfect-number-classifications/VBA/abundant,-deficient-and-perfect-number-classifications.vba @@ -0,0 +1,32 @@ +Option Explicit + +Public Sub Nb_Classifications() +Dim A As New Collection, D As New Collection, P As New Collection +Dim n As Long, l As Long, s As String, t As Single + + t = Timer + 'Start + For n = 1 To 20000 + l = SumPropers(n): s = CStr(n) + Select Case n + Case Is > l: D.Add s, s + Case Is < l: A.Add s, s + Case l: P.Add s, s + End Select + Next + + 'End. Return : + Debug.Print "Execution Time : " & Timer - t & " seconds." + Debug.Print "-------------------------------------------" + Debug.Print "Deficient := " & D.Count + Debug.Print "Perfect := " & P.Count + Debug.Print "Abundant := " & A.Count +End Sub + +Private Function SumPropers(n As Long) As Long +'returns the sum of the proper divisors of n +Dim j As Long + For j = 1 To n \ 2 + If n Mod j = 0 Then SumPropers = j + SumPropers + Next +End Function diff --git a/Task/Accumulator-factory/Astro/accumulator-factory.astro b/Task/Accumulator-factory/Astro/accumulator-factory.astro index 15b7d041e9..d3658b04cb 100644 --- a/Task/Accumulator-factory/Astro/accumulator-factory.astro +++ b/Task/Accumulator-factory/Astro/accumulator-factory.astro @@ -1,5 +1,5 @@ -fun accumulator(sum): |n| -> sum += n -let f = accumulator(5) -print f(5) # 10 -print f(10) # 20 +fun accumulator(sum) = |n| => sum += n +let f = accumulator(5.) +print f(5) # 10.0 +print f(10) # 20.0 print f(2.4) # 22.4 diff --git a/Task/Accumulator-factory/Elena/accumulator-factory.elena b/Task/Accumulator-factory/Elena/accumulator-factory.elena index 79b8cb52a4..8a2bba9eb0 100644 --- a/Task/Accumulator-factory/Elena/accumulator-factory.elena +++ b/Task/Accumulator-factory/Elena/accumulator-factory.elena @@ -1,21 +1,16 @@ -import system'dynamic. +function = + (:acc)((:n)(acc append:n)). -Function = - (:x)(closure append:x). +accumulator = + (:n)(function(Variable new(n))). -extension op -{ - accumulatorOf:func - = Variable new(self); mixInto(func). -} - -program = +public program = [ - var x := 1 accumulatorOf(Function). + var x := accumulator(1). - x eval(5). + x(5). - var y := 3 accumulatorOf(Function). + var y := accumulator(3). - console write(x eval(2.3r)). + console write(x(2.3r)). ]. diff --git a/Task/Accumulator-factory/Factor/accumulator-factory.factor b/Task/Accumulator-factory/Factor/accumulator-factory.factor index dbe12b3cda..41f2ac2280 100644 --- a/Task/Accumulator-factory/Factor/accumulator-factory.factor +++ b/Task/Accumulator-factory/Factor/accumulator-factory.factor @@ -1,3 +1,4 @@ +USE: locals :: accumulator ( n! -- quot ) [ n + dup n! ] ; 1 accumulator diff --git a/Task/Accumulator-factory/Java/accumulator-factory-1.java b/Task/Accumulator-factory/Java/accumulator-factory-1.java index 408e9f5b40..baaf7d1b53 100644 --- a/Task/Accumulator-factory/Java/accumulator-factory-1.java +++ b/Task/Accumulator-factory/Java/accumulator-factory-1.java @@ -1,16 +1,29 @@ -public class Accumulator { - private double sum; - public Accumulator(double sum0) { - sum = sum0; +public class Accumulator + //implements java.util.function.UnaryOperator // Java 8 +{ + private Number sum; + + public Accumulator(Number sum0) { + sum = sum0; } - public double call(double n) { - return sum += n; + + public Number apply(Number n) { + // Acts like sum += n, but chooses long or double. + // Converts weird types (like BigInteger) to double. + return (longable(sum) && longable(n)) ? + (sum = sum.longValue() + n.longValue()) : + (sum = sum.doubleValue() + n.doubleValue()); + } + + private static boolean longable(Number n) { + return n instanceof Byte || n instanceof Short || + n instanceof Integer || n instanceof Long; } public static void main(String[] args) { - Accumulator x = new Accumulator(1); - x.call(5); - System.out.println(new Accumulator(3)); - System.out.println(x.call(2.3)); + Accumulator x = new Accumulator(1); + x.apply(5); + new Accumulator(3); + System.out.println(x.apply(2.3)); } } diff --git a/Task/Accumulator-factory/Java/accumulator-factory-2.java b/Task/Accumulator-factory/Java/accumulator-factory-2.java index 408e9f5b40..809a579c04 100644 --- a/Task/Accumulator-factory/Java/accumulator-factory-2.java +++ b/Task/Accumulator-factory/Java/accumulator-factory-2.java @@ -1,16 +1,27 @@ -public class Accumulator { - private double sum; - public Accumulator(double sum0) { - sum = sum0; +import java.util.function.UnaryOperator; + +public class AccumulatorFactory { + + public static UnaryOperator accumulator(Number sum0) { + // Allows sum[0] = ... inside lambda. + Number[] sum = { sum0 }; + + // Acts like n -> sum[0] += n, but chooses long or double. + // Converts weird types (like BigInteger) to double. + return n -> (longable(sum[0]) && longable(n)) ? + (sum[0] = sum[0].longValue() + n.longValue()) : + (sum[0] = sum[0].doubleValue() + n.doubleValue()); } - public double call(double n) { - return sum += n; + + private static boolean longable(Number n) { + return n instanceof Byte || n instanceof Short || + n instanceof Integer || n instanceof Long; } public static void main(String[] args) { - Accumulator x = new Accumulator(1); - x.call(5); - System.out.println(new Accumulator(3)); - System.out.println(x.call(2.3)); + UnaryOperator x = accumulator(1); + x.apply(5); + accumulator(3); + System.out.println(x.apply(2.3)); } } diff --git a/Task/Accumulator-factory/Julia/accumulator-factory.julia b/Task/Accumulator-factory/Julia/accumulator-factory.julia index 0a6dd73cfd..fb101dc6bc 100644 --- a/Task/Accumulator-factory/Julia/accumulator-factory.julia +++ b/Task/Accumulator-factory/Julia/accumulator-factory.julia @@ -1,7 +1,10 @@ function accumulator(i) f(n) = i += n + return f end + x = accumulator(1) -x(5) +@show x(5) + accumulator(3) -x(2.3) +@show x(2.3) diff --git a/Task/Accumulator-factory/Oforth/accumulator-factory-1.oforth b/Task/Accumulator-factory/Oforth/accumulator-factory-1.oforth index bcec77c0f1..920d0c20a6 100644 --- a/Task/Accumulator-factory/Oforth/accumulator-factory-1.oforth +++ b/Task/Accumulator-factory/Oforth/accumulator-factory-1.oforth @@ -1,4 +1,2 @@ -: foo(n) -| ch | - Channel new dup ->ch send(n) drop - #[ ch receive swap + dup ch send drop ] ; +: foo( n -- bl ) + #[ n swap + dup ->n ] ; diff --git a/Task/Accumulator-factory/Oforth/accumulator-factory-2.oforth b/Task/Accumulator-factory/Oforth/accumulator-factory-2.oforth index cd9ea24f77..7aa551962c 100644 --- a/Task/Accumulator-factory/Oforth/accumulator-factory-2.oforth +++ b/Task/Accumulator-factory/Oforth/accumulator-factory-2.oforth @@ -1,9 +1,10 @@ : testfoo | x y z | - foo(1) ->x + 1 foo ->x 5 x perform . - foo(3) ->y - 2.3 x perform dup . ", x accumulator value is a " . class .cr - 10 y perform dup . ", y accumulator value is a " . class .cr - foo("aaa") ->z - "bbb" z perform dup . ", z accumulator value is a " . class .cr ; + 3 foo ->y + 2.3 x perform dup . ", x accumulator value is a" . class .cr + 10 y perform dup . ", y accumulator value is a" . class .cr + "aaa" foo ->z + "bbb" z perform dup . ", z accumulator value is a" . class .cr +; diff --git a/Task/Accumulator-factory/Perl-6/accumulator-factory.pl6 b/Task/Accumulator-factory/Perl-6/accumulator-factory.pl6 new file mode 100644 index 0000000000..3a62534eca --- /dev/null +++ b/Task/Accumulator-factory/Perl-6/accumulator-factory.pl6 @@ -0,0 +1,12 @@ +sub accum ($n is copy) { sub { $n += $^x } } + +#Example use: +my $a = accum 5; +$a(4.5); +say $a(.5); # Prints "10". + +# You can also use the "&" sigil to create a function that behaves syntactically +# like any other function (i.e. no sigil nor parentheses needed to call it): + +my &b = accum 5; +say b 3; # Prints "8". diff --git a/Task/Accumulator-factory/Ruby/accumulator-factory-1.rb b/Task/Accumulator-factory/Ruby/accumulator-factory-1.rb new file mode 100644 index 0000000000..7042462d26 --- /dev/null +++ b/Task/Accumulator-factory/Ruby/accumulator-factory-1.rb @@ -0,0 +1,9 @@ +def accumulator(sum) + lambda {|n| sum += n} +end + +# mixing Integer and Float +x = accumulator(1) +x.call(5) +accumulator(3) +puts x.call(2.3) # prints 8.3 diff --git a/Task/Accumulator-factory/Ruby/accumulator-factory-2.rb b/Task/Accumulator-factory/Ruby/accumulator-factory-2.rb new file mode 100644 index 0000000000..4ab3e08b18 --- /dev/null +++ b/Task/Accumulator-factory/Ruby/accumulator-factory-2.rb @@ -0,0 +1,15 @@ +require 'rational' +require 'complex' +y = accumulator(Rational(2, 3)) +puts y[Rational(1, 2)] # 7/6 +puts y[4] # 31/6 +puts y[Complex(0, 1)] # 31/6+1i + +t = accumulator(Time.utc(1999, 8, 7, 6, 5)) + # (Ruby 1.8.6) (Ruby 1.9.2) +puts t[4] # Sat Aug 07 06:05:04 UTC 1999 1999-08-07 06:05:04 UTC +puts t[-12 * 60 * 60] # Fri Aug 06 18:05:04 UTC 1999 1999-08-06 18:05:04 UTC + +require 'matrix' +m = accumulator(Matrix[[1, 2], [3, 4]]) +puts m[Matrix[[5, 6], [7, 8]]] # Matrix[[6, 8], [10, 12]] diff --git a/Task/Accumulator-factory/Ruby/accumulator-factory-3.rb b/Task/Accumulator-factory/Ruby/accumulator-factory-3.rb new file mode 100644 index 0000000000..4a8cbda8a9 --- /dev/null +++ b/Task/Accumulator-factory/Ruby/accumulator-factory-3.rb @@ -0,0 +1,9 @@ +def accumulator(sum) + lambda {|n| sum += n} +end +class << self + define_method :x, &accumulator(1) +end +x(5) +accumulator(3) +puts x(2.3) # prints 8.3 diff --git a/Task/Accumulator-factory/Ruby/accumulator-factory.rb b/Task/Accumulator-factory/Ruby/accumulator-factory.rb deleted file mode 100644 index c72af7eaa6..0000000000 --- a/Task/Accumulator-factory/Ruby/accumulator-factory.rb +++ /dev/null @@ -1,30 +0,0 @@ -def accumulator(sum) - lambda {|n| sum += n} -end - -# mixing Integer and Float -x = accumulator(1) -x.call(5) -p accumulator(3) # add some output to show what it returns -puts x.call(2.3) # prints 8.3 - -# mixing Rational and Complex -require 'rational' -require 'complex' -y = accumulator(Rational(2, 3)) -y.call(Rational(1, 2)) -puts y.call(4) -puts y.call(Complex(0, 1)) -puts y.call(Complex.polar(6, 5 * Math::PI / 4)) -puts x.call(0) # again prints 8.3 - -# using other things that have a + method -t = accumulator(Time.utc(1999, 8, 7, 6, 5)) -puts t.call(4) # prints 1999-08-07 06:05:04 UTC - -require 'matrix' -m = accumulator(Matrix[[1, 2], [3, 4]]) -puts m.call(Matrix[[5, 6], [7, 8]]) -puts t.call(-12 * 60 * 60) # subtracts 12 hours -puts y.call(1e200) -puts x.call(0) # again prints 8.3 diff --git a/Task/Accumulator-factory/XLISP/accumulator-factory.xlisp b/Task/Accumulator-factory/XLISP/accumulator-factory.xlisp new file mode 100644 index 0000000000..13e603ef16 --- /dev/null +++ b/Task/Accumulator-factory/XLISP/accumulator-factory.xlisp @@ -0,0 +1,4 @@ +(defun accumulator (x) + (lambda (n) + (setq x (+ n x)) + x ) ) diff --git a/Task/Ackermann-function/C-sharp/ackermann-function-1.cs b/Task/Ackermann-function/C-sharp/ackermann-function-1.cs new file mode 100644 index 0000000000..4b6effdb54 --- /dev/null +++ b/Task/Ackermann-function/C-sharp/ackermann-function-1.cs @@ -0,0 +1,32 @@ +using System; +class Program +{ + public static long Ackermann(long m, long n) + { + if(m > 0) + { + if (n > 0) + return Ackermann(m - 1, Ackermann(m, n - 1)); + else if (n == 0) + return Ackermann(m - 1, 1); + } + else if(m == 0) + { + if(n >= 0) + return n + 1; + } + + throw new System.ArgumentOutOfRangeException(); + } + + static void Main() + { + for (long m = 0; m <= 3; ++m) + { + for (long n = 0; n <= 4; ++n) + { + Console.WriteLine("Ackermann({0}, {1}) = {2}", m, n, Ackermann(m, n)); + } + } + } +} diff --git a/Task/Ackermann-function/C-sharp/ackermann-function.cs b/Task/Ackermann-function/C-sharp/ackermann-function-2.cs similarity index 100% rename from Task/Ackermann-function/C-sharp/ackermann-function.cs rename to Task/Ackermann-function/C-sharp/ackermann-function-2.cs diff --git a/Task/Ackermann-function/Elena/ackermann-function.elena b/Task/Ackermann-function/Elena/ackermann-function.elena index def9390a83..176b20b961 100644 --- a/Task/Ackermann-function/Elena/ackermann-function.elena +++ b/Task/Ackermann-function/Elena/ackermann-function.elena @@ -11,18 +11,18 @@ ackermann = (:m:n) 0 [ ^n + 1 ]; ! [ n => - 0 [ ^ackermann eval(m - 1,1) ]; - ! [ ^ackermann eval(m - 1,ackermann eval(m,n-1)) ] + 0 [ ^ackermann(m - 1,1) ]; + ! [ ^ackermann(m - 1,ackermann(m,n-1)) ] ] ]. -program = +public program = [ 0 to:3 do(:i) [ 0 to:5 do(:j) [ - console printLine("A(",i,",",j,")=",ackermann eval(i,j)) + console printLine("A(",i,",",j,")=",ackermann(i,j)) ] ]. diff --git a/Task/Ackermann-function/Gambas/ackermann-function.gambas b/Task/Ackermann-function/Gambas/ackermann-function.gambas new file mode 100644 index 0000000000..1e13833386 --- /dev/null +++ b/Task/Ackermann-function/Gambas/ackermann-function.gambas @@ -0,0 +1,21 @@ +Public Function ackermann (m as Float, n as Float) as Float + If m = 0 then + return n + 1 + end If + If n = 0 then + return ackermann(m - 1, 1) + end If +return ackermann(m - 1, ackermann(m, n - 1)) + +End + + +Public Sub Main() +Dim m, n as Float +For m = 0 to 3 + For n = 0 to 4 + print "Ackerman(";m;",";n;")=";ackermann(m, n) + Next +Next + +End diff --git a/Task/Ackermann-function/Julia/ackermann-function-2.julia b/Task/Ackermann-function/Julia/ackermann-function-2.julia index 63b6c3710c..549e163fc8 100644 --- a/Task/Ackermann-function/Julia/ackermann-function-2.julia +++ b/Task/Ackermann-function/Julia/ackermann-function-2.julia @@ -1 +1 @@ -ack2(m,n) = m == 0 ? n + 1 : n == 0 ? ack2(m-1,1) : ack2(m-1,ack2(m,n-1)) +ack2(m::Integer, n::Integer) = m == 0 ? n + 1 : n == 0 ? ack2(m - 1, 1) : ack2(m - 1, ack2(m, n - 1)) diff --git a/Task/Ackermann-function/Julia/ackermann-function-3.julia b/Task/Ackermann-function/Julia/ackermann-function-3.julia index 34d9313690..64226e159a 100644 --- a/Task/Ackermann-function/Julia/ackermann-function-3.julia +++ b/Task/Ackermann-function/Julia/ackermann-function-3.julia @@ -1,5 +1,2 @@ using Memoize -@memoize ack3(m, n) = - m == 0 ? n + 1 : - n == 0 ? ack3(m-1, 1) : - ack3(m-1, ack3(m, n-1)) +@memoize ack3(m::Integer, n::Integer) = m == 0 ? n + 1 : n == 0 ? ack3(m - 1, 1) : ack3(m - 1, ack3(m, n - 1)) diff --git a/Task/Ackermann-function/Klong/ackermann-function.klong b/Task/Ackermann-function/Klong/ackermann-function.klong new file mode 100644 index 0000000000..918b059fe3 --- /dev/null +++ b/Task/Ackermann-function/Klong/ackermann-function.klong @@ -0,0 +1,2 @@ +ack::{:[0=x;y+1:|0=y;.f(x-1;1);.f(x-1;.f(x;y-1))]} +ack(2;2) diff --git a/Task/Ackermann-function/Nim/ackermann-function.nim b/Task/Ackermann-function/Nim/ackermann-function.nim index e751f92918..5654adecc4 100644 --- a/Task/Ackermann-function/Nim/ackermann-function.nim +++ b/Task/Ackermann-function/Nim/ackermann-function.nim @@ -22,4 +22,4 @@ echo "First non-negative Integer please: " let first = getNumber() echo "Second non-negative Integer please: " let second = getNumber() -echo "Reslut: ", $ackermann(first, second) +echo "Result: ", $ackermann(first, second) diff --git a/Task/Ackermann-function/Oforth/ackermann-function.oforth b/Task/Ackermann-function/Oforth/ackermann-function.oforth index 57be08fca0..03e14bb713 100644 --- a/Task/Ackermann-function/Oforth/ackermann-function.oforth +++ b/Task/Ackermann-function/Oforth/ackermann-function.oforth @@ -1,4 +1,4 @@ -: A(m, n) +: A( m n -- p ) m ifZero: [ n 1+ return ] - n ifZero: [ A(m 1-, 1) return ] - A(m 1-, A(m, n 1-)) ; + m 1- n ifZero: [ 1 ] else: [ A( m, n 1- ) ] A +; diff --git a/Task/Ackermann-function/Perl-6/ackermann-function-3.pl6 b/Task/Ackermann-function/Perl-6/ackermann-function-3.pl6 index 15b6c179f2..4343025e4a 100644 --- a/Task/Ackermann-function/Perl-6/ackermann-function-3.pl6 +++ b/Task/Ackermann-function/Perl-6/ackermann-function-3.pl6 @@ -7,3 +7,7 @@ multi A(3, Int \𝑛) { 5 + 8 * (2 ** 𝑛 - 1) } multi A(Int \𝑚, 0 ) { A(𝑚 - 1, 1) } multi A(Int \𝑚, Int \𝑛) { A(𝑚 - 1, A(𝑚, 𝑛 - 1)) } + +# Testing: +say A(4,1); +say .chars, " digits starting with ", .substr(0,50), "..." given A(4,2); diff --git a/Task/Ackermann-function/Processing/ackermann-function b/Task/Ackermann-function/Processing/ackermann-function new file mode 100644 index 0000000000..8b381fa09a --- /dev/null +++ b/Task/Ackermann-function/Processing/ackermann-function @@ -0,0 +1,9 @@ +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) ); +} diff --git a/Task/Ackermann-function/Simula/ackermann-function.simula b/Task/Ackermann-function/Simula/ackermann-function.simula new file mode 100644 index 0000000000..fae3f34600 --- /dev/null +++ b/Task/Ackermann-function/Simula/ackermann-function.simula @@ -0,0 +1,15 @@ + BEGIN + INTEGER procedure + Ackermann(g, p); SHORT INTEGER g, p; + Ackermann:= IF g = 0 THEN p+1 + ELSE Ackermann(g-1, IF p = 0 THEN 1 + ELSE Ackermann(g, p-1)); + + INTEGER g, p; + FOR p := 0 STEP 3 UNTIL 13 DO BEGIN + g := 4 - p/3; + outtext("Ackermann("); outint(g, 0); + outchar(','); outint(p, 2); outtext(") = "); + outint(Ackermann(g, p), 0); outimage + END +END diff --git a/Task/Active-Directory-Connect/D/active-directory-connect.d b/Task/Active-Directory-Connect/D/active-directory-connect.d new file mode 100644 index 0000000000..947c910ea9 --- /dev/null +++ b/Task/Active-Directory-Connect/D/active-directory-connect.d @@ -0,0 +1,18 @@ +import openldap; +import std.stdio; + +void main() { + auto ldap = LDAP("ldap://localhost"); + auto r = ldap.search_s("dc=example,dc=com", LDAP_SCOPE_SUBTREE, "(uid=%s)".format("test")); + int b = ldap.bind_s(r[0].dn, "password"); + scope(exit) ldap.unbind; + if (b) + { + writeln("error on binding"); + return; + } + + // do something + ... + +} diff --git a/Task/Active-Directory-Connect/Haskell/active-directory-connect.hs b/Task/Active-Directory-Connect/Haskell/active-directory-connect.hs new file mode 100644 index 0000000000..d529134952 --- /dev/null +++ b/Task/Active-Directory-Connect/Haskell/active-directory-connect.hs @@ -0,0 +1,15 @@ +{-# LANGUAGE OverloadedStrings #-} + +module Main (main) where + +import Data.Foldable (for_) +import qualified Data.Text.Encoding as Text (encodeUtf8) +import Ldap.Client (Attr(..), Filter(..)) +import qualified Ldap.Client as Ldap (Dn(..), Host(..), search, with, typesOnly) + +main :: IO () +main = do + entries <- Ldap.with (Ldap.Plain "localhost") 389 $ \ldap -> + Ldap.search ldap (Ldap.Dn "o=example.com") (Ldap.typesOnly True) (Attr "uid" := Text.encodeUtf8 "user") [] + for_ entries $ \entry -> + print entry diff --git a/Task/Active-Directory-Connect/Scala/active-directory-connect.scala b/Task/Active-Directory-Connect/Scala/active-directory-connect.scala new file mode 100644 index 0000000000..64354a5f3a --- /dev/null +++ b/Task/Active-Directory-Connect/Scala/active-directory-connect.scala @@ -0,0 +1,18 @@ +import java.io.IOException + +import org.apache.directory.api.ldap.model.exception.LdapException +import org.apache.directory.ldap.client.api.{LdapConnection, LdapNetworkConnection} + +object LdapConnectionDemo { + @throws[LdapException] + @throws[IOException] + def main(args: Array[String]): Unit = { + try { + val connection: LdapConnection = new LdapNetworkConnection("localhost", 10389) + try { + connection.bind() + connection.unBind() + } finally if (connection != null) connection.close() + } + } +} diff --git a/Task/Active-Directory-Search-for-a-user/D/active-directory-search-for-a-user.d b/Task/Active-Directory-Search-for-a-user/D/active-directory-search-for-a-user.d new file mode 100644 index 0000000000..bdc961e9a5 --- /dev/null +++ b/Task/Active-Directory-Search-for-a-user/D/active-directory-search-for-a-user.d @@ -0,0 +1,28 @@ +import openldap; +import std.stdio; + +void main() { + // connect to server + auto ldap = LDAP("ldap://localhost"); + + // search for uid + auto r = ldap.search_s("dc=example,dc=com", LDAP_SCOPE_SUBTREE, "(uid=%s)".format("test")); + + // show properties + writeln("Found dn: %s", r[0].dn); + foreach(k, v; r[0].entry) + writeln("%s = %s", k, v); + + // bind on found entry + int b = ldap.bind_s(r[0].dn, "password"); + scope(exit) ldap.unbind; + if (b) + { + writeln("error on binding"); + return; + } + + // do something + ... + +} diff --git a/Task/Active-Directory-Search-for-a-user/Haskell/active-directory-search-for-a-user.hs b/Task/Active-Directory-Search-for-a-user/Haskell/active-directory-search-for-a-user.hs new file mode 100644 index 0000000000..d529134952 --- /dev/null +++ b/Task/Active-Directory-Search-for-a-user/Haskell/active-directory-search-for-a-user.hs @@ -0,0 +1,15 @@ +{-# LANGUAGE OverloadedStrings #-} + +module Main (main) where + +import Data.Foldable (for_) +import qualified Data.Text.Encoding as Text (encodeUtf8) +import Ldap.Client (Attr(..), Filter(..)) +import qualified Ldap.Client as Ldap (Dn(..), Host(..), search, with, typesOnly) + +main :: IO () +main = do + entries <- Ldap.with (Ldap.Plain "localhost") 389 $ \ldap -> + Ldap.search ldap (Ldap.Dn "o=example.com") (Ldap.typesOnly True) (Attr "uid" := Text.encodeUtf8 "user") [] + for_ entries $ \entry -> + print entry diff --git a/Task/Active-object/D/active-object.d b/Task/Active-object/D/active-object.d new file mode 100644 index 0000000000..bbcc9960f9 --- /dev/null +++ b/Task/Active-object/D/active-object.d @@ -0,0 +1,73 @@ +import core.thread; +import std.datetime; +import std.math; +import std.stdio; + +void main() { + auto func = (double t) => sin(cast(double) PI * t); + Integrator integrator = new Integrator(func); + Thread.sleep(2000.msecs); + + integrator.setFunc(t => 0.0); + Thread.sleep(500.msecs); + + integrator.stop(); + writeln(integrator.getOutput()); +} + +/** + * Integrates input function K over time + * S + (t1 - t0) * (K(t1) + K(t0)) / 2 + */ +public class Integrator { + public alias Function = double function (double); + + private SysTime start; + private shared bool running; + + private Function func; + private shared double t0; + private shared double v0; + private shared double sum = 0.0; + + public this(Function func) { + this.start = Clock.currTime(); + setFunc(func); + new Thread({ + integrate(); + }).start(); + } + + public void setFunc(Function func) { + this.func = func; + v0 = func(0.0); + t0 = 0.0; + } + + public double getOutput() { + return sum; + } + + public void stop() { + running = false; + } + + private void integrate() { + running = true; + while (running) { + Thread.sleep(1.msecs); + update(); + } + } + + private void update() { + import core.atomic; + + Duration t1 = (Clock.currTime() - start); + double v1 = func(t1.total!"msecs"); + double rect = (t1.total!"msecs" - t0) * (v0 + v1) / 2; + atomicOp!"+="(this.sum, rect); + t0 = t1.total!"msecs"; + v0 = v1; + } +} diff --git a/Task/Active-object/Julia/active-object.julia b/Task/Active-object/Julia/active-object.julia new file mode 100644 index 0000000000..b1da508ef1 --- /dev/null +++ b/Task/Active-object/Julia/active-object.julia @@ -0,0 +1,40 @@ +mutable struct Integrator + func::Function + runningsum::Float64 + dt::Float64 + running::Bool + function Integrator(f::Function, dt::Float64) + this = new() + this.func = f + this.runningsum = 0.0 + this.dt = dt + this.running = false + return this + end +end + +function run(integ::Integrator, lastval::Float64 = 0.0) + lasttime = time() + while integ.running + sleep(integ.dt) + newtime = time() + measuredinterval = newtime - lasttime + newval = integ.func(measuredinterval) + integ.runningsum += (lastval + newval) * measuredinterval / 2.0 + lasttime = newtime + lastval = newval + end +end + +start!(integ::Integrator) = (integ.running = true; @async run(integ)) +stop!(integ) = (integ.running = false) +f1(t) = sin(2π * t) +f2(t) = 0.0 + +it = Integrator(f1, 0.00001) +start!(it) +sleep(2.0) +it.func = f2 +sleep(0.5) +v2 = it.runningsum +println("After 2.5 seconds, integrator value was $v2") diff --git a/Task/Active-object/Kotlin/active-object.kotlin b/Task/Active-object/Kotlin/active-object.kotlin new file mode 100644 index 0000000000..3be9bced9f --- /dev/null +++ b/Task/Active-object/Kotlin/active-object.kotlin @@ -0,0 +1,69 @@ +// version 1.2.0 + +import kotlin.math.* + +typealias Function = (Double) -> Double + +/** + * Integrates input function K over time + * S + (t1 - t0) * (K(t1) + K(t0)) / 2 + */ +class Integrator { + private val start: Long + private @Volatile var running = false + private lateinit var func: Function + private var t0 = 0.0 + private var v0 = 0.0 + private var sum = 0.0 + + constructor(func: Function) { + start = System.nanoTime() + setFunc(func) + Thread(this::integrate).start() + } + + fun setFunc(func: Function) { + this.func = func + v0 = func(0.0) + t0 = 0.0 + } + + fun getOutput() = sum + + fun stop() { + running = false + } + + private fun integrate() { + running = true + while (running) { + try { + Thread.sleep(1) + update() + } + catch(e: InterruptedException) { + return + } + } + } + + private fun update() { + val t1 = (System.nanoTime() - start) / 1.0e9 + val v1 = func(t1) + val rect = (t1 - t0) * (v0 + v1) / 2.0 + sum += rect + t0 = t1 + v0 = v1 + } +} + +fun main(args: Array) { + val integrator = Integrator( { sin(PI * it) } ) + Thread.sleep(2000) + + integrator.setFunc( { 0.0 } ) + Thread.sleep(500) + + integrator.stop() + println(integrator.getOutput()) +} diff --git a/Task/Active-object/Lingo/active-object-1.lingo b/Task/Active-object/Lingo/active-object-1.lingo new file mode 100644 index 0000000000..87ccd49871 --- /dev/null +++ b/Task/Active-object/Lingo/active-object-1.lingo @@ -0,0 +1,41 @@ +property _sum +property _func +property _timeLast +property _valueLast +property _ms0 +property _updateTimer + +on new (me, func) + if voidP(func) then func = "0.0" + me._sum = 0.0 + -- update frequency: 100/sec (arbitrary) + me._updateTimer = timeout().new("update", 10, #_update, me) + me.input(func) + return me +end + +on stop (me) + me._updateTimer.period = 0 -- deactivates timer +end + +-- func is a term (as string) that might contain "t" and is evaluated at runtime +on input (me, func) + me._func = func + me._ms0 = _system.milliseconds + me._timeLast = 0.0 + t = 0.0 + me._valueLast = value(me._func) +end + +on output (me) + return me._sum +end + +on _update (me) + now = _system.milliseconds - me._ms0 + t = now/1000.0 + val = value(me._func) + me._sum = me._sum + (me._valueLast+val)*(t - me._timeLast)/2 + me._timeLast = t + me._valueLast = val +end diff --git a/Task/Active-object/Lingo/active-object-2.lingo b/Task/Active-object/Lingo/active-object-2.lingo new file mode 100644 index 0000000000..6bbfdf5276 --- /dev/null +++ b/Task/Active-object/Lingo/active-object-2.lingo @@ -0,0 +1,19 @@ +global gIntegrator + +-- entry point +on startMovie + gIntegrator = script("Integrator").new("sin(PI * t)") + timeout().new("timer", 2000, #step1) +end + +on step1 (_, timer) + gIntegrator.input("0.0") + timer.timeoutHandler = #step2 + timer.period = 500 +end + +on step2 (_, timer) + gIntegrator.stop() + put gIntegrator.output() + timer.forget() +end diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Elena/add-a-variable-to-a-class-instance-at-runtime.elena b/Task/Add-a-variable-to-a-class-instance-at-runtime/Elena/add-a-variable-to-a-class-instance-at-runtime.elena index 120f27657f..d2355e7508 100644 --- a/Task/Add-a-variable-to-a-class-instance-at-runtime/Elena/add-a-variable-to-a-class-instance-at-runtime.elena +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/Elena/add-a-variable-to-a-class-instance-at-runtime.elena @@ -10,7 +10,7 @@ class Extender :: BaseExtender ] } -program = +public program = [ var anObject := 234. diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Julia/add-a-variable-to-a-class-instance-at-runtime-1.julia b/Task/Add-a-variable-to-a-class-instance-at-runtime/Julia/add-a-variable-to-a-class-instance-at-runtime-1.julia new file mode 100644 index 0000000000..91261d3ebc --- /dev/null +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/Julia/add-a-variable-to-a-class-instance-at-runtime-1.julia @@ -0,0 +1,13 @@ +{"phoneNumbers": [ + { + "type": "home", + "number": "212 555-1234" + }, + { + "type": "office", + "number": "646 555-4567" + }, + { + "type": "mobile", + "number": "123 456-7890" + }]} diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Julia/add-a-variable-to-a-class-instance-at-runtime-2.julia b/Task/Add-a-variable-to-a-class-instance-at-runtime/Julia/add-a-variable-to-a-class-instance-at-runtime-2.julia new file mode 100644 index 0000000000..b2cb18acdb --- /dev/null +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/Julia/add-a-variable-to-a-class-instance-at-runtime-2.julia @@ -0,0 +1,7 @@ +mutable struct Contact + name::String + phonenumber::Dict{Any,Any} +end + +person = Contact("Jane Doe", Dict()) +person.phonenumber["home"] = "212 555-1234" diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Lingo/add-a-variable-to-a-class-instance-at-runtime.lingo b/Task/Add-a-variable-to-a-class-instance-at-runtime/Lingo/add-a-variable-to-a-class-instance-at-runtime.lingo new file mode 100644 index 0000000000..56130d8fcf --- /dev/null +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/Lingo/add-a-variable-to-a-class-instance-at-runtime.lingo @@ -0,0 +1,9 @@ +obj = script("MyClass").new() + +put obj.foo +-- "FOO" + +-- add new property 'bar' +obj.setProp(#bar, "BAR") +put obj.bar +-- "BAR" diff --git a/Task/Address-of-a-variable/ARM-Assembly/address-of-a-variable.arm b/Task/Address-of-a-variable/ARM-Assembly/address-of-a-variable.arm new file mode 100644 index 0000000000..69d2c86268 --- /dev/null +++ b/Task/Address-of-a-variable/ARM-Assembly/address-of-a-variable.arm @@ -0,0 +1,69 @@ +/* ARM assembly Raspberry PI */ +/* program adrvar.s */ + +/* Constantes */ +.equ STDOUT, 1 +.equ WRITE, 4 +.equ EXIT, 1 +/* Initialized data */ +.data +szMessage: .asciz "Hello. \n " @ message +szRetourLigne: .asciz "\n" +iValDeb: .int 5 @ value 5 in array of 4 bytes +/* No Initialized data */ +.bss +iValeur: .skip 4 @ reserve 4 bytes in memory + +.text +.global main +main: + ldr r0,=szMessage @ adresse of message short program + bl affichageMess @ call function + @ or + ldr r0,iAdrszMessage @ adresse of message big program (size code > 4K) + bl affichageMess @ call function + + ldr r1,=iValDeb @ adresse of variable -> r1 short program + ldr r0,[r1] @ value of iValdeb -> r0 + ldr r1,iAdriValDeb @ adresse of variable -> r1 big program + ldr r0,[r1] @ value of iValdeb -> r0 + + + /* set variables */ + ldr r1,=iValeur @ adresse of variable -> r1 short program + str r0,[r1] @ value of r0 -> iValeur + ldr r1,iAdriValeur @ adresse of variable -> r1 big program + str r0,[r1] @ value of r0 -> iValeur + + + /* end of program */ + mov r0, #0 @ return code + mov r7, #EXIT @ request to exit program + swi 0 @ perform the system call +iAdriValDeb: .int iValDeb +iAdriValeur: .int iValeur +iAdrszMessage: .int szMessage +iAdrszRetourLigne: .int szRetourLigne +/******************************************************************/ +/* affichage des messages avec calcul longueur */ +/******************************************************************/ +/* r0 contient l adresse du message */ +affichageMess: + push {fp,lr} /* save des 2 registres */ + push {r0,r1,r2,r7} /* save des autres registres */ + mov r2,#0 /* compteur longueur */ +1: /*calcul de la longueur */ + ldrb r1,[r0,r2] /* recup octet position debut + indice */ + cmp r1,#0 /* si 0 c est fini */ + beq 1f + add r2,r2,#1 /* sinon on ajoute 1 */ + b 1b +1: /* donc ici r2 contient la longueur du message */ + mov r1,r0 /* adresse du message en r1 */ + mov r0,#STDOUT /* code pour écrire sur la sortie standard Linux */ + mov r7, #WRITE /* code de l appel systeme 'write' */ + swi #0 /* appel systeme */ + pop {r0,r1,r2,r7} /* restaur des autres registres */ + pop {fp,lr} /* restaur des 2 registres */ + bx lr /* retour procedure */ + diff --git a/Task/Address-of-a-variable/Astro/address-of-a-variable.astro b/Task/Address-of-a-variable/Astro/address-of-a-variable.astro index 9c2eaee744..56bfc0a4a5 100644 --- a/Task/Address-of-a-variable/Astro/address-of-a-variable.astro +++ b/Task/Address-of-a-variable/Astro/address-of-a-variable.astro @@ -1,4 +1,5 @@ -var x = 12 -var pointer = ptr(x) # get pointer -print pointer # print address -pointer.set 0xFFFE # set the address +var num = 12 +var pointer = ptr(num) # get pointer +print pointer # print address +unsafe: # bad idea! + pointer.addr = 0xFFFE # set the address diff --git a/Task/Address-of-a-variable/C/address-of-a-variable-2.c b/Task/Address-of-a-variable/C/address-of-a-variable-2.c index 4c2a20746a..ebc3f786ec 100644 --- a/Task/Address-of-a-variable/C/address-of-a-variable-2.c +++ b/Task/Address-of-a-variable/C/address-of-a-variable-2.c @@ -1 +1,3 @@ -int& i = *(int*)0xA100; +#include +int i; +auto address_of_i = std::addressof(i); diff --git a/Task/Address-of-a-variable/C/address-of-a-variable-3.c b/Task/Address-of-a-variable/C/address-of-a-variable-3.c index 6a8a95e6b3..4c2a20746a 100644 --- a/Task/Address-of-a-variable/C/address-of-a-variable-3.c +++ b/Task/Address-of-a-variable/C/address-of-a-variable-3.c @@ -1,5 +1 @@ -static union -{ - int i; - int j; -}; +int& i = *(int*)0xA100; diff --git a/Task/Address-of-a-variable/C/address-of-a-variable-4.c b/Task/Address-of-a-variable/C/address-of-a-variable-4.c index 64d05b682b..1f489eab4c 100644 --- a/Task/Address-of-a-variable/C/address-of-a-variable-4.c +++ b/Task/Address-of-a-variable/C/address-of-a-variable-4.c @@ -1,2 +1,3 @@ -int i; -int& j = i; +#include +struct S { int i = 0; S() {} }; +auto& s = *new (reinterpret_cast(0xa100)) S; diff --git a/Task/Address-of-a-variable/C/address-of-a-variable-5.c b/Task/Address-of-a-variable/C/address-of-a-variable-5.c new file mode 100644 index 0000000000..6a8a95e6b3 --- /dev/null +++ b/Task/Address-of-a-variable/C/address-of-a-variable-5.c @@ -0,0 +1,5 @@ +static union +{ + int i; + int j; +}; diff --git a/Task/Address-of-a-variable/C/address-of-a-variable-6.c b/Task/Address-of-a-variable/C/address-of-a-variable-6.c new file mode 100644 index 0000000000..64d05b682b --- /dev/null +++ b/Task/Address-of-a-variable/C/address-of-a-variable-6.c @@ -0,0 +1,2 @@ +int i; +int& j = i; diff --git a/Task/Address-of-a-variable/C/address-of-a-variable-7.c b/Task/Address-of-a-variable/C/address-of-a-variable-7.c new file mode 100644 index 0000000000..36cb89df03 --- /dev/null +++ b/Task/Address-of-a-variable/C/address-of-a-variable-7.c @@ -0,0 +1,4 @@ +#include +inline float read_as_float(int const& i) { float f; memcpy(&f, &i, sizeof(f)); return f; } +int i = 0x0a112233; +float f = read_as_float(i); diff --git a/Task/Address-of-a-variable/Kotlin/address-of-a-variable.kotlin b/Task/Address-of-a-variable/Kotlin/address-of-a-variable.kotlin index 99aebba67a..bc713588dd 100644 --- a/Task/Address-of-a-variable/Kotlin/address-of-a-variable.kotlin +++ b/Task/Address-of-a-variable/Kotlin/address-of-a-variable.kotlin @@ -1,4 +1,4 @@ -// Kotlin/Native Technology Preview +// Kotlin Native v0.5 import kotlinx.cinterop.* diff --git a/Task/Address-of-a-variable/Oforth/address-of-a-variable.oforth b/Task/Address-of-a-variable/Oforth/address-of-a-variable.oforth new file mode 100644 index 0000000000..067a21c761 --- /dev/null +++ b/Task/Address-of-a-variable/Oforth/address-of-a-variable.oforth @@ -0,0 +1,14 @@ +tvar: A +10 to A + +tvar: B +#A to B +B .s +[1] (Variable) #A +>ok + +12 B put +A .s +[1] (Integer) 12 +[2] (Variable) #A +>ok diff --git a/Task/Address-of-a-variable/Stata/address-of-a-variable.stata b/Task/Address-of-a-variable/Stata/address-of-a-variable.stata new file mode 100644 index 0000000000..cc0c27f9ff --- /dev/null +++ b/Task/Address-of-a-variable/Stata/address-of-a-variable.stata @@ -0,0 +1,8 @@ +a = 1 +&a + +function f(x) { + return(x+1) +} + +&f() diff --git a/Task/Address-of-a-variable/XLISP/address-of-a-variable.xlisp b/Task/Address-of-a-variable/XLISP/address-of-a-variable.xlisp new file mode 100644 index 0000000000..4c93143ea2 --- /dev/null +++ b/Task/Address-of-a-variable/XLISP/address-of-a-variable.xlisp @@ -0,0 +1 @@ +(%ADDRESS-OF X) diff --git a/Task/Align-columns/Aime/align-columns.aime b/Task/Align-columns/Aime/align-columns.aime index 66d07bdeed..8882a1f76f 100644 --- a/Task/Align-columns/Aime/align-columns.aime +++ b/Task/Align-columns/Aime/align-columns.aime @@ -1,55 +1,45 @@ data b; file f; +text n, t; list c, r, s; -integer a, i, j, k, m, w; +integer a, i, k, m, w; -b_cast(b, "Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n" - "are$delineated$by$a$single$'dollar'$character,$write$a$program\n" - "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\n" - "column$are$separated$by$at$least$one$space.\n" - "Further,$allow$for$each$word$in$a$column$to$be$either$left$\n" - "justified,$right$justified,$or$center$justified$within$its$column."); +b = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n" + "are$delineated$by$a$single$'dollar'$character,$write$a$program\n" + "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\n" + "column$are$separated$by$at$least$one$space.\n" + "Further,$allow$for$each$word$in$a$column$to$be$either$left$\n" + "justified,$right$justified,$or$center$justified$within$its$column."; -f_b_affix(f, b); +f.b_affix(b); m = 0; -while (f_news(f, r, 0, 0, "$") ^ -1) { - l_append(c, r); - m = max(m, l_length(r)); +while (f.news(r, 0, 0, "$") ^ -1) { + c.append(r); + m = max(m, ~r); } i = 0; while (i < m) { w = 0; - j = 0; - while (j < l_length(c)) { - r = c[j]; - if (i < l_length(r)) { + for (, r in c) { + if (i < ~r) { w = max(w, length(r[i])); } - j += 1; } - l_append(s, w + 1); + s.append(w + 1); i += 1; } -k = 3; -while (k) { - k -= 1; - o_plan(l_effect("right", "center", "left")[k], " justified", "\n"); - j = 0; - while (j < l_length(c)) { - i = 0; - r = c[j]; - while (i < l_length(r)) { - w = s[i]; - m = w - length(r[i]); - o_form("/w~3/~/w~1/", a = k * m >> 1, "", m - a, "", r[i]); - i += 1; +for (k, t in list("left", "center", "right")) { + o_(t, " justified\n"); + for (, r in c) { + for (i, n in r) { + m = s[i] - ~n; + o_form("/w~3/~/w~1/", a = (2 - k) * m >> 1, "", m - a, "", n); } o_newline(); - j += 1; } o_newline(); } diff --git a/Task/Align-columns/BaCon/align-columns.bacon b/Task/Align-columns/BaCon/align-columns.bacon new file mode 100644 index 0000000000..6863d4db6b --- /dev/null +++ b/Task/Align-columns/BaCon/align-columns.bacon @@ -0,0 +1,34 @@ +DECLARE in$[] = { "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." } + +OPTION DELIM "$" + +CONST items = 6 + +SUB Print_In_Columns(style) + + ' Find widest column + FOR y = 0 TO items-1 + FOR x = 1 TO AMOUNT(in$[y]) + IF LEN(TOKEN$(in$[y], x)) > max THEN max = LEN(TOKEN$(in$[y], x)) + NEXT + NEXT + + ' Print aligned + FOR y = 0 TO items-1 + FOR x = 1 TO AMOUNT(in$[y]) + PRINT ALIGN$(TOKEN$(in$[y], x), max+1, style); + NEXT + PRINT + NEXT + PRINT + +END SUB + +Print_In_Columns(0) +Print_In_Columns(1) +Print_In_Columns(2) diff --git a/Task/Align-columns/Oforth/align-columns.oforth b/Task/Align-columns/Oforth/align-columns.oforth index 288cc2a654..03e47874f9 100644 --- a/Task/Align-columns/Oforth/align-columns.oforth +++ b/Task/Align-columns/Oforth/align-columns.oforth @@ -1,15 +1,21 @@ -String method: justify(n, just) // ( just size string -- string ) +import: mapping +import: file + +: <l 2 / ->m - StringBuffer new - just $RIGHT == ifTrue: [ " " <lines - 0 lines apply(#[ apply(#[ size max ]) ]) ->maxsize - - lines apply(#[ apply(#[ justify(maxsize, just) . ]) printcr ]) ; + #[ wordsWith( '$' ) ] file File new map ->lines + 0 #[ apply( #[ size max ] ) ] lines apply ->maxsize + #[ apply( #[ justify( maxsize , just) . ] ) printcr ] lines apply +; diff --git a/Task/Align-columns/Perl-6/align-columns-1.pl6 b/Task/Align-columns/Perl-6/align-columns-1.pl6 index 7dd3a61118..d06ed53a5d 100644 --- a/Task/Align-columns/Perl-6/align-columns-1.pl6 +++ b/Task/Align-columns/Perl-6/align-columns-1.pl6 @@ -1,38 +1,23 @@ -###to be called with perl6 columnaligner.pl (left, center , right ) -###with left as default -my $fh = open "example.txt" , :r or die "Can't read text file!\n" ; -my @filelines = $fh.lines ; -close $fh ; -my @maxcolwidths ; #array of the longest words per column -#########fill the array with values##################### -for @filelines -> $line { - my @words = $line.split( "\$" ) ; - for 0..@words.elems - 1 -> $i { - if @maxcolwidths[ $i ] { - if @words[ $i ].chars > @maxcolwidths[$i] { - @maxcolwidths[ $i ] = @words[ $i ].chars ; - } - } - else { - @maxcolwidths.push( @words[ $i ].chars ) ; - } - } -} -my $justification = @*ARGS[ 0 ] || "left" ; -##print lines , $gap holds the number of spaces, 1 to be added -##to allow for space preceding or following longest word -for @filelines -> $line { - my @words = $line.split( "\$" ) ; - for 0 ..^ @words -> $i { - my $gap = @maxcolwidths[$i] - @words[$i].chars + 1 ; - if $justification eq "left" { - print @words[ $i ] ~ " " x $gap ; - } elsif $justification eq "right" { - print " " x $gap ~ @words[$i] ; - } elsif $justification eq "center" { - $gap = ( @maxcolwidths[ $i ] + 2 - @words[$i].chars ) div 2 ; - print " " x $gap ~ @words[$i] ~ " " x $gap ; - } - } - say ''; #for the newline +my @lines = +q|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. +|.lines; + +my @widths; + +for @lines { for .split('$').kv { @widths[$^key] max= $^word.chars; } } +for @lines { say |.split('$').kv.map: { (align @widths[$^key], $^word) ~ " "; } } + +sub align($column_width, $word, $aligment = @*ARGS[0]) { + my $lr = $column_width - $word.chars; + my $c = $lr / 2; + given ($aligment) { + when "center" { " " x $c.ceiling ~ $word ~ " " x $c.floor } + when "right" { " " x $lr ~ $word } + default { $word ~ " " x $lr } + } } diff --git a/Task/Align-columns/Perl-6/align-columns-2.pl6 b/Task/Align-columns/Perl-6/align-columns-2.pl6 index 4893c7e36c..f590537048 100644 --- a/Task/Align-columns/Perl-6/align-columns-2.pl6 +++ b/Task/Align-columns/Perl-6/align-columns-2.pl6 @@ -1,15 +1,7 @@ -my @lines = slurp("example.txt").lines; -my @widths; - -for @lines { for .split('$').kv { @widths[$^key] max= $^word.chars; } } -for @lines { say |.split('$').kv.map: { (align @widths[$^key], $^word) ~ " "; } } - -sub align($column_width, $word, $aligment = @*ARGS[0]) { - my $lr = $column_width - $word.chars; - my $c = $lr / 2; - given ($aligment) { - when "center" { " " x $c.ceiling ~ $word ~ " " x $c.floor } - when "right" { " " x $lr ~ $word } - default { $word ~ " " x $lr } - } +sub MAIN ($alignment where 'left'|'right', $file) { + my @lines := $file.IO.lines.map(*.split('$').cache).cache; + my @widths = roundrobin(|@lines).map(*».chars.max); + my $align = {left=>'-', right=>''}{$alignment}; + my $format = @widths.map( '%' ~ ++$ ~ '$' ~ $align ~ * ~ 's' ).join(' ') ~ "\n"; + printf $format, |$_ for @lines; } diff --git a/Task/Aliquot-sequence-classifications/00DESCRIPTION b/Task/Aliquot-sequence-classifications/00DESCRIPTION index 252d10bd93..e9a534234a 100644 --- a/Task/Aliquot-sequence-classifications/00DESCRIPTION +++ b/Task/Aliquot-sequence-classifications/00DESCRIPTION @@ -24,8 +24,8 @@ being K and subsequent members being the sum of the [[Proper divisors]] of the p Show all output on this page. -;Cf. -* [[Abundant, deficient and perfect number classifications]]. (Classifications from only the first two members of the whole sequence). -* [[Proper divisors]] -* [[Amicable pairs]] +;Related tasks: +*   [[Abundant, deficient and perfect number classifications]]. (Classifications from only the first two members of the whole sequence). +*   [[Proper divisors]] +*   [[Amicable pairs]]

diff --git a/Task/Aliquot-sequence-classifications/ALGOL-68/aliquot-sequence-classifications.alg b/Task/Aliquot-sequence-classifications/ALGOL-68/aliquot-sequence-classifications.alg new file mode 100644 index 0000000000..5e1e085695 --- /dev/null +++ b/Task/Aliquot-sequence-classifications/ALGOL-68/aliquot-sequence-classifications.alg @@ -0,0 +1,106 @@ +BEGIN + # aliquot sequence classification # + # maximum sequence length we consider # + INT max sequence length = 16; + # possible classifications # + STRING perfect classification = "perfect "; + STRING amicable classification = "amicable "; + STRING sociable classification = "sociable "; + STRING aspiring classification = "aspiring "; + STRING cyclic classification = "cyclic "; + STRING terminating classification = "terminating "; + STRING non terminating classification = "non terminating"; + # structure to hold an aliquot sequence and its classification # + MODE ALIQUOT = STRUCT( STRING classification + , [ 1 : max sequence length ]LONG INT sequence + , INT length + ); + # maximum value for sequence elements - if any element is more than this, # + # we assume it is non-teriminating # + LONG INT max element = 140 737 488 355 328; + # returns the sum of the proper divisors of n # + OP DIVISORSUM = ( LONG INT n )LONG INT: + BEGIN + LONG INT abs n = ABS n; + IF abs n < 2 THEN + 0 # -1, 0 and 1 have no proper divisors # + ELSE + # have a number with possible divisors # + LONG INT result := 1; # 1 is always a divisor # + # a FOR loop counter can only be an INT, hence the WHILE loop # + LONG INT d := ENTIER long sqrt( abs n ); + WHILE d > 1 DO + IF abs n MOD d = 0 THEN + # found another divisor # + result +:= d; + IF d * d /= abs n THEN + # add the other divisor # + result +:= abs n OVER d + FI + FI; + d -:= 1 + OD; + result + FI + END # DIVISORSUM # ; + # generates the aliquot sequence of the number k and its classification # + # at most max elements of the sequence are considered # + OP CLASSIFY = ( LONG INT k )ALIQUOT : + BEGIN + ALIQUOT result; + classification OF result := "non-terminating"; + INT lb = LWB sequence OF result; + INT ub = UPB sequence OF result; + ( sequence OF result )[ lb ] := k; # the first element is always k # + length OF result := 1; + FOR i FROM lb + 1 TO ub DO + ( sequence OF result )[ i ] := 0 + OD; + BOOL classified := FALSE; + LONG INT prev k := k; + FOR i FROM lb + 1 TO ub WHILE NOT classified DO + length OF result +:= 1; + LONG INT next k := ( sequence OF result )[ i ] := DIVISORSUM prev k; + classified := TRUE; + IF next k = 0 THEN # the sequence terminates # + classification OF result := terminating classification + ELIF next k > max element THEN # the sequence gets too large # + classification OF result := non terminating classification + ELIF next k = k THEN # the sequence that returns to k # + classification OF result + := IF i = lb + 1 THEN perfect classification + ELIF i = lb + 2 THEN amicable classification + ELSE sociable classification + FI + ELIF next k = prev k THEN # the sequence repeats with non-k # + classification OF result := aspiring classification + ELSE # check for repeating sequence with a period more than 1 # + classified := FALSE; + FOR prev pos FROM lb TO i - 2 WHILE NOT classified DO + IF classified := ( sequence OF result )[ prev pos ] = next k THEN + # found a repeatition # + classification OF result := cyclic classification + FI + OD + FI; + prev k := next k + OD; + result + END # CLASSIFY # ; + # test cases as per the task # + []LONG INT test cases = + ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 + , 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909 + , 562, 1064, 1488 + , 15355717786080 + ); + FOR i FROM LWB test cases TO UPB test cases DO + LONG INT k := test cases[ i ]; + ALIQUOT seq = CLASSIFY k; + print( ( whole( k, -14 ), ": ", classification OF seq, ":" ) ); + FOR e FROM LWB sequence OF seq + 1 TO length OF seq DO + print( ( " ", whole( ( sequence OF seq )[ e ], 0 ) ) ) + OD; + print( ( newline ) ) + OD +END diff --git a/Task/Aliquot-sequence-classifications/C/aliquot-sequence-classifications-1.c b/Task/Aliquot-sequence-classifications/C/aliquot-sequence-classifications-1.c new file mode 100644 index 0000000000..d4eedffef7 --- /dev/null +++ b/Task/Aliquot-sequence-classifications/C/aliquot-sequence-classifications-1.c @@ -0,0 +1,73 @@ +/*Abhishek Ghosh, 1st November 2017*/ + +#include +#include +#include + +unsigned long long bruteForceProperDivisorSum(unsigned long long n){ + unsigned long long i,sum = 0; + + for(i=1;i<(n+1)/2;i++) + if(n%i==0 && n!=i) + sum += i; + + return sum; +} + +void printSeries(unsigned long long* arr,int size,char* type){ + int i; + + printf("\nInteger : %llu, Type : %s, Series : ",arr[0],type); + + for(i=0;i",argV[0]); + else{ + if(strchr(argV[1],'.')!=NULL) + processFile(argV[1]); + else + aliquotClassifier(strtoull(argV[1],(char**)NULL,10)); + } + return 0; +} diff --git a/Task/Aliquot-sequence-classifications/C/aliquot-sequence-classifications-2.c b/Task/Aliquot-sequence-classifications/C/aliquot-sequence-classifications-2.c new file mode 100644 index 0000000000..8813dcf239 --- /dev/null +++ b/Task/Aliquot-sequence-classifications/C/aliquot-sequence-classifications-2.c @@ -0,0 +1,103 @@ +/*Abhishek Ghosh, 7th November 2017*/ + +#include +#include +#include + +unsigned long long raiseTo(unsigned long long base, unsigned long long power){ + unsigned long long result = 1,i; + for (i=0; i 1) + prod *= ((raiseTo(i,count + 1) - 1)/(i-1)); + } + + if(n>2) + prod *= (n+1); + + return prod - temp; +} + +void printSeries(unsigned long long* arr,int size,char* type){ + int i; + + printf("\nInteger : %llu, Type : %s, Series : ",arr[0],type); + + for(i=0;i",argV[0]); + else{ + if(strchr(argV[1],'.')!=NULL) + processFile(argV[1]); + else + aliquotClassifier(strtoull(argV[1],(char**)NULL,10)); + } + return 0; +} diff --git a/Task/Aliquot-sequence-classifications/Go/aliquot-sequence-classifications.go b/Task/Aliquot-sequence-classifications/Go/aliquot-sequence-classifications.go new file mode 100644 index 0000000000..c61f07f7cb --- /dev/null +++ b/Task/Aliquot-sequence-classifications/Go/aliquot-sequence-classifications.go @@ -0,0 +1,109 @@ +package main + +import ( + "fmt" + "math" + "strings" +) + +const threshold = uint64(1) << 47 + +func indexOf(s []uint64, search uint64) int { + for i, e := range s { + if e == search { + return i + } + } + return -1 +} + +func contains(s []uint64, search uint64) bool { + return indexOf(s, search) > -1 +} + +func maxOf(i1, i2 int) int { + if i1 > i2 { + return i1 + } + return i2 +} + +func sumProperDivisors(n uint64) uint64 { + if n < 2 { + return 0 + } + sqrt := uint64(math.Sqrt(float64(n))) + sum := uint64(1) + for i := uint64(2); i <= sqrt; i++ { + if n % i != 0 { + continue + } + sum += i + n / i + } + if sqrt * sqrt == n { + sum -= sqrt + } + return sum +} + +func classifySequence(k uint64) ([]uint64, string) { + if k == 0 { + panic("Argument must be positive.") + } + last := k + var seq []uint64 + seq = append(seq, k) + for { + last = sumProperDivisors(last) + seq = append(seq, last) + n := len(seq) + aliquot := "" + switch { + case last == 0: + aliquot = "Terminating" + case n == 2 && last == k: + aliquot = "Perfect" + case n == 3 && last == k: + aliquot = "Amicable" + case n >= 4 && last == k: + aliquot = fmt.Sprintf("Sociable[%d]", n - 1) + case last == seq[n - 2]: + aliquot = "Aspiring" + case contains(seq[1 : maxOf(1, n - 2)], last): + aliquot = fmt.Sprintf("Cyclic[%d]", n - 1 - indexOf(seq[:], last)) + case n == 16 || last > threshold: + aliquot = "Non-Terminating" + } + if aliquot != "" { + return seq, aliquot + } + } +} + +func joinWithCommas(seq []uint64) string { + res := fmt.Sprint(seq) + res = strings.Replace(res, " ", ", ", -1) + return res +} + +func main() { + fmt.Println("Aliquot classifications - periods for Sociable/Cyclic in square brackets:\n") + for k := uint64(1); k <= 10; k++ { + seq, aliquot := classifySequence(k) + fmt.Printf("%2d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) + } + fmt.Println() + + s := []uint64{ + 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, + } + for _, k := range s { + seq, aliquot := classifySequence(k) + fmt.Printf("%7d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) + } + fmt.Println() + + k := uint64(15355717786080) + seq, aliquot := classifySequence(k) + fmt.Printf("%d: %-15s %s\n", k, aliquot, joinWithCommas(seq)) +} diff --git a/Task/Aliquot-sequence-classifications/Oforth/aliquot-sequence-classifications.oforth b/Task/Aliquot-sequence-classifications/Oforth/aliquot-sequence-classifications.oforth index 690ba6a13b..ec7a739116 100644 --- a/Task/Aliquot-sequence-classifications/Oforth/aliquot-sequence-classifications.oforth +++ b/Task/Aliquot-sequence-classifications/Oforth/aliquot-sequence-classifications.oforth @@ -1,27 +1,37 @@ +import: mapping +import: quicksort +import: math + +Object method: sum ( coll -- m ) + #+ self reduce dup ifNull: [ drop 0 ] ; + Integer method: properDivs | i l | - ListBuffer new dup add(1) ->l - 2 self nsqrt tuck for: i [ self i mod ifFalse: [ l add(i) l add(self i / ) ] ] - sq self == ifTrue: [ l removeLast drop ] - l sort ; + Array new dup 1 over add ->l + 2 self nsqrt tuck for: i [ self i mod ifFalse: [ i l add self i / l add ] ] + sq self == ifTrue: [ l pop drop ] + dup sort +; -: aliquot(n) // ( n -- aList ) : Returns aliquot sequence of n +: aliquot( n -- [] ) \ Returns aliquot sequence of n | end l | 2 47 pow ->end - ListBuffer new dup add(n) dup ->l - while (l size 16 < l last 0 <> and l last end <= and) [ l last properDivs sum l add ] ; + Array new dup n over add ->l + while ( l size 16 < l last 0 <> and l last end <= and ) [ l last properDivs sum l add ] +; -: aliquotClass(n) // ( n -- aList aString ) : Returns aliquot sequence and classification +: aliquotClass( n -- [] s ) \ Returns aliquot sequence and classification | l i j | n aliquot dup ->l l last 0 == ifTrue: [ "terminate" return ] l second n == ifTrue: [ "perfect" return ] - l third n == ifTrue: [ "amicable" return ] + 3 l at n == ifTrue: [ "amicable" return ] l indexOfFrom(n, 2) ifNotNull: [ "sociable" return ] l size loop: i [ - l indexOfFrom(l at(i), i 1 +) -> j - j i 1 + == ifTrue: [ "aspiring" return ] + l indexOfFrom(l at(i), i 1+ ) -> j + j i 1+ == ifTrue: [ "aspiring" return ] j ifNotNull: [ "cyclic" return ] ] - "non-terminating" ; + "non-terminating" +; diff --git a/Task/Aliquot-sequence-classifications/REXX/aliquot-sequence-classifications.rexx b/Task/Aliquot-sequence-classifications/REXX/aliquot-sequence-classifications.rexx index 29da9a563e..803a5d40c3 100644 --- a/Task/Aliquot-sequence-classifications/REXX/aliquot-sequence-classifications.rexx +++ b/Task/Aliquot-sequence-classifications/REXX/aliquot-sequence-classifications.rexx @@ -2,10 +2,10 @@ parse arg low high L /*obtain optional arguments from the CL*/ high=word(high low 10,1); low=word(low 1,1) /*obtain the LOW and HIGH (range). */ if L='' then L=11 12 28 496 220 1184 12496 1264460 790 909 562 1064 1488 15355717786080 -numeric digits 20 /*be able to handle the number: BIG */ -big=2**47; NTlimit=16+1 /*limits for a non─terminating sequence*/ +numeric digits 100 /*be able to compute the number: BIG */ +big= 2**47; NTlimit= 16 + 1 /*limits for a non─terminating sequence*/ numeric digits max(9, 1 + length(big) ) /*be able to handle big numbers for // */ -#.=.; #.0=0; #.1=0 /*#. are the proper divisor sums. */ +#.=.; #.0=0; #.1=0 /*#. are the proper divisor sums. */ say center('numbers from ' low " to " high, 79, "═") do n=low to high; call classify n /*call a subroutine to classify number.*/ end /*n*/ /* [↑] process a range of integers. */ @@ -14,13 +14,13 @@ say center('first numbers for each classification', 79, "═") class.=0 /* [↓] ensure one number of each class*/ do q=1 until class.sociable\==0 /*the only one that has to be counted. */ call classify -q /*minus (-) sign indicates don't tell. */ - _=what; upper _; class._=class._+1 /*bump counter for this class sequence.*/ + _=what; upper _; class._= class._ +1 /*bump counter for this class sequence.*/ if class._==1 then say right(q, digits()) 'is' center(what, 15) $ end /*q*/ /* [↑] only display the 1st occurrence*/ say /* [↑] process until all classes found*/ say center('classifications for specific numbers', 79, "═") do i=1 for words(L) /*L: is a list of "special numbers".*/ - call classify word(L,i) /*call a subroutine to classify number.*/ + call classify word(L, i) /*call a subroutine to classify number.*/ end /*i*/ /* [↑] process a list of integers. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ @@ -28,29 +28,29 @@ classify: parse arg a 1 aa; a=abs(a) /*obtain number that's to be cl if #.a\==. then s=#.a /*Was this number been summed before?*/ else s=sigma(a) /*No, then classify number the hard way*/ #.a=s; $=s /*define sum of the proper divisors. */ - what='terminating' /*assume this kind of classification. */ - c.=0; c.s=1 /*clear all cyclic sequences; set 1st.*/ - if $==a then what='perfect' /*check for a "perfect" number. */ + what= 'terminating' /*assume this kind of classification. */ + c.=0; c.s=1 /*clear all cyclic sequences; set 1st.*/ + if $==a then what= 'perfect' /*check for a "perfect" number. */ else do t=1 while s\==0 /*loop until sum isn't 0 or > big.*/ m=s /*obtain the last number in sequence. */ if #.m==. then s=sigma(m) /*Not defined? Then sum proper divisors*/ else s=#.m /*use the previously found integer. */ - if m==s & m\==0 then do; what='aspiring' ; leave; end - parse var $ . word2 . /* " " 2nd " " " */ - if word2==a then do; what='amicable' ; leave; end + if m==s & m\==0 then do; what= 'aspiring' ; leave; end + parse var $ . word2 . /*obtain the 2nd number in sequence. */ + if word2==a then do; what= 'amicable' ; leave; end $=$ s /*append a sum to the integer sequence.*/ - if s==a & t>3 then do; what='sociable' ; leave; end - if c.s & m\==0 then do; what='cyclic' ; leave; end + if s==a & t>3 then do; what= 'sociable' ; leave; end + if c.s & m\==0 then do; what= 'cyclic' ; leave; end c.s=1 /*assign another possible cyclic number*/ /* [↓] Rosetta Code task's limit: >16 */ - if t>NTlimit then do; what='non-terminating'; leave; end - if s>big then do; what='NON-TERMINATING'; leave; end + if t>NTlimit then do; what= 'non-terminating'; leave; end + if s>big then do; what= 'NON-TERMINATING'; leave; end end /*t*/ /* [↑] only permit within reason. */ if aa>0 then say right(a, digits() ) 'is' center(what, 15) $ - return /* [↑] only display if A is positive.*/ + return /* [↑] only display if AA is positive*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ -sigma: procedure expose #.; parse arg x; if x<2 then return 0; odd=x//2 - s=1 /* [↓] use only EVEN | ODD ints. ___*/ +sigma: procedure expose #. !.; parse arg x; if x<2 then return 0; odd=x//2 + s=1 /* [↓] use EVEN or ODD integers. ___*/ do j=2+odd by 1+odd while j*j + +see "Rosetta Code - aliquot sequence classnifications" + nl +while true + see "enter an integer: " + give k + k=fabs(floor(number(k))) + if k=0 + exit + ok + printas(k) +end +see "program complete." + +func printas(k) + length=52 + aseq = list(length) + n=k + classn=0 + priorn = 0 + inc = 0 + for element=2 to length + aseq[element]=pdtotal(n) + see aseq[element] + " " + nl + if aseq[element]=0 + see " terminating" + nl + classn=1 + exit + ok + if aseq[element]=k and element=2 + see " perfect" + nl + classn=2 + exit + ok + if aseq[element]=k and element=3 + see " amicable" + nl + classn=3 + exit + ok + if aseq[element]=k and element>3 + see " sociable" + nl + classn=4 + exit + ok + if aseq[element]!=k and aseq[element-1]=aseq[element] + see " aspiring" + nl + classn=5 + exit + ok + if aseq[element]!=k and element>2 and aseq[element-2]= aseq[element] + see " cyclic" + nl + classn=6 + exit + ok + n=aseq[element] + if n>priorn + priorn=n + inc=inc+1 + but n<=priorn + inc=0 + priorn=0 + ok + if inc=11 or n>30000000 + exit + ok + next + if classn=0 + see " non-terminating" + nl + ok + +func pdtotal(n) + pdtotal = 0 + for y=2 to n + if (n % y)=0 + pdtotal=pdtotal+(n/y) + ok + next + return pdtotal diff --git a/Task/Almost-prime/Factor/almost-prime.factor b/Task/Almost-prime/Factor/almost-prime.factor new file mode 100644 index 0000000000..0372de7e09 --- /dev/null +++ b/Task/Almost-prime/Factor/almost-prime.factor @@ -0,0 +1,12 @@ +USING: formatting fry kernel lists lists.lazy locals +math.combinatorics math.primes.factors math.ranges sequences ; +IN: rosetta-code.almost-prime + +: k-almost-prime? ( n k -- ? ) + '[ factors _ [ product ] map ] + [ [ = ] curry ] bi any? ; + +:: first10 ( k -- seq ) + 10 0 lfrom [ k k-almost-prime? ] lfilter ltake list>array ; + +5 [1,b] [ dup first10 "K = %d: %[%3d, %]\n" printf ] each diff --git a/Task/Almost-prime/GW-BASIC/almost-prime.gw-basic b/Task/Almost-prime/GW-BASIC/almost-prime.gw-basic new file mode 100644 index 0000000000..7e91d99f42 --- /dev/null +++ b/Task/Almost-prime/GW-BASIC/almost-prime.gw-basic @@ -0,0 +1,25 @@ +10 'Almost prime +20 FOR K% = 1 TO 5 +30 PRINT "k = "; K%; ": "; +40 LET I% = 2 +50 LET C% = 0 +60 WHILE C% < 10 +70 LET AN% = I%: LET AK% = K%: GOSUB 1000 +80 IF ISKPRIME <> 0 THEN PRINT USING "### "; I%;: LET C% = C% + 1 +90 LET I% = I% + 1 +100 WEND +110 PRINT +120 NEXT K% +130 END + +995 ' Check if n (AN%) is a k (AK%) prime +1000 LET F% = 0 +1010 FOR II% = 2 TO AN% +1020 WHILE AN% MOD II% = 0 +1030 IF F% = AK% THEN LET ISKPRIME = 0: RETURN +1040 LET F% = F% + 1 +1050 LET AN% = AN% \ II% +1060 WEND +1070 NEXT II% +1080 LET ISKPRIME = (F% = AK%) +1090 RETURN diff --git a/Task/Almost-prime/Julia/almost-prime.julia b/Task/Almost-prime/Julia/almost-prime.julia index 08e662e387..fa2a459097 100644 --- a/Task/Almost-prime/Julia/almost-prime.julia +++ b/Task/Almost-prime/Julia/almost-prime.julia @@ -1,10 +1,17 @@ -isalmostprime(n, k) = sum(values(factor(n))) == k -function almostprimes(N, k) # return first N almost-k primes - P = Array(Int, N) +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)}(N) i = 0; n = 2 while i < N - if isalmostprime(n, k); P[i += 1] = n; end + 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/Kotlin/almost-prime.kotlin b/Task/Almost-prime/Kotlin/almost-prime.kotlin index 0da7e9a380..9b7850a5bc 100644 --- a/Task/Almost-prime/Kotlin/almost-prime.kotlin +++ b/Task/Almost-prime/Kotlin/almost-prime.kotlin @@ -11,9 +11,9 @@ fun Int.k_prime(x: Int): Boolean { fun Int.primes(n : Int) : List { var i = 2 - var list = listOf() + var list = mutableListOf() while (list.size < n) { - if (k_prime(i)) list += i + if (k_prime(i)) list.add(i) i++ } return list diff --git a/Task/Almost-prime/Modula-2/almost-prime.mod2 b/Task/Almost-prime/Modula-2/almost-prime.mod2 new file mode 100644 index 0000000000..bccdeb9725 --- /dev/null +++ b/Task/Almost-prime/Modula-2/almost-prime.mod2 @@ -0,0 +1,46 @@ +MODULE AlmostPrime; +FROM FormatString IMPORT FormatString; +FROM Terminal IMPORT WriteString,WriteLn,ReadChar; + +PROCEDURE KPrime(n,k : INTEGER) : BOOLEAN; +VAR p,f : INTEGER; +BEGIN + f := 0; + p := 2; + WHILE (f1 THEN + RETURN f+1 = k + END; + RETURN f = k +END KPrime; + +VAR + buf : ARRAY[0..63] OF CHAR; + i,c,k : INTEGER; +BEGIN + FOR k:=1 TO 5 DO + FormatString("k = %i:", buf, k); + WriteString(buf); + + i:=2; + c:=0; + WHILE c<10 DO + IF KPrime(i,k) THEN + FormatString(" %i", buf, i); + WriteString(buf); + INC(c) + END; + INC(i) + END; + + WriteLn; + END; + + ReadChar; +END AlmostPrime. diff --git a/Task/Almost-prime/Oforth/almost-prime.oforth b/Task/Almost-prime/Oforth/almost-prime.oforth index d640556c5f..bb63ed465a 100644 --- a/Task/Almost-prime/Oforth/almost-prime.oforth +++ b/Task/Almost-prime/Oforth/almost-prime.oforth @@ -1,9 +1,14 @@ -: kprime(n, k) +: kprime?( n k -- b ) | i | - 0 2 n for: i [ while(n i /mod swap 0 &= ) [ ->n 1+ ] drop ] k == ; + 0 2 n for: i [ + while( n i /mod swap 0 = ) [ ->n 1+ ] drop + ] + k == +; -: table(k) +: table( k -- [] ) | l | - ListBuffer new ->l - 2 while (l size 10 <>) [ dup k kprime ifTrue: [ dup l add ] 1+ ] - drop l ; + Array new dup ->l + 2 while (l size 10 <>) [ dup k kprime? if dup l add then 1+ ] + drop +; diff --git a/Task/Almost-prime/PureBasic/almost-prime.purebasic b/Task/Almost-prime/PureBasic/almost-prime.purebasic new file mode 100644 index 0000000000..29edca3505 --- /dev/null +++ b/Task/Almost-prime/PureBasic/almost-prime.purebasic @@ -0,0 +1,43 @@ +EnableExplicit + +Procedure.b kprime(n.i, k.i) + Define p.i = 2, + f.i = 0 + + While f < k And p*p <= n + While n % p = 0 + n / p + f + 1 + Wend + p + 1 + Wend + + ProcedureReturn Bool(f + Bool(n > 1) = k) + +EndProcedure + +;___main____ +If Not OpenConsole("Almost prime") + End -1 +EndIf + +Define i.i, + c.i, + k.i + +For k = 1 To 5 + Print("k = " + Str(k) + ":") + + i = 2 + c = 0 + While c < 10 + If kprime(i, k) + Print(RSet(Str(i),4)) + c + 1 + EndIf + i + 1 + Wend + PrintN("") +Next + +Input() diff --git a/Task/Amb/C-sharp/amb-3.cs b/Task/Amb/C-sharp/amb-3.cs new file mode 100644 index 0000000000..e06935a997 --- /dev/null +++ b/Task/Amb/C-sharp/amb-3.cs @@ -0,0 +1,101 @@ +using System; +using System.Collections.Generic; + +namespace Amb +{ + public interface IValue + { + T Value { get; } + string ToString(); + } + + public sealed class Amb + { + public IValue Choose(params T[] choices) + { + var array = new ChoiceArray { Values = choices }; + _itemsChoices.Add(array); + return array; + } + + public void Require(Func predicate) => + _constraints.Add(new Constraint { Predicate = predicate, AppliesForItems = _itemsChoices.Count }); + + public bool RequireFinal(Func predicate) + { + Require(predicate); + return Disambiguate(); + } + + public bool Disambiguate() + { + try + { + Disambiguate(0, 0); + return false; + } + catch (Exception ex) when (ex.Message == "Success") + { + return true; + } + } + + interface IChoices + { + int Length { get; } + int Index { get; set; } + } + + interface IConstraint + { + int AppliesForItems { get; } + bool Invoke(); + } + + List _itemsChoices = new List(); + List _constraints = new List(); + + void Disambiguate(int itemsTracked, int constraintIndex) + { + while (constraintIndex < _constraints.Count && _constraints[constraintIndex].AppliesForItems <= itemsTracked) + { + if (!_constraints[constraintIndex].Invoke()) + return; + constraintIndex++; + } + + if (itemsTracked == _itemsChoices.Count) + { + throw new Exception("Success"); + } + + for (var i = 0; i < _itemsChoices[itemsTracked].Length; i++) + { + _itemsChoices[itemsTracked].Index = i; + Disambiguate(itemsTracked + 1, constraintIndex); + } + } + + class Constraint : IConstraint + { + internal int AppliesForItems; + int IConstraint.AppliesForItems => AppliesForItems; + + internal Func Predicate; + public bool Invoke() => Predicate?.Invoke() ?? default; + } + + class ChoiceArray : IChoices, IValue + { + internal T[] Values; + + public int Index { get; set; } + + public T Value { get { return Values[Index]; } } + + public int Length => Values.Length; + + public override string ToString() => Value.ToString(); + } + } +} diff --git a/Task/Amb/C-sharp/amb-4.cs b/Task/Amb/C-sharp/amb-4.cs new file mode 100644 index 0000000000..3176b13d43 --- /dev/null +++ b/Task/Amb/C-sharp/amb-4.cs @@ -0,0 +1,36 @@ +using System.Linq; +using static System.Console; + +namespace Amb +{ + class Program + { + static void Main(string[] args) + { + + var amb = new Amb(); + + var set1 = amb.Choose("the", "that", "a"); + var set2 = amb.Choose("frog", "elephant", "thing"); + amb.Require(() => set1.Value.Last() == set2.Value[0]); + var set3 = amb.Choose("walked", "treaded", "grows"); + amb.Require(() => set2.Value.Last() == set3.Value[0]); + var set4 = amb.Choose("slowly", "quickly"); + amb.RequireFinal(() => set3.Value.Last() == set4.Value[0]); + + WriteLine($"{set1} {set2} {set3} {set4}"); + Read(); + + // problem from http://www.randomhacks.net/articles/2005/10/11/amb-operator + amb = new Amb(); + + var x = amb.Choose(1, 2, 3); + var y = amb.Choose(4, 5, 6); + amb.RequireFinal(() => x.Value* y.Value == 8); + + WriteLine($"{x} * {y} = 8"); + Read(); + Read(); + } + } +} diff --git a/Task/Amb/Elena/amb.elena b/Task/Amb/Elena/amb.elena index c2760ef490..849f4f087f 100644 --- a/Task/Amb/Elena/amb.elena +++ b/Task/Amb/Elena/amb.elena @@ -6,24 +6,24 @@ joinable = (:aFormer:aLater)(aFormer[aFormer length - 1] == aLater[0]). dispatcher = { - eval object:anArray func2:aFunction + eval(object anArray, Func2 aFunction) [ - ^ aFunction eval(anArray[0],anArray[1]). + ^ aFunction(anArray[0],anArray[1]). ] - eval object:anArray func3:aFunction + eval(object anArray, Func3 aFunction) [ - ^ aFunction eval(anArray[0], anArray[1],anArray[2]). + ^ aFunction(anArray[0], anArray[1],anArray[2]). ] - eval object:anArray func4:aFunction + eval(object anArray, Func4 aFunction) [ - ^ aFunction eval(anArray[0],anArray[1],anArray[2],anArray[3]). + ^ aFunction(anArray[0],anArray[1],anArray[2],anArray[3]). ] - eval object:anArray func5:aFunction + eval(object anArray, Func5 aFunction) [ - ^ aFunction eval(anArray[0],anArray[1],anArray[2],anArray[3],anArray[4]). + ^ aFunction(anArray[0],anArray[1],anArray[2],anArray[3],anArray[4]). ] }. @@ -32,9 +32,9 @@ class AmbValueCollection { object theCombinator. - constructor new args:Arguments + constructor new(V Arguments) [ - theCombinator := SequentialEnumerator new args:Arguments. + theCombinator := SequentialEnumerator new(Arguments). ] seek : aCondition @@ -55,15 +55,15 @@ class AmbValueCollection ambOperator = { - generic for args:Arguments - = AmbValueCollection new args:Arguments. + generic for(V Arguments) + = AmbValueCollection new(Arguments). }. -program = +public program = [ try(ambOperator for(("the","that","a"),("frog", "elephant", "thing"),("walked", "treaded", "grows"),("slowly", "quickly")); - seek(:a:b:c:d) ( joinable eval(a,b) && joinable eval(b,c) && joinable eval(c,d) ); + 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) ]) { on(Exception e) diff --git a/Task/Amb/Julia/amb.julia b/Task/Amb/Julia/amb.julia index b4a194e443..f55e14ec56 100644 --- a/Task/Amb/Julia/amb.julia +++ b/Task/Amb/Julia/amb.julia @@ -2,51 +2,55 @@ # arbitrary number of iterable objects and returns the first solution found as an array # this function is in essence an iterative backtracking solver -function amb(failure,objs...) -n=length(objs) -if n==1 return end -states=cell(n) -values=cell(n) -# starting point, we put down the first value from the first iterable object -states[1]=start(objs[1]) -values[1],states[1]=next(objs[1],states[1]) -i=1 -# main solver loop -while true -# test for failure -if i>1&&failure(values[i-1],values[i]) -# loop for generating a new value upon failure -# in fact this would be way more readable using goto, but Julia doesn't seem to have that :( -while true -# if we failed, we must generate a new value, but first we must check whether there is any -if done(objs[i],states[i]) -# backtracking step with sanity check in case we ran out of values from the current generator -if i==1 return else i-=1; continue end -else -# if there is indeed a new value, generate it -values[i],states[i]=next(objs[i],states[i]) -break -end -end -else -# no failure branch -# if solution is ready (i.e. all generators are used) just return it -if i==n return values end -# else start up the next generator -i+=1 -states[i]=start(objs[i]) -values[i],states[i]=next(objs[i],states[i]) -end -end +function amb(failure, itrs...) + n = length(itrs) + if n == 1 return end + states = Vector(n) + values = Vector(n) + # starting point, we put down the first value from the first iterable object + states[1] = start(itrs[1]) + values[1], states[1] = next(itrs[1], states[1]) + i = 1 + # main solver loop + while true + # test for failure + if i > 1 && failure(values[i-1], values[i]) + # loop for generating a new value upon failure + # in fact this would be way more readable using goto, but Julia doesn't seem to have that :( + while true + # if we failed, we must generate a new value, but first we must check whether there is any + if done(itrs[i], states[i]) + # backtracking step with sanity check in case we ran out of values from the current generator + if i == 1 + return + else + i -= 1 + continue + end + else + # if there is indeed a new value, generate it + values[i], states[i] = next(itrs[i], states[i]) + break + end + end + else + # no failure branch + # if solution is ready (i.e. all generators are used) just return it + if i == n return values end + # else start up the next generator + i += 1 + states[i] = start(itrs[i]) + values[i], states[i] = next(itrs[i], states[i]) + end + end end # Call our generic AMB function according to the task description and # form the solution sentence from the returned array of words - -println(join(amb( -(s1,s2)->s1[end]!=s2[1], -["the","that","a"], -["frog","elephant","thing"], -["walked","treaded","grows"], -["slowly","quickly"] -)," ")) +amb((s1,s2) -> s1[end] != s2[1], # failure function + ["the", "that", "a"], + ["frog", "elephant", "thing"], + ["walked", "treaded", "grows"], + ["slowly", "quickly"]) |> + x -> join(x, " ") |> + println diff --git a/Task/Amb/Kotlin/amb.kotlin b/Task/Amb/Kotlin/amb.kotlin index a28a6adcd7..545338e78b 100644 --- a/Task/Amb/Kotlin/amb.kotlin +++ b/Task/Amb/Kotlin/amb.kotlin @@ -1,41 +1,104 @@ -// version 1.1.3 +// version 1.2.41 +import kotlin.coroutines.experimental.* +import kotlin.coroutines.experimental.intrinsics.* -typealias Constraint = (T, T) -> Boolean +fun main(args: Array) = amb { + val a = amb("the", "that", "a") + val b = amb("frog", "elephant", "thing") + val c = amb("walked", "treaded", "grows") + val d = amb("slowly", "quickly") -fun amb(lists: List>, res: MutableList, cons: Constraint): Boolean { - if (lists.isEmpty()) return true - if (lists[0].isEmpty()) return false - val z = res.size - for ((i, el) in lists[0].withIndex()) { - if (i == 0) res.add(el) else res[z] = el - if (z > 0 && !cons(res[z - 1], res[z])) continue - if (amb(lists.drop(1), res, cons)) return true + if (a[a.lastIndex] != b[0]) amb() + if (b[b.lastIndex] != c[0]) amb() + if (c[c.lastIndex] != d[0]) amb() + + println(listOf(a, b, c, d)) + + + val x = amb(1, 2, 3) + val y = amb(7, 6, 4, 5) + if (x * y != 8) amb() + println(listOf(x, y)) +} + + +class AmbException(): Exception("Refusing to execute") +data class AmbPair(val cont: Continuation, val valuesLeft: MutableList) + +@RestrictsSuspension +class AmbEnvironment { + val ambList = mutableListOf>() + + suspend fun amb(value: T, vararg rest: T): T = suspendCoroutineOrReturn { cont -> + if (rest.size > 0) { + ambList.add(AmbPair(clone(cont), mutableListOf(*rest))) + } + + value } - res.removeAt(z) - return false + + suspend fun amb(): Nothing = suspendCoroutine { } } -fun main(args: Array) { - val wordLists = listOf( - listOf("the", "that", "a"), - listOf("frog", "elephant", "thing"), - listOf("walked", "treaded", "grows"), - listOf("slowly", "quickly") - ) - val res = mutableListOf() - val cons: Constraint = { x, y -> x.last() == y.first() } - if (amb(wordLists, res, cons)) - println(res) +@Suppress("UNCHECKED_CAST") +fun amb(block: suspend AmbEnvironment.() -> R): R { + var result: R? = null + var toThrow: Throwable? = null + + val dist = AmbEnvironment() + block.startCoroutine(receiver = dist, completion = object : Continuation { + override val context: CoroutineContext get() = EmptyCoroutineContext + override fun resume(value: R) { result = value } + override fun resumeWithException(exception: Throwable) { toThrow = exception } + }) + + while (result == null && toThrow == null && !dist.ambList.isEmpty()) { + val last = dist.ambList.run { this[lastIndex] } + + if (last.valuesLeft.size == 1) { + dist.ambList.removeAt(dist.ambList.lastIndex) + last.apply { + (cont as Continuation).resume(valuesLeft[0]) + } + } else { + val value = last.valuesLeft.removeAt(last.valuesLeft.lastIndex) + (clone(last.cont) as Continuation).resume(value) + } + } + + if (toThrow != null) + { + throw toThrow!! + } + else if (result != null) + { + return result!! + } else - println("No solution found") - val numLists = listOf( - listOf(1, 2, 3), - listOf(7, 6, 4, 5) - ) - val res2 = mutableListOf() - val cons2: Constraint = { x, y -> x * y == 8 } - if (amb(numLists, res2, cons2)) - println(res2) - else - println("No solution found") + { + throw AmbException() + } +} + +val UNSAFE = Class.forName("sun.misc.Unsafe") + .getDeclaredField("theUnsafe") + .apply { isAccessible = true } + .get(null) as sun.misc.Unsafe + +@Suppress("UNCHECKED_CAST") +fun clone(obj: T): T { + val clazz = obj::class.java + val copy = UNSAFE.allocateInstance(clazz) as T + copyDeclaredFields(obj, copy, clazz) + return copy +} + +tailrec fun copyDeclaredFields(obj: T, copy: T, clazz: Class) { + for (field in clazz.declaredFields) { + field.isAccessible = true + val v = field.get(obj) + field.set(copy, if (v === obj) copy else v) + } + val superclass = clazz.superclass + if (superclass != null) copyDeclaredFields(obj, copy, superclass) } diff --git a/Task/Amb/Rust/amb.rust b/Task/Amb/Rust/amb.rust new file mode 100644 index 0000000000..6ae8afb7ed --- /dev/null +++ b/Task/Amb/Rust/amb.rust @@ -0,0 +1,44 @@ +use std::ops::Add; +struct Amb<'a> { + list: Vec>, +} +fn main() { + let amb = Amb { + list: vec![ + vec!["the", "that", "a"], + vec!["frog", "elephant", "thing"], + vec!["walked", "treaded", "grows"], + vec!["slowly", "quickly"], + ], + }; + match amb.do_amb(0, 0 as char) { + Some(text) => println!("{}", text), + None => println!("Nothing found"), + } +} +impl<'a> Amb<'a> { + fn do_amb(&self, level: usize, last_char: char) -> Option { + if self.list.is_empty() { + panic!("No word list"); + } + if self.list.len() <= level { + return Some(String::new()); + } + let mut res = String::new(); + let word_list = &self.list[level]; + for word in word_list { + if word.chars().next().unwrap() == last_char || last_char == 0 as char { + res = res.add(word).add(" "); + let answ = self.do_amb(level + 1, word.chars().last().unwrap()); + match answ { + Some(x) => { + res = res.add(&x); + return Some(res); + } + None => res.clear(), + } + } + } + None + } +} diff --git a/Task/Amicable-pairs/Ada/amicable-pairs.ada b/Task/Amicable-pairs/Ada/amicable-pairs.ada new file mode 100644 index 0000000000..71563fcf06 --- /dev/null +++ b/Task/Amicable-pairs/Ada/amicable-pairs.ada @@ -0,0 +1,32 @@ +with Ada.Text_IO; use Ada.Text_IO; + +procedure Amicable is + + function Sum_Of_Factors(Num : Integer) return Integer is + Sum : Integer := 1; + Test_Nr : Integer := 2; + begin + loop + if Num mod Test_Nr = 0 then + Sum := Sum + Test_Nr; + if Test_Nr * Test_Nr /= Num then + Sum := Sum + Num / Test_Nr; + end if; + end if; + Test_Nr := Test_Nr + 1; + exit when Test_Nr ** 2 > Num; + end loop; + return Sum; + end Sum_Of_Factors; + + Num2 : Integer; +begin + for Num1 in 4 .. 20_000 loop + Num2 := Sum_Of_Factors(Num1); + if Num1 < Num2 then + if Num1 = Sum_Of_Factors(Num2) then + Put_Line(Integer'Image(Num1) & "," & Integer'Image(Num2)); + end if; + end if; + end loop; +end Amicable; diff --git a/Task/Amicable-pairs/AppleScript/amicable-pairs-1.applescript b/Task/Amicable-pairs/AppleScript/amicable-pairs-1.applescript index e4e6622739..e2e3e285a3 100644 --- a/Task/Amicable-pairs/AppleScript/amicable-pairs-1.applescript +++ b/Task/Amicable-pairs/AppleScript/amicable-pairs-1.applescript @@ -1,38 +1,39 @@ +-- AMICABLE PAIRS ------------------------------------------------------------ + -- amicablePairsUpTo :: Int -> Int on amicablePairsUpTo(max) -- amicable :: [Int] -> Int -> Int -> [Int] -> [Int] script amicable - on lambda(lstAccumulator, m, n, lstSums) + on |λ|(a, m, n, lstSums) if (m > n) and (m ≤ max) and ((item m of lstSums) = n) then - lstAccumulator & [[n, m]] + a & [[n, m]] else - lstAccumulator + a end if - end lambda + end |λ| end script -- divisorsSummed :: Int -> Int script divisorsSummed -- sum :: Int -> Int -> Int script sum - on lambda(a, b) + on |λ|(a, b) a + b - end lambda + end |λ| end script - on lambda(n) + on |λ|(n) foldl(sum, 0, properDivisors(n)) - end lambda + end |λ| end script - foldl(amicable, [], ¬ - map(divisorsSummed, range(1, max))) + foldl(amicable, {}, ¬ + map(divisorsSummed, enumFromTo(1, max))) end amicablePairsUpTo --- TEST - +-- TEST ---------------------------------------------------------------------- on run amicablePairsUpTo(20000) @@ -40,23 +41,23 @@ on run end run --- PROPER DIVISORS +-- PROPER DIVISORS ----------------------------------------------------------- -- properDivisors :: Int -> [Int] on properDivisors(n) -- isFactor :: Int -> Bool script isFactor - on lambda(x) + on |λ|(x) n mod x = 0 - end lambda + end |λ| end script -- integerQuotient :: Int -> Int script integerQuotient - on lambda(x) + on |λ|(x) (n / x) as integer - end lambda + end |λ| end script if n = 1 then @@ -67,7 +68,7 @@ on properDivisors(n) set blnPerfectSquare to intRoot = realRoot -- Factors up to square root of n, - set lows to filter(isFactor, range(1, intRoot)) + set lows to filter(isFactor, enumFromTo(1, intRoot)) -- and quotients of these factors beyond the square root, -- excluding n itself (last item) @@ -76,10 +77,21 @@ on properDivisors(n) end if end properDivisors +-- GENERIC FUNCTIONS --------------------------------------------------------- ---------------------------------------------------------------------------- - --- GENERIC LIBRARY FUNCTIONS +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if m > n then + set d to -1 + else + set d to 1 + end if + set lst to {} + repeat with i from m to n by d + set end of lst to i + end repeat + return lst +end enumFromTo -- filter :: (a -> Bool) -> [a] -> [a] on filter(f, xs) @@ -88,7 +100,7 @@ on filter(f, xs) set lng to length of xs repeat with i from 1 to lng set v to item i of xs - if lambda(v, i, xs) then set end of lst to v + if |λ|(v, i, xs) then set end of lst to v end repeat return lst end tell @@ -100,7 +112,7 @@ on foldl(f, startValue, xs) set v to startValue set lng to length of xs repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell @@ -112,26 +124,12 @@ on map(f, xs) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell end map --- range :: Int -> Int -> [Int] -on range(m, n) - if n < m then - set d to -1 - else - set d to 1 - end if - set lst to {} - repeat with i from m to n by d - set end of lst to i - end repeat - return lst -end range - -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) @@ -139,7 +137,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn diff --git a/Task/Amicable-pairs/Elena/amicable-pairs.elena b/Task/Amicable-pairs/Elena/amicable-pairs.elena new file mode 100644 index 0000000000..ea7f3e6fe7 --- /dev/null +++ b/Task/Amicable-pairs/Elena/amicable-pairs.elena @@ -0,0 +1,32 @@ +import extensions. +import system'routines. +import system'math. + +const int Limit = 20000. + +extension op +{ + properDivisors + = Range new(1,self / 2); filterBy(:n)(self mod:n == 0). + + amicablePairs + [ + var divsums := Range new(0, self); selectBy(:i)(i properDivisors; summarize(Integer new)); toArray. + + ^ 1 repeatTill(divsums length); + filterBy(:i) + [ + var sum := divsums[i]. + ^ (i < sum) && (sum < divsums length) && (divsums[sum] == i) + ]; + selectBy(:i)({ item1 = i. item2 = divsums[i]. }). + ] +} + +public program = +[ + Limit amicablePairs; forEach(:pair) + [ + console printLine(pair item1, " ", pair item2). + ] +]. diff --git a/Task/Amicable-pairs/Factor/amicable-pairs.factor b/Task/Amicable-pairs/Factor/amicable-pairs.factor new file mode 100644 index 0000000000..67eaee4d1b --- /dev/null +++ b/Task/Amicable-pairs/Factor/amicable-pairs.factor @@ -0,0 +1,16 @@ +USING: grouping math.primes.factors math.ranges ; + +: pdivs ( n -- seq ) divisors but-last ; +: dsum ( n -- sum ) pdivs sum ; +: dsum= ( n m -- ? ) dsum = ; +: both-dsum= ( n m -- ? ) [ dsum= ] [ swap dsum= ] 2bi and ; +: amicable? ( n m -- ? ) [ both-dsum= ] [ = not ] 2bi and ; +: drange ( -- seq ) 2 20000 [a,b) ; +: dsums ( -- seq ) drange [ dsum ] map ; +: is-am?-seq ( -- seq ) dsums drange [ amicable? ] 2map ; +: am-nums ( -- seq ) t is-am?-seq indices ; +: am-nums-c ( -- seq ) am-nums [ 2 + ] map ; +: am-pairs ( -- seq ) am-nums-c 2 group ; +: print-am ( -- ) am-pairs [ >array . ] each ; + +print-am diff --git a/Task/Amicable-pairs/Julia/amicable-pairs-2.julia b/Task/Amicable-pairs/Julia/amicable-pairs-2.julia index a988c80acb..010af0f5aa 100644 --- a/Task/Amicable-pairs/Julia/amicable-pairs-2.julia +++ b/Task/Amicable-pairs/Julia/amicable-pairs-2.julia @@ -1,3 +1,5 @@ +using Primes + const L = 2*10^4 acnt = 0 diff --git a/Task/Amicable-pairs/Oforth/amicable-pairs.oforth b/Task/Amicable-pairs/Oforth/amicable-pairs.oforth index 195979dd1e..68cdab22ec 100644 --- a/Task/Amicable-pairs/Oforth/amicable-pairs.oforth +++ b/Task/Amicable-pairs/Oforth/amicable-pairs.oforth @@ -1,10 +1,14 @@ -Integer method: properDivs self 2 / seq filter(#[ self swap mod 0 == ]) ; +import: mapping + +Integer method: properDivs -- [] + #[ self swap mod 0 == ] self 2 / seq filter ; : amicables | i j | - ListBuffer new + Array new 20000 loop: i [ - i properDivs sum dup ->j i <= ifTrue: [ continue ] - j properDivs sum i <> ifTrue: [ continue ] + i properDivs sum dup ->j i <= if continue then + j properDivs sum i <> if continue then [ i, j ] over add - ] ; + ] +; diff --git a/Task/Amicable-pairs/R/amicable-pairs.r b/Task/Amicable-pairs/R/amicable-pairs.r new file mode 100644 index 0000000000..da5bb9580e --- /dev/null +++ b/Task/Amicable-pairs/R/amicable-pairs.r @@ -0,0 +1,11 @@ +divisors <- function (n) { + Filter( function (m) 0 == n %% m, 1:(n/2) ) +} + +table = sapply(1:19999, function (n) sum(divisors(n)) ) + +for (n in 1:19999) { + m = table[n] + if ((m > n) && (m < 20000) && (n == table[m])) + cat(n, " ", m, "\n") +} diff --git a/Task/Amicable-pairs/VBA/amicable-pairs.vba b/Task/Amicable-pairs/VBA/amicable-pairs.vba new file mode 100644 index 0000000000..dbf9c370a4 --- /dev/null +++ b/Task/Amicable-pairs/VBA/amicable-pairs.vba @@ -0,0 +1,38 @@ +Option Explicit + +Public Sub AmicablePairs() +Dim a(2 To 20000) As Long, c As New Collection, i As Long, j As Long, t# + t = Timer + For i = LBound(a) To UBound(a) + 'collect the sum of the proper divisors + 'of each numbers between 2 and 20000 + a(i) = S(i) + Next + 'Double Loops to test the amicable + For i = LBound(a) To UBound(a) + For j = i + 1 To UBound(a) + If i = a(j) Then + If a(i) = j Then + On Error Resume Next + c.Add i & " : " & j, CStr(i * j) + On Error GoTo 0 + Exit For + End If + End If + Next + Next + 'End. Return : + Debug.Print "Execution Time : " & Timer - t & " seconds." + Debug.Print "Amicable pairs below 20 000 are : " + For i = 1 To c.Count + Debug.Print c.Item(i) + Next i +End Sub + +Private Function S(n As Long) As Long +'returns the sum of the proper divisors of n +Dim j As Long + For j = 1 To n \ 2 + If n Mod j = 0 Then S = j + S + Next +End Function diff --git a/Task/Anagrams-Deranged-anagrams/BaCon/anagrams-deranged-anagrams.bacon b/Task/Anagrams-Deranged-anagrams/BaCon/anagrams-deranged-anagrams.bacon new file mode 100644 index 0000000000..058ce984c7 --- /dev/null +++ b/Task/Anagrams-Deranged-anagrams/BaCon/anagrams-deranged-anagrams.bacon @@ -0,0 +1,29 @@ +DECLARE idx$ ASSOC STRING + +FUNCTION Deranged(a$, b$) + FOR i = 1 TO LEN(a$) + IF MID$(a$, i, 1) = MID$(b$, i, 1) THEN RETURN FALSE + NEXT + RETURN TRUE +END FUNCTION + +FOR w$ IN LOAD$(DIRNAME$(ME$) & "/unixdict.txt") STEP NL$ + set$ = EXTRACT$(SORT$(EXPLODE$(w$, 1)), " ") + idx$(set$) = APPEND$(idx$(set$), 0, w$) +NEXT + +FOR w$ IN OBTAIN$(idx$) + FOR x = 1 TO AMOUNT(idx$(w$)) + FOR y = x+1 TO AMOUNT(idx$(w$)) + IF Deranged(TOKEN$(idx$(w$), x), TOKEN$(idx$(w$), y)) AND LEN(TOKEN$(idx$(w$), x)) > current THEN + current = LEN(TOKEN$(idx$(w$), x)) + an1$ = TOKEN$(idx$(w$), x) + an2$ = TOKEN$(idx$(w$), y) + END IF + NEXT + NEXT +NEXT + +PRINT "Maximum deranged anagrams: ", an1$, " and ", an2$ + +PRINT NL$, "Total time: ", TIMER, " msecs.", NL$ diff --git a/Task/Anagrams-Deranged-anagrams/Julia/anagrams-deranged-anagrams.julia b/Task/Anagrams-Deranged-anagrams/Julia/anagrams-deranged-anagrams.julia index c5558bc412..d6e49d2967 100644 --- a/Task/Anagrams-Deranged-anagrams/Julia/anagrams-deranged-anagrams.julia +++ b/Task/Anagrams-Deranged-anagrams/Julia/anagrams-deranged-anagrams.julia @@ -1,56 +1,42 @@ -import Base.isless - -#Let's define the less than operator for any two vectors that have the same type -# This does lexicographic comparison, we use it on vectors of chars in this task - -function isless{T}(t1::Array{T,1}, t2::Array{T,1}) - n1, n2 = length(t1), length(t2) - for i = 1:min(n1, n2) - a, b = t1[i], t2[i] +# Let's define the less than operator for any two vectors that have the same type: +# This does lexicographic comparison, we use it on vectors of chars in this task. +function Base.isless{T}(t1::Vector{T}, t2::Vector{T}) + for (a, b) in zip(t1, t2) # zip only to the shorter length if !isequal(a, b) return isless(a, b) end end - return n1 < n2 + return length(t1) < length(t2) end -#The sort function of Julia doesn't work on strings, so we write one +# The sort function of Julia doesn't work on strings, so we write one: # This returns a sorted vector of the chars of the given string - -sortchars(s)=sort(convert(Array{Char,1},s)) +sortchars(s::AbstractString) = sort(collect(Char, s)) # Custom comparator function for sorting the loaded wordlist +sortanagr(s1::AbstractString, s2::AbstractString) = + if length(s1) != length(s2) length(s1) < length(s2) else sortchars(s1) < sortchars(s2) end -function sort_ana(s1,s2) -if length(s1)!=length(s2) return length(s1)@.k then say @.k a.k - end /*k*/ /*above:REXX has no shortcircuits*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────ESORT───────────────────────────────*/ -esort:procedure expose !.;h=!.0;do while h>1;h=h%2;do i=1 for !.0-h;j=i;k=h+i -do while !.k=j then leave;j=j-h;k=k-h;end;end;end;return + do k=1 for words /*now, search all words for the maximum*/ + if #.k==m then if n.k\==0 then if word(a.k, 1) > @.k then say @.k a.k + end /*k*/ /* [↑] REXX has no short-circuits. */ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +esort: procedure expose !.; h=!.0; do while h>1; h=h%2; do i=1 for !.0-h; j=i; k=h+i + do while !.k=j then leave; j=j-h; k=k-h + end /*while !.k1*/; return diff --git a/Task/Anagrams-Deranged-anagrams/Ring/anagrams-deranged-anagrams.ring b/Task/Anagrams-Deranged-anagrams/Ring/anagrams-deranged-anagrams.ring new file mode 100644 index 0000000000..d884b23800 --- /dev/null +++ b/Task/Anagrams-Deranged-anagrams/Ring/anagrams-deranged-anagrams.ring @@ -0,0 +1,82 @@ +# Project : Anagrams/Deranged anagrams +# Date : 2017/11/28 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +load "stdlib.ring" +fn1 = "unixdict.txt" + +fp = fopen(fn1,"r") +str = fread(fp, getFileSize(fp)) +fclose(fp) +strlist = str2list(str) +anagram = newlist(len(strlist), 5) +anag = list(len(strlist)) +result = list(len(strlist)) +for x = 1 to len(result) + result[x] = 0 +next +for x = 1 to len(anag) + anag[x] = 0 +next +for x = 1 to len(anagram) + for y = 1 to 5 + anagram[x][y] = 0 + next +next + +strbig = 1 +for n = 1 to len(strlist) + for m = 1 to len(strlist) + sum = 0 + if len(strlist[n]) = len(strlist[m]) and n != m + for p = 1 to len(strlist[m]) + temp1 = count(strlist[n], strlist[m][p]) + temp2 = count(strlist[m], strlist[m][p]) + if temp1 = temp2 + sum = sum + 1 + ok + next + if sum = len(strlist[n]) + anag[n] = anag[n] + 1 + if anag[n] < 6 and result[n] = 0 and result[m] = 0 + anagram[n][anag[n]] = strlist[m] + if len(strlist[m]) > len(strlist[strbig]) + strbig = n + ok + result[m] = 1 + ok + ok + ok + next + if anag[n] > 0 + result[n] = 1 + ok +next + +flag = 0 +for m = 1 to 5 + if anagram[strbig][m] != 0 + if m = 1 + see strlist[strbig] + " " + flag = 1 + ok + see anagram[strbig][m] + " " + ok +next + +func getFileSize fp + c_filestart = 0 + c_fileend = 2 + fseek(fp,0,c_fileend) + nfilesize = ftell(fp) + fseek(fp,0,c_filestart) + return nfilesize + +func count(astring,bstring) + cnt = 0 + while substr(astring,bstring) > 0 + cnt = cnt + 1 + astring = substr(astring,substr(astring,bstring)+len(string(sum))) + end + return cnt diff --git a/Task/Anagrams/APL/anagrams-1.apl b/Task/Anagrams/APL/anagrams-1.apl new file mode 100644 index 0000000000..889e13eb7f --- /dev/null +++ b/Task/Anagrams/APL/anagrams-1.apl @@ -0,0 +1,7 @@ +anagrams←{ + tie←⍵ ⎕NTIE 0 + dict←⎕NREAD tie 80(⎕NSIZE tie)0 + boxes←((⎕UCS 10)≠dict)⊆dict + ana←(({⍵[⍋⍵]}¨boxes)({⍵}⌸)boxes) + ({~' '∊¨(⊃/¯1↑[2]⍵)}ana)⌿ana ⋄ ⎕NUNTIE +} diff --git a/Task/Anagrams/APL/anagrams-2.apl b/Task/Anagrams/APL/anagrams-2.apl new file mode 100644 index 0000000000..77e3c98675 --- /dev/null +++ b/Task/Anagrams/APL/anagrams-2.apl @@ -0,0 +1,2 @@ +⎕SH'wget http://www.puzzlers.org/pub/wordlists/unixdict.txt' +]display anagrams 'unixdict.txt' diff --git a/Task/Anagrams/BaCon/anagrams.bacon b/Task/Anagrams/BaCon/anagrams.bacon new file mode 100644 index 0000000000..aac58886ee --- /dev/null +++ b/Task/Anagrams/BaCon/anagrams.bacon @@ -0,0 +1,20 @@ +OPTION COLLAPSE TRUE + +DECLARE idx$ ASSOC STRING + +FOR w$ IN LOAD$("unixdict.txt") STEP NL$ + + set$ = SORT$(EXPLODE$(w$, 1)) + + idx$(set$) = APPEND$(idx$(set$), 0, w$) + total = AMOUNT(idx$(set$)) + + IF MaxCount < total THEN MaxCount = total +NEXT + +PRINT "Analyzing took ", TIMER, " msecs.", NL$ + +LOOKUP idx$ TO n$ SIZE x +FOR y = 0 TO x-1 + IF MaxCount = AMOUNT(idx$(n$[y])) THEN PRINT n$[y], ": ", idx$(n$[y]) +NEXT diff --git a/Task/Anagrams/Clojure/anagrams-2.clj b/Task/Anagrams/Clojure/anagrams-2.clj index 65ae8078d5..7ca2a423c4 100644 --- a/Task/Anagrams/Clojure/anagrams-2.clj +++ b/Task/Anagrams/Clojure/anagrams-2.clj @@ -1,9 +1,8 @@ (->> (slurp "http://www.puzzlers.org/pub/wordlists/unixdict.txt") - (apply str) clojure.string/split-lines (group-by sort) vals - (sort-by count #(compare %2 %1)) ;; sort in reverse + (sort-by count >) ;; sort in reverse (partition-by count) first) diff --git a/Task/Anagrams/Elena/anagrams.elena b/Task/Anagrams/Elena/anagrams.elena index 6ee99abcd0..3f7fe37a88 100644 --- a/Task/Anagrams/Elena/anagrams.elena +++ b/Task/Anagrams/Elena/anagrams.elena @@ -1,26 +1,25 @@ import system'routines. -import system'calendar. import system'io. import system'collections. import extensions. import extensions'routines. +import extensions'text. extension op { normalized - = self toArray; ascendant; summarize(String new); literal. + = self toArray; ascendant; summarize(StringWriter new); literal. } -symbol program = +public program = [ var aDictionary := Dictionary new. - File new("unixdict.txt"); forEachLine(:aWord) [ var s := aWord. var aKey := aWord normalized. var anItem := aDictionary[aKey]. - if ($nil == anItem) + if (nil == anItem) [ anItem := ArrayList new. aDictionary[aKey] := anItem. @@ -29,7 +28,7 @@ symbol program = anItem append:aWord. ]. - aDictionary array_list; + aDictionary values; sort(:aFormer:aLater)( aFormer length > aLater length ); top:20; forEach(:aPair)[ console printLine(aPair value) ]. diff --git a/Task/Anagrams/Julia/anagrams.julia b/Task/Anagrams/Julia/anagrams.julia index e5c7144a75..9585079109 100644 --- a/Task/Anagrams/Julia/anagrams.julia +++ b/Task/Anagrams/Julia/anagrams.julia @@ -1,15 +1,16 @@ url = "http://www.puzzlers.org/pub/wordlists/unixdict.txt" - wordlist = open(readlines, download(url)) -wsort(word) = join(sort(collect(word))) +wsort(word::AbstractString) = join(sort(collect(word))) -function anagram(wordlist) - hash = Dict() ; ananum = 0 - for word in wordlist - sorted = wsort(word) - hash[sorted] = [ get(hash, sorted, []); word ] - ananum = max(length(hash[sorted]), ananum) - end - collect(values(filter((x,y)-> length(y) == ananum, hash))) +function anagram(wordlist::Vector{<:AbstractString}) + dict = Dict{String, Set{String}}() + for word in wordlist + sorted = wsort(word) + push!(get!(dict, sorted, Set{String}()), word) + end + wcnt = maximum(length, values(dict)) + return collect(Iterators.filter((y) -> length(y) == wcnt, values(dict))) end + +println.(anagram(wordlist)) diff --git a/Task/Anagrams/Oforth/anagrams.oforth b/Task/Anagrams/Oforth/anagrams.oforth index 1707582529..0c7d876263 100644 --- a/Task/Anagrams/Oforth/anagrams.oforth +++ b/Task/Anagrams/Oforth/anagrams.oforth @@ -1,5 +1,11 @@ +import: mapping +import: collect +import: quicksort + : anagrams | m | - File new("unixdict.txt") groupBy(#sort) - dup sortBy(#[ second size]) last second size ->m - filter(#[ second size m == ]) apply(#[ second .cr ]) ; + "unixdict.txt" File new groupBy( #sort ) + dup sortBy( #[ second size] ) last second size ->m + filter( #[ second size m == ] ) + apply ( #[ second .cr ] ) +; diff --git a/Task/Anagrams/REXX/anagrams-1.rexx b/Task/Anagrams/REXX/anagrams-1.rexx index e45539b983..d2174f8398 100644 --- a/Task/Anagrams/REXX/anagrams-1.rexx +++ b/Task/Anagrams/REXX/anagrams-1.rexx @@ -1,30 +1,30 @@ /*REXX program finds words with the largest set of anagrams (of the same size). */ iFID= 'unixdict.txt' /*the dictionary input File IDentifier.*/ -$=; !.=; #.=0; w=0; uw=0; most=0 /*initialize a bunch of REXX variables.*/ +$=; !.=; ww=0; uw=0; most=0 /*initialize a bunch of REXX variables.*/ /* [↓] read the entire file (by lines)*/ - do while lines(iFID)\==0 /*Got any data? Then read a record. */ - @=space( linein(iFID), 0) /*pick off a word from the input line. */ - L=length(@); if L<3 then iterate /*onesies and twosies words can't win. */ - if \datatype(@, 'M') then iterate /*ignore any non─anagramable words. */ - uw=uw+1 /*count of the (useable) words in file.*/ - z=sortA(@) /*sort the letters in the word. */ - !.z=!.z @; #.z=#.z+1 /*append it to !.z; bump the counter. */ - if #.z>most then do; $=z; most=#.z; if L>w then w=L; iterate; end - if #.z==most then $=$ z /*append the sorted word──► max anagram*/ + do while lines(iFID) \== 0 /*Got any data? Then read a record. */ + parse value linein(iFID) with @ . /*obtain a word from an input line. */ + len=length(@); if len<3 then iterate /*onesies and twosies words can't win. */ + if \datatype(@, 'M') then iterate /*ignore any non─anagramable words. */ + uw=uw + 1 /*count of the (useable) words in file.*/ + _=sortA(@) /*sort the letters in the word. */ + !._=!._ @; #=words(!._) /*append it to !._; bump the counter. */ + if #==most then $=$ _ /*append the sorted word──► max anagram*/ + else if #>most then do; $=_; most=#; if len>ww then ww=len; end end /*while*/ /*$ ◄── list of high count anagrams. */ -say '─────────────────────────' uw "useable words in the dictionary file: " iFID +say '─────────────────────────' uw "usable words in the dictionary file: " iFID say do m=1 for words($); z=subword($, m, 1) /*the high count of the anagrams. */ - say ' ' left(subword(!.z, 1, 1), w) ' [anagrams: ' subword(!.z, 2)"]" + say ' ' left(word(!.z, 1), ww) ' [anagrams: ' subword(!.z, 2)"]" end /*m*/ /*W is the maximum width of any word.*/ say -say '───── Found' words($) "words (each of which have" #.z-1 'anagrams).' +say '───── Found' words($) "words (each of which have" words(!.z)-1 'anagrams).' exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -sortA: procedure; arg char +1 xx,@. /*get the first letter of arg; @.=null*/ +sortA: arg char 2 xx,@. /*get the first letter of arg; @.=null*/ @.char=char /*no need to concatenate the first char*/ /*[↓] sort/put letters alphabetically.*/ - do length(xx); parse var xx char +1 xx; @.char=@.char || char; end + do length(xx); parse var xx char 2 xx; @.char=@.char || char; end /*reassemble word with sorted letters. */ - return @.a||@.b||@.c||@.d||@.e||@.f||@.g||@.h||@.i||@.j||@.k||@.l||@.m||, - @.n||@.o||@.p||@.q||@.r||@.s||@.t||@.u||@.v||@.w||@.x||@.y||@.z + return @.a || @.b || @.c || @.d || @.e || @.f||@.g||@.h||@.i||@.j||@.k||@.l||@.m||, + @.n || @.o || @.p || @.q || @.r || @.s||@.t||@.u||@.v||@.w||@.x||@.y||@.z diff --git a/Task/Anagrams/REXX/anagrams-2.rexx b/Task/Anagrams/REXX/anagrams-2.rexx index d4a6adc963..4faf6d37b5 100644 --- a/Task/Anagrams/REXX/anagrams-2.rexx +++ b/Task/Anagrams/REXX/anagrams-2.rexx @@ -1,27 +1,30 @@ /*REXX program finds words with the largest set of anagrams (of the same size). */ iFID= 'unixdict.txt' /*the dictionary input File IDentifier.*/ -$=; !.=; #.=0; ww=0; uw=0; most=0 /*initialize a bunch of REXX variables.*/ +$=; !.=; ww=0; uw=0; most=0 /*initialize a bunch of REXX variables.*/ /* [↓] read the entire file (by lines)*/ - do while lines(iFID)\==0 /*Got any data? Then read a record. */ - @=space( linein(iFID), 0) /*pick off a word from the input line. */ - LL=length(@); if LL<3 then iterate /*onesies and twosies (words) can't win*/ - if \datatype(@, 'M') then iterate /*ignore any non─anagramable words. */ - uw=uw+1 /*count of the (useable) words in file.*/ - parse upper var @ _ +1 xx @. /*get uppercase @ and nullify @. */ - @._=_ /*get the first letter (special case). */ - /*[↓] sort/put letters alphabetically.*/ - do LL-1; parse var xx _ +1 xx; @._=@._||_; end /*get the rest of the word.*/ - /*reassemble word with sorted letters. */ - zz=@.a||@.b||@.c||@.d||@.e||@.f||@.g||@.h||@.i||@.j||@.k||@.l||@.m||, - @.n||@.o||@.p||@.q||@.r||@.s||@.t||@.u||@.v||@.w||@.x||@.y||@.z - !.zz=!.zz @; #.zz=#.zz+1 /*append it to !.zz; bump the counter.*/ - if #.zz>most then do; $=zz; most=#.zz; if LL>ww then ww=LL; iterate; end - if #.zz==most then $=$ zz /*append the sorted word──► $ anagrams.*/ - end /*while*/ -say '─────────────────────────' uw "useable words in the dictionary file: " iFID + do while lines(iFID) \== 0 /*Got any data? Then read a record. */ + parse value linein(iFID) with @ . /*obtain a word from an input line. */ + len=length(@); if len<3 then iterate /*onesies and twosies words can't win. */ + if \datatype(@, 'M') then iterate /*ignore any non─anagramable words. */ + uw=uw + 1 /*count of the (useable) words in file.*/ + _=sortA(@) /*sort the letters in the word. */ + !._=!._ @; #=words(!._) /*append it to !._; bump the counter. */ + if #==most then $=$ _ /*append the sorted word──► max anagram*/ + else if #>most then do; $=_; most=#; if len>ww then ww=len; end + end /*while*/ /*$ ◄── list of high count anagrams. */ +say '─────────────────────────' uw "usable words in the dictionary file: " iFID say - do m=1 for words($); z=subword($,m,1) /*the high count of the anagrams. */ - say ' ' left(subword(!.z, 1, 1), ww) " [anagrams: " subword(!.z,2)"]" - end /*m*/ /*WW is the maximum width of any word.*/ -say /*stick a fork in it, we're all done. */ -say '───── Found' words($) "words (each of which have" #.z-1 'anagrams).' + do m=1 for words($); z=subword($, m, 1) /*the high count of the anagrams. */ + say ' ' left(word(!.z, 1), ww) ' [anagrams: ' subword(!.z, 2)"]" + end /*m*/ /*W is the maximum width of any word.*/ +say +say '───── Found' words($) "words (each of which have" words(!.z)-1 'anagrams).' +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +sortA: arg char 2 xx,@. /*get the first letter of arg; @.=null*/ + @.char=char /*no need to concatenate the first char*/ + /*[↓] sort/put letters alphabetically.*/ + do length(xx); parse var xx char 2 xx; @.char=@.char || char; end + /*reassemble word with sorted letters. */ + return @.a || @.b || @.c || @.d || @.e || @.f||@.g||@.h||@.i||@.j||@.k||@.l||@.m||, + @.n || @.o || @.p || @.q || @.r || @.s||@.t||@.u||@.v||@.w||@.x||@.y||@.z diff --git a/Task/Anagrams/REXX/anagrams-3.rexx b/Task/Anagrams/REXX/anagrams-3.rexx index 33e17818f5..8fef3f9055 100644 --- a/Task/Anagrams/REXX/anagrams-3.rexx +++ b/Task/Anagrams/REXX/anagrams-3.rexx @@ -1,27 +1,23 @@ -/*REXX program finds words with the largest set of anagrams (of the same size). */ -iFID= 'unixdict.txt' /*the dictionary input File IDentifier.*/ -$=; !.=; #.=0; ww=0; uw=0; most=0 /*initialize a bunch of REXX variables.*/ - /* [↓] read the entire file (by lines)*/ - do while lines(iFID)\==0 /*Got any data? Then read a record. */ - @=space( linein(iFID), 0) /*pick off a word from the input line. */ - LL=length(@); if LL<3 then iterate /*onesies and twosies (words) can't win*/ - if \datatype(@, 'M') then iterate /*ignore any non─anagramable words. */ - uw=uw+1 /*count of the (useable) words in file.*/ - parse upper var @ _ +1 xx . @. /*get uppercase @ and nullify @. */ - @._=_ /*get the first letter (special case). */ - /*[↓] sort/put letters alphabetically.*/ - do LL-1; parse var xx _ +1 xx; @._=@._ || _; end /*get rest of the word*/ - /*reassemble word with sorted letters. */ - zz=@.a|| @.b|| @.c|| @.d|| @.e|| @.f|| @.g|| @.h|| @.i|| @.j|| @.k|| @.l|| @.m ||, - @.n|| @.o|| @.p|| @.q|| @.r|| @.s|| @.t|| @.u|| @.v|| @.w|| @.x|| @.y|| @.z - !.zz=!.zz @; #.zz=#.zz+1 /*append it to !.zz; bump the counter.*/ - if #.zz>most then do; $=zz; most=#.zz; if LL>ww then ww=LL; iterate; end - if #.zz==most then $=$ zz /*append the sorted word──► $ anagrams.*/ - end /*while*/ -say '─────────────────────────' uw 'useable words in the dictionary file: ' iFID -say - do m=1 for words($); z=subword($, m, 1) /*the high count of the anagrams. */ - say ' ' left(subword(!.z, 1, 1), ww) " [anagrams: " subword(!.z, 2)']' - end /*m*/ /*WW is the maximum width of any word.*/ -say /*stick a fork in it, we're all done. */ -say '───── Found' words($) "words (each of which have" #.z-1 'anagrams).' +u= 'Halloween' /*word to be sorted by (Latin) letter.*/ +upper u /*fast method to uppercase a variable. */ + /*another: u = translate(u) */ + /*another: parse upper var u u */ + /*another: u = upper(u) */ + /*not always available [↑] */ +say 'u=' u +_.= + do until u=='' /*keep truckin' until U is null. */ + parse var u y +1 u /*get the next (first) character in U.*/ + xx='?'y /*assign a prefixed character to XX. */ + _.xx=_.xx || y /*append it to all the Y characters. */ + end /*until*/ /*U now has the first character elided.*/ + /*Note: the variable U is destroyed.*/ + + /* [↓] constructs a sorted letter word*/ + +z=_.?a||_.?b||_.?c||_.?d||_.?e||_.?f||_.?g||_.?h||_.?i||_.?j||_.?k||_.?l||_.?m||, + _.?n||_.?o||_.?p||_.?q||_.?r||_.?s||_.?t||_.?u||_.?v||_.?w||_.?x||_.?y||_.?z + + /*Note: the ? is prefixed to the letter to avoid */ + /*collisions with other REXX one-character variables.*/ +say 'z=' z diff --git a/Task/Anagrams/REXX/anagrams-4.rexx b/Task/Anagrams/REXX/anagrams-4.rexx index 8fef3f9055..bf3588afb2 100644 --- a/Task/Anagrams/REXX/anagrams-4.rexx +++ b/Task/Anagrams/REXX/anagrams-4.rexx @@ -1,23 +1,18 @@ u= 'Halloween' /*word to be sorted by (Latin) letter.*/ upper u /*fast method to uppercase a variable. */ - /*another: u = translate(u) */ - /*another: parse upper var u u */ - /*another: u = upper(u) */ - /*not always available [↑] */ +L=length(u) /*get the length of the word (in bytes)*/ say 'u=' u +say 'L=' L _.= - do until u=='' /*keep truckin' until U is null. */ - parse var u y +1 u /*get the next (first) character in U.*/ + do k=1 for L /*keep truckin' for L characters. */ + parse var u =(k) y +1 /*get the Kth character in U string.*/ xx='?'y /*assign a prefixed character to XX. */ _.xx=_.xx || y /*append it to all the Y characters. */ - end /*until*/ /*U now has the first character elided.*/ - /*Note: the variable U is destroyed.*/ + end /*do k*/ /*U now has the first character elided.*/ - /* [↓] constructs a sorted letter word*/ + /* [↓] construct a sorted letter word.*/ z=_.?a||_.?b||_.?c||_.?d||_.?e||_.?f||_.?g||_.?h||_.?i||_.?j||_.?k||_.?l||_.?m||, _.?n||_.?o||_.?p||_.?q||_.?r||_.?s||_.?t||_.?u||_.?v||_.?w||_.?x||_.?y||_.?z - /*Note: the ? is prefixed to the letter to avoid */ - /*collisions with other REXX one-character variables.*/ say 'z=' z diff --git a/Task/Anagrams/REXX/anagrams-5.rexx b/Task/Anagrams/REXX/anagrams-5.rexx index bf3588afb2..23a0b51d80 100644 --- a/Task/Anagrams/REXX/anagrams-5.rexx +++ b/Task/Anagrams/REXX/anagrams-5.rexx @@ -1,18 +1,61 @@ -u= 'Halloween' /*word to be sorted by (Latin) letter.*/ -upper u /*fast method to uppercase a variable. */ -L=length(u) /*get the length of the word (in bytes)*/ -say 'u=' u -say 'L=' L -_.= - do k=1 for L /*keep truckin' for L characters. */ - parse var u =(k) y +1 /*get the Kth character in U string.*/ - xx='?'y /*assign a prefixed character to XX. */ - _.xx=_.xx || y /*append it to all the Y characters. */ - end /*do k*/ /*U now has the first character elided.*/ - - /* [↓] construct a sorted letter word.*/ - -z=_.?a||_.?b||_.?c||_.?d||_.?e||_.?f||_.?g||_.?h||_.?i||_.?j||_.?k||_.?l||_.?m||, - _.?n||_.?o||_.?p||_.?q||_.?r||_.?s||_.?t||_.?u||_.?v||_.?w||_.?x||_.?y||_.?z - -say 'z=' z +/*REXX program finds words with the largest set of anagrams (same size) +* 07.08.2013 Walter Pachl +* sorta for word compression courtesy Gerard Schildberger, +* modified, however, to obey lowercase +* 10.08.2013 Walter Pachl take care of mixed case dictionary +* following Version 1's method +**********************************************************************/ +Parse Value 'A B C D E F G H I J K L M N O P Q R S T U V W X Y Z', + With a b c d e f g h i j k l m n o p q r s t u v w x y z +Call time 'R' +ifid='unixdict.txt' /* input file identifier */ +words=0 /* number of usable words */ +maxl=0 /* maximum number of anagrams */ +wl.='' /* wl.ws words that have ws */ +Do ri=1 By 1 While lines(ifid)\==0 /* read each word in file */ + word=space(linein(ifid),0) /* pick off a word from the input.*/ + If length(word)<3 Then /* onesies and twosies can't win. */ + Iterate + If\datatype(word,'M') Then /* not an anagramable word */ + Iterate + words=words+1 /* count of (useable) words. */ + ws=sorta(word) /* sort the letters in the word. */ + wl.ws=wl.ws word /* add word to list of ws */ + wln=words(wl.ws) /* number of anagrams with ws */ + Select + When wln>maxl Then Do /* a new maximum */ + maxl=wln /* use this */ + wsl=ws /* list of resulting ws values */ + End + When wln=maxl Then /* same as the one found */ + wsl=wsl ws /* add ws to the list */ + Otherwise /* shorter */ + Nop /* not yet of interest */ + End + End +Say ' ' +Say copies('-',10) ri-1 'words in the dictionary file: ' ifid +Say copies(' ',10) words 'thereof are anagram candidates' +Say ' ' +Say 'There are' words(wsl) 'set(s) of anagrams with' maxl, + 'elements each:' +Say ' ' +Do while wsl<>'' + Parse Var wsl ws wsl + Say ' 'wl.ws + End +Say time('E') +Exit +sorta: +/********************************************************************** +* sort the characters in word_p (lowercase translated to uppercase) +* 'chARa' -> 'AACHR' +**********************************************************************/ + Parse Upper Arg word_p + c.='' + Do While word_p>'' + Parse Var word_p cc +1 word_p + c.cc=c.cc||cc + End + Return c.a||c.b||c.c||c.d||c.e||c.f||c.g||c.h||c.i||c.j||c.k||c.l||, + c.m||c.n||c.o||c.p||c.q||c.r||c.s||c.t||c.u||c.v||c.w||c.x||c.y||c.z diff --git a/Task/Anagrams/Red/anagrams.red b/Task/Anagrams/Red/anagrams.red new file mode 100644 index 0000000000..a45eb79b65 --- /dev/null +++ b/Task/Anagrams/Red/anagrams.red @@ -0,0 +1,16 @@ +Red [] + +m: make map! [] 25000 + +maxx: 0 +foreach word read/lines http://www.puzzlers.org/pub/wordlists/unixdict.txt [ +sword: sort copy word ;; sorted characters of word + +either find m sword [ + append m/:sword word + maxx: max maxx length? m/:sword + ] [ + put m sword append copy [] word + ] +] +foreach v values-of m [ if maxx = length? v [print v] ] diff --git a/Task/Anagrams/Ring/anagrams.ring b/Task/Anagrams/Ring/anagrams.ring new file mode 100644 index 0000000000..8833f3320e --- /dev/null +++ b/Task/Anagrams/Ring/anagrams.ring @@ -0,0 +1,83 @@ +# Project : Anagrams +# Date : 2017/11/28 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +load "stdlib.ring" +fn1 = "unixdict.txt" + +fp = fopen(fn1,"r") +str = fread(fp, getFileSize(fp)) +fclose(fp) +strlist = str2list(str) +anagram = newlist(len(strlist), 5) +anag = list(len(strlist)) +result = list(len(strlist)) +for x = 1 to len(result) + result[x] = 0 +next +for x = 1 to len(anag) + anag[x] = 0 +next +for x = 1 to len(anagram) + for y = 1 to 5 + anagram[x][y] = 0 + next +next + +for n = 1 to len(strlist) + for m = 1 to len(strlist) + sum = 0 + if len(strlist[n]) = 4 and len(strlist[m]) = 4 and n != m + for p = 1 to len(strlist[m]) + temp1 = count(strlist[n], strlist[m][p]) + temp2 = count(strlist[m], strlist[m][p]) + if temp1 = temp2 + sum = sum + 1 + ok + next + if sum = 4 + anag[n] = anag[n] + 1 + if anag[n] < 6 and result[n] = 0 and result[m] = 0 + anagram[n][anag[n]] = strlist[m] + result[m] = 1 + ok + ok + ok + next + if anag[n] > 0 + result[n] = 1 + ok +next + +for n = 1 to len(anagram) + flag = 0 + for m = 1 to 5 + if anagram[n][m] != 0 + if m = 1 + see strlist[n] + " " + flag = 1 + ok + see anagram[n][m] + " " + ok + next + if flag = 1 + see nl + ok +next + +func getFileSize fp + c_filestart = 0 + c_fileend = 2 + fseek(fp,0,c_fileend) + nfilesize = ftell(fp) + fseek(fp,0,c_filestart) + return nfilesize + +func count(astring,bstring) + cnt = 0 + while substr(astring,bstring) > 0 + cnt = cnt + 1 + astring = substr(astring,substr(astring,bstring)+len(string(sum))) + end + return cnt diff --git a/Task/Anagrams/Stata/anagrams.stata b/Task/Anagrams/Stata/anagrams.stata new file mode 100644 index 0000000000..1469f3471b --- /dev/null +++ b/Task/Anagrams/Stata/anagrams.stata @@ -0,0 +1,16 @@ +import delimited http://www.puzzlers.org/pub/wordlists/unixdict.txt, clear +mata +a=st_sdata(.,.) +n=rows(a) +for (i=1; i<=n; i++) a[i]=char(sort(ascii(a[i])',1)') +st_addvar(st_vartype(1),"group") +st_sstore(.,2,a) +end + +bysort group (v1): gen k=_N +qui sum k +keep if k==r(max) +by group: replace k=_n +reshape wide v1, i(k) j(group) string +drop k +list, noobs noheader diff --git a/Task/Anagrams/VBA/anagrams.vba b/Task/Anagrams/VBA/anagrams.vba new file mode 100644 index 0000000000..b11bca10de --- /dev/null +++ b/Task/Anagrams/VBA/anagrams.vba @@ -0,0 +1,162 @@ +Option Explicit + +Public Sub Main_Anagram() +Dim varReturn +Dim temp +Dim strContent As String +Dim strFile As String +Dim Num As Long +Dim i As Long +Dim countTime As Single + + 'Open & read txt file + Num = FreeFile + strFile = "C:\Users\" & Environ("Username") & "\Desktop\unixdict.txt" + Open strFile For Input As #Num + strContent = Input(LOF(1), #Num) + Close #Num + Debug.Print UBound(Split(strContent, vbCrLf)) + 1 & " words, in the dictionary" + countTime = Timer + 'Compute + varReturn = Anagrams(strContent) + 'Return + Debug.Print "The anagram set(s) with the greatest number of words (namely " & UBound(varReturn, 2) & ") is : " + Debug.Print "" + For i = LBound(varReturn, 1) To UBound(varReturn, 1) + ReDim temp(LBound(varReturn, 2) To UBound(varReturn, 2)) + For Num = LBound(varReturn, 2) To UBound(varReturn, 2) + temp(Num) = varReturn(i, Num) + Next + SortOneDimArray temp, LBound(temp), UBound(temp) + Debug.Print Mid(Join(temp, ", "), 3) + Next i + Debug.Print "" + Debug.Print "Time to go : " & Timer - countTime & " seconds." +End Sub + +Private Function Anagrams(strContent As String) As Variant +Dim arrList +Dim arrTemp() As String +Dim arrReturn() As String +Dim Num As Long +Dim lngCountTemp As Long +Dim lngCount As Long +Dim i As Long + + 'Put the content of txt file in an One Dim Array + arrList = Split(strContent, vbCrLf) + ReDim arrTemp(0 To UBound(arrList, 1), 0 To 2) + 'Transfer Datas in a 2nd Array Multi-Dim + 'Col 0 = words with letters sorted + 'Col 1 = words + 'Col 2 = Number of same words with letters sorted in the list + For Num = LBound(arrList) To UBound(arrList) + arrTemp(Num, 0) = SortLetters(CStr(arrList(Num)), Chr(0)) + arrTemp(Num, 1) = CStr(arrList(Num)) + Next + SortTwoDimArray arrTemp, LBound(arrTemp, 1), UBound(arrTemp, 1), 0 + For Num = LBound(arrTemp, 1) To UBound(arrTemp, 1) + arrTemp(Num, 2) = NbIf(arrTemp(Num, 0), arrTemp, Num, 0) + If arrTemp(Num, 2) > lngCountTemp Then lngCountTemp = arrTemp(Num, 2) + Next + 'return + ReDim arrReturn(0 To lngCountTemp, 0) + For Num = LBound(arrTemp, 1) To UBound(arrTemp, 1) + If lngCountTemp = arrTemp(Num, 2) Then + ReDim Preserve arrReturn(0 To lngCountTemp, 0 To lngCount) + For i = 0 To lngCountTemp - 1 + arrReturn(i, lngCount) = arrTemp(Num + i, 1) + Next i + lngCount = lngCount + 1 + End If + Next Num + Anagrams = Transposition(arrReturn) +End Function + +Private Function SortLetters(s As String, sep As String) As String +Dim temp + + temp = Split(StrConv(s, vbUnicode), sep) + SortOneDimArray temp, LBound(temp), UBound(temp) + SortLetters = Join(temp, sep) +End Function + +Private Function NbIf(strValue As String, arr As Variant, lngInd As Long, Optional lngColumn As Long) As Long +Dim i As Long +Dim lngCount As Long + + For i = lngInd To UBound(arr, 1) + If arr(i, lngColumn) = strValue Then + lngCount = lngCount + 1 + Else + Exit For + End If + Next i + NbIf = lngCount +End Function + +Private Function Transposition(ByRef myArr As Variant) As Variant +Dim tabl +Dim i As Long +Dim j As Long + + ReDim tabl(LBound(myArr, 2) To UBound(myArr, 2), LBound(myArr, 1) To UBound(myArr, 1)) + For i = LBound(myArr, 1) To UBound(myArr, 1) + For j = LBound(myArr, 2) To UBound(myArr, 2) + tabl(j, i) = myArr(i, j) + Next j + Next i + Transposition = tabl + Erase tabl +End Function + +Private Sub SortOneDimArray(ByRef myArr As Variant, mini As Long, Maxi As Long) +Dim i As Long +Dim j As Long +Dim Pivot As Variant +Dim temp As Variant + + On Error Resume Next + i = mini: j = Maxi + Pivot = myArr((mini + Maxi) \ 2) + While i <= j + While myArr(i) < Pivot And i < Maxi: i = i + 1: Wend + While Pivot < myArr(j) And j > mini: j = j - 1: Wend + If i <= j Then + temp = myArr(i) + myArr(i) = myArr(j) + myArr(j) = temp + i = i + 1: j = j - 1 + End If + Wend + If (mini < j) Then Call SortOneDimArray(myArr, mini, j) + If (i < Maxi) Then Call SortOneDimArray(myArr, i, Maxi) +End Sub + +Private Sub SortTwoDimArray(ByRef myArr As Variant, mini As Long, Maxi As Long, Optional Colonne As Long = 0) +Dim i As Long +Dim j As Long +Dim Pivot As Variant +Dim myArrTemp As Variant +Dim ColTemp As Long + + On Error Resume Next + i = mini: j = Maxi + Pivot = myArr((mini + Maxi) \ 2, Colonne) + While i <= j + While myArr(i, Colonne) < Pivot And i < Maxi: i = i + 1: Wend + While Pivot < myArr(j, Colonne) And j > mini: j = j - 1: Wend + If i <= j Then + ReDim myArrTemp(LBound(myArr, 2) To UBound(myArr, 2)) + For ColTemp = LBound(myArr, 2) To UBound(myArr, 2) + myArrTemp(ColTemp) = myArr(i, ColTemp) + myArr(i, ColTemp) = myArr(j, ColTemp) + myArr(j, ColTemp) = myArrTemp(ColTemp) + Next ColTemp + Erase myArrTemp + i = i + 1: j = j - 1 + End If + Wend + If (mini < j) Then Call SortTwoDimArray(myArr, mini, j, Colonne) + If (i < Maxi) Then Call SortTwoDimArray(myArr, i, Maxi, Colonne) +End Sub diff --git a/Task/Animate-a-pendulum/BASIC/animate-a-pendulum-1.basic b/Task/Animate-a-pendulum/BASIC/animate-a-pendulum-1.basic new file mode 100644 index 0000000000..cb468a1c9d --- /dev/null +++ b/Task/Animate-a-pendulum/BASIC/animate-a-pendulum-1.basic @@ -0,0 +1,29 @@ + MODE 8 + *FLOAT 64 + VDU 23,23,4;0;0;0; : REM Set line thickness + + theta = RAD(40) : REM initial displacement + g = 9.81 : REM acceleration due to gravity + l = 0.50 : REM length of pendulum in metres + + REPEAT + PROCpendulum(theta, l) + WAIT 1 + PROCpendulum(theta, l) + accel = - g * SIN(theta) / l / 100 + speed += accel / 100 + theta += speed + UNTIL FALSE + END + + DEF PROCpendulum(a, l) + LOCAL pivotX, pivotY, bobX, bobY + pivotX = 640 + pivotY = 800 + bobX = pivotX + l * 1000 * SIN(a) + bobY = pivotY - l * 1000 * COS(a) + GCOL 3,6 + LINE pivotX, pivotY, bobX, bobY + GCOL 3,11 + CIRCLE FILL bobX + 24 * SIN(a), bobY - 24 * COS(a), 24 + ENDPROC diff --git a/Task/Animate-a-pendulum/BASIC/animate-a-pendulum-2.basic b/Task/Animate-a-pendulum/BASIC/animate-a-pendulum-2.basic new file mode 100644 index 0000000000..99c5cafb26 --- /dev/null +++ b/Task/Animate-a-pendulum/BASIC/animate-a-pendulum-2.basic @@ -0,0 +1,24 @@ +10 GOSUB 1000 +20 THETA = π/2 +30 G = 9.81 +40 L = 0.5 +50 SPEED = 0 +60 PX = 20 +70 PY = 1 +80 BX = PX+L*20*SIN(THETA) +90 BY = PY-L*20*COS(THETA) +100 PRINT CHR$(147); +110 FOR X=PX TO BX STEP (BX-PX)/10 +120 Y=PY+(X-PX)*(BY-PY)/(BX-PX) +130 PRINT CHR$(19);LEFT$(X$,X);LEFT$(Y$,Y);"." +140 NEXT +150 PRINT CHR$(19);LEFT$(X$,BX);LEFT$(Y$,BY);CHR$(113) +160 ACCEL=G*SIN(THETA)/L/50 +170 SPEED=SPEED+ACCEL/10 +180 THETA=THETA+SPEED +190 GOTO 80 +980 REM ** SETUP STRINGS TO BE USED ** +990 REM ** FOR CURSOR POSITIONING ** +1000 FOR I=0 TO 39: X$ = X$+CHR$(29): NEXT +1010 FOR I=0 TO 24: Y$ = Y$+CHR$(17): NEXT +1020 RETURN diff --git a/Task/Animate-a-pendulum/BASIC/animate-a-pendulum-3.basic b/Task/Animate-a-pendulum/BASIC/animate-a-pendulum-3.basic new file mode 100644 index 0000000000..e92d2a6774 --- /dev/null +++ b/Task/Animate-a-pendulum/BASIC/animate-a-pendulum-3.basic @@ -0,0 +1,22 @@ +Const PI = 3.141592920 +Dim As Double theta, g, l, accel, speed, px, py, bx, by +theta = PI/2 +g = 9.81 +l = 1 +speed = 0 +px = 320 +py = 10 +Screen 17 '640x400 graphic +Do + bx=px+l*300*Sin(theta) + by=py-l*300*Cos(theta) + Cls + Line (px,py)-(bx,by) + Circle (bx,by),5,,,,,F + accel=g*Sin(theta)/l/100 + speed=speed+accel/100 + theta=theta+speed + Draw String (0,370), "Pendulum" + Draw String (0,385), "Press any key to quit" + Sleep 10 +Loop Until Inkey()<>"" diff --git a/Task/Animate-a-pendulum/JavaScript/animate-a-pendulum-2.js b/Task/Animate-a-pendulum/JavaScript/animate-a-pendulum-2.js index 906b58e578..e44b9af153 100644 --- a/Task/Animate-a-pendulum/JavaScript/animate-a-pendulum-2.js +++ b/Task/Animate-a-pendulum/JavaScript/animate-a-pendulum-2.js @@ -17,9 +17,9 @@ in_angle.value = 0; var cx = 150, cy = 50; var radius = 100; // cm - var g = 981; // cm/s^2 + var g = 9.81; // m/s^2 var angle = 0; // radians - var vel = 0; // cm/s + var vel = 0; // m/s var dx = 0.02; // s var acc, vel, penx, peny; var timerFunction = null; @@ -33,9 +33,9 @@ if(!timerFunction) timerFunction = setInterval(swing, dx * 1000); } function swing(){ - acc = g * Math.cos(angle) * dx; - vel += acc * dx; - angle += vel * dx; + acc = g * Math.cos(angle); + vel += acc * dx;//Convert m/s/s to m/s + angle += vel/(radius/100) * dx; //convert m/s into rad/s and then into rad setPenPos(); } function setPenPos(){ diff --git a/Task/Animate-a-pendulum/Julia/animate-a-pendulum.julia b/Task/Animate-a-pendulum/Julia/animate-a-pendulum.julia new file mode 100644 index 0000000000..dc58567eb3 --- /dev/null +++ b/Task/Animate-a-pendulum/Julia/animate-a-pendulum.julia @@ -0,0 +1,46 @@ +using Luxor +using Colors +using BoundaryValueDiffEq + +# constants for differential equations and movie +const g = 9.81 +const L = 1.0 # pendulum length in meters +const bobd = 0.10 # pendulum bob diameter in meters +const framerate = 50.0 # intended frame rate/sec +const t0 = 0.0 # start time (s) +const tf = 2.3 # end simulation time (s) +const dtframe = 1.0/framerate # time increment per frame +const tspan = linspace(t0, tf, Int(floor(tf*framerate))) # array of time points in animation + +const bgcolor = "black" # gif background +const leaderhue = (0.80, 0.70, 0.20) # gif swing arm hue light gold +const hslcolors = [HSL(col) for col in (distinguishable_colors( + Int(floor(tf*framerate)+3),[RGB(1,1,1)])[2:end])] +const giffilename = "pendulum.gif" # output file + +# differential equations +simplependulum(t,u,du) = (θ=u[1]; dθ=u[2]; du[1]=dθ; du[2]=-(g/L)*sin(θ)) +bc2(residual, ua, ub) = (residual[1] = ua[1] + pi/2; residual[2] = ub[1] + pi/2) +bvp2 = TwoPointBVProblem(simplependulum, bc2, [pi/2,pi/2], (tspan[1],tspan[end])) +sol2 = solve(bvp2, MIRK4(), dt=dtframe) # use the MIRK4 solver for TwoPointBVProblem + +# movie making background +backdrop(scene, framenumber) = background(bgcolor) + +function frame(scene, framenumber) + u1, u2 = sol2.u[framenumber] + y, x = L*cos(u1), L*sin(u1) + sethue(leaderhue) + poly([Point(-4.0, 0.0), Point(4.0, 0.0), + Point(160.0x,160.0y)], :fill) + sethue(Colors.HSV(framenumber*4.0, 1, 1)) + circle(Point(160.0x,160.0y), 160bobd, :fill) + text(string("frame $framenumber of $(scene.framerange.stop)"), + Point(0.0, -190.0), + halign=:center) +end + +muv = Movie(400, 400, "Pendulum Demo", 1:length(tspan)) +animate(muv, [Scene(muv, backdrop), + Scene(muv, frame, easingfunction=easeinoutcubic)], + creategif=true, pathname=giffilename) diff --git a/Task/Animate-a-pendulum/Lingo/animate-a-pendulum.lingo b/Task/Animate-a-pendulum/Lingo/animate-a-pendulum.lingo new file mode 100644 index 0000000000..b5545e9a98 --- /dev/null +++ b/Task/Animate-a-pendulum/Lingo/animate-a-pendulum.lingo @@ -0,0 +1,43 @@ +global RODLEN, GRAVITY, DT +global velocity, acceleration, angle, posX, posY + +on startMovie + + -- window properties + _movie.stage.title = "Pendulum" + _movie.stage.titlebarOptions.visible = TRUE + _movie.stage.rect = rect(0, 0, 400, 400) + _movie.centerStage = TRUE + _movie.puppetTempo(30) + + RODLEN = 180 + GRAVITY = -9.8 + DT = 0.03 + + velocity = 0.0 + acceleration = 0.0 + angle = PI/3 + posX = 200 - sin(angle) * RODLEN + posY = 100 + cos(angle) * RODLEN + paint() + + -- show the window + _movie.stage.visible = TRUE +end + +on enterFrame + acceleration = GRAVITY * sin(angle) + velocity = velocity + acceleration * DT + angle = angle + velocity * DT + posX = 200 - sin(angle) * rodLen + posY = 100 + cos(angle) * rodLen + paint() +end + +on paint + img = _movie.stage.image + img.fill(img.rect, rgb(255,255,255)) + img.fill(point(200-5, 100-5), point(200+5, 100+5), [#shapeType:#oval,#color:rgb(0,0,0)]) + img.draw(point(200, 100), point(posX, posY), [#color:rgb(0,0,0)]) + img.fill(point(posX-20, posY-20), point(posX+20, posY+20), [#shapeType:#oval,#lineSize:1,#bgColor:rgb(0,0,0),#color:rgb(255,255,0)]) +end diff --git a/Task/Animate-a-pendulum/Ring/animate-a-pendulum.ring b/Task/Animate-a-pendulum/Ring/animate-a-pendulum.ring new file mode 100644 index 0000000000..e693c9325c --- /dev/null +++ b/Task/Animate-a-pendulum/Ring/animate-a-pendulum.ring @@ -0,0 +1,82 @@ +# Project : Animate a pendulum +# Date : 2018/04/09 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +load "guilib.ring" +load "stdlib.ring" + +CounterMan = 1 +paint = null +pi = 22/7 +theta = pi/180*40 +g = 9.81 +l = 0.50 +speed = 0 + +new qapp + { + win1 = new qwidget() { + setwindowtitle("Animate a pendulum") + setgeometry(100,100,800,600) + label1 = new qlabel(win1) { + setgeometry(10,10,800,600) + settext("") + } + new qpushbutton(win1) { + setgeometry(150,500,100,30) + settext("draw") + setclickevent("draw()") + } + TimerMan = new qtimer(win1) + { + setinterval(1000) + settimeoutevent("draw()") + start() + } + show() + } + exec() + } + +func draw + p1 = new qpicture() + color = new qcolor() { + setrgb(0,0,255,255) + } + pen = new qpen() { + setcolor(color) + setwidth(1) + } + paint = new qpainter() { + begin(p1) + setpen(pen) + ptime() + endpaint() + } + label1 { setpicture(p1) show() } + return + + func ptime() + TimerMan.start() + pPlaySleep() + sleep(0.1) + CounterMan++ + if CounterMan = 20 + TimerMan.stop() + ok + +func pPlaySleep() + pendulum(theta, l) + pendulum(theta, l) + accel = - g * sin(theta) / l / 100 + speed = speed + accel / 100 + theta = theta + speed + +func pendulum(a, l) + pivotx = 640 + pivoty = 800 + bobx = pivotx + l * 1000 * sin(a) + boby = pivoty - l * 1000 * cos(a) + paint.drawline(pivotx, pivoty, bobx, boby) + paint.drawellipse(bobx + 24 * sin(a), boby - 24 * cos(a), 24, 24) diff --git a/Task/Animation/FreeBASIC/animation.freebasic b/Task/Animation/FreeBASIC/animation.freebasic index 9317e4af7b..64349f1051 100644 --- a/Task/Animation/FreeBASIC/animation.freebasic +++ b/Task/Animation/FreeBASIC/animation.freebasic @@ -1,9 +1,9 @@ DIM C AS STRING = "Hello World! ", SIZE AS USHORT = LEN(C) DIM DIRECTION AS BYTE = 0 DIM AS INTEGER X, Y, BTNS -DIM BUTHELD AS BYTE = 0 +DIM HELD AS BYTE = 0 -SCREEN 12 +SCREEN 19 DO LOCATE 1, 1 @@ -11,15 +11,14 @@ DO GETMOUSE X, Y, , BTNS - IF BTNS <> 0 THEN - IF BUTHELD = 0 THEN 'remember if it was pressed, to not react - BUTHELD = 1 'every frame on the mouse being just held - IF (X >= 0 AND X < SIZE * 8) AND (Y >= 0 AND Y < 16) THEN - DIRECTION = 1 - DIRECTION - END IF + IF BTNS <> 0 AND HELD = 0 THEN + 'remember if it was pressed, to not react every frame + HELD = 1 + IF X >= 0 AND X < SIZE * 8 AND Y >= 0 AND Y < 16 THEN + DIRECTION = 1 - DIRECTION END IF ELSE - BUTHELD = 0 + HELD = 0 END IF IF INKEY = CHR(255) + CHR(107) THEN EXIT DO diff --git a/Task/Animation/J/animation-1.j b/Task/Animation/J/animation-1.j new file mode 100644 index 0000000000..bb2ffd05e6 --- /dev/null +++ b/Task/Animation/J/animation-1.j @@ -0,0 +1,26 @@ +coinsert'jgl2' [ require'gl2' + +MESSAGE =: 'Hello World! ' +TIMER_INTERVAL =: 0.5 * 1000 NB. Milliseconds +DIRECTION =: -1 NB. Initial direction is right --> + +ANIM =: noun define + pc anim closeok;pn "Basic Animation in J"; + minwh 350 5; + cc isi isigraph flush; + pcenter;pshow; +) + +anim_run =: verb def 'wd ANIM,''; ptimer '',":TIMER_INTERVAL' NB. Set form timer +anim_timer =: verb def 'glpaint MESSAGE=: DIRECTION |. MESSAGE' NB. Rotate MESSAGE according to DIRECTION +anim_isi_mbldown=: verb def 'DIRECTION=: - DIRECTION' NB. Reverse direction when user clicks +anim_close =: verb def 'wd ''timer 0; pclose; reset'' ' NB. Shut down timer +anim_isi_paint =: verb define + glclear '' NB. Clear out old drawing + glrgb 255 0 0 + gltextcolor'' + glfont '"courier new" 36' + gltext MESSAGE +) + +anim_run '' diff --git a/Task/Animation/J/animation.j b/Task/Animation/J/animation-2.j similarity index 100% rename from Task/Animation/J/animation.j rename to Task/Animation/J/animation-2.j diff --git a/Task/Animation/Julia/animation-1.julia b/Task/Animation/Julia/animation-1.julia new file mode 100644 index 0000000000..629c4fd6f2 --- /dev/null +++ b/Task/Animation/Julia/animation-1.julia @@ -0,0 +1,35 @@ +using Tk + +const frameinterval = 0.12 # partial seconds between change on screen display + +function windowanim(stepinterval::Float64) + wind = Window("Animation", 300, 100) + frm = Frame(wind) + hello = "Hello World! " + but = Button(frm, width=30, text=hello) + rightward = true + callback(s) = (rightward = !rightward) + bind(but, "command", callback) + pack(frm, expand=true, fill = "both") + pack(but, expand=true, fill = "both") + permut = [hello[i:end] * hello[1:i-1] for i in length(hello)+1:-1:2] + ppos = 1 + pmod = length(permut) + while true + but[:text] = permut[ppos] + sleep(stepinterval) + if rightward + ppos += 1 + if ppos > pmod + ppos = 1 + end + else + ppos -= 1 + if ppos < 1 + ppos = pmod + end + end + end +end + +windowanim(frameinterval) diff --git a/Task/Animation/Julia/animation-2.julia b/Task/Animation/Julia/animation-2.julia new file mode 100644 index 0000000000..d6e2642dbd --- /dev/null +++ b/Task/Animation/Julia/animation-2.julia @@ -0,0 +1,35 @@ +using Gtk.ShortNames + +const frameinterval = 0.12 # partial seconds between change on screen display + +function textanimation(stepinterval::Float64) + hello = "Hello World! " + win = Window("Animation", 210, 40) |> (Frame() |> (but = Button("Switch Directions"))) + rightward = true + switchdirections(s) = (rightward = !rightward) + signal_connect(switchdirections, but, "clicked") + permut = [hello[i:end] * hello[1:i-1] for i in length(hello)+1:-1:2] + ppos = 1 + pmod = length(permut) + nobreak = true + endit(w) = (nobreak = false) + signal_connect(endit, win, :destroy) + showall(win) + while nobreak + setproperty!(but, :label, permut[ppos]) + sleep(stepinterval) + if rightward + ppos += 1 + if(ppos > pmod) + ppos = 1 + end + else + ppos -= 1 + if(ppos < 1) + ppos = pmod + end + end + end +end + +textanimation(frameinterval) diff --git a/Task/Animation/Maple/animation-1.maple b/Task/Animation/Maple/animation-1.maple new file mode 100644 index 0000000000..b2c9ff90fd --- /dev/null +++ b/Task/Animation/Maple/animation-1.maple @@ -0,0 +1 @@ +ScrollText(GP("Text",value),"Forward",65); diff --git a/Task/Animation/Maple/animation-2.maple b/Task/Animation/Maple/animation-2.maple new file mode 100644 index 0000000000..dca8f562cb --- /dev/null +++ b/Task/Animation/Maple/animation-2.maple @@ -0,0 +1 @@ +ScrollText(GP("Text",value),"Reverse",65); diff --git a/Task/Animation/Maple/animation-3.maple b/Task/Animation/Maple/animation-3.maple new file mode 100644 index 0000000000..67c66a69d9 --- /dev/null +++ b/Task/Animation/Maple/animation-3.maple @@ -0,0 +1,18 @@ +macro(SP=DocumentTools:-SetProperty, GP=DocumentTools:-GetProperty); +SP("Text",value,"Hello World! "); +ScrollText := proc( msg, direction::identical("Forward","Reverse"),n::posint:=20 ) + local word, count; + word:=msg; + count:=0; + + while count element + self.setStyleSheet("QLabel {color: cyan; }") -TIMETICK = 180 -TICK = USEREVENT + 2 + def timerEvent(self, event): + i = 1 if self.right_to_left_direction else -1 + self.setText(self.text()[i:] + self.text()[:i]) # rotate -TEXTBOX = pygame.Rect(10,10,XSIZE,YSIZE) + def mouseReleaseEvent(self, event): # change direction on mouse release + self.right_to_left_direction = not self.right_to_left_direction -pygame.time.set_timer(TICK, TIMETICK) + def keyPressEvent(self, event): # exit on Esc + if event.key() == Qt.Key_Escape: + self.close() -window = pygame.display.set_mode((XSIZE, YSIZE)) -pygame.display.set_caption("Animation") -font = pygame.font.SysFont(None, FONTSIZE) -screen = pygame.display.get_surface() - -def rotate(): - index = DIR and -1 or 1 - global TEXT - TEXT = TEXT[index:]+TEXT[:index] - -def click(position): - if TEXTBOX.collidepoint(position): - global DIR - DIR = not DIR - -def draw(): - surface = font.render(TEXT, True, (255,255,255), (0,0,0)) - global TEXTBOX - TEXTBOX = screen.blit(surface, TEXTBOX) - -def input(event): - if event.type == QUIT: - sys.exit(0) - elif event.type == MOUSEBUTTONDOWN: - click(event.pos) - elif event.type == TICK: - draw() - rotate() - -while True: - input(pygame.event.wait()) - pygame.display.flip() +app = QApplication(sys.argv) +w = Marquee() +# center widget on the screen +w.adjustSize() # update w.rect() now +w.move(QApplication.instance().desktop().screen().rect().center() + - w.rect().center()) +w.show() +sys.exit(app.exec()) diff --git a/Task/Animation/Python/animation-2.py b/Task/Animation/Python/animation-2.py index 5668db0373..a72cbad5d2 100644 --- a/Task/Animation/Python/animation-2.py +++ b/Task/Animation/Python/animation-2.py @@ -1,23 +1,55 @@ -import Tkinter as tki +import pygame, sys +from pygame.locals import * +pygame.init() -def scroll_text(s, how_many): - return s[how_many:] + s[:how_many] +YSIZE = 40 +XSIZE = 150 -direction = 1 -tk = tki.Tk() -var = tki.Variable(tk) +TEXT = "Hello World! " +FONTSIZE = 32 -def mouse_handler(point): - global direction - direction *= -1 +LEFT = False +RIGHT = True -def timer_handler(): - var.set(scroll_text(var.get(),direction)) - tk.after(125, timer_handler) +DIR = RIGHT -var.set('Hello, World! ') -tki.Label(tk, textvariable=var).pack() -tk.bind("", mouse_handler) -tk.after(125, timer_handler) -tk.title('Python Animation') -tki.mainloop() +TIMETICK = 180 +TICK = USEREVENT + 2 + +TEXTBOX = pygame.Rect(10,10,XSIZE,YSIZE) + +pygame.time.set_timer(TICK, TIMETICK) + +window = pygame.display.set_mode((XSIZE, YSIZE)) +pygame.display.set_caption("Animation") + +font = pygame.font.SysFont(None, FONTSIZE) +screen = pygame.display.get_surface() + +def rotate(): + index = DIR and -1 or 1 + global TEXT + TEXT = TEXT[index:]+TEXT[:index] + +def click(position): + if TEXTBOX.collidepoint(position): + global DIR + DIR = not DIR + +def draw(): + surface = font.render(TEXT, True, (255,255,255), (0,0,0)) + global TEXTBOX + TEXTBOX = screen.blit(surface, TEXTBOX) + +def input(event): + if event.type == QUIT: + sys.exit(0) + elif event.type == MOUSEBUTTONDOWN: + click(event.pos) + elif event.type == TICK: + draw() + rotate() + +while True: + input(pygame.event.wait()) + pygame.display.flip() diff --git a/Task/Animation/Python/animation-3.py b/Task/Animation/Python/animation-3.py new file mode 100644 index 0000000000..5668db0373 --- /dev/null +++ b/Task/Animation/Python/animation-3.py @@ -0,0 +1,23 @@ +import Tkinter as tki + +def scroll_text(s, how_many): + return s[how_many:] + s[:how_many] + +direction = 1 +tk = tki.Tk() +var = tki.Variable(tk) + +def mouse_handler(point): + global direction + direction *= -1 + +def timer_handler(): + var.set(scroll_text(var.get(),direction)) + tk.after(125, timer_handler) + +var.set('Hello, World! ') +tki.Label(tk, textvariable=var).pack() +tk.bind("", mouse_handler) +tk.after(125, timer_handler) +tk.title('Python Animation') +tki.mainloop() diff --git a/Task/Animation/Ring/animation.ring b/Task/Animation/Ring/animation.ring new file mode 100644 index 0000000000..301386de58 --- /dev/null +++ b/Task/Animation/Ring/animation.ring @@ -0,0 +1,43 @@ +# Project : Animation +# Date : 2018/01/18 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : + +Load "guilib.ring" +load "stdlib.ring" +rotate = false + +MyApp = New qApp { + win1 = new qWidget() { + setwindowtitle("Hello World") + setGeometry(100,100,370,250) + + lineedit1 = new qlineedit(win1) { + setGeometry(10,100,350,30) + lineedit1.settext(" Hello World! ") + myfilter = new qallevents(lineedit1) + myfilter.setMouseButtonPressevent("rotatetext()") + installeventfilter(myfilter)} + show()} +exec()} + +func rotatetext() + rotate = not rotate + strold = " Hello World! " + for n = 1 to 15 + if rotate = true + see "str = " + '"' + strold + '"' + nl + strnew = right(strold, 1) + left(strold, len(strold) - 1) + lineedit1.settext(strnew) + strold = strnew + sleep(1) + ok + if rotate = false + see "str = " + '"' + strold + '"' + nl + strnew = right(strold, len(strold) - 1) + left(strold, 1) + lineedit1.settext(strnew) + strold = strnew + sleep(1) + ok + next + see nl diff --git a/Task/Anonymous-recursion/AutoIt/anonymous-recursion.autoit b/Task/Anonymous-recursion/AutoIt/anonymous-recursion.autoit new file mode 100644 index 0000000000..fd835ac606 --- /dev/null +++ b/Task/Anonymous-recursion/AutoIt/anonymous-recursion.autoit @@ -0,0 +1,15 @@ +ConsoleWrite(Fibonacci(10) & @CRLF) ; ## USAGE EXAMPLE +ConsoleWrite(Fibonacci(20) & @CRLF) ; ## USAGE EXAMPLE +ConsoleWrite(Fibonacci(30)) ; ## USAGE EXAMPLE + +Func Fibonacci($number) + + If $number < 0 Then Return "Invalid argument" ; No negative numbers + + If $number < 2 Then ; If $number equals 0 or 1 + Return $number ; then return that $number + Else ; Else $number equals 2 or more + Return Fibonacci($number - 1) + Fibonacci($number - 2) ; FIBONACCI! + EndIf + +EndFunc diff --git a/Task/Anonymous-recursion/Elena/anonymous-recursion.elena b/Task/Anonymous-recursion/Elena/anonymous-recursion.elena index 147dbe12f3..b7066df3f2 100644 --- a/Task/Anonymous-recursion/Elena/anonymous-recursion.elena +++ b/Task/Anonymous-recursion/Elena/anonymous-recursion.elena @@ -7,17 +7,16 @@ extension mathOp if (self < 0) [ InvalidArgumentException new:"Must be non negative"; raise ]. - ^ control do:self with - (:n) + ^ target evalSelf(:n) [ if (n > 1) - [ ^ $closure eval(n - 2) + $closure eval(n - 1) ]; + [ ^ @self(n - 2) + @self(n - 1) ]; [ ^ n ] ]. ] } -program = +public program = [ -1 to:10 do(:i) [ diff --git a/Task/Anonymous-recursion/Haskell/anonymous-recursion-4.hs b/Task/Anonymous-recursion/Haskell/anonymous-recursion-4.hs new file mode 100644 index 0000000000..fc8c7b4387 --- /dev/null +++ b/Task/Anonymous-recursion/Haskell/anonymous-recursion-4.hs @@ -0,0 +1,23 @@ +fib :: Integer -> Maybe Integer +fib n + | n < 0 = Nothing + | otherwise = + Just $ + (\f -> + let x = f x + in x) + (\f n -> + if n > 1 + then f (n - 1) + f (n - 2) + else 1) + n + +-- TEST ---------------------------------------------------------------------- +main :: IO () +main = + print $ + fib <$> [-4 .. 10] >>= + \m -> + case m of + Just x -> [x] + _ -> [] diff --git a/Task/Anonymous-recursion/Klong/anonymous-recursion.klong b/Task/Anonymous-recursion/Klong/anonymous-recursion.klong new file mode 100644 index 0000000000..f47eef485e --- /dev/null +++ b/Task/Anonymous-recursion/Klong/anonymous-recursion.klong @@ -0,0 +1 @@ +fib::{:[x<0;"error: negative":|x<2;x;.f(x-1)+.f(x-2)]} diff --git a/Task/Anonymous-recursion/Ring/anonymous-recursion.ring b/Task/Anonymous-recursion/Ring/anonymous-recursion.ring new file mode 100644 index 0000000000..3506c51532 --- /dev/null +++ b/Task/Anonymous-recursion/Ring/anonymous-recursion.ring @@ -0,0 +1,40 @@ +# Project : Anonymous recursion +# Date : 2018/01/03 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +t=0 +for x = -2 to 12 + n = x + recursion() + if x > -1 + see t + nl + ok +next + +func recursion() + nold1=1 + nold2=0 + if n < 0 + see "positive argument required!" + nl + return + ok + if n=0 + t=nold2 + return t + ok + if n=1 + t=nold1 + return t + ok + while n + t=nold2+nold1 + if n>2 + n=n-1 + nold2=nold1 + nold1=t + loop + ok + return t + end + return t diff --git a/Task/Anonymous-recursion/VBA/anonymous-recursion.vba b/Task/Anonymous-recursion/VBA/anonymous-recursion.vba new file mode 100644 index 0000000000..f153c912c4 --- /dev/null +++ b/Task/Anonymous-recursion/VBA/anonymous-recursion.vba @@ -0,0 +1,14 @@ +Sub Main() +Debug.Print F(-10) +Debug.Print F(10) +End Sub + +Private Function F(N As Long) As Variant + If N < 0 Then + F = "Error. Negative argument" + ElseIf N <= 1 Then + F = N + Else + F = F(N - 1) + F(N - 2) + End If +End Function diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/D/append-a-record-to-the-end-of-a-text-file.d b/Task/Append-a-record-to-the-end-of-a-text-file/D/append-a-record-to-the-end-of-a-text-file.d new file mode 100644 index 0000000000..d78d1c0251 --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/D/append-a-record-to-the-end-of-a-text-file.d @@ -0,0 +1,93 @@ +class Record { + private const string account; + private const string password; + private const int uid; + private const int gid; + private const string[] gecos; + private const string directory; + private const string shell; + + public this(string account, string password, int uid, int gid, string[] gecos, string directory, string shell) { + import std.exception; + this.account = enforce(account); + this.password = enforce(password); + this.uid = uid; + this.gid = gid; + this.gecos = enforce(gecos); + this.directory = enforce(directory); + this.shell = enforce(shell); + } + + public void toString(scope void delegate(const(char)[]) sink) const { + import std.conv : toTextRange; + import std.format : formattedWrite; + import std.range : put; + + sink(account); + put(sink, ':'); + sink(password); + put(sink, ':'); + toTextRange(uid, sink); + put(sink, ':'); + toTextRange(gid, sink); + put(sink, ':'); + formattedWrite(sink, "%-(%s,%)", gecos); + put(sink, ':'); + sink(directory); + put(sink, ':'); + sink(shell); + } +} + +public Record parse(string text) { + import std.array : split; + import std.conv : to; + import std.string : chomp; + + string[] tokens = text.chomp.split(':'); + return new Record( + tokens[0], + tokens[1], + to!int(tokens[2]), + to!int(tokens[3]), + tokens[4].split(','), + tokens[5], + tokens[6]); +} + +void main() { + import std.algorithm : map; + import std.file : exists, mkdir; + import std.stdio; + + auto rawData = [ + "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash", + "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash", + "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash" + ]; + + auto records = rawData.map!parse; + + if (!exists("_rosetta")) { + mkdir("_rosetta"); + } + + auto passwd = File("_rosetta/.passwd", "w"); + passwd.lock(); + passwd.writeln(records[0]); + passwd.writeln(records[1]); + passwd.unlock(); + passwd.close(); + + passwd.open("_rosetta/.passwd", "a"); + passwd.lock(); + passwd.writeln(records[2]); + passwd.unlock(); + passwd.close(); + + passwd.open("_rosetta/.passwd"); + foreach(string line; passwd.lines()) { + parse(line).writeln(); + } + passwd.close(); +} diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Julia/append-a-record-to-the-end-of-a-text-file.julia b/Task/Append-a-record-to-the-end-of-a-text-file/Julia/append-a-record-to-the-end-of-a-text-file.julia new file mode 100644 index 0000000000..aca01a5ac9 --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/Julia/append-a-record-to-the-end-of-a-text-file.julia @@ -0,0 +1,46 @@ +using SHA # security instincts say do not write bare passwords to a shared file even in toy code :) + +mutable struct Personnel + fullname::String + office::String + extension::String + homephone::String + email::String + Personnel(ful,off,ext,hom,ema) = new(ful,off,ext,hom,ema) +end + +mutable struct Passwd + account::String + password::String + uid::Int32 + gid::Int32 + personal::Personnel + directory::String + shell::String + Passwd(acc,pas,uid,gid,per,dir,she) = new(acc,pas,uid,gid,per,dir,she) +end + +function writepasswd(filename, passrecords) + if(passrecords isa Array) == false + passrecords = [passrecords] + end + fh = open(filename, "a") # should throw an exception if cannot open in a locked or exclusive mode for append + for pas in passrecords + record = join([pas.account, bytes2hex(sha256(pas.password)), pas.uid, pas.gid, + join([pas.personal.fullname, pas.personal.office, pas.personal.extension, + pas.personal.homephone, pas.personal.email], ','), + pas.directory, pas.shell], ':') + write(fh, record, "\n") + end + close(fh) +end + +const jsmith = Passwd("jsmith","x",1001, 1000, Personnel("Joe Smith", "Room 1007", "(234)555-8917", "(234)555-0077", "jsmith@rosettacode.org"), "/home/jsmith", "/bin/bash") +const jdoe = Passwd("jdoe","x",1002, 1000, Personnel("Jane Doe", "Room 1004", "(234)555-8914", "(234)555-0044", "jdoe@rosettacode.org"), "/home/jdoe", "/bin/bash") +const xyz = Passwd("xyz","x",1003, 1000, Personnel("X Yz", "Room 1003", "(234)555-8913", "(234)555-0033", "xyz@rosettacode.org"), "/home/xyz", "/bin/bash") + +const pfile = "pfile.csv" +writepasswd(pfile, [jsmith, jdoe]) +println("Before last record added, file is:\n$(readstring(pfile))") +writepasswd(pfile, xyz) +println("After last record added, file is:\n$(readstring(pfile))") diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Kotlin/append-a-record-to-the-end-of-a-text-file.kotlin b/Task/Append-a-record-to-the-end-of-a-text-file/Kotlin/append-a-record-to-the-end-of-a-text-file.kotlin new file mode 100644 index 0000000000..fd1f9aa704 --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/Kotlin/append-a-record-to-the-end-of-a-text-file.kotlin @@ -0,0 +1,56 @@ +// Version 1.2.41 + +import java.io.File + +class Record( + val account: String, + val password: String, + val uid: Int, + val gid: Int, + val gecos: List, + val directory: String, + val shell: String +){ + override fun toString() = + "$account:$password:$uid:$gid:${gecos.joinToString(",")}:$directory:$shell" +} + +fun parseRecord(line: String): Record { + val fields = line.split(':') + return Record( + fields[0], + fields[1], + fields[2].toInt(), + fields[3].toInt(), + fields[4].split(','), + fields[5], + fields[6] + ) +} + +fun main(args: Array) { + val startData = listOf( + "jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,[email protected]:/home/jsmith:/bin/bash", + "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,[email protected]:/home/jdoe:/bin/bash" + ) + val records = startData.map { parseRecord(it) } + val f = File("passwd.csv") + f.printWriter().use { + for (record in records) it.println(record) + } + println("Initial records:\n") + f.forEachLine { + println(parseRecord(it)) + } + + val newData = "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,[email protected]:/home/xyz:/bin/bash" + val record = parseRecord(newData) + if (!f.setWritable(true, true)) { + println("\nFailed to make file writable only by owner\n.") + } + f.appendText("$record\n") + println("\nRecords after another one is appended:\n") + f.forEachLine { + println(parseRecord(it)) + } +} diff --git a/Task/Append-a-record-to-the-end-of-a-text-file/Perl-6/append-a-record-to-the-end-of-a-text-file.pl6 b/Task/Append-a-record-to-the-end-of-a-text-file/Perl-6/append-a-record-to-the-end-of-a-text-file.pl6 new file mode 100644 index 0000000000..4c612ab0a1 --- /dev/null +++ b/Task/Append-a-record-to-the-end-of-a-text-file/Perl-6/append-a-record-to-the-end-of-a-text-file.pl6 @@ -0,0 +1,66 @@ +class record { + has $.name; + has $.password; + has $.UID; + has $.GID; + has $.fullname; + has $.office; + has $.extension; + has $.homephone; + has $.email; + has $.directory; + has $.shell; + + method gecos { join ',', $.fullname, $.office, $.extension, $.homephone, $.email } + + method gist { + join ':', + $.name, + $.password, + $.UID, + $.GID, + self.gecos, + $.directory, + $.shell; + } +}; + +my $fname = 'foo.fil'; + +given $fname.IO.open(:w) { .close }; # clear file + +sub append ($file, $line){ + my $fh = $file.IO.open(:a) or fail "Unable to open $file"; + given $fh { + # Get a lock on the file, waits until lock is active + .lock; + # seek to the end in case some other process wrote to + # the file while we were waiting for the lock + .seek(0, SeekType::SeekFromEnd); + # write the record + .say: $line; + .close; + } +} + +sub str-to-record ($str) { + my %rec = Z=> $str.split(/<[:,]>/); + my $user = record.new(|%rec); +} + +for + 'jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/bash', + 'jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/bash' +-> $line { + my $thisuser = str-to-record $line; + $fname.&append: $thisuser.gist; +} + +put "Last line of $fname before append:"; +put $fname.IO.lines.tail; + +$fname.&append: str-to-record('xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/bash').gist; + +put "Last line of $fname after append:"; +put $fname.IO.lines.tail; diff --git a/Task/Apply-a-callback-to-an-array/APL/apply-a-callback-to-an-array.apl b/Task/Apply-a-callback-to-an-array/APL/apply-a-callback-to-an-array.apl new file mode 100644 index 0000000000..b113907111 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/APL/apply-a-callback-to-an-array.apl @@ -0,0 +1,10 @@ + - 1 2 3 +¯1 ¯2 ¯3 + 2 * 1 2 3 4 +2 4 8 16 + 2 × ⍳4 +2 4 6 8 + 3 * 3 3 ⍴ ⍳9 + 3 9 27 + 81 243 729 +2187 6561 19683 diff --git a/Task/Apply-a-callback-to-an-array/Aime/apply-a-callback-to-an-array.aime b/Task/Apply-a-callback-to-an-array/Aime/apply-a-callback-to-an-array.aime index 992104cdb6..17b72e0d27 100644 --- a/Task/Apply-a-callback-to-an-array/Aime/apply-a-callback-to-an-array.aime +++ b/Task/Apply-a-callback-to-an-array/Aime/apply-a-callback-to-an-array.aime @@ -1,21 +1,19 @@ void map(list l, void (*fp)(object)) { - l_ucall(l, fp, 0); + l.ucall(fp, 0); } - void out(object o) { o_(o, "\n"); } - integer main(void) { - map(l_effect(0, 1, 2, 3), out); + list(0, 1, 2, 3).map(out); return 0; } diff --git a/Task/Apply-a-callback-to-an-array/Bracmat/apply-a-callback-to-an-array.bracmat b/Task/Apply-a-callback-to-an-array/Bracmat/apply-a-callback-to-an-array.bracmat index ee2c7be23f..0319a41993 100644 --- a/Task/Apply-a-callback-to-an-array/Bracmat/apply-a-callback-to-an-array.bracmat +++ b/Task/Apply-a-callback-to-an-array/Bracmat/apply-a-callback-to-an-array.bracmat @@ -8,7 +8,7 @@ . !arg:(?location,?value) & !!value^2:?!value ) -& ( map +& ( mapar = arr len callback i . !arg:(?arr,?len,?callback) & 0:?i @@ -23,7 +23,7 @@ & 2:?(1$array) & 3:?(2$array) & 4:?(3$array) -& map$(array,4,callbackFunction1) -& map$(array,4,callbackFunction2) -& map$(array,4,callbackFunction1) +& mapar$(array,4,callbackFunction1) +& mapar$(array,4,callbackFunction2) +& mapar$(array,4,callbackFunction1) ); diff --git a/Task/Apply-a-callback-to-an-array/Elena/apply-a-callback-to-an-array.elena b/Task/Apply-a-callback-to-an-array/Elena/apply-a-callback-to-an-array.elena index 3086e60e6d..932559578d 100644 --- a/Task/Apply-a-callback-to-an-array/Elena/apply-a-callback-to-an-array.elena +++ b/Task/Apply-a-callback-to-an-array/Elena/apply-a-callback-to-an-array.elena @@ -1,6 +1,6 @@ import system'routines. -program = +public program = [ (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) forEach(:n) [ console writeLine(n * n) ]. ]. diff --git a/Task/Apply-a-callback-to-an-array/Julia/apply-a-callback-to-an-array.julia b/Task/Apply-a-callback-to-an-array/Julia/apply-a-callback-to-an-array.julia index d213dbf5df..eb797c33ca 100644 --- a/Task/Apply-a-callback-to-an-array/Julia/apply-a-callback-to-an-array.julia +++ b/Task/Apply-a-callback-to-an-array/Julia/apply-a-callback-to-an-array.julia @@ -1,22 +1,8 @@ numbers = [1, 3, 5, 7] -square1 = [square(n) for n in numbers] # list comprehension - -squares2a = map(square, numbers) # functional form - -squares2b = map(x -> x*x, numbers) # functional form with `lambda` - -#There is also extended block form for the map function -squares2c = map(numbers) do x - sum = 0 - for i = 1:x - sum += x^2 #trivial, but you get the point - end - return sum -end - -squares3 = [n * n for n in numbers] # no need for a function, - -squares4 = numbers .* numbers # element-wise operation - -squares4a = numbers .^ 2 # most arithmetic operations can be done element-wise +@show [n ^ 2 for n in numbers] # list comprehension +square(x) = x ^ 2; @show map(square, numbers) # functional form +@show map(x -> x ^ 2, numbers) # functional form with anonymous function +@show [n * n for n in numbers] # no need for a function, +@show numbers .* numbers # element-wise operation +@show numbers .^ 2 # includes .+, .-, ./, comparison, and bitwise operations as well diff --git a/Task/Apply-a-callback-to-an-array/Stata/apply-a-callback-to-an-array.stata b/Task/Apply-a-callback-to-an-array/Stata/apply-a-callback-to-an-array.stata new file mode 100644 index 0000000000..79a282beb9 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Stata/apply-a-callback-to-an-array.stata @@ -0,0 +1,23 @@ +function map(f,a) { + nr = rows(a) + nc = cols(a) + b = J(nr,nc,.) + for (i=1;i<=nr;i++) { + for (j=1;j<=nc;j++) b[i,j] = (*f)(a[i,j]) + } + return(b) +} + +function maps(f,a) { + nr = rows(a) + nc = cols(a) + b = J(nr,nc,"") + for (i=1;i<=nr;i++) { + for (j=1;j<=nc;j++) b[i,j] = (*f)(a[i,j]) + } + return(b) +} + +function square(x) { + return(x*x) +} diff --git a/Task/Apply-a-callback-to-an-array/VBA/apply-a-callback-to-an-array.vba b/Task/Apply-a-callback-to-an-array/VBA/apply-a-callback-to-an-array.vba new file mode 100644 index 0000000000..64de4336d0 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/VBA/apply-a-callback-to-an-array.vba @@ -0,0 +1,21 @@ +Option Explicit + +Sub Main() +Dim arr, i + 'init + arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + + 'Loop and apply a function (Fibonacci) to each element + For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next + + 'return + Debug.Print Join(arr, ", ") +End Sub + +Private Function Fibonacci(N) As Variant + If N <= 1 Then + Fibonacci = N + Else + Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2) + End If +End Function diff --git a/Task/Arbitrary-precision-integers--included-/C++/arbitrary-precision-integers--included-.cpp b/Task/Arbitrary-precision-integers--included-/C++/arbitrary-precision-integers--included-.cpp new file mode 100644 index 0000000000..48b290e675 --- /dev/null +++ b/Task/Arbitrary-precision-integers--included-/C++/arbitrary-precision-integers--included-.cpp @@ -0,0 +1,23 @@ +#include +#include +#include + +namespace mp = boost::multiprecision; + +int main(int argc, char const *argv[]) +{ + // We could just use (1 << 18) instead of tmpres, but let's point out one + // pecularity with gmp and hence boost::multiprecision: they won't accept + // a second mpz_int with pow(). Therefore, if we stick to multiprecision + // pow we need to convert_to(). + uint64_t tmpres = mp::pow(mp::mpz_int(4) + , mp::pow(mp::mpz_int(3) + , 2).convert_to() + ).convert_to(); + mp::mpz_int res = mp::pow(mp::mpz_int(5), tmpres); + std::string s = res.str(); + std::cout << s.substr(0, 20) + << "..." + << s.substr(s.length() - 20, 20) << std::endl; + return 0; +} diff --git a/Task/Arbitrary-precision-integers--included-/Ceylon/arbitrary-precision-integers--included-.ceylon b/Task/Arbitrary-precision-integers--included-/Ceylon/arbitrary-precision-integers--included-.ceylon new file mode 100644 index 0000000000..1f23ab432b --- /dev/null +++ b/Task/Arbitrary-precision-integers--included-/Ceylon/arbitrary-precision-integers--included-.ceylon @@ -0,0 +1,25 @@ +import ceylon.whole { + wholeNumber, + two +} + +shared void run() { + + value five = wholeNumber(5); + value four = wholeNumber(4); + value three = wholeNumber(3); + + value bigNumber = five ^ four ^ three ^ two; + + value firstTwenty = "62060698786608744707"; + value lastTwenty = "92256259918212890625"; + value bigString = bigNumber.string; + + "The number must start with ``firstTwenty`` and end with ``lastTwenty``" + assert(bigString.startsWith(firstTwenty), bigString.endsWith(lastTwenty)); + + value bigSize = bigString.size; + print("The first twenty digits are ``bigString[...19]``"); + print("The last twenty digits are ``bigString[(bigSize - 20)...]``"); + print("The number of digits in 5^4^3^2 is ``bigSize``"); +} diff --git a/Task/Arbitrary-precision-integers--included-/Oforth/arbitrary-precision-integers--included-.oforth b/Task/Arbitrary-precision-integers--included-/Oforth/arbitrary-precision-integers--included-.oforth index 32c2440271..26f60644d3 100644 --- a/Task/Arbitrary-precision-integers--included-/Oforth/arbitrary-precision-integers--included-.oforth +++ b/Task/Arbitrary-precision-integers--included-/Oforth/arbitrary-precision-integers--included-.oforth @@ -1 +1,3 @@ -5 4 3 2 pow pow pow asString dup left(20) . dup right(20) . size . +import: mapping + +5 4 3 2 pow pow pow >string dup left( 20 ) . dup right( 20 ) . size . diff --git a/Task/Arbitrary-precision-integers--included-/REXX/arbitrary-precision-integers--included--1.rexx b/Task/Arbitrary-precision-integers--included-/REXX/arbitrary-precision-integers--included--1.rexx index 4fd5adf515..be724a0151 100644 --- a/Task/Arbitrary-precision-integers--included-/REXX/arbitrary-precision-integers--included--1.rexx +++ b/Task/Arbitrary-precision-integers--included-/REXX/arbitrary-precision-integers--included--1.rexx @@ -1,14 +1,14 @@ /*REXX program calculates and demonstrates arbitrary precision numbers (using powers). */ numeric digits 200000 /*two hundred thousand decimal digits. */ - n = 5 ** (4 ** (3 ** 2) ) /*calculate multiple exponentiations. */ + # = 5 ** (4 ** (3 ** 2) ) /*calculate multiple exponentiations. */ true=62060698786608744707...92256259918212890625 /*what answer is supposed to look like.*/ -rexx= left(n, 20)'...'right(n, 20) /*the left and right 20 decimal digits.*/ +rexx= left(#, 20)'...'right(#, 20) /*the left and right 20 decimal digits.*/ say ' true:' true /*show what the "true" answer is. */ say ' REXX:' rexx /* " " " REXX " " */ -say 'digits:' length(n) /* " " " length of answer is. */ +say 'digits:' length(#) /* " " " length of answer is. */ say if true == rexx then say 'passed!' /*either it passed, ··· */ else say 'failed!' /* or it didn't. */ diff --git a/Task/Arbitrary-precision-integers--included-/REXX/arbitrary-precision-integers--included--2.rexx b/Task/Arbitrary-precision-integers--included-/REXX/arbitrary-precision-integers--included--2.rexx index 972913632a..07e2654a98 100644 --- a/Task/Arbitrary-precision-integers--included-/REXX/arbitrary-precision-integers--included--2.rexx +++ b/Task/Arbitrary-precision-integers--included-/REXX/arbitrary-precision-integers--included--2.rexx @@ -1,21 +1,21 @@ /*REXX program calculates and demonstrates arbitrary precision numbers (using powers). */ numeric digits 5 /*just use enough digits for 1st time. */ - n=5** (4** (3** 2) ) /*calculate multiple exponentiations. */ + #=5** (4** (3** 2) ) /*calculate multiple exponentiations. */ -parse var n 'E' pow . /*POW might be null, so N is OK. */ +parse var # 'E' pow . /*POW might be null, so N is OK. */ if pow\=='' then do /*general case: POW might be < zero.*/ numeric digits abs(pow) + 9 /*recalculate with more decimal digits.*/ - n=5** (4** (3** 2) ) /*calculate multiple exponentiations. */ + #=5** (4** (3** 2) ) /*calculate multiple exponentiations. */ end /* [↑] calculation is the real McCoy. */ true=62060698786608744707...92256259918212890625 /*what answer is supposed to look like.*/ -rexx= left(n, 20)'...'right(n, 20) /*the left and right 20 decimal digits.*/ +rexx= left(#, 20)'...'right(#, 20) /*the left and right 20 decimal digits.*/ say ' true:' true /*show what the "true" answer is. */ say ' REXX:' rexx /* " " " REXX " " */ -say 'digits:' length(n) /* " " " length of answer is. */ +say 'digits:' length(#) /* " " " length of answer is. */ say if true == rexx then say 'passed!' /*either it passed, ··· */ else say 'failed!' /* or it didn't. */ diff --git a/Task/Arbitrary-precision-integers--included-/Ruby/arbitrary-precision-integers--included-.rb b/Task/Arbitrary-precision-integers--included-/Ruby/arbitrary-precision-integers--included-.rb index ff50bf1764..8ecb895018 100644 --- a/Task/Arbitrary-precision-integers--included-/Ruby/arbitrary-precision-integers--included-.rb +++ b/Task/Arbitrary-precision-integers--included-/Ruby/arbitrary-precision-integers--included-.rb @@ -1,2 +1,2 @@ -irb(main):001:0> y = ( 5**4**3**2 ).to_s; puts "5**4**3**2 = #{y[0..19]}...#{y[-20..-1]} and has #{y.length} digits" -5**4**3**2 = 62060698786608744707...92256259918212890625 and has 183231 digits +irb(main):001:0> y = ( 5**4**3**2 ).to_s +puts "5**4**3**2 = #{y[0..19]}...#{y[-20..-1]} and has #{y.length} digits" diff --git a/Task/Arbitrary-precision-integers--included-/Rust/arbitrary-precision-integers--included-.rust b/Task/Arbitrary-precision-integers--included-/Rust/arbitrary-precision-integers--included-.rust index b906225cae..9c9aa87195 100644 --- a/Task/Arbitrary-precision-integers--included-/Rust/arbitrary-precision-integers--included-.rust +++ b/Task/Arbitrary-precision-integers--included-/Rust/arbitrary-precision-integers--included-.rust @@ -5,5 +5,12 @@ use num::pow::pow; fn main() { let big = BigUint::from_u8(5).unwrap(); - println!("{}", pow(big,pow(4,pow(3,2)))); + let answer_as_string = format!("{}", pow(big,pow(4,pow(3,2)))); + + // The rest is output formatting. + let first_twenty: String = answer_as_string.chars().take(20).collect(); + let last_twenty_reversed: Vec = answer_as_string.chars().rev().take(20).collect(); + let last_twenty: String = last_twenty_reversed.into_iter().rev().collect(); + println!("Number of digits: {}", answer_as_string.len()); + println!("First and last digits: {:?}..{:?}", first_twenty, last_twenty); } diff --git a/Task/Arena-storage-pool/Julia/arena-storage-pool.julia b/Task/Arena-storage-pool/Julia/arena-storage-pool.julia new file mode 100644 index 0000000000..4296b88a9b --- /dev/null +++ b/Task/Arena-storage-pool/Julia/arena-storage-pool.julia @@ -0,0 +1,3 @@ +matrix = zeros(Float64, (1000,1000,1000)) +# use matrix, then when done set variable to 0 to garbage collect the matrix: +matrix = 0 # large memory pool will now be collected when needed diff --git a/Task/Arena-storage-pool/Kotlin/arena-storage-pool.kotlin b/Task/Arena-storage-pool/Kotlin/arena-storage-pool.kotlin index d6431b8789..92919a1548 100644 --- a/Task/Arena-storage-pool/Kotlin/arena-storage-pool.kotlin +++ b/Task/Arena-storage-pool/Kotlin/arena-storage-pool.kotlin @@ -1,4 +1,4 @@ -// Kotlin Native v0.3 +// Kotlin Native v0.5 import kotlinx.cinterop.* diff --git a/Task/Arithmetic-Complex/Oforth/arithmetic-complex-1.oforth b/Task/Arithmetic-Complex/Oforth/arithmetic-complex-1.oforth index d487d670d5..cdf8fde6b9 100644 --- a/Task/Arithmetic-Complex/Oforth/arithmetic-complex-1.oforth +++ b/Task/Arithmetic-Complex/Oforth/arithmetic-complex-1.oforth @@ -1,4 +1,4 @@ -Number 100 Class newPriority: Complex(re, im) +Object Class new: Complex(re, im) Complex method: re @re ; Complex method: im @im ; @@ -6,21 +6,34 @@ Complex method: im @im ; Complex method: initialize := im := re ; Complex method: << '(' <n - Complex new(@re n /, @im neg n / ) ; + @re sq @im sq + >float ->n + @re n / @im neg n / Complex new +; -Complex method: /(c) c self inv * ; +Complex method: /( c -- d ) + c self inv * ; + +Integer method: >complex self 0 Complex new ; +Float method: >complex self 0 Complex new ; diff --git a/Task/Arithmetic-Complex/Oforth/arithmetic-complex-2.oforth b/Task/Arithmetic-Complex/Oforth/arithmetic-complex-2.oforth index 140589409e..1bb3be3cd8 100644 --- a/Task/Arithmetic-Complex/Oforth/arithmetic-complex-2.oforth +++ b/Task/Arithmetic-Complex/Oforth/arithmetic-complex-2.oforth @@ -1,4 +1,4 @@ -2 3.2 I * + .cr -Complex new(2, 3) 1.2 + .cr -Complex new(2, 3) 1.2 * .cr -2 Complex new(2, 3) / .cr +3.2 >complex I * 2 >complex + .cr +2 3 Complex new 1.2 >complex + .cr +2 3 Complex new 1.2 >complex * .cr +2 >complex 2 3 Complex new / .cr diff --git a/Task/Arithmetic-Integer/APL/arithmetic-integer.apl b/Task/Arithmetic-Integer/APL/arithmetic-integer.apl new file mode 100644 index 0000000000..21a491ff5b --- /dev/null +++ b/Task/Arithmetic-Integer/APL/arithmetic-integer.apl @@ -0,0 +1,4 @@ +∇res ← integer_arithmetic; l; r + l ← ⎕ + r ← ⎕ + res ← 6 2 ⍴ 'sum' (l+r) 'diff' (l-r) 'prod' (l×r) 'quot' (⌊l÷r) 'rem' (r|l) 'pow' (l*r) diff --git a/Task/Arithmetic-Integer/ARM-Assembly/arithmetic-integer.arm b/Task/Arithmetic-Integer/ARM-Assembly/arithmetic-integer.arm new file mode 100644 index 0000000000..3474c3f80e --- /dev/null +++ b/Task/Arithmetic-Integer/ARM-Assembly/arithmetic-integer.arm @@ -0,0 +1,287 @@ +/* ARM assembly Raspberry PI */ +/* program arith.s */ +/* Constantes */ +.equ STDOUT, 1 +.equ WRITE, 4 +.equ EXIT, 1 + +/***********************/ +/* Initialized data */ +/***********************/ +.data +szMessError: .asciz " Two numbers in command line please ! \n" @ message +szRetourLigne: .asciz "\n" +szMessResult: .asciz "Resultat " @ message result +sMessValeur: .fill 12, 1, ' ' + .asciz "\n" +szMessAddition: .asciz "addition :" +szMessSoustraction: .asciz "soustraction :" +szMessMultiplication: .asciz "multiplication :" +szMessDivision: .asciz "division :" +szMessReste: .asciz "reste :" + +/***********************/ +/* No Initialized data */ +/***********************/ +.bss +iValeur: .skip 4 @ reserve 4 bytes in memory + +.text +.global main +main: + push {fp,lr} /* save des 2 registres */ + add fp,sp,#8 /* fp <- adresse début */ + ldr r0,[fp] @ recup number of parameter in command line + cmp r0,#3 + blt error + ldr r0,[fp,#8] @ adresse of 1er number + bl conversionAtoD + mov r3,r0 + ldr r0,[fp,#12] @ adresse of 2eme number + bl conversionAtoD + mov r4,r0 + @ addition + add r0,r3,r4 + ldr r1,iAdrsMessValeur @ result in r0 + bl conversion10S @ call function with 2 parameter (r0,r1) + ldr r0,iAdrszMessResult + bl affichageMess @ display message + ldr r0,iAdrszMessAddition + bl affichageMess @ display message + ldr r0,iAdrsMessValeur + bl affichageMess @ display message + @ soustraction + sub r0,r3,r4 + ldr r1,=sMessValeur + bl conversion10S @ call function with 2 parameter (r0,r1) + ldr r0,iAdrszMessResult + bl affichageMess @ display message + ldr r0,iAdrszMessSoustraction + bl affichageMess @ display message + ldr r0,iAdrsMessValeur + bl affichageMess @ display message + + @ multiplication + mul r0,r3,r4 + ldr r1,=sMessValeur + bl conversion10S @ call function with 2 parameter (r0,r1) + ldr r0,iAdrszMessResult + bl affichageMess @ display message + ldr r0,iAdrszMessMultiplication + bl affichageMess @ display message + ldr r0,iAdrsMessValeur + bl affichageMess @ display message + + @ division + mov r0,r3 + mov r1,r4 + bl division + mov r0,r2 @ quotient + ldr r1,=sMessValeur + bl conversion10S @ call function with 2 parameter (r0,r1) + ldr r0,iAdrszMessResult + bl affichageMess @ display message + ldr r0,iAdrszMessDivision + bl affichageMess @ display message + ldr r0,iAdrsMessValeur + bl affichageMess @ display message + + mov r0,r3 @ remainder + ldr r1,=sMessValeur + bl conversion10S @ call function with 2 parameter (r0,r1) + ldr r0,iAdrszMessResult + bl affichageMess @ display message + ldr r0,iAdrszMessReste + bl affichageMess @ display message + ldr r0,iAdrsMessValeur + bl affichageMess @ display message + + mov r0, #0 @ return code + b 100f +error: + ldr r0,iAdrszMessError + bl affichageMess @ call function with 1 parameter (r0) + mov r0, #1 @ return code +100: /* end of program */ + mov r7, #EXIT @ request to exit program + swi 0 @ perform the system call +iAdrsMessValeur: .int sMessValeur +iAdrszMessResult: .int szMessResult +iAdrszMessError: .int szMessError +iAdrszMessAddition: .int szMessAddition +iAdrszMessSoustraction: .int szMessSoustraction +iAdrszMessMultiplication: .int szMessMultiplication +iAdrszMessDivision: .int szMessDivision +iAdrszMessReste: .int szMessReste +/******************************************************************/ +/* affichage des messages avec calcul longueur */ +/******************************************************************/ +/* r0 contient l adresse du message */ +affichageMess: + push {fp,lr} /* save des 2 registres */ + push {r0,r1,r2,r7} /* save des autres registres */ + mov r2,#0 /* compteur longueur */ +1: /*calcul de la longueur */ + ldrb r1,[r0,r2] /* recup octet position debut + indice */ + cmp r1,#0 /* si 0 c est fini */ + beq 1f + add r2,r2,#1 /* sinon on ajoute 1 */ + b 1b +1: /* donc ici r2 contient la longueur du message */ + mov r1,r0 /* adresse du message en r1 */ + mov r0,#STDOUT /* code pour écrire sur la sortie standard Linux */ + mov r7, #WRITE /* code de l appel systeme 'write' */ + swi #0 /* appel systeme */ + pop {r0,r1,r2,r7} /* restaur des autres registres */ + pop {fp,lr} /* restaur des 2 registres */ + bx lr /* retour procedure */ +/***************************************************/ +/* conversion registre en décimal signé */ +/***************************************************/ +/* r0 contient le registre */ +/* r1 contient l adresse de la zone de conversion */ +conversion10S: + push {fp,lr} /* save des 2 registres frame et retour */ + push {r0-r5} /* save autres registres */ + mov r2,r1 /* debut zone stockage */ + mov r5,#'+' /* par defaut le signe est + */ + cmp r0,#0 /* nombre négatif ? */ + movlt r5,#'-' /* oui le signe est - */ + mvnlt r0,r0 /* et inversion en valeur positive */ + addlt r0,#1 + mov r4,#10 /* longueur de la zone */ +1: /* debut de boucle de conversion */ + bl divisionpar10 /* division */ + add r1,#48 /* ajout de 48 au reste pour conversion ascii */ + strb r1,[r2,r4] /* stockage du byte en début de zone r5 + la position r4 */ + sub r4,r4,#1 /* position précedente */ + cmp r0,#0 + bne 1b /* boucle si quotient different de zéro */ + strb r5,[r2,r4] /* stockage du signe à la position courante */ + subs r4,r4,#1 /* position précedente */ + blt 100f /* si r4 < 0 fin */ + /* sinon il faut completer le debut de la zone avec des blancs */ + mov r3,#' ' /* caractere espace */ +2: + strb r3,[r2,r4] /* stockage du byte */ + subs r4,r4,#1 /* position précedente */ + bge 2b /* boucle si r4 plus grand ou egal a zero */ +100: /* fin standard de la fonction */ + pop {r0-r5} /*restaur des autres registres */ + pop {fp,lr} /* restaur des 2 registres frame et retour */ + bx lr + +/***************************************************/ +/* division par 10 signé */ +/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/* +/* and http://www.hackersdelight.org/ */ +/***************************************************/ +/* r0 contient le dividende */ +/* r0 retourne le quotient */ +/* r1 retourne le reste */ +divisionpar10: + /* r0 contains the argument to be divided by 10 */ + push {r2-r4} /* save autres registres */ + mov r4,r0 + ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */ + smull r1, r2, r3, r0 /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */ + mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */ + mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */ + add r0, r2, r1 /* r0 <- r2 + r1 */ + add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */ + sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */ + pop {r2-r4} + bx lr /* leave function */ + .align 4 +.Ls_magic_number_10: .word 0x66666667 +/******************************************************************/ +/* Conversion d une chaine en nombre stocké dans un registre */ +/******************************************************************/ +/* r0 contient l adresse de la zone terminée par 0 ou 0A */ +conversionAtoD: + push {fp,lr} /* save des 2 registres */ + push {r1-r7} /* save des autres registres */ + mov r1,#0 + 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 */ + beq 100f + 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 */ + blt 3f + cmp r5,#'9' /* caractere n est pas un chiffre */ + bgt 3f + /* caractère est un chiffre */ + sub r5,#48 + 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 */ +3: + 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 */ + beq 4f + b 2b /* boucler */ +4: + 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 */ + b 100f +99: /* erreur de dépassement */ + ldr r1,=szMessErrDep + bl afficheerreur + 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 */ + bx lr /* retour procedure */ +/* constante programme */ +iMaxi: .int 1073741824 +szMessErrDep: .asciz "Nombre trop grand : dépassement de capacite de 32 bits. :\n" +.align 4 +/*=============================================*/ +/* division entiere non signée */ +/*============================================*/ +division: + /* r0 contains N */ + /* r1 contains D */ + /* r2 contains Q */ + /* r3 contains R */ + push {r4, lr} + 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) */ + adc r3, r3, r3 /* r3 ? r3 + r3 + C. This is equivalent to r3 ? (r3 << 1) + C */ + + cmp r3, r1 /* compute r3 - r1 and update cpsr */ + subhs r3, r3, r1 /* if r3 >= r1 (C=1) then r3 ? r3 - r1 */ + 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 */ + + pop {r4, lr} + bx lr diff --git a/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena b/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena index c0f0fa3bb4..fe084f7417 100644 --- a/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena +++ b/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena @@ -1,7 +1,7 @@ import system'math. import extensions. -program = +public program = [ var a := console readLineTo(Integer new). var b := console readLineTo(Integer new). diff --git a/Task/Arithmetic-Integer/HolyC/arithmetic-integer.holyc b/Task/Arithmetic-Integer/HolyC/arithmetic-integer.holyc new file mode 100644 index 0000000000..6d99eae7bf --- /dev/null +++ b/Task/Arithmetic-Integer/HolyC/arithmetic-integer.holyc @@ -0,0 +1,14 @@ +I64 *a, *b; +a = Str2I64(GetStr("Enter your first number: ")); +b = Str2I64(GetStr("Enter your second number: ")); + +if (b == 0) + Print("Error: The second number must not be zero.\n"); +else { + Print("a + b = %d\n", a + b); + Print("a - b = %d\n", a - b); + Print("a * b = %d\n", a * b); + Print("a / b = %d\n", a / b); /* rounds down */ + Print("a % b = %d\n", a % b); /* same sign as first operand */ + Print("a ` b = %d\n", a ` b); +} diff --git a/Task/Arithmetic-Integer/Java/arithmetic-integer.java b/Task/Arithmetic-Integer/Java/arithmetic-integer.java index 9ecb561113..8ac4ea5657 100644 --- a/Task/Arithmetic-Integer/Java/arithmetic-integer.java +++ b/Task/Arithmetic-Integer/Java/arithmetic-integer.java @@ -2,15 +2,21 @@ import java.util.Scanner; public class IntegerArithmetic { public static void main(String[] args) { + // Get the 2 numbers from command line arguments Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); - int sum = a + b; // integer addition is discouraged in print statements due to confusion with string concatenation + int sum = a + b; // The result of adding 'a' and 'b' (Note: integer addition is discouraged in print statements due to confusion with string concatenation) + int difference = a - b; // The result of subtracting 'b' from 'a' + int product = a * b; // The result of multiplying 'a' and 'b' + int division = a / b; // The result of dividing 'a' by 'b' (Note: 'division' does not contain the fractional result) + int remainder = a % b; // The remainder of dividing 'a' by 'b' + System.out.println("a + b = " + sum); - System.out.println("a - b = " + (a - b)); - System.out.println("a * b = " + (a * b)); - System.out.println("quotient of a / b = " + (a / b)); // truncates towards 0 - System.out.println("remainder of a / b = " + (a % b)); // same sign as first operand + System.out.println("a - b = " + difference); + System.out.println("a * b = " + product); + System.out.println("quotient of a / b = " + division); // truncates towards 0 + System.out.println("remainder of a / b = " + remainder); // same sign as first operand } } diff --git a/Task/Arithmetic-Integer/JavaScript/arithmetic-integer.js b/Task/Arithmetic-Integer/JavaScript/arithmetic-integer-1.js similarity index 100% rename from Task/Arithmetic-Integer/JavaScript/arithmetic-integer.js rename to Task/Arithmetic-Integer/JavaScript/arithmetic-integer-1.js diff --git a/Task/Arithmetic-Integer/JavaScript/arithmetic-integer-2.js b/Task/Arithmetic-Integer/JavaScript/arithmetic-integer-2.js new file mode 100644 index 0000000000..d1273f2beb --- /dev/null +++ b/Task/Arithmetic-Integer/JavaScript/arithmetic-integer-2.js @@ -0,0 +1,15 @@ +// Invoked as node script_name.js . Positions 0 and 1 in the argv array contain 'node' and 'script_name.js' respectively +var a = parseInt(process.argv[2], 10); +var b = parseInt(process.argv[3], 10); + +var sum = a + b; +var difference = a - b; +var product = a * b; +var division = a / b; +var remainder = a % b; // This produces the remainder after dividing 'b' into 'a'. The '%' operator is called the 'modulo' operator + +console.log('a + b = %d', sum); // The %d syntax is a placeholder that is replaced by the sum +console.log('a - b = %d', difference); +console.log('a * b = %d', product); +console.log('a / b = %d', division); +console.log('a % b = %d', remainder); diff --git a/Task/Arithmetic-Integer/Lingo/arithmetic-integer.lingo b/Task/Arithmetic-Integer/Lingo/arithmetic-integer.lingo new file mode 100644 index 0000000000..49da68d6c9 --- /dev/null +++ b/Task/Arithmetic-Integer/Lingo/arithmetic-integer.lingo @@ -0,0 +1,10 @@ +-- X, Y: 2 editable field members, shown as sprites in the current GUI +x = integer(member("X").text) +y = integer(member("Y").text) + +put "Sum: " , x + y +put "Difference: ", x - y +put "Product: " , x * y +put "Quotient: " , x / y -- Truncated towards zero +put "Remainder: " , x mod y -- Result has sign of left operand +put "Exponent: " , power(x, y) diff --git a/Task/Arithmetic-Integer/Oforth/arithmetic-integer.oforth b/Task/Arithmetic-Integer/Oforth/arithmetic-integer.oforth index 5323fe88cc..93bf5f44c6 100644 --- a/Task/Arithmetic-Integer/Oforth/arithmetic-integer.oforth +++ b/Task/Arithmetic-Integer/Oforth/arithmetic-integer.oforth @@ -1,7 +1,8 @@ -: integers(a, b) +: integers (a b -- ) "a + b =" . a b + .cr "a - b =" . a b - .cr "a * b =" . a b * .cr "a / b =" . a b / .cr "a mod b =" . a b mod .cr - "a pow b =" . a b pow .cr ; + "a pow b =" . a b pow .cr +; diff --git a/Task/Arithmetic-Rational/Factor/arithmetic-rational.factor b/Task/Arithmetic-Rational/Factor/arithmetic-rational.factor new file mode 100644 index 0000000000..76cdc7e5f5 --- /dev/null +++ b/Task/Arithmetic-Rational/Factor/arithmetic-rational.factor @@ -0,0 +1,21 @@ +USING: generalizations io kernel math math.functions +math.primes.factors math.ranges prettyprint sequences ; +IN: rosetta-code.arithmetic-rational + +2/5 ! literal syntax 2/5 +2/4 ! automatically simplifies to 1/2 +5/1 ! automatically coerced to 5 +26/5 ! mixed fraction 5+1/5 +13/178 >fraction ! get the numerator and denominator 13 178 +8 recip ! get the reciprocal 1/8 + +! ratios can be any size +12417829731289312/61237812937138912735712 +8 ndrop ! clear the stack +! arithmetic works the same as any other number. + +: perfect? ( n -- ? ) + divisors rest [ recip ] map-sum 1 = ; + +"Perfect numbers <= 2^19: " print +2 19 ^ [1,b] [ perfect? ] filter . diff --git a/Task/Arithmetic-Rational/Groovy/arithmetic-rational-1.groovy b/Task/Arithmetic-Rational/Groovy/arithmetic-rational-1.groovy index 92147c18af..5bc4fc6354 100644 --- a/Task/Arithmetic-Rational/Groovy/arithmetic-rational-1.groovy +++ b/Task/Arithmetic-Rational/Groovy/arithmetic-rational-1.groovy @@ -1,4 +1,4 @@ -class Rational implements Comparable { +class Rational extends Number implements Comparable { final BigInteger num, denom static final Rational ONE = new Rational(1) @@ -6,8 +6,9 @@ class Rational implements Comparable { Rational(BigDecimal decimal) { this( - decimal.scale() < 0 ? decimal.unscaledValue()*10**(-decimal.scale()) : decimal.unscaledValue(), - decimal.scale() < 0 ? 1 : 10**(decimal.scale())) + decimal.scale() < 0 ? decimal.unscaledValue() * 10 ** -decimal.scale() : decimal.unscaledValue(), + decimal.scale() < 0 ? 1 : 10 ** decimal.scale() + ) } Rational(BigInteger n, BigInteger d = 1) { @@ -16,14 +17,14 @@ class Rational implements Comparable { } private List reduce(BigInteger n, BigInteger d) { - BigInteger sign = ((n < 0) != (d < 0)) ? -1 : 1 + BigInteger sign = ((n < 0) ^ (d < 0)) ? -1 : 1 (n, d) = [n.abs(), d.abs()] BigInteger commonFactor = gcd(n, d) [n.intdiv(commonFactor) * sign, d.intdiv(commonFactor)] } - public Rational toLeastTerms() { reduce(num, denom) as Rational } + Rational toLeastTerms() { reduce(num, denom) as Rational } private BigInteger gcd(BigInteger n, BigInteger m) { n == 0 ? m : { while(m%n != 0) { (n, m) = [m%n, n] }; n }() @@ -83,15 +84,15 @@ class Rational implements Comparable { Object asType(Class type) { switch (type) { - case this.getClass(): return this - case [Boolean.class,Boolean.TYPE]: return asBoolean() - case BigDecimal.class: return toBigDecimal() - case BigInteger.class: return toBigInteger() - case [Double.class,Double.TYPE]: return toDouble() - case [Float.class,Float.TYPE]: return toFloat() - case [Integer.class,Integer.TYPE]: return toInteger() - case [Long.class,Long.TYPE]: return toLong() - case String.class: return toString() + case this.class: return this + case [Boolean, Boolean.TYPE]: return asBoolean() + case BigDecimal: return toBigDecimal() + case BigInteger: return toBigInteger() + case [Double, Double.TYPE]: return toDouble() + case [Float, Float.TYPE]: return toFloat() + case [Integer, Integer.TYPE]: return toInteger() + case [Long, Long.TYPE]: return toLong() + case String: return toString() default: throw new ClassCastException("Cannot convert from type Rational to type " + type) } } @@ -99,10 +100,10 @@ class Rational implements Comparable { boolean equals(o) { compareTo(o) == 0 } int compareTo(o) { - o instanceof Rational \ - ? compareTo(o as Rational) \ - : o instanceof Number \ - ? compareTo(o as Number)\ + o instanceof Rational + ? compareTo(o as Rational) + : o instanceof Number + ? compareTo(o as Number) : (Double.NaN as int) } int compareTo(Rational r) { num*r.denom <=> denom*r.num } diff --git a/Task/Arithmetic-Rational/Sidef/arithmetic-rational.sidef b/Task/Arithmetic-Rational/Sidef/arithmetic-rational.sidef new file mode 100644 index 0000000000..344788613e --- /dev/null +++ b/Task/Arithmetic-Rational/Sidef/arithmetic-rational.sidef @@ -0,0 +1,13 @@ +for n in (1 .. 2**19) { + var frac = 0 + + n.divisors.each {|d| + frac += 1/d + } + + if (frac.is_int) { + say "Sum of reciprocal divisors of #{n} = #{frac} exactly #{ + frac == 2 ? '- perfect!' : '' + }" + } +} diff --git a/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation.elena b/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation.elena index 0d8390e410..31bb6b4cbe 100644 --- a/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation.elena +++ b/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation.elena @@ -4,11 +4,11 @@ import extensions'text. class Token { - object theValue. + object theValue. - object rprop level :: theLevel. + int rprop level :: theLevel. - constructor new level:aLevel + constructor new(int aLevel) [ theValue := StringWriter new. theLevel := aLevel + 9. @@ -19,16 +19,16 @@ class Token theValue << aChar. ] - number = theValue get; toReal. + number = theValue toReal. } class Node { object prop left :: theLeft. object prop right :: theRight. - object rprop level :: theLevel. + int rprop level :: theLevel. - constructor new level:aLevel + constructor new(int aLevel) [ theLevel := aLevel. ] @@ -36,42 +36,42 @@ class Node class SummaryNode :: Node { - constructor new level:aLevel - <= new level(aLevel + 1). + constructor new(int aLevel) + <= new(aLevel + 1). number = theLeft number + theRight number. } class DifferenceNode :: Node { - constructor new level:aLevel - <= new level(aLevel + 1). + constructor new(int aLevel) + <= new(aLevel + 1). number = theLeft number - theRight number. } class ProductNode :: Node { - constructor new level:aLevel - <= new level(aLevel + 2). + constructor new(int aLevel) + <= new(aLevel + 2). number = theLeft number * theRight number. } class FractionNode :: Node { - constructor new level:aLevel - <= new level(aLevel + 2). + constructor new(int aLevel) + <= new(aLevel + 2). number = theLeft number / theRight number. } class Expression { - object rprop level :: theLevel. + int rprop level :: theLevel. object prop top :: theTop. - constructor new level:aLevel + constructor new(int aLevel) [ theLevel := aLevel ] @@ -83,101 +83,101 @@ class Expression number => theTop. } -operatorState = (:ch) +operatorState : ch [ ch => $40 [ // ( - ^ closure newBracket; gotoStarting + ^ target newBracket; gotoStarting ]; ! [ - ^ closure newToken; append:ch; gotoToken + ^ target newToken; append:ch; gotoToken ]. -]. +] -tokenState = (:ch) +tokenState : ch [ ch => $41 [ // ) - ^ closure closeBracket; gotoToken + ^ target closeBracket; gotoToken ]; $42 [ // * - ^ closure newProduct; gotoOperator + ^ target newProduct; gotoOperator ]; $43 [ // + - ^ closure newSummary; gotoOperator + ^ target newSummary; gotoOperator ]; $45 [ // - - ^ closure newDifference; gotoOperator + ^ target newDifference; gotoOperator ]; $47 [ // / - ^ closure newFraction; gotoOperator + ^ target newFraction; gotoOperator ]; ! [ - ^ closure append:ch + ^ target append:ch ]. -]. +] -startState = (:ch) +startState : ch [ ch => $40 [ // ( - ^ closure newBracket; gotoStarting + ^ target newBracket; gotoStarting ]; $45 [ // - - ^ closure newToken; append literal:"0"; newDifference; gotoOperator + ^ target newToken; append:"0"; newDifference; gotoOperator ]; ! [ - ^ closure newToken; append:ch; gotoToken + ^ target newToken; append:ch; gotoToken ]. -]. +] class Scope { object theState. - object theLevel. + int theLevel. object theParser. object theToken. object theExpression. - constructor new parser:aParser + constructor new:aParser [ theState := startState. theLevel := 0. - theExpression := Expression new level:0. + theExpression := Expression new(0). theParser := aParser. ] newToken [ - theToken := theParser appendToken expression:theExpression level:theLevel. + theToken := theParser appendToken(theExpression, theLevel). ] newSummary [ theToken := nil. - theParser appendSummary expression:theExpression level:theLevel. + theParser appendSummary(theExpression, theLevel). ] newDifference [ theToken := nil. - theParser appendDifference expression:theExpression level:theLevel + theParser appendDifference(theExpression, theLevel) ] newProduct [ theToken := nil. - theParser appendProduct expression:theExpression level:theLevel + theParser appendProduct(theExpression, theLevel) ] newFraction [ theToken := nil. - theParser appendFraction expression:theExpression level:theLevel + theParser appendFraction(theExpression, theLevel) ] newBracket @@ -186,7 +186,7 @@ class Scope theLevel := theLevel + 10. - theParser appendSubexpression expression:theExpression level:theLevel. + theParser appendSubexpression(theExpression, theLevel). ] closeBracket @@ -204,7 +204,7 @@ class Scope [ InvalidArgumentException new:"Invalid expression"; raise ] ] - append literal:aLiteral + append(literal aLiteral) [ aLiteral forEach(:ch)[ self append:ch ] ] @@ -231,63 +231,63 @@ class Scope class Parser { - appendToken expression:anExpression level:aLevel + appendToken(object anExpression, int aLevel) [ - var aToken := Token new level:aLevel. + var aToken := Token new(aLevel). - anExpression set top:($self append last(anExpression top) new:aToken). + anExpression top := self append(anExpression top, aToken). ^ aToken ] - appendSummary expression:anExpression level:aLevel + appendSummary(object anExpression, int aLevel) [ - anExpression set top($self append last(anExpression top) new(SummaryNode new level:aLevel)). + anExpression top := self append(anExpression top, SummaryNode new(aLevel)). ] - appendDifference expression:anExpression level:aLevel + appendDifference(object anExpression, int aLevel) [ - anExpression set top($self append last(anExpression top) new(DifferenceNode new level:aLevel)). + anExpression top := self append(anExpression top, DifferenceNode new(aLevel)). ] - appendProduct expression:anExpression level:aLevel + appendProduct(object anExpression, int aLevel) [ - anExpression set top($self append last(anExpression top) new(ProductNode new level:aLevel)). + anExpression top := self append(anExpression top, ProductNode new(aLevel)). ] - appendFraction expression:anExpression level:aLevel + appendFraction(object anExpression, int aLevel) [ - anExpression set top($self append last(anExpression top) new(FractionNode new level:aLevel)) + anExpression top := self append(anExpression top, FractionNode new(aLevel)) ] - appendSubexpression expression:anExpression level:aLevel + appendSubexpression(object anExpression, int aLevel) [ - anExpression set top($self append last(anExpression top) new(Expression new level:aLevel)). + anExpression top := self append(anExpression top, Expression new(aLevel)). ] - append last:aLastNode new:aNewNode + append(object aLastNode, object aNewNode) [ - if($nil == aLastNode) + if(nil == aLastNode) [ ^ aNewNode ]. if (aNewNode level <= aLastNode level) - [ aNewNode set left:aLastNode. ^ aNewNode ]. + [ aNewNode left := aLastNode. ^ aNewNode ]. var aParent := aLastNode. var aCurrent := aLastNode right. - while (($nil != aCurrent) && $(aNewNode level > aCurrent level)) + while ((nil != aCurrent) && (aNewNode level > aCurrent level)) [ aParent := aCurrent. aCurrent := aCurrent right. ]. - if ($nil == aCurrent) - [ aParent set right:aNewNode. ]; - [ aNewNode set left:aCurrent. aParent set right:aNewNode ]. + if (nil == aCurrent) + [ aParent right := aNewNode. ]; + [ aNewNode left := aCurrent. aParent right := aNewNode ]. ^ aLastNode ] run : aText [ - var aScope := Scope new parser:$self. + var aScope := Scope new(self). aText forEach(:ch)[ aScope eval:ch ]. @@ -295,9 +295,9 @@ class Parser ] } -program = +public program = [ - var aText := String new. + var aText := StringWriter new. var aParser := Parser new. $(console readLine; saveTo:aText; length > 0) doWhile: diff --git a/Task/Arithmetic-evaluation/Kotlin/arithmetic-evaluation.kotlin b/Task/Arithmetic-evaluation/Kotlin/arithmetic-evaluation.kotlin new file mode 100644 index 0000000000..46a181415a --- /dev/null +++ b/Task/Arithmetic-evaluation/Kotlin/arithmetic-evaluation.kotlin @@ -0,0 +1,86 @@ +// version 1.2.10 + +/* if string is empty, returns zero */ +fun String.toDoubleOrZero() = this.toDoubleOrNull() ?: 0.0 + +fun multiply(s: String): String { + val b = s.split('*').map { it.toDoubleOrZero() } + return (b[0] * b[1]).toString() +} + +fun divide(s: String): String { + val b = s.split('/').map { it.toDoubleOrZero() } + return (b[0] / b[1]).toString() +} + +fun add(s: String): String { + var t = s.replace(Regex("""^\+"""), "").replace(Regex("""\++"""), "+") + val b = t.split('+').map { it.toDoubleOrZero() } + return (b[0] + b[1]).toString() +} + +fun subtract(s: String): String { + var t = s.replace(Regex("""(\+-|-\+)"""), "-") + if ("--" in t) return add(t.replace("--", "+")) + val b = t.split('-').map { it.toDoubleOrZero() } + return (if (b.size == 3) -b[1] - b[2] else b[0] - b[1]).toString() +} + +fun evalExp(s: String): String { + var t = s.replace(Regex("""[()]"""), "") + val reMD = Regex("""\d+\.?\d*\s*[*/]\s*[+-]?\d+\.?\d*""") + val reM = Regex( """\*""") + val reAS = Regex("""-?\d+\.?\d*\s*[+-]\s*[+-]?\d+\.?\d*""") + val reA = Regex("""\d\+""") + + while (true) { + val match = reMD.find(t) + if (match == null) break + val exp = match.value + val match2 = reM.find(exp) + t = if (match2 != null) + t.replace(exp, multiply(exp)) + else + t.replace(exp, divide(exp)) + } + + while (true) { + val match = reAS.find(t) + if (match == null) break + val exp = match.value + val match2 = reA.find(exp) + t = if (match2 != null) + t.replace(exp, add(exp)) + else + t.replace(exp, subtract(exp)) + } + + return t +} + +fun evalArithmeticExp(s: String): Double { + var t = s.replace(Regex("""\s"""), "").replace("""^\+""", "") + val rePara = Regex("""\([^()]*\)""") + while(true) { + val match = rePara.find(t) + if (match == null) break + val exp = match.value + t = t.replace(exp, evalExp(exp)) + } + return evalExp(t).toDoubleOrZero() +} + +fun main(arsg: Array) { + listOf( + "2+3", + "2+3/4", + "2*3-4", + "2*(3+4)+5/6", + "2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10", + "2*-3--4+-0.25", + "-4 - 3", + "((((2))))+ 3 * 5", + "1 + 2 * (3 + (4 * 5 + 6 * 7 * 8) - 9) / 10", + "1 + 2*(3 - 2*(3 - 2)*((2 - 4)*5 - 22/(7 + 2*(3 - 1)) - 1)) + 1" + ).forEach { println("$it = ${evalArithmeticExp(it)}") } +} diff --git a/Task/Arithmetic-evaluation/Perl-6/arithmetic-evaluation.pl6 b/Task/Arithmetic-evaluation/Perl-6/arithmetic-evaluation.pl6 new file mode 100644 index 0000000000..535dd75aba --- /dev/null +++ b/Task/Arithmetic-evaluation/Perl-6/arithmetic-evaluation.pl6 @@ -0,0 +1,44 @@ +sub ev (Str $s --> Numeric) { + + grammar expr { + token TOP { ^ $ } + token sum { (('+' || '-') )* } + token product { (('*' || '/') )* } + token factor { ? [ || ] } + token unary_minus { '-' } + token parens { '(' ')' } + token literal { \d+ ['.' \d+]? || '.' \d+ } + } + + my sub minus ($b) { $b ?? -1 !! +1 } + + my sub sum ($x) { + [+] flat product($x), map + { minus($^y[0] eq '-') * product $^y }, + |($x[0] or []) + } + + my sub product ($x) { + [*] flat factor($x), map + { factor($^y) ** minus($^y[0] eq '/') }, + |($x[0] or []) + } + + my sub factor ($x) { + minus($x) * ($x + ?? sum $x + !! $x) + } + + expr.parse([~] split /\s+/, $s); + $/ or fail 'No parse.'; + sum $/; + +} + +# Testing: + +say ev '5'; # 5 +say ev '1 + 2 - 3 * 4 / 5'; # 0.6 +say ev '1 + 5*3.4 - .5 -4 / -2 * (3+4) -6'; # 25.5 +say ev '((11+15)*15)* 2 + (3) * -4 *1'; # 768 diff --git a/Task/Arithmetic-geometric-mean-Calculate-Pi/Java/arithmetic-geometric-mean-calculate-pi.java b/Task/Arithmetic-geometric-mean-Calculate-Pi/Java/arithmetic-geometric-mean-calculate-pi.java new file mode 100644 index 0000000000..c1a0c44ec0 --- /dev/null +++ b/Task/Arithmetic-geometric-mean-Calculate-Pi/Java/arithmetic-geometric-mean-calculate-pi.java @@ -0,0 +1,36 @@ +import java.math.BigDecimal; +import java.math.MathContext; +import java.util.Objects; + +public class Calculate_Pi { + private static final MathContext con1024 = new MathContext(1024); + private static final BigDecimal bigTwo = new BigDecimal(2); + private static final BigDecimal bigFour = new BigDecimal(4); + + private static BigDecimal bigSqrt(BigDecimal bd, MathContext con) { + BigDecimal x0 = BigDecimal.ZERO; + BigDecimal x1 = BigDecimal.valueOf(Math.sqrt(bd.doubleValue())); + while (!Objects.equals(x0, x1)) { + x0 = x1; + x1 = bd.divide(x0, con).add(x0).divide(bigTwo, con); + } + return x1; + } + + public static void main(String[] args) { + BigDecimal a = BigDecimal.ONE; + BigDecimal g = a.divide(bigSqrt(bigTwo, con1024), con1024); + BigDecimal t; + BigDecimal sum = BigDecimal.ZERO; + BigDecimal pow = bigTwo; + while (!Objects.equals(a, g)) { + t = a.add(g).divide(bigTwo, con1024); + g = bigSqrt(a.multiply(g), con1024); + a = t; + pow = pow.multiply(bigTwo); + sum = sum.add(a.multiply(a).subtract(g.multiply(g)).multiply(pow)); + } + BigDecimal pi = bigFour.multiply(a.multiply(a)).divide(BigDecimal.ONE.subtract(sum), con1024); + System.out.println(pi); + } +} diff --git a/Task/Arithmetic-geometric-mean-Calculate-Pi/Julia/arithmetic-geometric-mean-calculate-pi.julia b/Task/Arithmetic-geometric-mean-Calculate-Pi/Julia/arithmetic-geometric-mean-calculate-pi.julia index e346905f89..1f2ded74df 100644 --- a/Task/Arithmetic-geometric-mean-Calculate-Pi/Julia/arithmetic-geometric-mean-calculate-pi.julia +++ b/Task/Arithmetic-geometric-mean-Calculate-Pi/Julia/arithmetic-geometric-mean-calculate-pi.julia @@ -1,34 +1,24 @@ -function agm_step{T<:FloatingPoint}(x::T, y::T) - (0.5*(x + y), sqrt(x*y)) -end +agm1step{T<:AbstractFloat}(x::T, y::T) = (x + y) / 2, sqrt(x * y) -function approx_pi_step{T<:FloatingPoint,U<:Integer}(x::T, y::T, z::T, n::U) - (a, g) = agm_step(x, y) +function approxπstep{T<:AbstractFloat}(x::T, y::T, z::T, n::Integer) + a, g = agm1step(x, y) k = n + 1 - s = z + 2^(k+1)*(a^2 - g^2) - return (a, g, s, k) + s = z + 2 ^ (k + 1) * (a ^ 2 - g ^ 2) + return a, g, s, k end -function approx_pi{T<:FloatingPoint}(a::T, g::T, s::T) - 4a^2/(1 - s) -end +approxπ{T<:AbstractFloat}(a::T, g::T, s::T) = 4a ^ 2 / (1 - s) -prec = 512 -set_bigfloat_precision(prec) -println("Approximating pi using ", prec, "-bit floats.") +setprecision(512) +a, g, s, k = big(1.0), 1 / √big(2.0), big(0.0), 0 +oldπ = big(0.0) +println("Approximating π using ", precision(BigFloat), "-bit floats.") println(" k Error Result") -a = big(1.0) -g = a/sqrt(big(2.0)) -s = big(0.0) -k = 0 -oldagpi = big(0.0) for i in 1:100 - (a, g, s, k) = approx_pi_step(a, g, s, k) - agpi = approx_pi(a, g, s) - 2eps(agpi) < abs(agpi-oldagpi) || break - oldagpi = agpi - err = pi - agpi - print(@sprintf(" %2d ", i)) - print(@sprintf(" %9.1e", err)) - println(@sprintf(" %.60e", agpi)) + a, g, s, k = approxπstep(a, g, s, k) + estπ = approxπ(a, g, s) + if abs(estπ - oldπ) < 2eps(estπ) break end + oldπ = estπ + err = abs(π - estπ) + @printf("%4d%10.1e%68.60e\n", i, err, estπ) end diff --git a/Task/Arithmetic-geometric-mean-Calculate-Pi/Scala/arithmetic-geometric-mean-calculate-pi.scala b/Task/Arithmetic-geometric-mean-Calculate-Pi/Scala/arithmetic-geometric-mean-calculate-pi.scala new file mode 100644 index 0000000000..c62e83ba80 --- /dev/null +++ b/Task/Arithmetic-geometric-mean-Calculate-Pi/Scala/arithmetic-geometric-mean-calculate-pi.scala @@ -0,0 +1,36 @@ +import java.math.MathContext + +import scala.annotation.tailrec +import scala.compat.Platform.currentTime +import scala.math.BigDecimal + +object Calculate_Pi extends App { + val precision = new MathContext(32768 /*65536*/) + val (bigZero, bigOne, bigTwo, bigFour) = + (BigDecimal(0, precision), BigDecimal(1, precision), BigDecimal(2, precision), BigDecimal(4, precision)) + + def bigSqrt(bd: BigDecimal) = { + @tailrec + def iter(x0: BigDecimal, x1: BigDecimal): BigDecimal = + if (x0 == x1) x1 else iter(x1, (bd / x1 + x1) / bigTwo) + + iter(bigZero, BigDecimal(Math.sqrt(bd.toDouble), precision)) + } + + @tailrec + private def loop(a: BigDecimal, g: BigDecimal, sum: BigDecimal, pow: BigDecimal): BigDecimal = { + if (a == g) (bigFour * (a * a)) / (bigOne - sum) + else { + val (_a, _g, _pow) = ((a + g) / bigTwo, bigSqrt(a * g), pow * bigTwo) + loop(_a, _g, sum + ((_a * _a - (_g * _g)) * _pow), _pow) + } + } + + println(precision) + val pi = loop(bigOne, bigOne / bigSqrt(bigTwo), bigZero, bigTwo) + println(s"This are ${pi.toString.length - 1} digits of π:") + val lines = pi.toString().sliding(103, 103).mkString("\n") + println(lines) + + println(s"Successfully completed without errors. [total ${currentTime - executionStart} ms]") +} diff --git a/Task/Arithmetic-geometric-mean/8th/arithmetic-geometric-mean.8th b/Task/Arithmetic-geometric-mean/8th/arithmetic-geometric-mean.8th new file mode 100644 index 0000000000..ff2d657a5d --- /dev/null +++ b/Task/Arithmetic-geometric-mean/8th/arithmetic-geometric-mean.8th @@ -0,0 +1,14 @@ +: epsilon 1.0e-12 ; + +with: n + +: iter \ n1 n2 -- n1 n2 + 2dup * sqrt >r + 2 / r> ; + +: agn \ n1 n2 -- n + repeat iter 2dup epsilon ~= not while! drop ; + +"agn(1, 1/sqrt(2)) = " . 1 1 2 sqrt / agn "%.10f" s:strfmt . cr + +;with +bye diff --git a/Task/Arithmetic-geometric-mean/AppleScript/arithmetic-geometric-mean.applescript b/Task/Arithmetic-geometric-mean/AppleScript/arithmetic-geometric-mean.applescript index 6ce2c0d860..f7673df82c 100644 --- a/Task/Arithmetic-geometric-mean/AppleScript/arithmetic-geometric-mean.applescript +++ b/Task/Arithmetic-geometric-mean/AppleScript/arithmetic-geometric-mean.applescript @@ -1,46 +1,46 @@ +-- ARITHMETIC GEOMETRIC MEAN ------------------------------------------------- + property tolerance : 1.0E-5 -- agm :: Num a => a -> a -> a on agm(a, g) script withinTolerance - on lambda(m) + on |λ|(m) tell m to ((its an) - (its gn)) < tolerance - end lambda + end |λ| end script script nextRefinement - on lambda(m) + on |λ|(m) tell m set {an, gn} to {its an, its gn} {an:(an + gn) / 2, gn:(an * gn) ^ 0.5} end tell - end lambda + end |λ| end script an of |until|(withinTolerance, ¬ nextRefinement, {an:(a + g) / 2, gn:(a * g) ^ 0.5}) end agm - --- TEST +-- TEST ---------------------------------------------------------------------- on run agm(1, 1 / (2 ^ 0.5)) + --> 0.847213084835 + end run - - --- GENERIC FUNCTIONS +-- GENERIC FUNCTIONS --------------------------------------------------------- -- until :: (a -> Bool) -> (a -> a) -> a -> a on |until|(p, f, x) set mp to mReturn(p) set v to x - tell mReturn(f) - repeat until mp's lambda(v) - set v to lambda(v) + repeat until mp's |λ|(v) + set v to |λ|(v) end repeat end tell return v @@ -53,7 +53,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn diff --git a/Task/Arithmetic-geometric-mean/BASIC/arithmetic-geometric-mean.basic b/Task/Arithmetic-geometric-mean/BASIC/arithmetic-geometric-mean.basic new file mode 100644 index 0000000000..f23eb1b3bd --- /dev/null +++ b/Task/Arithmetic-geometric-mean/BASIC/arithmetic-geometric-mean.basic @@ -0,0 +1,10 @@ +10 A = 1 +20 G = 1/SQR(2) +30 GOSUB 100 +40 PRINT A +50 END +100 TA = A +110 A = (A+G)/2 +120 G = SQR(TA*G) +130 IF A +#include +#include + +double agm( double a, double g ) { + /* arithmetic-geometric mean */ + double iota = 1.0E-16; + double a1, g1; + + if( a*g < 0.0 ) { + printf( "arithmetic-geometric mean undefined when x*y<0\n" ); + exit(1); + } + + while( fabs(a-g)>iota ) { + a1 = (a + g) / 2.0; + g1 = sqrt(a * g); + + a = a1; + g = g1; + } + + return a; +} + +int main( void ) { + double x, y; + printf( "Enter two numbers: " ); + scanf( "%lf%lf", &x, &y ); + printf( "The arithmetic-geometric mean is %lf\n", agm(x, y) ); + return 0; +} diff --git a/Task/Arithmetic-geometric-mean/C/arithmetic-geometric-mean.c b/Task/Arithmetic-geometric-mean/C/arithmetic-geometric-mean-2.c similarity index 100% rename from Task/Arithmetic-geometric-mean/C/arithmetic-geometric-mean.c rename to Task/Arithmetic-geometric-mean/C/arithmetic-geometric-mean-2.c diff --git a/Task/Arithmetic-geometric-mean/Factor/arithmetic-geometric-mean.factor b/Task/Arithmetic-geometric-mean/Factor/arithmetic-geometric-mean.factor new file mode 100644 index 0000000000..5c3cfe827e --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Factor/arithmetic-geometric-mean.factor @@ -0,0 +1,6 @@ +USING: kernel math math.functions prettyprint ; +IN: rosetta-code.arithmetic-geometric-mean + +: agm ( a g -- a' g' ) 2dup [ + 0.5 * ] 2dip * sqrt ; + +1 1 2 sqrt / [ 2dup - 1e-15 > ] [ agm ] while drop . diff --git a/Task/Arithmetic-geometric-mean/Julia/arithmetic-geometric-mean.julia b/Task/Arithmetic-geometric-mean/Julia/arithmetic-geometric-mean.julia index c7b230d474..cd90bb50da 100644 --- a/Task/Arithmetic-geometric-mean/Julia/arithmetic-geometric-mean.julia +++ b/Task/Arithmetic-geometric-mean/Julia/arithmetic-geometric-mean.julia @@ -1,29 +1,21 @@ -function agm{T<:FloatingPoint,U<:Integer}(x::T, y::T, e::U=5) - 0 < y && 0 < y && 0 < e || throw(DomainError()) - err = e*eps(x) - (g, a) = extrema([x, y]) +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) + g, a = minmax(x, y) while err < (a - g) - ap = a - a = 0.5*(a + g) - g = sqrt(ap*g) + a, g = (a + g) / 2, sqrt(a * g) end return a end x = 1.0 -y = 1.0/sqrt(2.0) +y = 1 / √2 -println("Using literal-precision float numbers:") -println(" agm(", x, ",", y, ") = ", agm(x, y)) - -println() -println("Using half-precision float numbers:") -x = float16(x) -y = float16(y) -println(" agm(", x, ",", y, ") = ", agm(x, y)) - -println() -println("Using ", get_bigfloat_precision(), "-bit float numbers:") -x = BigFloat(1.0) -y = x/sqrt(BigFloat(2.0)) -println(" agm(", x, ",", y, ") = \n ", agm(x, y)) +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/Arithmetic-geometric-mean/Oforth/arithmetic-geometric-mean-1.oforth b/Task/Arithmetic-geometric-mean/Oforth/arithmetic-geometric-mean-1.oforth index cf897d86c9..42660de905 100644 --- a/Task/Arithmetic-geometric-mean/Oforth/arithmetic-geometric-mean-1.oforth +++ b/Task/Arithmetic-geometric-mean/Oforth/arithmetic-geometric-mean-1.oforth @@ -1 +1,2 @@ -: agm while(2dup <>) [ 2dup + 2 / tor * sqrt ] drop ; +: agm \ a b -- m + while( 2dup <> ) [ 2dup + 2 / -rot * sqrt ] drop ; diff --git a/Task/Arithmetic-geometric-mean/Prolog/arithmetic-geometric-mean.pro b/Task/Arithmetic-geometric-mean/Prolog/arithmetic-geometric-mean.pro new file mode 100644 index 0000000000..9b8064d1d2 --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Prolog/arithmetic-geometric-mean.pro @@ -0,0 +1,5 @@ +agm(A,G,A) :- abs(A-G) < 1.0e-15, !. +agm(A,G,Res) :- A1 is (A+G)/2.0, G1 is sqrt(A*G),!, agm(A1,G1,Res). + +?- agm(1,1/sqrt(2),Res). +Res = 0.8472130847939792. diff --git a/Task/Arithmetic-geometric-mean/REXX/arithmetic-geometric-mean.rexx b/Task/Arithmetic-geometric-mean/REXX/arithmetic-geometric-mean.rexx index 1c21ffd6c1..1ec07c0d76 100644 --- a/Task/Arithmetic-geometric-mean/REXX/arithmetic-geometric-mean.rexx +++ b/Task/Arithmetic-geometric-mean/REXX/arithmetic-geometric-mean.rexx @@ -3,26 +3,25 @@ parse arg a b digs . /*obtain optional numbers from if digs=='' | digs=="," then digs=110 /*No DIGS specified? Then use default.*/ numeric digits digs /*REXX will use lots of decimal digits.*/ if a=='' | a=="," then a=1 /*No A specified? Then use the default*/ -if b=='' | b=="," then b=1/sqrt(2) /* " B " " " " " */ +if b=='' | b=="," then b=1 / sqrt(2) /* " B " " " " " */ call AGM a,b /*invoke the AGM function. */ say '1st # =' a /*display the A value. */ say '2nd # =' b /* " " B " */ say ' AGM =' agm(a, b) /* " " AGM " */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -agm: procedure: parse arg x,y; if x=y then return x /*is this an equality case?*/ - if y=0 then return 0 /*is Y equal to zero ? */ - if x=0 then return y/2 /* " X " " " */ - d=digits(); numeric digits d+5 /*add 5 more digs to ensure convergence*/ - tiny='1e-' || ( digits() -1 ) /*construct a pretty tiny REXX number. */ - ox=x+1 +agm: procedure: parse arg x,y; if x=y then return x /*is this an equality case?*/ + if y=0 then return 0 /*is Y equal to zero ? */ + if x=0 then return y / 2 /* " X " " " */ + d=digits(); numeric digits d+5 /*add 5 more digs to ensure convergence*/ + tiny='1e-' || (digits() - 1) /*construct a pretty tiny REXX number. */ + ox=x + 1 do #=1 while ox\=x & abs(ox)>tiny; ox=x; oy=y x=(ox+oy)/2; y=sqrt(ox*oy) end /*#*/ - numeric digits d; return x/1 /*restore digs, normalize X to new digs*/ + numeric digits d; return x / 1 /*restore digs, normalize X to new digs*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); m.=9; numeric form; h=d+6 numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g *.5'e'_ % 2 - do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ - do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ - return g + 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/Array-concatenation/Aime/array-concatenation.aime b/Task/Array-concatenation/Aime/array-concatenation.aime index 06b83614d4..173a66b4ca 100644 --- a/Task/Array-concatenation/Aime/array-concatenation.aime +++ b/Task/Array-concatenation/Aime/array-concatenation.aime @@ -3,10 +3,10 @@ ac(list a, list b) { list o; - l_ucall(a, l_append, 1, o); - l_ucall(b, l_append, 1, o); + o.copy(a); + b.ucall(l_append, 1, o); - return o; + o; } integer @@ -14,12 +14,12 @@ main(void) { list a, b, c; - a = l_effect(1, 2, 3, 4); - b = l_effect(5, 6, 7, 8); + a = list(1, 2, 3, 4); + b = list(5, 6, 7, 8); c = ac(a, b); - l_ucall(c, o_, 1, " "); + c.ucall(o_, 1, " "); return 0; } diff --git a/Task/Array-concatenation/Common-Lisp/array-concatenation.lisp b/Task/Array-concatenation/Common-Lisp/array-concatenation-1.lisp similarity index 100% rename from Task/Array-concatenation/Common-Lisp/array-concatenation.lisp rename to Task/Array-concatenation/Common-Lisp/array-concatenation-1.lisp diff --git a/Task/Array-concatenation/Common-Lisp/array-concatenation-2.lisp b/Task/Array-concatenation/Common-Lisp/array-concatenation-2.lisp new file mode 100644 index 0000000000..6f65e957a1 --- /dev/null +++ b/Task/Array-concatenation/Common-Lisp/array-concatenation-2.lisp @@ -0,0 +1,13 @@ +(setf arr1 (make-array '(3) :initial-contents '(1 2 3))) +(setf arr2 (make-array '(3) :initial-contents '(4 5 6))) +(setf arr3 (make-array '(3) :initial-contents '(7 8 9))) +(setf arr4 (make-array '(6))) +(setf arr5 (make-array '(9))) +(setf arr4 (concatenate `(vector ,(array-element-type arr1)) arr1 arr2)) +(format t "~a" "concatenate arr1 and arr2: ") +(write arr4) +(terpri) +(setf arr5 (concatenate `(vector ,(array-element-type arr1)) arr4 arr3)) +(format t "~a" "concatenate arr4 and arr3: ") +(write arr5) +(terpri) diff --git a/Task/Array-concatenation/Elena/array-concatenation.elena b/Task/Array-concatenation/Elena/array-concatenation.elena index 759689788b..042dea4f07 100644 --- a/Task/Array-concatenation/Elena/array-concatenation.elena +++ b/Task/Array-concatenation/Elena/array-concatenation.elena @@ -1,6 +1,6 @@ import extensions. -program = +public program = [ var a := (1,2,3). var b := (4,5). diff --git a/Task/Array-concatenation/Fortran/array-concatenation.f b/Task/Array-concatenation/Fortran/array-concatenation.f new file mode 100644 index 0000000000..588dc6dc2e --- /dev/null +++ b/Task/Array-concatenation/Fortran/array-concatenation.f @@ -0,0 +1,21 @@ +program Concat_Arrays +implicit none + + ! Note: in Fortran 90 you must use the old array delimiters (/ , /) + integer, dimension(3) :: a = [1, 2, 3] ! (/1, 2, 3/) + integer, dimension(3) :: b = [4, 5, 6] ! (/4, 5, 6/) + integer, dimension(:), allocatable :: c, d + + allocate(c(size(a)+size(b))) + c(1 : size(a)) = a + c(size(a)+1 : size(a)+size(b)) = b + write(*,*) c + + ! alternative + d = [a, b] ! (/a, b/) + write(*,*) d + + deallocate(c) + deallocate(d) + +end program Concat_Arrays diff --git a/Task/Array-concatenation/Klong/array-concatenation.klong b/Task/Array-concatenation/Klong/array-concatenation.klong new file mode 100644 index 0000000000..c1149a5060 --- /dev/null +++ b/Task/Array-concatenation/Klong/array-concatenation.klong @@ -0,0 +1,8 @@ + [1 2 3],[4 5 6] :" join " +[1 2 3 4 5 6] + + [1 2],:\[[3 4] [5 6] [7 8]] :" join each-left " +[[1 2 3 4] [1 2 5 6] [1 2 7 8]] + + [1 2],:/[[3 4] [5 6] [7 8]] :" join each-right " +[[3 4 1 2] [5 6 1 2] [7 8 1 2]] diff --git a/Task/Array-concatenation/Limbo/array-concatenation.limbo b/Task/Array-concatenation/Limbo/array-concatenation.limbo new file mode 100644 index 0000000000..3585acdcd9 --- /dev/null +++ b/Task/Array-concatenation/Limbo/array-concatenation.limbo @@ -0,0 +1,23 @@ +implement Command; + +include "sys.m"; +sys: Sys; + +include "draw.m"; + +include "sh.m"; + +init(nil: ref Draw->Context, nil: list of string) +{ + sys = load Sys Sys->PATH; + + a := array[] of {1, 2}; + b := array[] of {3, 4, 5}; + + c := array[len a + len b] of int; + c[:] = a; + c[len a:] = b; + + for (i := 0; i < len c; i++) + sys->print("%d\n", c[i]); +} diff --git a/Task/Array-concatenation/Oforth/array-concatenation.oforth b/Task/Array-concatenation/Oforth/array-concatenation.oforth index 3f2a4556fb..db831c6250 100644 --- a/Task/Array-concatenation/Oforth/array-concatenation.oforth +++ b/Task/Array-concatenation/Oforth/array-concatenation.oforth @@ -1 +1,3 @@ +import: mapping + [1, 2, 3 ] [ 4, 5, 6, 7 ] + diff --git a/Task/Array-concatenation/Red/array-concatenation.red b/Task/Array-concatenation/Red/array-concatenation.red new file mode 100644 index 0000000000..4e6dd5270c --- /dev/null +++ b/Task/Array-concatenation/Red/array-concatenation.red @@ -0,0 +1,12 @@ +>> arr1: ["a" "b" "c"] +>> arr2: ["d" "e" "f"] +>> append arr1 arr2 +== ["a" "b" "c" "d" "e" "f"] +>> arr3: [1 2 3] +>> insert arr1 arr3 +>> arr1 +== [1 2 3 "a" "b" "c" "d" "e" "f"] +>> arr4: [22 33 44] +== [22 33 44] +>> append/only arr1 arr4 +== [1 2 3 "a" "b" "c" "d" "e" "f" [22 33 44]] diff --git a/Task/Array-concatenation/Scheme/array-concatenation.ss b/Task/Array-concatenation/Scheme/array-concatenation-1.ss similarity index 100% rename from Task/Array-concatenation/Scheme/array-concatenation.ss rename to Task/Array-concatenation/Scheme/array-concatenation-1.ss diff --git a/Task/Array-concatenation/Scheme/array-concatenation-2.ss b/Task/Array-concatenation/Scheme/array-concatenation-2.ss new file mode 100644 index 0000000000..2274bd80bd --- /dev/null +++ b/Task/Array-concatenation/Scheme/array-concatenation-2.ss @@ -0,0 +1,25 @@ +(use gauche.array) + +(define (print-matrix m) + (define row-num #f) + (array-for-each-index m + (lambda (row col) + (when (and row-num (not (= row-num row))) (newline)) + (format #t "~a " (array-ref m row col)) + (set! row-num row))) + (newline)) + +(define a + #,( (0 3 0 2) + a b + c d + e f)) + +(define b + #,( (0 3 0 2) + 1 2 + 3 4 + 5 6)) + +(print-matrix (array-concatenate a b)) +(print-matrix (array-concatenate a b 1)) diff --git a/Task/Array-concatenation/Simula/array-concatenation.simula b/Task/Array-concatenation/Simula/array-concatenation.simula index 5b60f006e4..e0d00db4c4 100644 --- a/Task/Array-concatenation/Simula/array-concatenation.simula +++ b/Task/Array-concatenation/Simula/array-concatenation.simula @@ -1,50 +1,95 @@ -BEGIN +BEGIN ! Concatenate arrays - of REAL, here; - CLASS ARRAYHOLDER(N); INTEGER N; + CLASS REAL_ARRAY(N); INTEGER N; BEGIN REAL ARRAY DATA(1:N); - END; - REF(ARRAYHOLDER) PROCEDURE CONCAT(A, B); REF(ARRAYHOLDER) A, B; + ! Return a new REAL_ARRAY containing + ! the values from this REAL_ARRAY + ! followed by the values from other; + REF(REAL_ARRAY) PROCEDURE CONCAT(other); + REF(REAL_ARRAY) other; + BEGIN + REF(REAL_ARRAY) C; + INTEGER I; + + C :- NEW REAL_ARRAY(N + other.N); + + FOR I := 1 STEP 1 UNTIL N DO + C.DATA(I) := DATA(I); + + FOR I := 1 STEP 1 UNTIL other.N DO + C.DATA(N + I) := other.DATA(I); + + CONCAT :- C; + END; + + ! Fill DATA; + REF(REAL_ARRAY) PROCEDURE linearFill(start, stride); + REAL start, stride; + BEGIN + linearFillFrom(DATA, 1, N, start, stride); + linearFill :- this REAL_ARRAY + END; + + PROCEDURE out(sink); REF(printfile) sink; + BEGIN + INTEGER i; + FOR i := 1 STEP 1 UNTIL N DO + sink.OUTFIX(DATA(i), 2, 7); + sink.OUTIMAGE; + END; + END REAL_ARRAY; + + ! "The problem" is not array as an input parameter: + ! I don't know how to + ! "pass a new ARRAY out of a PROCEDURE"; + REF(REAL_ARRAY) PROCEDURE concatenate(a, b); + REAL ARRAY a, b; BEGIN - REF(ARRAYHOLDER) C; - INTEGER I, J; + INTEGER i, a_, N, b_, M; + REF(REAL_ARRAY) c; + a_ := LOWERBOUND(a, 1) - 1; + N := UPPERBOUND(a, 1) - a_; + b_ := LOWERBOUND(a, 1) - 1; + M := UPPERBOUND(b, 1) - b_; + c :- NEW REAL_ARRAY(N + M); - C :- NEW ARRAYHOLDER(A.N + B.N); + FOR i := 1 STEP 1 UNTIL N DO + c.DATA(i) := a(a_+i); + ! for readability, don't + ! reduce one index expression to a variable + FOR i := 1 STEP 1 UNTIL M DO + c.DATA(N + i) := b(b_+i); - FOR I := 1 STEP 1 UNTIL A.N DO - BEGIN - J := J+1; C.DATA(J) := A.DATA(I); - END; + concatenate :- c; + END concatenate REAL ARRAYs; - FOR I := 1 STEP 1 UNTIL B.N DO - BEGIN - J := J+1; C.DATA(J) := B.DATA(I); - END; - - CONCAT :- C; + ! two more convenience PROCEDUREs; + PROCEDURE linearFillFrom(a, from, inclusive, start, stride); + REAL ARRAY a; ! passed by reference; + INTEGER from, inclusive; + REAL start, stride; + BEGIN + INTEGER i; + FOR i := from STEP 1 UNTIL inclusive DO + a(i) := start + stride * (i - from) END; + PROCEDURE linearFill(a, start, stride); + REAL ARRAY a; + REAL start, stride; + linearFillFrom(a, LOWERBOUND(a, 1), UPPERBOUND(a, 1), + start, stride); - REF(ARRAYHOLDER) X, Y, Z; - INTEGER I; - X :- NEW ARRAYHOLDER(3); - Y :- NEW ARRAYHOLDER(4); - - I := 0; - I := I+1; X.DATA(I) := 2*I; - I := I+1; X.DATA(I) := 2*I; - I := I+1; X.DATA(I) := 2*I; - - I := 0; - I := I+1; Y.DATA(I) := -3*I; - I := I+1; Y.DATA(I) := -3*I; - I := I+1; Y.DATA(I) := -3*I; - I := I+1; Y.DATA(I) := -3*I; - - Z :- CONCAT(X, Y); - FOR I := 1 STEP 1 UNTIL Z.N DO - OUTFIX(Z.DATA(I), 2, 7); - OUTIMAGE; + REF(REAL_ARRAY) X; + REAL ARRAY u(1:3), v(1:4); + linearFill(u, 3, 7); + linearFill(v, 0, 5); + concatenate(u, v).out(SYSOUT); + X :- NEW REAL_ARRAY(3).linearFill(1, 2); + X.out(SYSOUT); + X.CONCAT(NEW REAL_ARRAY(4) + .linearFill(-1, -3)).out(SYSOUT); END. diff --git a/Task/Array-concatenation/VBA/array-concatenation.vba b/Task/Array-concatenation/VBA/array-concatenation.vba new file mode 100644 index 0000000000..400ca37957 --- /dev/null +++ b/Task/Array-concatenation/VBA/array-concatenation.vba @@ -0,0 +1,25 @@ +Option Explicit + +Sub MainConcat_Array() +Dim Aray_1() As Variant, Aray_2() As Variant +Dim Result() As Variant + + Aray_1 = Array(1, 2, 3, 4, 5, #11/24/2017#, "azerty") + Aray_2 = Array("A", "B", "C", 18, "End") + Result = Concat_Array(Aray_1, Aray_2) + Debug.Print "With Array 1 : " & Join(Aray_1, ", ") + Debug.Print "And Array 2 : " & Join(Aray_2, ", ") + Debug.Print "The result is Array 3 : " & Join(Result, ", ") +End Sub + +Function Concat_Array(A1() As Variant, A2() As Variant) As Variant() +Dim TmpA1() As Variant, N As Long, i As Long + + N = UBound(A1) + 1 + TmpA1 = A1 + ReDim Preserve TmpA1(N + UBound(A2)) + For i = N To UBound(TmpA1) + TmpA1(i) = A2(i - N) + Next + Concat_Array = TmpA1 +End Function diff --git a/Task/Arrays/Delphi/arrays.delphi b/Task/Arrays/Delphi/arrays.delphi index a9ebb3d530..f2bb850472 100644 --- a/Task/Arrays/Delphi/arrays.delphi +++ b/Task/Arrays/Delphi/arrays.delphi @@ -1,29 +1,35 @@ procedure TForm1.Button1Click(Sender: TObject); var - StaticArray: array[0..9] of Integer; - DynamicArray: array of Integer; + StaticArray: array[1..10] of Integer; // static arrays can start at any index + DynamicArray: array of Integer; // dynamic arrays always start at 0 StaticArrayText, DynamicArrayText: string; - lcv: Integer; + ixS, ixD: Integer; begin // Setting the length of the dynamic array the same as the static one SetLength(DynamicArray, Length(StaticArray)); // Asking random numbers storing into the static array - for lcv := 0 to Pred(Length(StaticArray)) do + for ixS := Low(StaticArray) to High(StaticArray) do begin - StaticArray[lcv] := StrToInt( + StaticArray[ixS] := StrToInt( InputBox('Random number', 'Enter a random number for position', - IntToStr(Succ(lcv)))); + IntToStr(ixS))); end; // Storing entered numbers of the static array in reverse order into the dynamic - for lcv := 0 to Pred(Length(StaticArray)) do - DynamicArray[Pred(Length(DynamicArray)) - lcv] := StaticArray[lcv]; - // Concatenating the static and dynamic array into a single string variable - for lcv := 0 to Pred(Length(StaticArray)) do + ixD := High(DynamicArray); + for ixS := Low(StaticArray) to High(StaticArray) do begin - StaticArrayText := StaticArrayText + IntToStr(StaticArray[lcv]); - DynamicArrayText := DynamicArrayText + IntToStr(DynamicArray[lcv]); + DynamicArray[ixD] := StaticArray[ixS]; + Dec(ixD); + end; + // Concatenating the static and dynamic array into a single string variable + StaticArrayText := ''; + for ixS := Low(StaticArray) to High(StaticArray) do + StaticArrayText := StaticArrayText + IntToStr(StaticArray[ixS]); + DynamicArrayText := ''; + for ixD := Low(DynamicArray) to High(DynamicArray) do + DynamicArrayText := DynamicArrayText + IntToStr(DynamicArray[ixD]); end; // Displaying both arrays (#13#10 = Carriage Return/Line Feed) ShowMessage(StaticArrayText + #13#10 + DynamicArrayText); diff --git a/Task/Arrays/Elena/arrays-3.elena b/Task/Arrays/Elena/arrays-3.elena index 6eb16c2699..a743c90cc1 100644 --- a/Task/Arrays/Elena/arrays-3.elena +++ b/Task/Arrays/Elena/arrays-3.elena @@ -1,4 +1,4 @@ - int[] aStackAllocatedArray(3). + V aStackAllocatedArray. aStackAllocatedArray[0] := 1. aStackAllocatedArray[1] := 2. aStackAllocatedArray[2] := 3. diff --git a/Task/Arrays/Elena/arrays-4.elena b/Task/Arrays/Elena/arrays-4.elena index f2b5fd4874..8294d1fbab 100644 --- a/Task/Arrays/Elena/arrays-4.elena +++ b/Task/Arrays/Elena/arrays-4.elena @@ -1,6 +1,6 @@ var aDynamicArray := ArrayList new. - aDynamicArray += 1. - aDynamicArray += 2. - aDynamicArray += 4. + aDynamicArray append:1. + aDynamicArray append:2. + aDynamicArray append:4. aDynamicArray[2] := 3. diff --git a/Task/Arrays/HolyC/arrays-1.holyc b/Task/Arrays/HolyC/arrays-1.holyc new file mode 100644 index 0000000000..673c71d95f --- /dev/null +++ b/Task/Arrays/HolyC/arrays-1.holyc @@ -0,0 +1,8 @@ +// Create an array of fixed size +U8 array[10] = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10; + +// The first element of a HolyC array is indexed at 0. To set a value: +array[0] = 123; + +// Access an element +Print("%d\n", array[0]); diff --git a/Task/Arrays/HolyC/arrays-2.holyc b/Task/Arrays/HolyC/arrays-2.holyc new file mode 100644 index 0000000000..ae65dbdff8 --- /dev/null +++ b/Task/Arrays/HolyC/arrays-2.holyc @@ -0,0 +1,98 @@ +record aThing(a, b, c) # arbitrary object (record or class) for illustration + +procedure main() + A0 := [] # empty list + A0 := list() # empty list (default size 0) + A0 := list(0) # empty list (literal size 0) + + A1 := list(10) # 10 elements, default initializer &null + A2 := list(10, 1) # 10 elements, initialized to 1 + + # literal array construction - arbitrary dynamically typed members + A3 := [1, 2, 3, ["foo", "bar", "baz"], aThing(1, 2, 3), "the end"] + + # left-end workers + # NOTE: get() is a synonym for pop() which allows nicely-worded use of put() and get() to implement queues + # + Q := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + x := pop(A0) # x is 1 + x := get(A0) # x is 2 + push(Q,0) + # Q is now [0,3, 4, 5, 6, 7, 8, 9, 10] + + # right-end workers + x := pull(Q) # x is 10 + put(Q, 100) # Q is now [0, 3, 4, 5, 6, 7, 8, 9, 100] + + # push and put return the list they are building + # they also can have multiple arguments which work like repeated calls + + Q2 := put([],1,2,3) # Q2 is [1,2,3] + Q3 := push([],1,2,3) # Q3 is [3,2,1] + Q4 := push(put(Q2),4),0] # Q4 is [0,1,2,3,4] and so is Q2 + + # array access follows with A as the sample array + A := [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] + + # get element indexed from left + x := A[1] # x is 10 + x := A[2] # x is 20 + x := A[10] # x is 100 + + # get element indexed from right + x := A[-1] # x is 100 + x := A[-2] # x is 90 + x := A[-10] # x is 10 + + # copy array to show assignment to elements + B := copy(A) + + # assign element indexed from left + B[1] := 11 + B[2] := 21 + B[10] := 101 + # B is now [11, 21, 30, 50, 60, 60, 70, 80, 90, 101] + + # assign element indexed from right - see below + B[-1] := 102 + B[-2] := 92 + B[-10] := 12 + # B is now [12, 21, 30, 50, 60, 60, 70, 80, 92, 102] + + # list slicing + # the unusual nature of the slice - returning 1 less element than might be expected + # in many languages - is best understood if you imagine indexes as pointing to BEFORE + # the item of interest. When a slice is made, the elements between the two points are + # collected. eg in the A[3 : 6] sample, it will get the elements between the [ ] marks + # + # sample list: 10 20 [30 40 50] 60 70 80 90 100 + # positive indexes: 1 2 3 4 5 6 7 8 9 10 11 + # non-positive indexes: -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 + # + # I have deliberately drawn the indexes between the positions of the values. + # The nature of this indexing brings simplicity to string operations + # + # list slicing can also use non-positive indexes to access values from the right. + # The final index of 0 shown above shows how the end of the list can be nominated + # without having to know it's length + # + # NOTE: list slices are distinct lists, so assigning to the slice + # or a member of the slice does not change the values in A + # + # Another key fact to understand: once the non-positive indexes and length-offsets are + # resolved to a simple positive index, the index pair (if two are given) are swapped + # if necessary to yield the elements between the two. + # + S := A[3 : 6] # S is [30, 40, 50] + S := A[6 : 3] # S is [30, 40, 50] not illegal or erroneous + S := A[-5 : -8] # S is [30, 40, 50] + S := A[-8 : -5] # S is [30, 40, 50] also legal and meaningful + + # list slicing with length request + S := A[3 +: 3] # S is [30, 40, 50] + S := A[6 -: 3] # S is [30, 40, 50] + S := A[-8 +: 3] # S is [30, 40, 50] + S := A[-5 -: 3] # S is [30, 40, 50] + S := A[-8 -: -3] # S is [30, 40, 50] + S := A[-5 +: -3] # S is [30, 40, 50] +end diff --git a/Task/Arrays/HolyC/arrays-3.holyc b/Task/Arrays/HolyC/arrays-3.holyc new file mode 100644 index 0000000000..a3a972a13f --- /dev/null +++ b/Task/Arrays/HolyC/arrays-3.holyc @@ -0,0 +1,3 @@ +# Unicon provides a number of extensions +# insert and delete work on lists allowing changes in the middle +# possibly others diff --git a/Task/Arrays/Oforth/arrays.oforth b/Task/Arrays/Oforth/arrays.oforth index 0c80c7d547..ae49912821 100644 --- a/Task/Arrays/Oforth/arrays.oforth +++ b/Task/Arrays/Oforth/arrays.oforth @@ -1,3 +1,3 @@ -[ "abd", "def", "ghi" ] at(3) println +[ "abd", "def", "ghi" ] at( 3 ) . -ListBuffer new dup addAll([1, 2, 3]) dup put(2, 8.1) println +Array new dup addAll( [1, 2, 3] ) dup put( 2, 8.1 ) . diff --git a/Task/Arrays/Pony/arrays.pony b/Task/Arrays/Pony/arrays.pony index b148ddc65a..35deaac131 100644 --- a/Task/Arrays/Pony/arrays.pony +++ b/Task/Arrays/Pony/arrays.pony @@ -1,3 +1,7 @@ +use "assert" // due to the use of Fact + +- - - + var numbers = Array[I32](16) // creating array of 32-bit ints with initial allocation for 16 elements numbers.push(10) // add value 10 to the end of array, extending the underlying memory if needed try diff --git a/Task/Arrays/Red/arrays-1.red b/Task/Arrays/Red/arrays-1.red new file mode 100644 index 0000000000..33d699add6 --- /dev/null +++ b/Task/Arrays/Red/arrays-1.red @@ -0,0 +1,14 @@ +arr1: [] ;create empty array +arr2: ["apple" "orange" 1 2 3] ;create an array with data +>> insert arr1 "blue" +>> arr1 +== ["blue"] +append append arr1 "black" "green" +>> arr1 +== ["blue" "black" "green"] +>> arr1/2 +== "black" +>> second arr1 +== "black" +>> pick arr1 2 +== "black" diff --git a/Task/Arrays/Red/arrays-2.red b/Task/Arrays/Red/arrays-2.red new file mode 100644 index 0000000000..45a31278fc --- /dev/null +++ b/Task/Arrays/Red/arrays-2.red @@ -0,0 +1,16 @@ +>> vec1: make vector! [ 20 30 70] +== make vector! [20 30 70] +>> vec1/2 +== 30 +>> second vec1 +== 30 +>> append vec1 90 +== make vector! [20 30 70 90] +>> append vec1 "string" +*** Script Error: invalid argument: "string" +*** Where: append +*** Stack: +>> append vec1 3.0 +*** Script Error: invalid argument: 3.0 +*** Where: append +*** Stack: diff --git a/Task/Assertions/Julia/assertions.julia b/Task/Assertions/Julia/assertions.julia index f51e34b12c..c811a0e89d 100644 --- a/Task/Assertions/Julia/assertions.julia +++ b/Task/Assertions/Julia/assertions.julia @@ -1,9 +1,14 @@ -#assert() function takes expression as 1st argument, failed-assertion message as optional 2nd argument -julia> assert(x==42,"x is not 42") -ERROR: assertion failed: x is not 42 -#@assert macro checks the supplied conditional expression, with the expression returned in the failed-assertion message -julia> @assert x==42 -ERROR: assertion failed: :((x==42)) -#Julia also has type assertions of the form, x::Type which can be appended to a variable for type-checking at any point -julia> x::String -ERROR: type: typeassert: expected String, got Int32 +# assert() function takes expression as 1st argument, failed-assertion message +# as optional 2nd argument +assert(x == 42) +# ERROR: assertion failed: x is not 42 + +# @assert macro checks the supplied conditional expression, with the expression +# returned in the failed-assertion message +@assert x == 42 +# ERROR: assertion failed: :((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 diff --git a/Task/Associative-array-Creation/AutoIt/associative-array-creation.autoit b/Task/Associative-array-Creation/AutoIt/associative-array-creation.autoit new file mode 100644 index 0000000000..e11b219143 --- /dev/null +++ b/Task/Associative-array-Creation/AutoIt/associative-array-creation.autoit @@ -0,0 +1,127 @@ +; Associative arrays in AutoIt. +; All the required functions are below the examples. + +; Initialize an error handler to deal with any COM errors.. +global $oMyError = ObjEvent("AutoIt.Error", "AAError") + +; first example, simple. +global $simple + +; Initialize your array ... +AAInit($simple) + +AAAdd($simple, "Appple", "fruit") +AAAdd($simple, "Dog", "animal") +AAAdd($simple, "Silicon", "tetravalent metalloid semiconductor") + +ConsoleWrite("It is well-known that Silicon is a " & AAGetItem($simple, "Silicon") & "." & @CRLF) +ConsoleWrite(@CRLF) + + +; A more interesting example.. + +$ini_path = "AA_Test.ini" +; Put this prefs section in your ini file.. +; [test] +; foo=foo value +; foo2=foo2 value +; bar=bar value +; bar2=bar2 value + + +global $associative_array +AAInit($associative_array) + +; We are going to convert this 2D array into a cute associative array where we +; can access the values by simply using their respective key names.. +$test_array = IniReadSection($ini_path, "test") + +for $z = 1 to 2 ; do it twice, to show that the items are *really* there! + for $i = 1 to $test_array[0][0] + $key_name = $test_array[$i][0] + ConsoleWrite("Adding '" & $key_name & "'.." & @CRLF) + ; key already exists in "$associative_array", use the pre-determined value.. + if AAExists($associative_array, $key_name) then + $this_value = AAGetItem($associative_array, $key_name) + ConsoleWrite("key_name ALREADY EXISTS! : =>" & $key_name & "<=" & @CRLF) + else + $this_value = $test_array[$i][1] + ; store left=right value pair in AA + if $this_value then + AAAdd($associative_array, $key_name, $this_value) + endif + endif + next +next + +ConsoleWrite(@CRLF & "Array Count: =>" & AACount($associative_array) & "<=" & @CRLF) +AAList($associative_array) + +ConsoleWrite(@CRLF & "Removing 'foo'..") +AARemove($associative_array, "foo") + +ConsoleWrite(@CRLF & "Array Count: =>" & AACount($associative_array) & "<=" & @CRLF) +AAList($associative_array) + + +AAWipe($associative_array) + + +; end + + + +func AAInit(ByRef $dict_obj) +$dict_obj = ObjCreate("Scripting.Dictionary") +endfunc + +; Adds a key and item pair to a Dictionary object.. +func AAAdd(ByRef $dict_obj, $key, $val) + $dict_obj.Add($key, $val) + If @error Then return SetError(1, 1, -1) +endfunc + +; Removes a key and item pair from a Dictionary object.. +func AARemove(ByRef $dict_obj, $key) + $dict_obj.Remove($key) + If @error Then return SetError(1, 1, -1) +endfunc + +; Returns true if a specified key exists in the associative array, false if not.. +func AAExists(ByRef $dict_obj, $key) + return $dict_obj.Exists($key) +endfunc + +; Returns a value for a specified key name in the associative array.. +func AAGetItem(ByRef $dict_obj, $key) + return $dict_obj.Item($key) +endfunc + +; Returns the total number of keys in the array.. +func AACount(ByRef $dict_obj) + return $dict_obj.Count +endfunc + +; List all the "Key" > "Item" pairs in the array.. +func AAList(ByRef $dict_obj) +ConsoleWrite("AAList: =>" & @CRLF) + local $k = $dict_obj.Keys ; Get the keys + ; local $a = $dict_obj.Items ; Get the items (for reference) + for $i = 0 to AACount($dict_obj) -1 ; Iterate the array + ConsoleWrite($k[$i] & " ==> " & AAGetItem($dict_obj, $k[$i]) & @CRLF) + next +endfunc + +; Wipe the array, obviously. +func AAWipe(ByRef $dict_obj) + $dict_obj.RemoveAll() +endfunc + +; Oh oh! +func AAError() + Local $err = $oMyError.number + If $err = 0 Then $err = -1 + SetError($err) ; to check for after this function returns +endfunc + +;; End AA Functions. diff --git a/Task/Associative-array-Creation/Elena/associative-array-creation.elena b/Task/Associative-array-Creation/Elena/associative-array-creation.elena index 33a9699421..9443d082cf 100644 --- a/Task/Associative-array-Creation/Elena/associative-array-creation.elena +++ b/Task/Associative-array-Creation/Elena/associative-array-creation.elena @@ -1,6 +1,6 @@ import system'collections. -program = +public program = [ // 1. Create var aMap := Dictionary new. diff --git a/Task/Associative-array-Creation/Julia/associative-array-creation.julia b/Task/Associative-array-Creation/Julia/associative-array-creation.julia index 601e0df921..6301317503 100644 --- a/Task/Associative-array-Creation/Julia/associative-array-creation.julia +++ b/Task/Associative-array-Creation/Julia/associative-array-creation.julia @@ -1,27 +1,26 @@ -julia> hash = {'a' => 97, 'b' => 98} # list keys/values -{'a'=>97,'b'=>98} +dict = Dict('a' => 97, 'b' => 98) # list keys/values +# Dict{Char,Int64} with 2 entries: +# 'b' => 98 +# 'a' => 97 -julia> hash = {c => int(c) for c = 'a':'d'} # dict comprehension -{'a'=>97,'c'=>99,'b'=>98,'d'=>100} +dict = Dict(c => Int(c) for c = 'a':'d') # dict comprehension +# Dict{Char,Int64} with 4 entries: +# 'b' => 98 +# 'a' => 97 +# 'd' => 100 +# 'c' => 99 -julia> hash['é'] = 233 ; hash # add an element -{'a'=>97,'c'=>99,'b'=>98,'é'=>233,'d'=>100} +dict['é'] = 233; dict # add an element +# Dict{Char,Int64} with 3 entries: +# 'b' => 98 +# 'a' => 97 +# 'é' => 233 -julia> hash = Dict() # create an empty dict -Dict{Any,Any}() +emptydict = Dict() # create an empty dict +# Dict{Any,Any} with 0 entries -julia> for c = 'a':'d' hash[c] = int(c) end ; hash # fill it -{'a'=>97,'c'=>99,'b'=>98,'d'=>100} +dict["a"] = 1 # type mismatch +# ERROR: MethodError: Cannot `convert` an object of type String to an object of type Char -julia> hash = (Char=>Int64)['a' => 97, 'b' => 98] # create a typed dict -['a'=>97,'b'=>98] - -julia> hash["a"] = 1 # type mismatch -ERROR: no method convert(Type{Char}, ASCIIString) - in setindex! at dict.jl:533 - -julia> hash = Dict(['a','b','c'], [97,98,99]) # constructor -['a'=>97,'c'=>99,'b'=>98] - -julia> typeof(hash) # type is infered correctly -Dict{Char,Int64} (constructor with 3 methods +typeof(dict) # type is infered correctly +# Dict{Char,Int64} diff --git a/Task/Associative-array-Creation/Perl-6/associative-array-creation.pl6 b/Task/Associative-array-Creation/Perl-6/associative-array-creation.pl6 new file mode 100644 index 0000000000..1aa9faef3f --- /dev/null +++ b/Task/Associative-array-Creation/Perl-6/associative-array-creation.pl6 @@ -0,0 +1,28 @@ +my %h1 = key1 => 'val1', 'key-2' => 2, three => -238.83, 4 => 'val3'; +my %h2 = 'key1', 'val1', 'key-2', 2, 'three', -238.83, 4, 'val3'; + +# Creating a hash from two lists using a metaoperator. + +my @a = 1..5; +my @b = 'a'..'e'; +my %h = @a Z=> @b; + +# Hash elements and hash slices now use the same sigil as the whole hash. This is construed as a feature. +# Curly braces no longer auto-quote, but Perl 6's qw (shortcut < ... >) now auto-subscripts. + +say %h1{'key1'}; +say %h1; +%h1 = 'val1'; +%h1 = 'val1', -238.83; + +# Special syntax is no longer necessary to access a hash stored in a scalar. + +my $h = {key1 => 'val1', 'key-2' => 2, three => -238.83, 4 => 'val3'}; +say $h; + +# Keys are of type Str or Int by default. The type of the key can be provided. + +my %hash{Any}; # same as %hash{*} +class C {}; +my %cash{C}; +%cash{C.new} = 1; diff --git a/Task/Associative-array-Creation/Ring/associative-array-creation.ring b/Task/Associative-array-Creation/Ring/associative-array-creation.ring new file mode 100644 index 0000000000..015cfa4861 --- /dev/null +++ b/Task/Associative-array-Creation/Ring/associative-array-creation.ring @@ -0,0 +1,10 @@ +# Project Associative array/Creation +# Date 2018/03/24 +# Author Gal Zsolt [~ CalmoSoft ~] +# Email + +myarray = [["one",1], + ["two",2], + ["three",3]] +see find(myarray,"two",1) + nl +see find(myarray,2,2) + nl diff --git a/Task/Associative-array-Iteration/Common-Lisp/associative-array-iteration-6.lisp b/Task/Associative-array-Iteration/Common-Lisp/associative-array-iteration-6.lisp new file mode 100644 index 0000000000..181ea93d7d --- /dev/null +++ b/Task/Associative-array-Iteration/Common-Lisp/associative-array-iteration-6.lisp @@ -0,0 +1,14 @@ +;; Project : Associative array/Iteration +;; Date : 2018/03/08 +;; Author : Gal Zsolt [~ CalmoSoft ~] +;; Email : + +(setf x (make-array '(3 2) + :initial-contents '(("hello" 13 ) ("world" 31) ("!" 71)))) +(setf xlen (array-dimensions x)) +(setf len (car xlen)) +(dotimes (n len) + (terpri) + (format t "~a" (aref x n 0)) + (format t "~a" " : ") + (format t "~a" (aref x n 1))) diff --git a/Task/Associative-array-Iteration/Elena/associative-array-iteration.elena b/Task/Associative-array-Iteration/Elena/associative-array-iteration.elena index c0375f9fcd..673f855c76 100644 --- a/Task/Associative-array-Iteration/Elena/associative-array-iteration.elena +++ b/Task/Associative-array-Iteration/Elena/associative-array-iteration.elena @@ -2,7 +2,7 @@ import system'collections. import system'routines. import extensions. -program = +public program = [ // 1. Create var aMap := Dictionary new. @@ -14,5 +14,5 @@ program = // Enumerate aMap forEach - (:aKeyValue)[ console printLine(aKeyValue key," : ",aKeyValue) ]. + (:aKeyValue)[ console printLine(aKeyValue key," : ",aKeyValue value) ]. ]. diff --git a/Task/Associative-array-Iteration/Julia/associative-array-iteration.julia b/Task/Associative-array-Iteration/Julia/associative-array-iteration.julia index 5e872ae7ba..43443a8be4 100644 --- a/Task/Associative-array-Iteration/Julia/associative-array-iteration.julia +++ b/Task/Associative-array-Iteration/Julia/associative-array-iteration.julia @@ -1,19 +1,19 @@ -mydict = [ "hello"=>13, "world"=>31, "!"=>71 ] +dict = Dict("hello" => 13, "world" => 31, "!" => 71) # applying a function to key-value pairs: - map(println, mydict); +foreach(println, dict) # iterating over key-value pairs: -for (key,value) in mydict - println("key = $key, value = $value") +for (key, value) in dict + println("dict[$key] = $value") end # iterating over keys: -for key in keys(mydict) - println("key = $key") +for key in keys(dict) + @show key end # iterating over values: -for value in values(mydict) - println("value = $value") +for value in values(dict) + @show value end diff --git a/Task/Associative-array-Iteration/Perl-6/associative-array-iteration.pl6 b/Task/Associative-array-Iteration/Perl-6/associative-array-iteration.pl6 index b830e3afe1..290e61120e 100644 --- a/Task/Associative-array-Iteration/Perl-6/associative-array-iteration.pl6 +++ b/Task/Associative-array-Iteration/Perl-6/associative-array-iteration.pl6 @@ -4,6 +4,11 @@ for %pairs.kv -> $k, $v { say "(k,v) = ($k, $v)"; } +# Stable order +for %pairs.sort(*.value)>>.kv -> ($k, $v) { + say "(k,v) = ($k, $v)"; +} + { say "$^a => $^b" } for %pairs.kv; say "key = $_" for %pairs.keys; diff --git a/Task/Associative-array-Iteration/Ring/associative-array-iteration.ring b/Task/Associative-array-Iteration/Ring/associative-array-iteration.ring new file mode 100644 index 0000000000..66f6fb651d --- /dev/null +++ b/Task/Associative-array-Iteration/Ring/associative-array-iteration.ring @@ -0,0 +1,9 @@ +# Project : Associative array/Iteration +# Date : 2017/10/22 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +lst = [["hello", 13], ["world", 31], ["!", 71]] +for n = 1 to len(lst) + see lst[n][1] + " : " + lst[n][2] + nl +next diff --git a/Task/Atomic-updates/Common-Lisp/atomic-updates-1.lisp b/Task/Atomic-updates/Common-Lisp/atomic-updates-1.lisp new file mode 100644 index 0000000000..13fa77dffb --- /dev/null +++ b/Task/Atomic-updates/Common-Lisp/atomic-updates-1.lisp @@ -0,0 +1,37 @@ +(ql:quickload '(:alexandria :stmx :bordeaux-threads)) + +(defpackage :atomic-updates + (:use :cl)) + +(in-package :atomic-updates) + +(defvar *buckets* nil) +(defvar *running* nil) + +(defun distribute (ratio a b) + "Atomically redistribute the values of buckets A and B by RATIO." + (stmx:atomic + (let* ((sum (+ (stmx:$ a) (stmx:$ b))) + (a2 (truncate (* ratio sum)))) + (setf (stmx:$ a) a2) + (setf (stmx:$ b) (- sum a2))))) + +(defun runner (ratio-func) + "Continously distribute to two different elements in *BUCKETS* with the +value returned from RATIO-FUNC." + (loop while *running* + do (let ((a (alexandria:random-elt *buckets*)) + (b (alexandria:random-elt *buckets*))) + (unless (eq a b) + (distribute (funcall ratio-func) a b))))) + +(defun print-buckets () + "Atomically get the bucket values and print out their metrics." + (let ((buckets (stmx:atomic (map 'vector 'stmx:$ *buckets*)))) + (format t "Buckets: ~a~%Sum: ~a~%" buckets (reduce '+ buckets)))) + +(defun scenario () + (setf *buckets* (coerce (loop repeat 20 collect (stmx:tvar 10)) 'vector)) + (setf *running* t) + (bt:make-thread (lambda () (runner (constantly 0.5)))) + (bt:make-thread (lambda () (runner (lambda () (random 1.0)))))) diff --git a/Task/Atomic-updates/Common-Lisp/atomic-updates-2.lisp b/Task/Atomic-updates/Common-Lisp/atomic-updates-2.lisp new file mode 100644 index 0000000000..9350239db8 --- /dev/null +++ b/Task/Atomic-updates/Common-Lisp/atomic-updates-2.lisp @@ -0,0 +1,10 @@ +ATOMIC-UPDATES> (scenario) +# +ATOMIC-UPDATES> (loop repeat 3 do (print-buckets) (sleep 1)) +Buckets: #(8 4 12 17 12 10 5 10 9 10 4 11 4 15 16 20 11 8 4 10) +Sum: 200 +Buckets: #(2 12 24 7 8 3 13 6 8 31 0 9 7 11 12 8 8 12 15 4) +Sum: 200 +Buckets: #(1 2 3 3 2 8 33 23 0 8 4 11 24 2 3 5 32 8 2 26) +Sum: 200 +NIL diff --git a/Task/Atomic-updates/Julia/atomic-updates.julia b/Task/Atomic-updates/Julia/atomic-updates.julia new file mode 100644 index 0000000000..04e1c7b019 --- /dev/null +++ b/Task/Atomic-updates/Julia/atomic-updates.julia @@ -0,0 +1,60 @@ +using StatsBase + +function runall() + nbuckets = 16 + unfinish = true + spinner = ReentrantLock() + buckets = rand(1:99, nbuckets) + totaltrans = 0 + + bucketsum() = sum(buckets) + smallpause() = sleep(rand() / 2000) + picktwo() = (samplepair(nbuckets)...) + function equalizer() + while unfinish + smallpause() + if trylock(spinner) + i, j = picktwo() + sm = buckets[i] + buckets[j] + m = fld(sm + 1, 2) + buckets[i], buckets[j] = m, sm - m + totaltrans += 1 + unlock(spinner) + end + end + end + function redistributor() + while unfinish + smallpause() + if trylock(spinner) + i, j = picktwo() + sm = buckets[i] + buckets[j] + buckets[i] = rand(0:sm) + buckets[j] = sm - buckets[i] + totaltrans += 1 + unlock(spinner) + end + end + end + function accountant() + count = 0 + while count < 16 + smallpause() + if trylock(spinner) + println("Current state of buckets: $buckets. Total in buckets: $(bucketsum())") + unlock(spinner) + count += 1 + sleep(1) + end + end + unfinish = false + end + t = time() + @async equalizer() + @async redistributor() + @async accountant() + while unfinish sleep(0.25) end + println("Total transactions: $totaltrans ($(round(Int, totaltrans / (time() - t))) unlocks per second).") +end + +runall() diff --git a/Task/Atomic-updates/Kotlin/atomic-updates.kotlin b/Task/Atomic-updates/Kotlin/atomic-updates.kotlin new file mode 100644 index 0000000000..b16d6c4b1f --- /dev/null +++ b/Task/Atomic-updates/Kotlin/atomic-updates.kotlin @@ -0,0 +1,84 @@ +// version 1.2.0 + +import java.util.concurrent.ThreadLocalRandom +import kotlin.concurrent.thread + +const val NUM_BUCKETS = 10 + +class Buckets(data: IntArray) { + private val data = data.copyOf() + + operator fun get(index: Int) = synchronized(data) { data[index] } + + fun transfer(srcIndex: Int, dstIndex: Int, amount: Int): Int { + if (amount < 0) { + throw IllegalArgumentException("Negative amount: $amount") + } + if (amount == 0) return 0 + synchronized(data) { + var a = amount + if (data[srcIndex] - a < 0) a = data[srcIndex] + if (data[dstIndex] + a < 0) a = Int.MAX_VALUE - data[dstIndex] + if (a < 0) throw IllegalStateException() + data[srcIndex] -= a + data[dstIndex] += a + return a + } + } + + val buckets get() = synchronized(data) { data.copyOf() } + + fun transferRandomAmount() { + val rnd = ThreadLocalRandom.current() + while (true) { + val srcIndex = rnd.nextInt(NUM_BUCKETS) + val dstIndex = rnd.nextInt(NUM_BUCKETS) + val amount = rnd.nextInt() and Int.MAX_VALUE + transfer(srcIndex, dstIndex, amount) + } + } + + fun equalize() { + val rnd = ThreadLocalRandom.current() + while (true) { + val srcIndex = rnd.nextInt(NUM_BUCKETS) + val dstIndex = rnd.nextInt(NUM_BUCKETS) + val amount = (this[srcIndex] - this[dstIndex]) / 2 + if (amount >= 0) transfer(srcIndex, dstIndex, amount) + } + } + + fun print() { + while (true) { + val nextPrintTime = System.currentTimeMillis() + 3000 + while (true) { + val now = System.currentTimeMillis() + if (now >= nextPrintTime) break + try { + Thread.sleep(nextPrintTime - now) + } + catch (e: InterruptedException) { + return + } + } + val bucketValues = buckets + println("Current values: ${bucketValues.total} ${bucketValues.asList()}") + } + } +} + +val IntArray.total: Long get() { + var sum = 0L + for (d in this) sum += d + return sum +} + +fun main(args: Array) { + val rnd = ThreadLocalRandom.current() + val values = IntArray(NUM_BUCKETS) { rnd.nextInt() and Int.MAX_VALUE } + println("Initial array: ${values.total} ${values.asList()}") + val buckets = Buckets(values) + thread(name = "equalizer") { buckets.equalize() } + thread(name = "transferrer") { buckets.transferRandomAmount() } + thread(name = "printer") { buckets.print() } +} diff --git a/Task/Atomic-updates/PicoLisp/atomic-updates.l b/Task/Atomic-updates/PicoLisp/atomic-updates.l index 6b5f91a3e8..526a893364 100644 --- a/Task/Atomic-updates/PicoLisp/atomic-updates.l +++ b/Task/Atomic-updates/PicoLisp/atomic-updates.l @@ -1,72 +1,68 @@ -(de *Buckets . 15) # Number of buckets +(seed (in "/dev/urandom" (rd 8))) + +(de *Buckets . 15) # Number of buckets # E/R model (class +Bucket +Entity) -(rel key (+Key +Number)) # Key 1 .. *Buckets -(rel val (+Number)) # Value 1 .. 999 - - -# Start with an empty DB -(call 'rm "-f" "buckets.db") # Remove old DB (if any) -(pool "buckets.db") # Create new DB file +(rel key (+Key +Number)) # Key 1 .. *Buckets +(rel val (+Number)) # Value 1 .. 999 +# Create new DB file +(pool (tmp "buckets.db")) # Create *Buckets buckets with values between 1 and 999 (for K *Buckets (new T '(+Bucket) 'key K 'val (rand 1 999)) ) (commit) - # Pick a random bucket (de pickBucket () (db 'key '+Bucket (rand 1 *Buckets)) ) -# Create process -(de process (QuadFunction) - (unless (fork) - (seed *Pid) # Ensure local random sequence - (loop - (let (B1 (pickBucket) B2 (pickBucket)) # Pick two buckets 'B1' and 'B2' - (unless (== B1 B2) # Found two different ones? - (dbSync) # Atomic DB operation - (let (V1 (; B1 val) V2 (; B2 val)) # Get current values - (QuadFunction B1 V1 B2 V2) ) - (commit 'upd) ) ) ) ) ) # Close transaction - - # First process -(process - (quote (B1 V1 B2 V2) - (cond - ((> V1 V2) - (dec> B1 'val) # Make them closer to equal - (inc> B2 'val) ) - ((> V2 V1) - (dec> B2 'val) - (inc> B1 'val) ) ) ) ) +(unless (fork) + (seed *Pid) # Ensure local random sequence + (loop + (let (B1 (pickBucket) B2 (pickBucket)) # Pick two buckets 'B1' and 'B2' + (dbSync) # Atomic DB operation + (let (V1 (; B1 val) V2 (; B2 val)) # Get current values + (cond + ((> V1 V2) + (dec> B1 'val) # Make them closer to equal + (inc> B2 'val) ) + ((> V2 V1) + (dec> B2 'val) + (inc> B1 'val) ) ) ) + (commit 'upd) # Close transaction + (wait 1) ) ) ) # Second process -(process - (quote (B1 V1 B2 V2) - (cond - ((> V1 V2 0) - (inc> B1 'val) # Redistribute them - (dec> B2 'val) ) - ((> V2 V1 0) - (inc> B2 'val) - (dec> B1 'val) ) ) ) ) +(unless (fork) + (seed *Pid) # Ensure local random sequence + (loop + (let (B1 (pickBucket) B2 (pickBucket)) # Pick two buckets 'B1' and 'B2' + (unless (== B1 B2) # Found two different ones? + (dbSync) # Atomic DB operation + (let (V1 (; B1 val) V2 (; B2 val)) # Get current values + (cond + ((> V1 V2 0) + (inc> B1 'val) # Redistribute them + (dec> B2 'val) ) + ((> V2 V1 0) + (inc> B2 'val) + (dec> B1 'val) ) ) ) + (commit 'upd) # Close transaction + (wait 1) ) ) ) ) # Third process (unless (fork) (loop - (dbSync) # Atomic DB operation - (let Lst (collect 'key '+Bucket) # Get all buckets - (for This Lst # Print current values + (let Lst (collect 'key '+Bucket) # Get all buckets + (for This Lst # Print current values (printsp (: val)) ) - (prinl # and total sum + (prinl # and total sum "-- Total: " (sum '((This) (: val)) Lst) ) ) - (rollback) - (wait 2000) ) ) # Sleep two seconds + (wait 2000) ) ) # Sleep two seconds (wait) diff --git a/Task/Atomic-updates/Ring/atomic-updates.ring b/Task/Atomic-updates/Ring/atomic-updates.ring new file mode 100644 index 0000000000..d48b251e53 --- /dev/null +++ b/Task/Atomic-updates/Ring/atomic-updates.ring @@ -0,0 +1,45 @@ +# Project : Atomic updates +# Date : 2018/01/01 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +bucket = list(10) +f2 = 0 +for i = 1 to 10 + bucket[i] = floor(random(9)*10) +next + +a = display("display:") +see nl +a = flatten(a) +see "" + a + nl +a = display("flatten:") +see nl +a = transfer(3,5) +see a + nl +see "19 from 3 to 5: " +a = display(a) +see nl + +func display(a) + display = 0 + see "" + a + " " + char(9) + for i = 1 to 10 + display = display + bucket[i] + see "" + bucket[i] + " " + next + see " total:" + display + return display + +func flatten(f) + f1 = floor((f / 10) + 0.5) + for i = 1 to 10 + bucket[i] = f1 + f2 = f2 + f1 + next + bucket[10] = bucket[10] + f - f2 + +func transfer(a1,a2) + transfer = floor(random(9)/10 * bucket[a1]) + bucket[a1] = bucket[a1] - transfer + bucket[a2] = bucket[a2] + transfer diff --git a/Task/Average-loop-length/C++/average-loop-length.cpp b/Task/Average-loop-length/C++/average-loop-length.cpp new file mode 100644 index 0000000000..e3816e0d45 --- /dev/null +++ b/Task/Average-loop-length/C++/average-loop-length.cpp @@ -0,0 +1,62 @@ +#include +#include +#include + +#define MAX_N 20 +#define TIMES 1000000 + +/** + * Used to generate a uniform random distribution + */ +static std::random_device rd; //Will be used to obtain a seed for the random number engine +static std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd() +static std::uniform_int_distribution<> dis; + +int randint(int n) { + int r, rmax = RAND_MAX / n * n; + dis=std::uniform_int_distribution(0,rmax) ; + r = dis(gen); + return r / (RAND_MAX / n); +} + +unsigned long factorial(size_t n) { + //Factorial using dynamic programming to memoize the values. + static std::vectorfactorials{1,1,2}; + for (;factorials.size() <= n;) + factorials.push_back(factorials.back()*factorials.size()); + return factorials[n]; +} + +long double expected(size_t n) { + long double sum = 0; + for (size_t i = 1; i <= n; i++) + sum += factorial(n) / pow(n, i) / factorial(n - i); + return sum; +} + +int test(int n, int times) { + int i, count = 0; + for (i = 0; i < times; i++) { + unsigned int x = 1, bits = 0; + while (!(bits & x)) { + count++; + bits |= x; + x = static_cast(1 << randint(n)); + } + } + return count; +} + +int main() { + puts(" n\tavg\texp.\tdiff\n-------------------------------"); + + int n; + for (n = 1; n <= MAX_N; n++) { + int cnt = test(n, TIMES); + long double avg = (double)cnt / TIMES; + long double theory = expected(static_cast(n)); + long double diff = (avg / theory - 1) * 100; + printf("%2d %8.4f %8.4f %6.3f%%\n", n, static_cast(avg), static_cast(theory), static_cast(diff)); + } + return 0; +} diff --git a/Task/Average-loop-length/Oberon-2/average-loop-length.oberon-2 b/Task/Average-loop-length/Oberon-2/average-loop-length.oberon-2 new file mode 100644 index 0000000000..47fa207644 --- /dev/null +++ b/Task/Average-loop-length/Oberon-2/average-loop-length.oberon-2 @@ -0,0 +1,71 @@ +MODULE AvgLoopLen; +(* Oxford Oberon-2 *) +IMPORT Random, Out; + +PROCEDURE Fac(n: INTEGER; f: REAL): REAL; +BEGIN + IF n = 0 THEN + RETURN f + ELSE + RETURN Fac(n - 1,n*f) + END +END Fac; + +PROCEDURE Power(n,i: INTEGER): REAL; +VAR + p: REAL; +BEGIN + p := 1.0; + WHILE i > 0 DO p := p * n; DEC(i) END; + RETURN p +END Power; + +PROCEDURE Abs(x: REAL): REAL; +BEGIN + IF x < 0 THEN RETURN -x ELSE RETURN x END +END Abs; + +PROCEDURE Analytical(n: INTEGER): REAL; +VAR + i: INTEGER; + res: REAL; +BEGIN + res := 0.0; + FOR i := 1 TO n DO + res := res + (Fac(n,1.0) / Power(n,i) / Fac(n - i,1.0)); + END; + RETURN res +END Analytical; + +PROCEDURE Averages(n: INTEGER): REAL; +CONST + times = 100000; +VAR + rnds: SET; + r,count,i: INTEGER; +BEGIN + count := 0; i := 0; + WHILE i < times DO + rnds := {}; + LOOP + r := Random.Roll(n); + IF r IN rnds THEN EXIT ELSE INCL(rnds,r); INC(count) END + END; + INC(i) + END; + + RETURN count / times +END Averages; + +VAR + i: INTEGER; + av,an,df: REAL; +BEGIN + Random.Randomize; + Out.String(" Averages Analytical Diff% ");Out.Ln; + FOR i := 1 TO 20 DO + Out.Int(i,3); Out.String(": "); + av := Averages(i);an := Analytical(i);df := Abs(av - an) / an * 100.0; + Out.Fixed(av,10,4);Out.Fixed(an,11,4);Out.Fixed(df,10,4);Out.Ln + END +END AvgLoopLen. diff --git a/Task/Average-loop-length/REXX/average-loop-length.rexx b/Task/Average-loop-length/REXX/average-loop-length.rexx index 12d8ff69e3..bde77c5aa9 100644 --- a/Task/Average-loop-length/REXX/average-loop-length.rexx +++ b/Task/Average-loop-length/REXX/average-loop-length.rexx @@ -2,7 +2,7 @@ parse arg runs tests seed . /*obtain optional arguments from the CL*/ if runs =='' | runs =="," then runs = 40 /*Not specified? Then use the default.*/ if tests =='' | tests =="," then tests= 1000000 /* " " " " " " */ -if datatype(seed,'W') then call random ,, seed /*Is integer? For RAND repeatability.*/ +if datatype(seed, 'W') then call random ,, seed /*Is integer? For RAND repeatability.*/ !.=0; !.0=1 /*used for factorial (!) memoization.*/ numeric digits 100000 /*be able to calculate 25k! if need be.*/ numeric digits max(9, length( !(runs) ) ) /*set the NUMERIC DIGITS for !(runs). */ diff --git a/Task/Averages-Arithmetic-mean/Aime/averages-arithmetic-mean.aime b/Task/Averages-Arithmetic-mean/Aime/averages-arithmetic-mean.aime index d81327ad0d..c065a9df09 100644 --- a/Task/Averages-Arithmetic-mean/Aime/averages-arithmetic-mean.aime +++ b/Task/Averages-Arithmetic-mean/Aime/averages-arithmetic-mean.aime @@ -1,21 +1,20 @@ real mean(list l) { - integer i; real sum, x; sum = 0; - for (i, x in l) { + for (, x in l) { sum += x; } - return sum / ~l; + sum / ~l; } integer main(void) { - o_form("%f\n", mean(l_effect(4.5, 7.25, 5r, 5.75))); + o_form("%f\n", mean(list(4.5, 7.25, 5r, 5.75))); - return 0; + 0; } diff --git a/Task/Averages-Arithmetic-mean/Astro/averages-arithmetic-mean.astro b/Task/Averages-Arithmetic-mean/Astro/averages-arithmetic-mean.astro index 8e948d7c0a..f3c2920348 100644 --- a/Task/Averages-Arithmetic-mean/Astro/averages-arithmetic-mean.astro +++ b/Task/Averages-Arithmetic-mean/Astro/averages-arithmetic-mean.astro @@ -1,3 +1,3 @@ mean([1, 2, 3]) -mean([1:10]) +mean(1..10) mean([]) diff --git a/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena b/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena index 11bbbe118e..ae9281582b 100644 --- a/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena +++ b/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena @@ -18,7 +18,7 @@ extension op ^ aSum / aCount. ] } -program = +public program = [ var anArray := (1, 2, 3, 4, 5, 6, 7, 8). console printLine("Arithmetic mean of {",anArray,"} is ",anArray average); readChar. diff --git a/Task/Averages-Arithmetic-mean/Limbo/averages-arithmetic-mean.limbo b/Task/Averages-Arithmetic-mean/Limbo/averages-arithmetic-mean.limbo new file mode 100644 index 0000000000..a0ccb20f49 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Limbo/averages-arithmetic-mean.limbo @@ -0,0 +1,24 @@ +implement Command; + +include "sys.m"; +sys: Sys; + +include "draw.m"; + +include "sh.m"; + +init(nil: ref Draw->Context, nil: list of string) +{ + sys = load Sys Sys->PATH; + + a := array[] of {1.0, 2.0, 500.0, 257.0}; + sys->print("mean of a: %f\n", getmean(a)); +} + +getmean(a: array of real): real +{ + n: real = 0.0; + for (i := 0; i < len a; i++) + n += a[i]; + return n / (real len a); +} diff --git a/Task/Averages-Arithmetic-mean/Lingo/averages-arithmetic-mean-1.lingo b/Task/Averages-Arithmetic-mean/Lingo/averages-arithmetic-mean-1.lingo new file mode 100644 index 0000000000..fdd1342278 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Lingo/averages-arithmetic-mean-1.lingo @@ -0,0 +1,14 @@ +-- v can be (2D) point, (3D) vector or list of integers/floats +on mean (v) + case ilk(v) of + #point: cnt = 2 + #vector: cnt = 3 + #list: cnt = v.count + otherwise: return + end case + sum = 0 + repeat with i = 1 to cnt + sum = sum + v[i] + end repeat + return float(sum)/cnt +end diff --git a/Task/Averages-Arithmetic-mean/Lingo/averages-arithmetic-mean-2.lingo b/Task/Averages-Arithmetic-mean/Lingo/averages-arithmetic-mean-2.lingo new file mode 100644 index 0000000000..da91839955 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Lingo/averages-arithmetic-mean-2.lingo @@ -0,0 +1,6 @@ +put mean(point(1, 2.5)) +-- 1.7500 +put mean(vector(1.2, 4.7, 5.6)) +-- 3.8333 +put mean([6,12,18,24,30,36,42,48,54,60,66,72,78]) +-- 42.0000 diff --git a/Task/Averages-Arithmetic-mean/Oforth/averages-arithmetic-mean.oforth b/Task/Averages-Arithmetic-mean/Oforth/averages-arithmetic-mean.oforth index e6f3e8827d..6956e66f62 100644 --- a/Task/Averages-Arithmetic-mean/Oforth/averages-arithmetic-mean.oforth +++ b/Task/Averages-Arithmetic-mean/Oforth/averages-arithmetic-mean.oforth @@ -1,2 +1,4 @@ -[1, 2, 2.718, 3, 3.142] avg println -[ ] avg println +: avg ( x -- avg ) + x sum + x size dup ifZero: [ 2drop null ] else: [ >float / ] +; diff --git a/Task/Averages-Arithmetic-mean/Python/averages-arithmetic-mean-7.py b/Task/Averages-Arithmetic-mean/Python/averages-arithmetic-mean-7.py new file mode 100644 index 0000000000..1d1f73b7a7 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Python/averages-arithmetic-mean-7.py @@ -0,0 +1,10 @@ +>>> from statistics import mean +>>> mean([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]) +2.3 +>>> mean([10**10000, -10**10000, 3, 1, 4, 1, 5, 9, 0, 0]) +2.3 +>>> mean([10**10000, -10**10000, 3, 1, 4, 1, 5, 9, Fraction(1, 10**10000), Fraction(-1, 10**10000)]) +Fraction(23, 10) +>>> big = 10**10000 +>>> mean([Decimal(big), Decimal(-big), 3, 1, 4, 1, 5, 9, 1/Decimal(big), -1/Decimal(big)]) +Decimal('2.3') diff --git a/Task/Averages-Arithmetic-mean/Ruby/averages-arithmetic-mean.rb b/Task/Averages-Arithmetic-mean/Ruby/averages-arithmetic-mean.rb index 1e1b1411e9..f2b3e9f316 100644 --- a/Task/Averages-Arithmetic-mean/Ruby/averages-arithmetic-mean.rb +++ b/Task/Averages-Arithmetic-mean/Ruby/averages-arithmetic-mean.rb @@ -1,5 +1,5 @@ def mean(nums) - nums.inject(0.0, :+) / nums.size + nums.sum(0.0) / nums.size end nums = [3, 1, 4, 1, 5, 9] diff --git a/Task/Averages-Mean-angle/JavaScript/averages-mean-angle.js b/Task/Averages-Mean-angle/JavaScript/averages-mean-angle.js index e139007ef2..5d56d636e6 100644 --- a/Task/Averages-Mean-angle/JavaScript/averages-mean-angle.js +++ b/Task/Averages-Mean-angle/JavaScript/averages-mean-angle.js @@ -1,18 +1,21 @@ function sum(a) { - s = 0; - for (var i in a) s += a[i]; + var s = 0; + for (var i = 0; i < a.length; i++) s += a[i]; return s; } function degToRad(a) { - return Math.PI/180*a; + return Math.PI / 180 * a; } function meanAngleDeg(a) { - return 180/Math.PI*Math.atan2(sum(a.map(degToRad).map(Math.sin))/a.length,sum(a.map(degToRad).map(Math.cos))/a.length); + return 180 / Math.PI * Math.atan2( + sum(a.map(degToRad).map(Math.sin)) / a.length, + sum(a.map(degToRad).map(Math.cos)) / a.length + ); } -var a = [350, 10], b = [90, 180, 270, 360], c =[10, 20, 30]; +var a = [350, 10], b = [90, 180, 270, 360], c = [10, 20, 30]; console.log(meanAngleDeg(a)); console.log(meanAngleDeg(b)); console.log(meanAngleDeg(c)); diff --git a/Task/Averages-Mean-angle/Ring/averages-mean-angle.ring b/Task/Averages-Mean-angle/Ring/averages-mean-angle.ring new file mode 100644 index 0000000000..07152d44c4 --- /dev/null +++ b/Task/Averages-Mean-angle/Ring/averages-mean-angle.ring @@ -0,0 +1,37 @@ +# Project : Averages/Mean angle +# Date : 2018/01/08 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +load "stdlib.ring" +decimals(6) +pi = 3.1415926535897 +angles = [350,10] +see meanangle(angles, len(angles)) + nl +angles = [90,180,270,360] +see meanangle(angles, len(angles)) + nl +angles = [10,20,30] +see meanangle(angles, len(angles)) + nl + +func meanangle(angles, n) + sumsin = 0 + sumcos = 0 + for i = 1 to n + sumsin = sumsin + sin(angles[i]*pi/180) + sumcos = sumcos + cos(angles[i]*pi/180) + next + return 180/pi*atan3(sumsin, sumcos) + +func atan3(y,x) + if x <= 0 + return sign(y)*pi/2 + ok + if x>0 + return atan(y/x) + else + if y>0 + return atan(y/x)+pi + else + return atan(y/x)-pi + ok + ok diff --git a/Task/Averages-Mean-angle/Stata/averages-mean-angle.stata b/Task/Averages-Mean-angle/Stata/averages-mean-angle.stata index 38b1682a99..a6ebc4047d 100644 --- a/Task/Averages-Mean-angle/Stata/averages-mean-angle.stata +++ b/Task/Averages-Mean-angle/Stata/averages-mean-angle.stata @@ -1,9 +1,9 @@ mata function meanangle(a) { -return(arg(sum(exp(C(0,a))))) + return(arg(sum(exp(C(0,a))))) } -deg=acos(-1)/180 +deg=pi()/180 meanangle((350,10)*deg)/deg -1.61481e-15 diff --git a/Task/Averages-Mean-time-of-day/Java/averages-mean-time-of-day.java b/Task/Averages-Mean-time-of-day/Java/averages-mean-time-of-day.java new file mode 100644 index 0000000000..632d6b995e --- /dev/null +++ b/Task/Averages-Mean-time-of-day/Java/averages-mean-time-of-day.java @@ -0,0 +1,48 @@ +public class MeanTimeOfDay { + + static double meanAngle(double[] angles) { + int len = angles.length; + double sinSum = 0.0; + for (int i = 0; i < len; i++) { + sinSum += Math.sin(angles[i] * Math.PI / 180.0); + } + + double cosSum = 0.0; + for (int i = 0; i < len; i++) { + cosSum += Math.cos(angles[i] * Math.PI / 180.0); + } + + return Math.atan2(sinSum / len, cosSum / len) * 180.0 / Math.PI; + } + + /* time string assumed to be in format "hh:mm:ss" */ + static int timeToSecs(String t) { + int hours = Integer.parseInt(t.substring(0, 2)); + int mins = Integer.parseInt(t.substring(3, 5)); + int secs = Integer.parseInt(t.substring(6, 8)); + return 3600 * hours + 60 * mins + secs; + } + + /* 1 second of time = 360/(24 * 3600) = 1/240th degree */ + static double timeToDegrees(String t) { + return timeToSecs(t) / 240.0; + } + + static String degreesToTime(double d) { + if (d < 0.0) d += 360.0; + int secs = (int)(d * 240.0); + int hours = secs / 3600; + int mins = secs % 3600; + secs = mins % 60; + mins /= 60; + return String.format("%2d:%2d:%2d", hours, mins, secs); + } + + public static void main(String[] args) { + String[] tm = {"23:00:17", "23:40:20", "00:12:45", "00:17:19"}; + double[] angles = new double[4]; + for (int i = 0; i < 4; i++) angles[i] = timeToDegrees(tm[i]); + double mean = meanAngle(angles); + System.out.println("Average time is : " + degreesToTime(mean)); + } +} 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 new file mode 100644 index 0000000000..a7064accf8 --- /dev/null +++ b/Task/Averages-Mean-time-of-day/Julia/averages-mean-time-of-day.julia @@ -0,0 +1,18 @@ +function meantime(times::Array, dlm::String=":") + c = π / (12 * 60 * 60) + a = map(x -> parse.(Int, x), split.(times, dlm)) + ϕ = collect(3600t[1] + 60t[2] + t[3] for t in a) + d = angle(mean(exp.(c * im * ϕ))) / 2π # days + if d < 0 d += 1 end + # Convert to h:m:s + h = trunc(Int, d * 24) + m = trunc(Int, d * 24 * 60) - h * 60 + s = trunc(Int, d * 24 * 60 * 60) - h * 60 * 60 - m * 60 + return "$h:$m:$s" +end + +times = String["23:00:17", "23:40:20", "00:12:45", "00:17:19"] +mtime = meantime(times) +println("Times:") +println.(times) +println("Mean: $mtime") diff --git a/Task/Averages-Mean-time-of-day/Lua/averages-mean-time-of-day.lua b/Task/Averages-Mean-time-of-day/Lua/averages-mean-time-of-day.lua new file mode 100644 index 0000000000..3657466b9c --- /dev/null +++ b/Task/Averages-Mean-time-of-day/Lua/averages-mean-time-of-day.lua @@ -0,0 +1,34 @@ +local times = {"23:00:17","23:40:20","00:12:45","00:17:19"} + +-- returns time converted to a radian format +local function timeToAngle(str) + local h,m,s = str:match("(..):(..):(..)") + return (h + m / 60 + s / 3600)/12 * math.pi +end + +-- computes the mean of the angles inside a list +local function meanAngle(angles) + local sumSin,sumCos = 0,0 + for k,v in pairs(angles) do + sumSin = sumSin + math.sin(v) + sumCos = sumCos + math.cos(v) + end + return math.atan2(sumSin,sumCos) +end + +-- converts and angle back to a time string +local function angleToTime(angle) + local abs = angle % (math.pi * 2) + local time = abs / math.pi * 12 + local h = math.floor(time) + local m = math.floor(time * 60) % 60 + local s = math.floor(time * 3600) % 60 + return string.format("%02d:%02d:%02d", h, m, s) +end + +-- convert times to angles +for k,v in pairs(times) do + times[k] = timeToAngle(v) +end + +print(angleToTime(meanAngle(times))) diff --git a/Task/Averages-Median/BaCon/averages-median.bacon b/Task/Averages-Median/BaCon/averages-median.bacon new file mode 100644 index 0000000000..86e5f66e6c --- /dev/null +++ b/Task/Averages-Median/BaCon/averages-median.bacon @@ -0,0 +1,12 @@ +DECLARE a[] = { 4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2 } TYPE FLOATING +DECLARE b[] = { 4.1, 7.2, 1.7, 9.3, 4.4, 3.2 } TYPE FLOATING + +DEF FN Dim(x) = SIZEOF(x) / SIZEOF(double) + +DEF FN Median(x) = IIF(ODD(Dim(x)), x[(Dim(x)-1)/2], (x[Dim(x)/2-1]+x[Dim(x)/2])/2 ) + +SORT a +PRINT "Median of a: ", Median(a) + +SORT b +PRINT "Median of b: ", Median(b) diff --git a/Task/Averages-Median/Elena/averages-median.elena b/Task/Averages-Median/Elena/averages-median.elena index 7f1c9daec9..bef896f86a 100644 --- a/Task/Averages-Median/Elena/averages-median.elena +++ b/Task/Averages-Median/Elena/averages-median.elena @@ -20,7 +20,7 @@ extension op ] } -program = +public program = [ var a1 := (4.1r, 5.6r, 7.2r, 1.7r, 9.3r, 4.4r, 3.2r). var a2 := (4.1r, 7.2r, 1.7r, 9.3r, 4.4r, 3.2r). diff --git a/Task/Averages-Median/Go/averages-median.go b/Task/Averages-Median/Go/averages-median-1.go similarity index 100% rename from Task/Averages-Median/Go/averages-median.go rename to Task/Averages-Median/Go/averages-median-1.go diff --git a/Task/Averages-Median/Go/averages-median-2.go b/Task/Averages-Median/Go/averages-median-2.go new file mode 100644 index 0000000000..c009c9ae1b --- /dev/null +++ b/Task/Averages-Median/Go/averages-median-2.go @@ -0,0 +1,31 @@ +package main + +import "fmt" + +func main() { + fmt.Println(median([]float64{3, 1, 4, 1})) // prints 2 + fmt.Println(median([]float64{3, 1, 4, 1, 5})) // prints 3 +} + +func median(a []float64) float64 { + half := len(a) / 2 + med := sel(a, half) + if len(a)%2 == 0 { + return (med + a[half-1]) / 2 + } + return med +} + +func sel(list []float64, k int) float64 { + for i, minValue := range list[:k+1] { + minIndex := i + for j := i + 1; j < len(list); j++ { + if list[j] < minValue { + minIndex = j + minValue = list[j] + list[i], list[minIndex] = minValue, list[i] + } + } + } + return list[k] +} diff --git a/Task/Averages-Median/Go/averages-median-3.go b/Task/Averages-Median/Go/averages-median-3.go new file mode 100644 index 0000000000..546f8c9dd9 --- /dev/null +++ b/Task/Averages-Median/Go/averages-median-3.go @@ -0,0 +1,52 @@ +package main + +import ( + "fmt" + "math/rand" +) + +func main() { + fmt.Println(median([]float64{3, 1, 4, 1})) // prints 2 + fmt.Println(median([]float64{3, 1, 4, 1, 5})) // prints 3 +} + +func median(list []float64) float64 { + half := len(list) / 2 + med := qsel(list, half) + if len(list)%2 == 0 { + return (med + qsel(list, half-1)) / 2 + } + return med +} + +func qsel(a []float64, k int) float64 { + for len(a) > 1 { + px := rand.Intn(len(a)) + pv := a[px] + last := len(a) - 1 + a[px], a[last] = a[last], pv + px = 0 + for i, v := range a[:last] { + if v < pv { + a[px], a[i] = v, a[px] + px++ + } + } + if px == k { + return pv + } + if k < px { + a = a[:px] + } else { + // swap elements. simply assigning a[last] would be enough to + // allow qsel to return the correct result but it would leave slice + // "a" unusable for subsequent use. we want this full swap so that + // we can make two successive qsel calls in the case of median + // of an even number of elements. + a[px], a[last] = pv, a[px] + a = a[px+1:] + k -= px + 1 + } + } + return a[0] +} diff --git a/Task/Averages-Median/Lingo/averages-median.lingo b/Task/Averages-Median/Lingo/averages-median.lingo new file mode 100644 index 0000000000..d4e1475977 --- /dev/null +++ b/Task/Averages-Median/Lingo/averages-median.lingo @@ -0,0 +1,9 @@ +on median (numlist) + -- numlist = numlist.duplicate() -- if input list should not be altered + numlist.sort() + if numlist.count mod 2 then + return numlist[numlist.count/2+1] + else + return (numlist[numlist.count/2]+numlist[numlist.count/2+1])/2.0 + end if +end diff --git a/Task/Averages-Median/REXX/averages-median.rexx b/Task/Averages-Median/REXX/averages-median.rexx index a706567eb3..94be0cc0db 100644 --- a/Task/Averages-Median/REXX/averages-median.rexx +++ b/Task/Averages-Median/REXX/averages-median.rexx @@ -1,25 +1,24 @@ /*REXX program finds the median of a vector (and displays the vector and median).*/ /* ══════════vector════════════ ══show vector═══ ════════show result═══════════ */ - v= '1 9 2 4 '; say 'vector:' v; say 'median──────►' median(v); say - v= '3 1 4 1 5 9 7 6 '; say 'vector:' v; say 'median──────►' median(v); say + v= 1 9 2 4 ; say 'vector:' v; say 'median──────►' median(v); say + v= 3 1 4 1 5 9 7 6 ; say 'vector:' v; say 'median──────►' median(v); say v= '3 4 1 -8.4 7.2 4 1 1.2'; say 'vector:' v; say 'median──────►' median(v); say - v= '-1.2345678e99 2.3e700'; say 'vector:' v; say 'median──────►' median(v); say + v= -1.2345678e99 2.3e700 ; say 'vector:' v; say 'median──────►' median(v); say exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -eSORT: procedure expose @. #; parse arg $; #=words($) /*$: is the vector. */ - do g=1 for #; @.g=word($,g); end /*g*/ /*convert list──►array*/ +eSORT: procedure expose @. #; parse arg $; #=words($) /*$: is the vector. */ + do g=1 for #; @.g=word($, g); end /*g*/ /*convert list──►array*/ h=# /*#: number elements.*/ do while h>1; h=h % 2 /*cut entries by half.*/ - do i=1 for #-h; j=i; k=h+i /*sort lower section. */ + do i=1 for #-h; j=i; k=h + i /*sort lower section. */ do while @.k<@.j; parse value @.j @.k with @.k @.j /*swap.*/ - if h>=j then leave; j=j-h; k=k-h /*diminish J and K.*/ + if h>=j then leave; j=j - h; k=k - h /*diminish J and K.*/ end /*while @.k<@.j*/ end /*i*/ - end /*while h>l*/ /*end of exchange sort*/ + end /*while h>1*/ /*end of exchange sort*/ return /*──────────────────────────────────────────────────────────────────────────────────────*/ -median: procedure; call eSORT arg(1) /*obtain the elements of the vector.*/ - m=# % 2 /* % is REXX's integer division.*/ - n=m+1 /*N: the next element after M. */ - if #//2 then return @.n /*(odd?) // is REXX's ÷ remainder.*/ - return (@.m + @.n) / 2 /*process an even─element vector. */ +median: procedure; call eSORT arg(1); m=# % 2 /* % is REXX's integer division.*/ + n=m + 1 /*N: the next element after M. */ + if # // 2 then return @.n /*[odd?] // ◄───REXX's ÷ remainder*/ + return (@.m + @.n) / 2 /*process an even─element vector. */ diff --git a/Task/Averages-Mode/Elena/averages-mode.elena b/Task/Averages-Mode/Elena/averages-mode.elena index c79956657d..65ebd78cf5 100644 --- a/Task/Averages-Mode/Elena/averages-mode.elena +++ b/Task/Averages-Mode/Elena/averages-mode.elena @@ -6,24 +6,24 @@ extension op { mode [ - var aCountMap := Dictionary new default:0. + var aCountMap := Dictionary new(0). self forEach(:anItem) [ aCountMap[anItem] := aCountMap[anItem] + 1 ]. - aCountMap := aCountMap array_list; sort(:p:n)(p > n). + aCountMap := aCountMap values; sort(:p:n)(p > n). var aMax := aCountMap firstMember. ^ aCountMap - filterBy(:kv)(aMax equal:kv); + filterBy(:kv)(aMax equal(kv value)); selectBy(:kv)(kv key); toArray. ] } -program = +public program = [ var anArray1 := (1, 1, 2, 4, 4). var anArray2 := (1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17). diff --git a/Task/Averages-Mode/Perl-6/averages-mode-1.pl6 b/Task/Averages-Mode/Perl-6/averages-mode-1.pl6 index 719fb56dab..7d8baf2a65 100644 --- a/Task/Averages-Mode/Perl-6/averages-mode-1.pl6 +++ b/Task/Averages-Mode/Perl-6/averages-mode-1.pl6 @@ -3,3 +3,7 @@ sub mode (*@a) { my $max = %counts.values.max; return |%counts.grep(*.value == $max).map(*.key); } + +# Testing with arrays: +say mode [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]; +say mode [1, 1, 2, 4, 4]; diff --git a/Task/Averages-Mode/Perl-6/averages-mode-2.pl6 b/Task/Averages-Mode/Perl-6/averages-mode-2.pl6 index 7dfa7161fa..3c2fe3bfaf 100644 --- a/Task/Averages-Mode/Perl-6/averages-mode-2.pl6 +++ b/Task/Averages-Mode/Perl-6/averages-mode-2.pl6 @@ -1,2 +1,11 @@ +sub mode (*@a) { + return |(@a + .Bag # count elements + .classify(*.value) # group elements with the same count + .max(*.key) # get group with the highest count + .value.map(*.key); # get elements in the group + ); +} + say mode [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]; say mode [1, 1, 2, 4, 4]; diff --git a/Task/Averages-Mode/Ring/averages-mode.ring b/Task/Averages-Mode/Ring/averages-mode.ring new file mode 100644 index 0000000000..bfe7725803 --- /dev/null +++ b/Task/Averages-Mode/Ring/averages-mode.ring @@ -0,0 +1,45 @@ +# Project : Averages/Mode +# Date : 2018/04/11 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +a = [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17] +b = [1, 2, 4, 4, 1] +amodes = list(12) +see "mode(s) of a() = " + nl +for i1 = 1 to modes(a,amodes) + see "" + amodes[i1] + " " +next +see nl +see "mode(s) of b() = " + nl +for i1 = 1 to modes(b,amodes) + see "" + amodes [i1] + " " +next +see nl + +func modes(a,amodes) + max = 0 + n = len(a) + if n = 0 + amodes[1] = a[1] + return 1 + ok + c = list(n) + for i = 1 to n + for j = i+1 to n + if a[i] = a[j] + c[i] = c[i] + 1 + ok + next + if c[i] > max + max = c[i] + ok + next + j = 0 + for i = 1 to n + if c[i] = max + j = j + 1 + amodes[j] = a[i] + ok + next + return j diff --git a/Task/Averages-Pythagorean-means/Modula-2/averages-pythagorean-means.mod2 b/Task/Averages-Pythagorean-means/Modula-2/averages-pythagorean-means.mod2 new file mode 100644 index 0000000000..905c694310 --- /dev/null +++ b/Task/Averages-Pythagorean-means/Modula-2/averages-pythagorean-means.mod2 @@ -0,0 +1,79 @@ +MODULE PythagoreanMeans; +FROM FormatString IMPORT FormatString; +FROM LongMath IMPORT power; +FROM LongStr IMPORT RealToStr; +FROM Terminal IMPORT WriteString,WriteLn,ReadChar; + +PROCEDURE ArithmeticMean(numbers : ARRAY OF LONGREAL) : LONGREAL; +VAR + i,cnt : CARDINAL; + mean : LONGREAL; +BEGIN + mean := 0.0; + cnt := 0; + FOR i:=0 TO HIGH(numbers) DO + mean := mean + numbers[i]; + INC(cnt); + END; + RETURN mean / LFLOAT(cnt) +END ArithmeticMean; + +PROCEDURE GeometricMean(numbers : ARRAY OF LONGREAL) : LONGREAL; +VAR + i,cnt : CARDINAL; + mean : LONGREAL; +BEGIN + mean := 1.0; + cnt := 0; + FOR i:=0 TO HIGH(numbers) DO + mean := mean * numbers[i]; + INC(cnt); + END; + RETURN power(mean, 1.0 / LFLOAT(cnt)) +END GeometricMean; + +PROCEDURE HarmonicMean(numbers : ARRAY OF LONGREAL) : LONGREAL; +VAR + i,cnt : CARDINAL; + mean : LONGREAL; +BEGIN + mean := 0.0; + cnt := 0; + FOR i:=0 TO HIGH(numbers) DO + mean := mean + ( 1.0 / numbers[i]); + INC(cnt); + END; + RETURN LFLOAT(cnt) / mean +END HarmonicMean; + + +CONST Size = 10; +TYPE DA = ARRAY[1..Size] OF LONGREAL; + +VAR + buf : ARRAY[0..63] OF CHAR; + array : DA; + arithmetic,geometric,harmonic : LONGREAL; +BEGIN + array := DA{1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0}; + + arithmetic := ArithmeticMean(array); + geometric := GeometricMean(array); + harmonic := HarmonicMean(array); + + WriteString("A = "); + RealToStr(arithmetic, buf); + WriteString(buf); + WriteString(" G = "); + RealToStr(geometric, buf); + WriteString(buf); + WriteString(" H = "); + RealToStr(harmonic, buf); + WriteString(buf); + WriteLn; + + FormatString("A >= G is %b, G >= H is %b\n", buf, arithmetic >= geometric, geometric >= harmonic); + WriteString(buf); + + ReadChar +END PythagoreanMeans. diff --git a/Task/Averages-Pythagorean-means/Oforth/averages-pythagorean-means.oforth b/Task/Averages-Pythagorean-means/Oforth/averages-pythagorean-means.oforth index c061f928b9..5f3542aac7 100644 --- a/Task/Averages-Pythagorean-means/Oforth/averages-pythagorean-means.oforth +++ b/Task/Averages-Pythagorean-means/Oforth/averages-pythagorean-means.oforth @@ -1,9 +1,17 @@ -: A(l) l avg ; -: G(l) l prod l size inv powf ; -: H(l) l size l map(#inv) sum / ; +import: mapping + +: A ( x ) + x sum + x size dup ifZero: [ 2drop null ] else: [ >float / ] +; + +: G( x ) #* x reduce x size inv powf ; + +: H( x ) x size x map( #inv ) sum / ; : averages | g | - "Geometric mean :" . G(10 seq) dup .cr ->g - "Arithmetic mean :" . A(10 seq) dup . g >= ifTrue: [ " ==> A >= G" .cr ] - "Harmonic mean :" . H(10 seq) dup . g <= ifTrue: [ " ==> G >= H" .cr ] ; + "Geometric mean :" . 10 seq G dup .cr ->g + "Arithmetic mean :" . 10 seq A dup . g >= ifTrue: [ " ==> A >= G" .cr ] + "Harmonic mean :" . 10 seq H dup . g <= ifTrue: [ " ==> G >= H" .cr ] +; diff --git a/Task/Averages-Root-mean-square/Astro/averages-root-mean-square.astro b/Task/Averages-Root-mean-square/Astro/averages-root-mean-square.astro index 2e171c44c5..81edcd4b7d 100644 --- a/Task/Averages-Root-mean-square/Astro/averages-root-mean-square.astro +++ b/Task/Averages-Root-mean-square/Astro/averages-root-mean-square.astro @@ -1 +1 @@ -fun rootMeanSq(l): sqrt(mean(l²)) +sqrt(mean(x²)) diff --git a/Task/Averages-Root-mean-square/Elena/averages-root-mean-square.elena b/Task/Averages-Root-mean-square/Elena/averages-root-mean-square.elena new file mode 100644 index 0000000000..0529e3112f --- /dev/null +++ b/Task/Averages-Root-mean-square/Elena/averages-root-mean-square.elena @@ -0,0 +1,16 @@ +import extensions. +import system'routines. +import system'math. + +extension op +{ + rootMeanSquare + [ + ^ (self selectBy(:x)(x * x); summarize(Real new) / self length) sqrt. + ] +} + +public program = +[ + console printLine(Range new(1, 10); rootMeanSquare) +]. diff --git a/Task/Averages-Root-mean-square/Shen/averages-root-mean-square.shen b/Task/Averages-Root-mean-square/Shen/averages-root-mean-square.shen new file mode 100644 index 0000000000..f58d1d3b5f --- /dev/null +++ b/Task/Averages-Root-mean-square/Shen/averages-root-mean-square.shen @@ -0,0 +1,26 @@ +(declare scm.sqrt [number --> number]) + +(tc +) + +(define mean + { (list number) --> number } + Xs -> (/ (sum Xs) (length Xs))) + +(define square + { number --> number } + X -> (* X X)) + +(define rms + { (list number) --> number } + Xs -> (scm.sqrt (mean (map (function square) Xs)))) + +(define iota-h + { number --> number --> (list number) } + X X -> [X] + X Lim -> (cons X (iota-h (+ X 1) Lim))) + +(define iota + { number --> (list number) } + Lim -> (iota-h 1 Lim)) + +(output "~A~%" (rms (iota 10))) diff --git a/Task/Averages-Root-mean-square/Sidef/averages-root-mean-square.sidef b/Task/Averages-Root-mean-square/Sidef/averages-root-mean-square-1.sidef similarity index 100% rename from Task/Averages-Root-mean-square/Sidef/averages-root-mean-square.sidef rename to Task/Averages-Root-mean-square/Sidef/averages-root-mean-square-1.sidef diff --git a/Task/Averages-Root-mean-square/Sidef/averages-root-mean-square-2.sidef b/Task/Averages-Root-mean-square/Sidef/averages-root-mean-square-2.sidef new file mode 100644 index 0000000000..27f868dffd --- /dev/null +++ b/Task/Averages-Root-mean-square/Sidef/averages-root-mean-square-2.sidef @@ -0,0 +1 @@ +func rms(a) { a »**» 2 «+» / a.len -> sqrt } diff --git a/Task/Averages-Root-mean-square/Stata/averages-root-mean-square-1.stata b/Task/Averages-Root-mean-square/Stata/averages-root-mean-square-1.stata new file mode 100644 index 0000000000..31a09fb1c0 --- /dev/null +++ b/Task/Averages-Root-mean-square/Stata/averages-root-mean-square-1.stata @@ -0,0 +1,7 @@ +program rms, rclass + syntax varname(numeric) [if] [in] + tempvar x + gen `x'=`varlist'^2 `if' `in' + qui sum `x' `if' `in' + return scalar rms=sqrt(r(mean)) +end diff --git a/Task/Averages-Root-mean-square/Stata/averages-root-mean-square-2.stata b/Task/Averages-Root-mean-square/Stata/averages-root-mean-square-2.stata new file mode 100644 index 0000000000..d6f163e6c2 --- /dev/null +++ b/Task/Averages-Root-mean-square/Stata/averages-root-mean-square-2.stata @@ -0,0 +1,11 @@ +clear +set obs 20 +gen x=rnormal() + +rms x +di r(rms) +1.0394189 + +rms x if x>0 +di r(rms) +.7423647 diff --git a/Task/Averages-Simple-moving-average/Elena/averages-simple-moving-average.elena b/Task/Averages-Simple-moving-average/Elena/averages-simple-moving-average.elena index 6d7f51d50d..ba40125915 100644 --- a/Task/Averages-Simple-moving-average/Elena/averages-simple-moving-average.elena +++ b/Task/Averages-Simple-moving-average/Elena/averages-simple-moving-average.elena @@ -23,19 +23,19 @@ class SMA ! [ if (aCount > thePeriod) [ - theList remove at:0. + theList removeAt:0. aCount := thePeriod ]. - var aSum := theList summarize(Real new int:0). + var aSum := theList summarize(Real new). ^ aSum / aCount ] ] } -program = +public program = [ var SMA3 := SMA new:3. var SMA5 := SMA new:5. 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 new file mode 100644 index 0000000000..691844d737 --- /dev/null +++ b/Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average.julia @@ -0,0 +1,22 @@ +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/Perl-6/averages-simple-moving-average.pl6 b/Task/Averages-Simple-moving-average/Perl-6/averages-simple-moving-average.pl6 new file mode 100644 index 0000000000..1021cc1cf1 --- /dev/null +++ b/Task/Averages-Simple-moving-average/Perl-6/averages-simple-moving-average.pl6 @@ -0,0 +1,14 @@ +sub sma-generator (Int $P where * > 0) { + sub ($x) { + state @a = 0 xx $P; + @a.push($x).shift; + @a.sum / $P; + } +} + +# Usage: +my &sma = sma-generator 3; + +for 1, 2, 3, 2, 7 { + printf "append $_ --> sma = %.2f (with period 3)\n", sma $_; +} diff --git a/Task/Balanced-brackets/00DESCRIPTION b/Task/Balanced-brackets/00DESCRIPTION index 23eb9aeafe..f9c4eb9536 100644 --- a/Task/Balanced-brackets/00DESCRIPTION +++ b/Task/Balanced-brackets/00DESCRIPTION @@ -5,8 +5,11 @@ ;Examples: - (empty) OK - [] OK ][ NOT OK - [][] OK ][][ NOT OK - [[][]] OK []][[] NOT OK + (empty) OK + [] OK + [][] OK + [[][]] OK + ][ NOT OK + ][][ NOT OK + []][[] NOT OK

diff --git a/Task/Balanced-brackets/ARM-Assembly/balanced-brackets.arm b/Task/Balanced-brackets/ARM-Assembly/balanced-brackets.arm new file mode 100644 index 0000000000..7e6603e5da --- /dev/null +++ b/Task/Balanced-brackets/ARM-Assembly/balanced-brackets.arm @@ -0,0 +1,58 @@ +.data + +balanced_message: + .ascii "OK\n" + +unbalanced_message: + .ascii "NOT OK\n" + + +.text + +.equ balanced_msg_len, 3 +.equ unbalanced_msg_len, 7 + + +BalancedBrackets: + + mov r1, #0 + mov r2, #0 + mov r3, #0 + + process_bracket: + ldrb r2, [r0, r1] + + cmp r2, #0 + beq evaluate_balance + + cmp r2, #'[' + addeq r3, r3, #1 + + cmp r2, #']' + subeq r3, r3, #1 + + cmp r3, #0 + blt unbalanced + + add r1, r1, #1 + b process_bracket + + evaluate_balance: + cmp r3, #0 + beq balanced + + unbalanced: + ldr r1, =unbalanced_message + mov r2, #unbalanced_msg_len + b display_result + + balanced: + ldr r1, =balanced_message + mov r2, #balanced_msg_len + + display_result: + mov r7, #4 + mov r0, #1 + svc #0 + + mov pc, lr diff --git a/Task/Balanced-brackets/BASIC/balanced-brackets.basic b/Task/Balanced-brackets/BASIC/balanced-brackets-1.basic similarity index 100% rename from Task/Balanced-brackets/BASIC/balanced-brackets.basic rename to Task/Balanced-brackets/BASIC/balanced-brackets-1.basic diff --git a/Task/Balanced-brackets/BASIC/balanced-brackets-2.basic b/Task/Balanced-brackets/BASIC/balanced-brackets-2.basic new file mode 100644 index 0000000000..df97553c1f --- /dev/null +++ b/Task/Balanced-brackets/BASIC/balanced-brackets-2.basic @@ -0,0 +1,21 @@ +10 PRINT CHR$(147): REM CLEAR SCREEN +20 FOR N=1 TO 7 +30 READ S$ +40 IF S$="" THEN PRINT"(EMPTY)";: GOTO 60 +50 PRINT S$; +60 PRINT TAB(20); +70 GOSUB 1000 +80 NEXT N +90 END +100 REM ******************************** +1000 S = 0 +1010 FOR K=1 TO LEN(S$) +1020 C$ = MID$(S$,K,1) +1030 IF C$="[" THEN S = S+1 +1040 IF C$="]" THEN S = S-1 +1050 IF S<0 THEN PRINT "NOT OK": RETURN +1060 NEXT K +1070 IF S=0 THEN PRINT "OK": RETURN +1090 PRINT "NOT OK" +1100 RETURN +2000 DATA , [], ][, [][], ][][, [[][]], []][[] diff --git a/Task/Balanced-brackets/Elena/balanced-brackets.elena b/Task/Balanced-brackets/Elena/balanced-brackets.elena index 8ad617b5d5..3ae169e2bf 100644 --- a/Task/Balanced-brackets/Elena/balanced-brackets.elena +++ b/Task/Balanced-brackets/Elena/balanced-brackets.elena @@ -1,21 +1,22 @@ import system'routines. import extensions. +import extensions'text. randomBrackets = { new : aLength [ if (0 == aLength) - [ ^emptyLiteralValue ]; + [ ^emptyLiteral ]; [ var aBrackets := - Array new length:(aLength int); populate(:i)($91) + Array new(aLength); populate(:i)($91) + - Array new length:(aLength int); populate(:i)($93). + Array new(aLength); populate(:i)($93). aBrackets := aBrackets randomize:(aLength * 2). - ^ aBrackets summarize:(String new); literal + ^ aBrackets summarize:(StringWriter new); toLiteral ] ] }. @@ -32,7 +33,7 @@ extension op ] } -program = +public program = [ 0 to:9 do(:aLength) [ diff --git a/Task/Balanced-brackets/Julia/balanced-brackets-1.julia b/Task/Balanced-brackets/Julia/balanced-brackets-1.julia index 6bac68cc9c..80b7e622b9 100644 --- a/Task/Balanced-brackets/Julia/balanced-brackets-1.julia +++ b/Task/Balanced-brackets/Julia/balanced-brackets-1.julia @@ -1,12 +1,14 @@ -function balanced(str) - i = 0 - for c in str - if c == '[' i +=1 elseif c == ']' i -=1 end - if i < 0 return false end - end - i == 0 ? true : false +function balancedbrackets(str::AbstractString) + i = 0 + for c in str + if c == '[' i += 1 elseif c == ']' i -=1 end + if i < 0 return false end + end + return i == 0 end -brackets(n) = join(shuffle([("[]"^n)...])) +brackets(n::Integer) = join(shuffle(collect(Char, "[]" ^ n))) -map(x -> (x, balanced(x)), [brackets(i) for i = 0:8]) +for (test, pass) in map(x -> (x, balancedbrackets(x)), collect(brackets(i) for i = 0:8)) + @printf("%22s%10s\n", test, pass ? "pass" : "fail") +end diff --git a/Task/Balanced-brackets/Julia/balanced-brackets-2.julia b/Task/Balanced-brackets/Julia/balanced-brackets-2.julia index 2beba0cc23..e4ae6d270c 100644 --- a/Task/Balanced-brackets/Julia/balanced-brackets-2.julia +++ b/Task/Balanced-brackets/Julia/balanced-brackets-2.julia @@ -1 +1 @@ -balanced(str) = foldl((x,y)->x<0? -1: x+y, 0, [(x=='[')-(x==']') for x=str])==0 +balancedbrackets(str::AbstractString) = foldl((x, y) -> x < 0 ? -1 : x + y, 0, collect((x == '[') - (x == ']') for x in str)) == 0 diff --git a/Task/Balanced-brackets/Perl-6/balanced-brackets-2.pl6 b/Task/Balanced-brackets/Perl-6/balanced-brackets-2.pl6 index 9195dffad8..098771141f 100644 --- a/Task/Balanced-brackets/Perl-6/balanced-brackets-2.pl6 +++ b/Task/Balanced-brackets/Perl-6/balanced-brackets-2.pl6 @@ -1,6 +1,6 @@ sub balanced($s) { .none < 0 and .[*-1] == 0 - given [\+] '\\' «leg« $s.comb; + given ([\+] '\\' «leg« $s.comb).cache; } my $n = prompt "Number of bracket pairs: "; diff --git a/Task/Balanced-brackets/Python/balanced-brackets.py b/Task/Balanced-brackets/Python/balanced-brackets-1.py similarity index 100% rename from Task/Balanced-brackets/Python/balanced-brackets.py rename to Task/Balanced-brackets/Python/balanced-brackets-1.py diff --git a/Task/Balanced-brackets/Python/balanced-brackets-2.py b/Task/Balanced-brackets/Python/balanced-brackets-2.py new file mode 100644 index 0000000000..b4b140e448 --- /dev/null +++ b/Task/Balanced-brackets/Python/balanced-brackets-2.py @@ -0,0 +1,24 @@ +>>> from itertools import accumulate +>>> from random import shuffle +>>> def gen(n): +... txt = list('[]' * n) +... shuffle(txt) +... return ''.join(txt) +... +>>> def balanced(txt): +... brackets = ({'[': 1, ']': -1}.get(ch, 0) for ch in txt) +... return all(x>=0 for x in accumulate(brackets)) +... +>>> for txt in (gen(N) for N in range(10)): +... print ("%-22r is%s balanced" % (txt, '' if balanced(txt) else ' not')) +... +'' is balanced +'][' is not balanced +'[]][' is not balanced +']][[[]' is not balanced +'][[][][]' is not balanced +'[[[][][]]]' is balanced +'][[[][][]][]' is not balanced +'][]][][[]][[][' is not balanced +'][[]]][][[]][[[]' is not balanced +'][[][[]]]][[[]][][' is not balanced diff --git a/Task/Balanced-brackets/Python/balanced-brackets-3.py b/Task/Balanced-brackets/Python/balanced-brackets-3.py new file mode 100644 index 0000000000..6ebc310636 --- /dev/null +++ b/Task/Balanced-brackets/Python/balanced-brackets-3.py @@ -0,0 +1,25 @@ +>>> import numpy as np +>>> from random import shuffle +>>> def gen(n): +... txt = list('[]' * n) +... shuffle(txt) +... return ''.join(txt) +... +>>> m = np.array([{'[': 1, ']': -1}.get(chr(c), 0) for c in range(128)]) +>>> def balanced(txt): +... a = np.array(txt, 'c').view(np.uint8) +... return np.all(m[a].cumsum() >= 0) +... +>>> for txt in (gen(N) for N in range(10)): +... print ("%-22r is%s balanced" % (txt, '' if balanced(txt) else ' not')) +... +'' is balanced +'][' is not balanced +'[[]]' is balanced +'[]][][' is not balanced +']][]][[[' is not balanced +'[[]][[][]]' is balanced +'[][[]][[]]][' is not balanced +'[][[[]][[]]][]' is balanced +'[[][][[]]][[[]]]' is balanced +'][]][][[]][]][][[[' is not balanced diff --git a/Task/Balanced-brackets/R/balanced-brackets-3.r b/Task/Balanced-brackets/R/balanced-brackets-3.r index 044416269f..927b3c7bfa 100644 --- a/Task/Balanced-brackets/R/balanced-brackets-3.r +++ b/Task/Balanced-brackets/R/balanced-brackets-3.r @@ -1,4 +1,4 @@ -rand.parens <- function(n) paste(permute(c(rep('[',n),rep(']',n))),collapse="") +rand.parens <- function(n) paste(sample(c("[","]"),2*n,replace=T),collapse="") as.data.frame(within(list(), { parens <- replicate(10, rand.parens(sample.int(10,size=1))) diff --git a/Task/Balanced-brackets/Red/balanced-brackets.red b/Task/Balanced-brackets/Red/balanced-brackets.red new file mode 100644 index 0000000000..a5fc247878 --- /dev/null +++ b/Task/Balanced-brackets/Red/balanced-brackets.red @@ -0,0 +1,22 @@ +; Functional code +balanced-brackets: [#"[" any balanced-brackets #"]"] +rule: [any balanced-brackets end] +balanced?: func [str][parse str rule] + +; Tests +tests: [ + good: ["" "[]" "[][]" "[[]]" "[[][]]" "[[[[[]]][][[]]]]"] + bad: ["[" "]" "][" "[[]" "[]]" "[]][[]" "[[[[[[]]]]]]]"] +] + +foreach str tests/good [ + if not balanced? str [print [mold str "failed!"]] +] +foreach str tests/bad [ + if balanced? str [print [mold str "failed!"]] +] + +repeat i 10 [ + str: random copy/part "[][][][][][][][][][]" i * 2 + print [mold str "is" either balanced? str ["balanced"]["unbalanced"]] +] diff --git a/Task/Balanced-brackets/Stata/balanced-brackets.stata b/Task/Balanced-brackets/Stata/balanced-brackets.stata new file mode 100644 index 0000000000..ce238f97e3 --- /dev/null +++ b/Task/Balanced-brackets/Stata/balanced-brackets.stata @@ -0,0 +1,12 @@ +mata +function random_brackets(n) { + return(invtokens(("[","]")[runiformint(1,2*n,1,2)],"")) +} + +function is_balanced(s) { + n = strlen(s) + if (n==0) return(1) + a = runningsum(92:-ascii(s)) + return(all(a:>=0) & a[n]==0) +} +end diff --git a/Task/Balanced-brackets/Visual-Basic-.NET/balanced-brackets.visual b/Task/Balanced-brackets/Visual-Basic-.NET/balanced-brackets.visual new file mode 100644 index 0000000000..9dcad1be26 --- /dev/null +++ b/Task/Balanced-brackets/Visual-Basic-.NET/balanced-brackets.visual @@ -0,0 +1,44 @@ +Module Module1 + + Private rand As New Random + + Sub Main() + For numInputs As Integer = 1 To 10 '10 is the number of bracket sequences to test. + Dim input As String = GenerateBrackets(rand.Next(0, 5)) '5 represents the number of pairs of brackets (n) + Console.WriteLine(String.Format("{0} : {1}", input.PadLeft(10, CChar(" ")), If(IsBalanced(input) = True, "OK", "NOT OK"))) + Next + Console.ReadLine() + End Sub + + Private Function GenerateBrackets(n As Integer) As String + + Dim randomString As String = "" + Dim numOpen, numClosed As Integer + + Do Until numOpen = n And numClosed = n + If rand.Next(0, 501) Mod 2 = 0 AndAlso numOpen < n Then + randomString = String.Format("{0}{1}", randomString, "[") + numOpen += 1 + ElseIf rand.Next(0, 501) Mod 2 <> 0 AndAlso numClosed < n Then + randomString = String.Format("{0}{1}", randomString, "]") + numClosed += 1 + End If + Loop + Return randomString + End Function + + Private Function IsBalanced(brackets As String) As Boolean + + Dim numOpen As Integer = 0 + Dim numClosed As Integer = 0 + + For Each character As Char In brackets + If character = "["c Then numOpen += 1 + If character = "]"c Then + numClosed += 1 + If numClosed > numOpen Then Return False + End If + Next + Return numOpen = numClosed + End Function +End Module diff --git a/Task/Balanced-brackets/X86-Assembly/balanced-brackets.x86 b/Task/Balanced-brackets/X86-Assembly/balanced-brackets.x86 new file mode 100644 index 0000000000..35879ada08 --- /dev/null +++ b/Task/Balanced-brackets/X86-Assembly/balanced-brackets.x86 @@ -0,0 +1,66 @@ +section .data + +MsgBalanced: db "OK", 10 +MsgBalancedLen: equ 3 + +MsgUnbalanced: db "NOT OK", 10 +MsgUnbalancedLen: equ 7 + +MsgBadInput: db "BAD INPUT", 10 +MsgBadInputLen: equ 10 + +Open: equ '[' +Closed: equ ']' + +section .text + +BalancedBrackets: + + xor rcx, rcx + mov rsi, rdi + cld + + processBracket: + lodsb + cmp al, 0 + je determineBalance + + cmp al, Open + je processOpenBracket + + cmp al, Closed + je processClosedBracket + + mov rsi, MsgBadInput + mov rdx, MsgBadInputLen + jmp displayResult + + processOpenBracket: + add rcx, 1 + jmp processBracket + + processClosedBracket: + cmp rcx, 0 + je unbalanced + + sub rcx, 1 + jmp processBracket + + + determineBalance: + cmp rcx, 0 + jne unbalanced + + mov rsi, MsgBalanced + mov rdx, MsgBalancedLen + jmp displayResult + + unbalanced: + mov rsi, MsgUnbalanced + mov rdx, MsgUnbalancedLen + + displayResult: + mov rax, 1 + mov rdi, 1 + syscall + ret diff --git a/Task/Balanced-ternary/00DESCRIPTION b/Task/Balanced-ternary/00DESCRIPTION index 8b5e2bf233..2cc84d0709 100644 --- a/Task/Balanced-ternary/00DESCRIPTION +++ b/Task/Balanced-ternary/00DESCRIPTION @@ -1,16 +1,25 @@ -[[wp:Balanced ternary|Balanced ternary]] is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. For example, decimal 11 = 32 + 31 − 30, thus can be written as "++−", while 6 = 32 − 31 + 0 × 30, i.e., "+−0". +[[wp:Balanced ternary|Balanced ternary]] is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or −1. -For this task, implement balanced ternary representation of integers with the following -'''Requirements''' +;Examples: +Decimal 11 = 32 + 31 − 30, thus it can be written as "++−" + +Decimal 6 = 32 − 31 + 0 × 30, thus it can be written as "+−0" + + +;Task: +Implement balanced ternary representation of integers with the following: # Support arbitrarily large integers, both positive and negative; # Provide ways to convert to and from text strings, using digits '+', '-' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5). # Provide ways to convert to and from native integer type (unless, improbably, your platform's native integer type ''is'' balanced ternary). If your native integers can't support arbitrary length, overflows during conversion must be indicated. # Provide ways to perform addition, negation and multiplication directly on balanced ternary integers; do ''not'' convert to native integers first. # Make your implementation efficient, with a reasonable definition of "efficient" (and with a reasonable definition of "reasonable"). + '''Test case''' With balanced ternaries ''a'' from string "+-0++0+", ''b'' from native integer -436, ''c'' "+-++-": * write out ''a'', ''b'' and ''c'' in decimal notation; * calculate ''a'' × (''b'' − ''c''), write out the result in both ternary and decimal notations. + '''Note:''' The pages [[generalised floating point addition]] and [[generalised floating point multiplication]] have code implementing [[wp:arbitrary precision|arbitrary precision]] [[wp:floating point|floating point]] balanced ternary. +

diff --git a/Task/Balanced-ternary/Julia/balanced-ternary.julia b/Task/Balanced-ternary/Julia/balanced-ternary.julia new file mode 100644 index 0000000000..b59e750d75 --- /dev/null +++ b/Task/Balanced-ternary/Julia/balanced-ternary.julia @@ -0,0 +1,85 @@ +struct BalancedTernary <: Signed + digits::Vector{Int8} +end +BalancedTernary() = zero(BalancedTernary) +BalancedTernary(n) = convert(BalancedTernary, n) + +const sgn2chr = Dict{Int8,Char}(-1 => '-', 0 => '0', +1 => '+') +Base.show(io::IO, bt::BalancedTernary) = print(io, join(sgn2chr[x] for x in reverse(bt.digits))) +Base.copy(bt::BalancedTernary) = BalancedTernary(copy(bt.digits)) +Base.zero(::Type{BalancedTernary}) = BalancedTernary(Int8[0]) +Base.iszero(bt::BalancedTernary) = bt.digits == Int8[0] +Base.convert(::Type{T}, bt::BalancedTernary) where T<:Number = sum(3 ^ T(ex - 1) * s for (ex, s) in enumerate(bt.digits)) +function Base.convert(::Type{BalancedTernary}, n::Signed) + r = BalancedTernary(Int8[]) + if iszero(n) push!(r.digits, 0) end + while n != 0 + if mod(n, 3) == 0 + push!(r.digits, 0) + n = fld(n, 3) + elseif mod(n, 3) == 1 + push!(r.digits, 1) + n = fld(n, 3) + else + push!(r.digits, -1) + n = fld(n + 1, 3) + end + end + return r +end +const chr2sgn = Dict{Char,Int8}('-' => -1, '0' => 0, '+' => 1) +function Base.convert(::Type{BalancedTernary}, s::AbstractString) + return BalancedTernary(getindex.(chr2sgn, collect(reverse(s)))) +end + +macro bt_str(s) + convert(BalancedTernary, s) +end + +const table = NTuple{2,Int8}[(0, -1), (1, -1), (-1, 0), (0, 0), (1, 0), (-1, 1), (0, 1)] +function _add(a::Vector{Int8}, b::Vector{Int8}, c::Int8=Int8(0)) + if isempty(a) || isempty(b) + if c == 0 return isempty(a) ? b : a end + return _add([c], isempty(a) ? b : a) + else + d, c = table[4 + (isempty(a) ? 0 : a[1]) + (isempty(b) ? 0 : b[1]) + c] + r = _add(a[2:end], b[2:end], c) + if !isempty(r) || d != 0 + return unshift!(r, d) + else + return r + end + end +end +function Base.:+(a::BalancedTernary, b::BalancedTernary) + v = _add(a.digits, b.digits) + return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) +end +Base.:-(bt::BalancedTernary) = BalancedTernary(-bt.digits) +Base.:-(a::BalancedTernary, b::BalancedTernary) = a + (-b) +function _mul(a::Vector{Int8}, b::Vector{Int8}) + if isempty(a) || isempty(b) + return Int8[] + else + if a[1] == -1 x = (-BalancedTernary(b)).digits + elseif a[1] == 0 x = Int8[] + elseif a[1] == 1 x = b end + y = append!(Int8[0], _mul(a[2:end], b)) + return _add(x, y) + end +end +function Base.:*(a::BalancedTernary, b::BalancedTernary) + v = _mul(a.digits, b.digits) + return isempty(v) ? BalancedTernary(0) : BalancedTernary(v) +end + +a = bt"+-0++0+" +println("a: $(Int(a)), $a") +b = BalancedTernary(-436) +println("b: $(Int(b)), $b") +c = BalancedTernary("+-++-") +println("c: $(Int(c)), $c") +r = a * (b - c) +println("a * (b - c): $(Int(r)), $r") + +@assert Int(r) == Int(a) * (Int(b) - Int(c)) diff --git a/Task/Balanced-ternary/REXX/balanced-ternary.rexx b/Task/Balanced-ternary/REXX/balanced-ternary.rexx index ebe6dc0340..f8cb8afe85 100644 --- a/Task/Balanced-ternary/REXX/balanced-ternary.rexx +++ b/Task/Balanced-ternary/REXX/balanced-ternary.rexx @@ -1,56 +1,52 @@ -/*REXX pgm converts decimal ◄───► balanced ternary; also performs arithmetic.*/ -numeric digits 10000 /*be able to handle gihugic numbers. */ -Ao = '+-0++0+' ; Abt = Ao /* [↓] 2 literals used by subroutine*/ -Bo = '-436' ; Bbt = d2bt(Bo) ; @ = '(decimal)' -Co = '+-++-' ; Cbt = Co ; @@ = 'balanced ternary =' +/*REXX program converts decimal ◄───► balanced ternary; it also performs arithmetic. */ +numeric digits 10000 /*be able to handle gihugic numbers. */ +Ao = '+-0++0+' ; Abt = Ao /* [↓] 2 literals used by subroutine*/ +Bo = '-436' ; Bbt = d2bt(Bo); @ = '(decimal)' +Co = '+-++-' ; Cbt = Co ; @@ = 'balanced ternary =' call btShow '[a]', Abt call btShow '[b]', Bbt call btShow '[c]', Cbt - say; $bt = btMul(Abt,btSub(Bbt,Cbt)) + say; $bt = btMul(Abt, btSub(Bbt, Cbt) ) 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; #= - x=x/1 - do until x==0; _=(x//(3**(p+1)))%3**p - if _== 2 then _= -1 - 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 # -/*────────────────────────────────────────────────────────────────────────────*/ -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 - 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 || # - end /*j*/ - 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.*/ -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.*/ - end /*until*/ -if S==-1 then P=btNeg(P) /*adjust product sign. */ -return P /*return the product P.*/ -/*────────────────────────────────────────────────────────────────────────────*/ -btNeg: return translate(arg(1), '-+', "+-") /*negate the bal_tern #*/ -btNorm: _=strip(arg(1),'L',0); if _=='' then _=0; return _ /*normalize a #*/ -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 +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +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 # +/*──────────────────────────────────────────────────────────────────────────────────────*/ +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= '+' + #=; 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 + 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 || # + end /*j*/ + 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 /* " " " */ + 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.*/ + 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 diff --git a/Task/Benfords-law/8th/benfords-law.8th b/Task/Benfords-law/8th/benfords-law.8th index d17bb3c0bb..f9e55b873e 100644 --- a/Task/Benfords-law/8th/benfords-law.8th +++ b/Task/Benfords-law/8th/benfords-law.8th @@ -24,8 +24,8 @@ var counts 0 s:@ '0 - nip ; : bump-digit \ n -- - counts @ swap 1- dup >r a:@ - 1+ r> swap a:! drop ; + 1 swap + counts @ swap 1- ' + a:op! drop ; : count-fibs \ -- ( leading bump-digit ) 1000 fibs ; diff --git a/Task/Benfords-law/Aime/benfords-law.aime b/Task/Benfords-law/Aime/benfords-law.aime index 2eb7a0227e..357ca68764 100644 --- a/Task/Benfords-law/Aime/benfords-law.aime +++ b/Task/Benfords-law/Aime/benfords-law.aime @@ -4,8 +4,8 @@ sum(text a, text b) data d; integer e, f, n, r; - e = length(a); - f = length(b); + e = ~a; + f = ~b; r = 0; @@ -36,7 +36,7 @@ sum(text a, text b) b_insert(d, 0, r + '0'); } - return b_string(d); + d; } text @@ -45,7 +45,7 @@ fibs(list l, integer n) integer c, i; text a, b, w; - l_r_integer(l, 1, 1); + l[1] = 1; a = "0"; b = "1"; @@ -55,11 +55,11 @@ fibs(list l, integer n) a = b; b = w; c = w[0] - '0'; - l_r_integer(l, c, 1 + l_q_integer(l, c)); + l[c] = 1 + l[c]; i += 1; } - return w; + w; } integer @@ -71,11 +71,7 @@ main(void) n = 1000; - i = 10; - while (i) { - i -= 1; - lb_p_integer(f, 0); - } + f.pn_integer(0, 10, 0); fibs(f, n); @@ -85,11 +81,8 @@ main(void) i = 0; while (i < 9) { i += 1; - o_winteger(8, i); - o_wpreal(16, 3, 3, 100 * log10(1 + 1r / i)); - o_wpreal(16, 3, 3, l_q_integer(f, i) * m); - o_text("\n"); + o_form("%8d/p3d3w16//p3d3w16/\n", i, 100 * log10(1 + 1r / i), f[i] * m); } - return 0; + 0; } diff --git a/Task/Benfords-law/Factor/benfords-law.factor b/Task/Benfords-law/Factor/benfords-law.factor new file mode 100644 index 0000000000..1b5dd23304 --- /dev/null +++ b/Task/Benfords-law/Factor/benfords-law.factor @@ -0,0 +1,29 @@ +USING: assocs compiler.tree.propagation.call-effect formatting +kernel math math.functions math.statistics math.text.utils +sequences ; +IN: rosetta-code.benfords-law + +: expected ( n -- x ) recip 1 + log10 ; + +: next-fib ( vec -- vec' ) + [ last2 ] keep [ + ] dip [ push ] keep ; + +: data ( -- seq ) V{ 1 1 } clone 998 [ next-fib ] times ; + +: 1st-digit ( n -- m ) 1 digit-groups last ; + +: leading ( -- seq ) data [ 1st-digit ] map ; + +: .header ( -- ) + "Digit" "Expected" "Actual" "%-10s%-10s%-10s\n" printf ; + +: digit-report ( digit digit-count -- digit expected actual ) + dupd [ expected ] dip 1000 /f ; + +: .digit-report ( digit digit-count -- ) + digit-report "%-10d%-10.4f%-10.4f\n" printf ; + +: main ( -- ) + .header leading histogram [ .digit-report ] assoc-each ; + +MAIN: main diff --git a/Task/Benfords-law/REXX/benfords-law.rexx b/Task/Benfords-law/REXX/benfords-law.rexx index 165487bc19..d26351962f 100644 --- a/Task/Benfords-law/REXX/benfords-law.rexx +++ b/Task/Benfords-law/REXX/benfords-law.rexx @@ -1,32 +1,38 @@ /*REXX program demonstrates some common functions (thirty decimal digits are shown). */ -numeric digits 50 /*use only 50 dec digits for LN & LOG.*/ -parse arg N .; if N=='' | N=="," then N=1000 /*allow sample size to be specified. */ -@benny= "Benford's law applied to" /*a handy-dandy literal for some SAYs. */ -w1= max(2+length('observed'), length(N-2) ); pad=" " /*used for aligning output.*/ -w2= max(2+length('expected'), length(N ) ) /* " " " " */ - -@.=1; do j=3 to N; jm1=j-1; jm2=j-2; @.j=@.jm2 + @.jm1; end /*j*/ -call show @benny N 'Fibonacci numbers' -p=1 -@.1=2; do j=3 by 2 until p==N; if \isPrime(j) then iterate; p=p+1; @.p=j; end /*j*/ -call show @benny N 'prime numbers' - -!=1; do j=1 for N; !=!*j; end /*j*/ -call show @benny N 'factorial products' +numeric digits length( e() ) - 1 /*use the width of (e) for LN & LOG. */ +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.*/ +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; a=j-1; b=a-1; @.j= @.a + @.b + end /*j*/ /* [↑] generate N Fibonacci numbers.*/ +call show "Benford's law applied to" N 'Fibonacci numbers' +@.1=1 + do j=1 for N; @.j= @.j * N + end /*j*/ /* [↑] generate N factorials. */ +call show "Benford's law applied to" N 'factorial products' exit /*stick a fork in it, we're all done. */ -/*───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/ -e: return 2.7182818284590452353602874713526624977572470936999595749669676277240766303535 -isPrime: procedure; parse arg x; if wordpos(x,'2 3 5 7')\==0 then return 1; if x//2==0 then return 0; if x//3==0 then return 0; do j=5 by 6 until j*j>x; if x//j==0 then return 0; if x//(j+2)==0 then return 0; end; return 1 -ln: procedure; parse arg x; _=e(); ig=(x>1.5); is=1 - 2 * (ig \== 1); ii=0; s=x; return .ln() -.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;s=izz;ii=ii+is*2**k;end;x=x*e()**-ii-1;z=0;_=-1;p=z;do k=1;_=-_*x;z=z+_/k;if z=p then leave;p=z;end;return z+ii -log: return ln( arg(1) ) / ln(10) +/*──────────────────────────────────────────────────────────────────────────────────────*/ +e: return 2.71828182845904523536028747135266249775724709369995957496696762772407663 +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() +/*──────────────────────────────────────────────────────────────────────────────────────*/ +.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*/ + 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 /*──────────────────────────────────────────────────────────────────────────────────────*/ 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; end /*get 1st digits.*/ + !.=0; do j=1 for N; _=left(@.j, 1); !._= !._ +1 /*get the 1st digit.*/ + end /*j*/ - do k=1 for 9 /*display results for decimal digits. */ - say pad center(k,7) pad center(format(!.k /N , , length(N-2) ), w1), - pad center(format(log(1+1 /k) , , length(N)+2 ), w2) - end /*k*/ + 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*/ return diff --git a/Task/Benfords-law/Ring/benfords-law.ring b/Task/Benfords-law/Ring/benfords-law.ring new file mode 100644 index 0000000000..90e95533f9 --- /dev/null +++ b/Task/Benfords-law/Ring/benfords-law.ring @@ -0,0 +1,36 @@ +# Project : Benford's law +# Date : 2017/11/29 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +decimals(3) +n= 1000 +actual = list(n) +for x = 1 to len(actual) + actual[x] = 0 +next + +for nr = 1 to n + n1 = string(fibonacci(nr)) + j = number(left(n1,1)) + actual[j] = actual[j] + 1 +next + +see "Digit " + "Actual " + "Expected" + nl +for m = 1 to 9 + fr = frequency(m)*100 + see "" + m + " " + (actual[m]/10) + " " + fr + nl +next + +func frequency(n) + freq = log10(n+1) - log10(n) + return freq + +func log10(n) + log1 = log(n) / log(10) + return log1 + +func fibonacci(y) + if y = 0 return 0 ok + if y = 1 return 1 ok + if y > 1 return fibonacci(y-1) + fibonacci(y-2) ok diff --git a/Task/Bernoulli-numbers/00DESCRIPTION b/Task/Bernoulli-numbers/00DESCRIPTION index d5f8286fb3..2e647bc7c8 100644 --- a/Task/Bernoulli-numbers/00DESCRIPTION +++ b/Task/Bernoulli-numbers/00DESCRIPTION @@ -28,5 +28,5 @@ The Akiyama–Tanigawa algorithm for the "second Bernoulli numbers" as taken fro * Sequence [http://oeis.org/A027641 A027641 Numerator of Bernoulli number B_n] on The On-Line Encyclopedia of Integer Sequences. * Sequence [http://oeis.org/A027642 A027642 Denominator of Bernoulli number B_n] on The On-Line Encyclopedia of Integer Sequences. * Entry [http://mathworld.wolfram.com/BernoulliNumber.html Bernoulli number] on The Eric Weisstein's World of Mathematics (TM). -* Luschny's [http://luschny.de/math/zeta/The-Bernoulli-Manifesto.html The Bernoulli Manifesto] for a discussion on B_1 = -½ vs. +½. +* Luschny's [http://luschny.de/math/zeta/The-Bernoulli-Manifesto.html The Bernoulli Manifesto] for a discussion on   '''B1   =   -½'''   versus   '''+½'''.

diff --git a/Task/Bernoulli-numbers/C++/bernoulli-numbers.cpp b/Task/Bernoulli-numbers/C++/bernoulli-numbers.cpp new file mode 100644 index 0000000000..3832f3f557 --- /dev/null +++ b/Task/Bernoulli-numbers/C++/bernoulli-numbers.cpp @@ -0,0 +1,39 @@ +/** + * Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 + * Apple LLVM version 9.1.0 (clang-902.0.39.1) + * Target: x86_64-apple-darwin17.5.0 + * Thread model: posix +*/ + +#include //std::cout +#include //formatting +#include //Container +#include // Rationals +#include //1024bit precision + + +typedef boost::rational rational; // reduce boilerplate + +rational bernulli(size_t n){ + + auto out = std::vector(); + + for(size_t m=0;m<=n;m++){ + out.emplace_back(1,(m+1)); // automatically constructs object + for (size_t j = m;j>=1;j--){ + out[j-1] = rational(j) * (out[j-1]-out[j]); + } + } + return out[0]; + } + +int main() { + for(size_t n = 0; n <= 60;n+=n>=2?2:1){ + auto b = bernulli(n); + std::cout << "B("<0 because b on its own isn't considered true - b > 0 ? gcd(b, a % b) : a -end +b = Bernoulli.new +bn = b.first(61).to_a -def calculate_bernoulli(bern) - row = [] of Fraction - 0_i64.step(bern) do |m| - row << Fraction.new(1_i64, m + 1) - m.step(1, -1) do |j| - row[j - 1].subtract(row[j]) - row[j - 1].multiply(j) - row[j - 1].reduce - end - end - - row[0] -end - -1_i64.step(30_i64) do |bern| - puts "#{bern} : #{calculate_bernoulli(bern).to_s}" +max_width = bn.map { |_, v| v.numerator.to_s.size }.max +bn.reject { |i, v| v.zero? }.each do |i, v| + puts "B(%2i) = %*i/%i" % [i, max_width, v.numerator, v.denominator] end diff --git a/Task/Bernoulli-numbers/Perl-6/bernoulli-numbers-3.pl6 b/Task/Bernoulli-numbers/Perl-6/bernoulli-numbers-3.pl6 index eb2c94c4cf..4196f6c4ad 100644 --- a/Task/Bernoulli-numbers/Perl-6/bernoulli-numbers-3.pl6 +++ b/Task/Bernoulli-numbers/Perl-6/bernoulli-numbers-3.pl6 @@ -14,3 +14,10 @@ constant bernoulli = map { .key => .value[*-1] }, (0 => [FatRat.new(1,1)], &next-bernoulli ... *) ; + +constant @bpairs = bernoulli[^52]; + +my $width = [max] @bpairs.map: *.value.numerator.chars; +my $form = "B(%d)\t= \%{$width}d/%d\n"; + +printf $form, .key, .value.nude for @bpairs; diff --git a/Task/Bernoulli-numbers/REXX/bernoulli-numbers.rexx b/Task/Bernoulli-numbers/REXX/bernoulli-numbers.rexx index bae83df81a..926286a252 100644 --- a/Task/Bernoulli-numbers/REXX/bernoulli-numbers.rexx +++ b/Task/Bernoulli-numbers/REXX/bernoulli-numbers.rexx @@ -42,7 +42,14 @@ comb: procedure expose !.; parse arg x,y; if x==y then return 1 gcd: procedure; parse arg x,y; x=abs(x) do until y==0; parse value x//y y with y x; end; return x /*──────────────────────────────────────────────────────────────────────────────────────*/ -lcm: procedure; parse arg x,y; x=abs(x); return x*y/gcd(x,y) +lcm: procedure; parse arg x,y; if x<0 then x=-x + if y<0 then y= -y + if y==0 then return 0 /*if zero, then LCM is also zero. */ + d=x*y /*calculate part of the LCM here. */ + do until y==0; parse value x//y y with y x + end /*until*/ /* [↑] this is a short & fast GCD*/ + x=d%x /*divide the pre─calculated value.*/ + return x /*return with the LCM of the args.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ perm: procedure expose !.; parse arg x,y; if !.p.x.y\==0 then return !.p.x.y z=1; do j=x-y+1 to x; z=z*j; end; !.p.x.y=z; return z diff --git a/Task/Bernoulli-numbers/Visual-Basic-.NET/bernoulli-numbers.visual b/Task/Bernoulli-numbers/Visual-Basic-.NET/bernoulli-numbers.visual index c98a15b19a..62433a8751 100644 --- a/Task/Bernoulli-numbers/Visual-Basic-.NET/bernoulli-numbers.visual +++ b/Task/Bernoulli-numbers/Visual-Basic-.NET/bernoulli-numbers.visual @@ -1,5 +1,5 @@ ' Bernoulli numbers - vb.net - 06/03/2017 -Imports System.Numerics 'BinInteger +Imports System.Numerics 'BigInteger Module Bernoulli_numbers diff --git a/Task/Best-shuffle/Common-Lisp/best-shuffle-3.lisp b/Task/Best-shuffle/Common-Lisp/best-shuffle-3.lisp new file mode 100644 index 0000000000..60f12068c3 --- /dev/null +++ b/Task/Best-shuffle/Common-Lisp/best-shuffle-3.lisp @@ -0,0 +1,6 @@ +abracadabra: (caardrabaab 0) +seesaw: (ewsase 0) +elk: (kel 0) +grrrrrr: (rrrgrrr 5) +up: (pu 0) +a: (a 1) diff --git a/Task/Best-shuffle/Elena/best-shuffle.elena b/Task/Best-shuffle/Elena/best-shuffle.elena index fa8eaa65fd..88e32344db 100644 --- a/Task/Best-shuffle/Elena/best-shuffle.elena +++ b/Task/Best-shuffle/Elena/best-shuffle.elena @@ -1,5 +1,6 @@ import system'routines. import extensions. +import extensions'text. extension op { @@ -8,18 +9,18 @@ extension op var anOriginal := self toArray. var aShuffled := self toArray. - 0 to(anOriginal length - 1) do(:i) + 0 to:(anOriginal length - 1) do(:i) [ - 0 to(anOriginal length - 1) do(:j) + 0 to:(anOriginal length - 1) do(:j) [ - if ((i != j) && $(anOriginal[i] != aShuffled[j]) && $(anOriginal[j] != aShuffled[i])) + if ((i != j) && (anOriginal[i] != aShuffled[j]) && $(anOriginal[j] != aShuffled[i])) [ aShuffled exchange(i,j) ]. ]. ]. - ^ aShuffled summarize(String new); literal + ^ aShuffled summarize(StringWriter new); toLiteral ] score : anOriginalText @@ -35,7 +36,7 @@ extension op ] } -program = +public program = [ ("abracadabra", "seesaw", "grrrrrr", "pop", "up", "a") forEach(:aWord) [ diff --git a/Task/Best-shuffle/REXX/best-shuffle.rexx b/Task/Best-shuffle/REXX/best-shuffle.rexx new file mode 100644 index 0000000000..070045a39c --- /dev/null +++ b/Task/Best-shuffle/REXX/best-shuffle.rexx @@ -0,0 +1,30 @@ +/*REXX program determines and displays the best shuffle for any list of words/characters*/ +parse arg $ /*get some words from the command line.*/ +if $='' then $= 'tree abracadabra seesaw elk grrrrrr up a' /*use the defaults?*/ +w=0; #=words($) /* [↑] finds the widest word in $ list*/ + do i=1 for #; @.i=word($,i); w=max(w, length(@.i) ); end /*i*/ +w=w+9 /*add 9 blanks for output indentation. */ + do n=1 for #; new=bestShuffle(@.n) /*process the examples in the @ array. */ + same=0; do m=1 for length(@.n) + same=same + (substr(@.n, m, 1) == substr(new, m, 1) ) + end /*m*/ + say 'original:' left(@.n, w) 'new:' left(new,w) 'count:' same + end /*n*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +bestShuffle: procedure; parse arg x 1 ox; L=length(x); if L<3 then return reverse(x) + /*[↑] fast track short strs*/ + do j=1 for L-1; parse var x =(j) a +1 b +1 /*get A,B at Jth & J+1 pos.*/ + if a\==b then iterate /*ignore any replicates. */ + c=verify(x,a); if c==0 then iterate /* " " " */ + x=overlay( substr(x,c,1), overlay(a,x,c), j) /*swap the x,c characters*/ + rx=reverse(x) /*obtain the reverse of X. */ + y=substr(rx, verify(rx,a), 1) /*get 2nd replicated char. */ + x=overlay(y, overlay(a,x, lastpos(y,x)),j+1) /*fast swap of 2 characters*/ + end /*j*/ + do k=1 for L; a=substr(x,k,1) /*handle a possible rep. */ + if a\==substr(ox,k,1) then iterate /*skip non-replications*/ + if k==L then x=left(x,k-2)a || substr(x,k-1,1) /*last case*/ + else x=left(x,k-1)substr(x,k+1,1)a || substr(x, k+2) + end /*k*/ + return x diff --git a/Task/Best-shuffle/Ring/best-shuffle-1.ring b/Task/Best-shuffle/Ring/best-shuffle-1.ring new file mode 100644 index 0000000000..6ffbc4acb7 --- /dev/null +++ b/Task/Best-shuffle/Ring/best-shuffle-1.ring @@ -0,0 +1,36 @@ +# Project : Best shuffle +# Date : 2018/02/15 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +test = ["abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"] + +for n = 1 to len(test) + bs = bestshuffle(test[n]) + count = 0 + for p = 1 to len(test[n]) + if substr(test[n],p,1) = substr(bs,p,1) + count = count + 1 + ok + next + see test[n] + " -> " + bs + " " + count + nl +next + +func bestshuffle(s1) + s2 = s1 + for i = 1 to len(s2) + for j = 1 to len(s2) + if (i != j) and (s2[i] != s1[j]) and (s2[j] != s1[i]) + if j < i + i1 = j + j1 = i + else + i1 = i + j1 = j + ok + s2 = left(s2,i1-1) + substr(s2,j1,1) + substr(s2,i1+1,(j1-i1)-1) + substr(s2,i1,1) + substr(s2,j1+1) + ok + next + next + bestshuffle = s2 + return bestshuffle diff --git a/Task/Best-shuffle/Ring/best-shuffle-2.ring b/Task/Best-shuffle/Ring/best-shuffle-2.ring new file mode 100644 index 0000000000..f5ef7adc8a --- /dev/null +++ b/Task/Best-shuffle/Ring/best-shuffle-2.ring @@ -0,0 +1,36 @@ +def best_shuffle(s) + # Fill _pos_ with positions in the order + # that we want to fill them. + pos = [] + # g["a"] = [2, 4] implies that s[2] == s[4] == "a" + g = s.length.times.group_by { |i| s[i] } + + # k sorts letters from low to high count + k = g.sort_by { |k, v| v.length }.map { |k, v| k } + + until g.empty? + k.each do |letter| + g[letter] or next + pos.push(g[letter].pop) + g[letter].empty? and g.delete letter + end + end + + # Now fill in _new_ with _letters_ according to each position + # in _pos_, but skip ahead in _letters_ if we can avoid + # matching characters that way. + letters = s.dup + new = "?" * s.length + until letters.empty? + i, p = 0, pos.pop + i += 1 while letters[i] == s[p] and i < (letters.length - 1) + new[p] = letters.slice! i + end + + score = new.chars.zip(s.chars).count { |c, d| c == d } + [new, score] +end + +%w(abracadabra seesaw elk grrrrrr up a).each do |word| + puts "%s, %s, (%d)" % [word, *best_shuffle(word)] +end diff --git a/Task/Best-shuffle/Ring/best-shuffle-3.ring b/Task/Best-shuffle/Ring/best-shuffle-3.ring new file mode 100644 index 0000000000..d7eb9abdc9 --- /dev/null +++ b/Task/Best-shuffle/Ring/best-shuffle-3.ring @@ -0,0 +1,25 @@ +list$ = "abracadabra seesaw pop grrrrrr up a" + +while word$(list$,ii + 1," ") <> "" + ii = ii + 1 + w$ = word$(list$,ii," ") + bs$ = bestShuffle$(w$) + count = 0 + for i = 1 to len(w$) + if mid$(w$,i,1) = mid$(bs$,i,1) then count = count + 1 + next i + print w$;" ";bs$;" ";count +wend + +function bestShuffle$(s1$) + s2$ = s1$ + for i = 1 to len(s2$) + for j = 1 to len(s2$) + if (i <> j) and (mid$(s2$,i,1) <> mid$(s1$,j,1)) and (mid$(s2$,j,1) <> mid$(s1$,i,1)) then + if j < i then i1 = j:j1 = i else i1 = i:j1 = j + s2$ = left$(s2$,i1-1) + mid$(s2$,j1,1) + mid$(s2$,i1+1,(j1-i1)-1) + mid$(s2$,i1,1) + mid$(s2$,j1+1) + end if + next j + next i +bestShuffle$ = s2$ +end function diff --git a/Task/Best-shuffle/Ring/best-shuffle-4.ring b/Task/Best-shuffle/Ring/best-shuffle-4.ring new file mode 100644 index 0000000000..e8b8fca8c0 --- /dev/null +++ b/Task/Best-shuffle/Ring/best-shuffle-4.ring @@ -0,0 +1,135 @@ +extern crate permutohedron; +extern crate rand; + +use std::cmp::{min, Ordering}; +use std::env; +use rand::{thread_rng, Rng}; +use std::str; + +const WORDS: &'static [&'static str] = &["abracadabra", "seesaw", "elk", "grrrrrr", "up", "a"]; + +#[derive(Eq)] +struct Solution { + original: String, + shuffled: String, + score: usize, +} + +// Ordering trait implementations are only needed for the permutations method +impl PartialOrd for Solution { + fn partial_cmp(&self, other: &Solution) -> Option { + match (self.score, other.score) { + (s, o) if s < o => Some(Ordering::Less), + (s, o) if s > o => Some(Ordering::Greater), + (s, o) if s == o => Some(Ordering::Equal), + _ => None, + } + } +} + + +impl PartialEq for Solution { + fn eq(&self, other: &Solution) -> bool { + match (self.score, other.score) { + (s, o) if s == o => true, + _ => false, + } + } +} + +impl Ord for Solution { + fn cmp(&self, other: &Solution) -> Ordering { + match (self.score, other.score) { + (s, o) if s < o => Ordering::Less, + (s, o) if s > o => Ordering::Greater, + _ => Ordering::Equal, + } + } +} + +fn _help() { + println!("Usage: best_shuffle ..."); +} + +fn main() { + let args: Vec = env::args().collect(); + let mut words: Vec = vec![]; + + match args.len() { + 1 => { + for w in WORDS.iter() { + words.push(String::from(*w)); + } + } + _ => { + for w in args.split_at(1).1 { + words.push(w.clone()); + } + } + } + + let solutions = words.iter().map(|w| best_shuffle(w)).collect::>(); + + for s in solutions { + println!("{}, {}, ({})", s.original, s.shuffled, s.score); + } +} + +// Implementation iterating over all permutations +fn _best_shuffle_perm(w: &String) -> Solution { + let mut soln = Solution { + original: w.clone(), + shuffled: w.clone(), + score: w.len(), + }; + let w_bytes: Vec = w.clone().into_bytes(); + let mut permutocopy = w_bytes.clone(); + let mut permutations = permutohedron::Heap::new(&mut permutocopy); + while let Some(p) = permutations.next_permutation() { + let hamm = hamming(&w_bytes, p); + soln = min(soln, + Solution { + original: w.clone(), + shuffled: String::from(str::from_utf8(p).unwrap()), + score: hamm, + }); + // Accept the solution if score 0 found + if hamm == 0 { + break; + } + } + soln +} + +// Quadratic implementation +fn best_shuffle(w: &String) -> Solution { + let w_bytes: Vec = w.clone().into_bytes(); + let mut shuffled_bytes: Vec = w.clone().into_bytes(); + + // Shuffle once + let sh: &mut [u8] = shuffled_bytes.as_mut_slice(); + thread_rng().shuffle(sh); + + // Swap wherever it doesn't decrease the score + for i in 0..sh.len() { + for j in 0..sh.len() { + if (i == j) | (sh[i] == w_bytes[j]) | (sh[j] == w_bytes[i]) | (sh[i] == sh[j]) { + continue; + } + sh.swap(i, j); + break; + } + } + + let res = String::from(str::from_utf8(sh).unwrap()); + let res_bytes: Vec = res.clone().into_bytes(); + Solution { + original: w.clone(), + shuffled: res, + score: hamming(&w_bytes, &res_bytes), + } +} + +fn hamming(w0: &Vec, w1: &Vec) -> usize { + w0.iter().zip(w1.iter()).filter(|z| z.0 == z.1).count() +} diff --git a/Task/Best-shuffle/VBA/best-shuffle.vba b/Task/Best-shuffle/VBA/best-shuffle.vba new file mode 100644 index 0000000000..15a8f0dd50 --- /dev/null +++ b/Task/Best-shuffle/VBA/best-shuffle.vba @@ -0,0 +1,94 @@ +Option Explicit + +Sub Main_Best_shuffle() +Dim S() As Long, W, b As Byte, Anagram$, Count&, myB As Boolean, Limit As Byte, i As Integer + + W = Array("a", "abracadabra", "seesaw", "elk", "grrrrrr", "up", "qwerty", "tttt") + For b = 0 To UBound(W) + Count = 0 + Select Case Len(W(b)) + Case 1: Limit = 1 + Case Else + i = NbLettersDiff(W(b)) + If i >= Len(W(b)) \ 2 Then + Limit = 0 + ElseIf i = 1 Then + Limit = Len(W(b)) + Else + Limit = Len(W(b)) - i + End If + End Select +RePlay: + Do + S() = ShuffleIntegers(Len(W(b))) + myB = GoodShuffle(S, Limit) + Loop While Not myB + Anagram = ShuffleWord(CStr(W(b)), S) + Count = Nb(W(b), Anagram) + If Count > Limit Then GoTo RePlay + Debug.Print W(b) & " ==> " & Anagram & " (Score : " & Count & ")" + Next +End Sub + +Function ShuffleIntegers(l As Long) As Long() +Dim i As Integer, ou As Integer, temp() As Long +Dim C As New Collection + + ReDim temp(l - 1) + If l = 1 Then + temp(0) = 0 + ElseIf l = 2 Then + temp(0) = 1: temp(1) = 0 + Else + Randomize + Do + ou = Int(Rnd * l) + On Error Resume Next + C.Add CStr(ou), CStr(ou) + If Err <> 0 Then + On Error GoTo 0 + Else + temp(ou) = i + i = i + 1 + End If + Loop While C.Count <> l + End If + ShuffleIntegers = temp +End Function + +Function GoodShuffle(t() As Long, Lim As Byte) As Boolean +Dim i&, C& + + For i = LBound(t) To UBound(t) + If t(i) = i Then C = C + 1 + Next i + GoodShuffle = (C <= Lim) +End Function + +Function ShuffleWord(W$, S() As Long) As String +Dim i&, temp, strR$ + + temp = Split(StrConv(W, vbUnicode), Chr(0)) + For i = 0 To UBound(S) + strR = strR & temp(S(i)) + Next i + ShuffleWord = strR +End Function + +Function Nb(W, A) As Integer +Dim i As Integer, l As Integer + + For i = 1 To Len(W) + If Mid(W, i, 1) = Mid(A, i, 1) Then l = l + 1 + Next i + Nb = l +End Function + +Function NbLettersDiff(W) As Integer +Dim i&, C As New Collection + For i = 1 To Len(W) + On Error Resume Next + C.Add Mid(W, i, 1), Mid(W, i, 1) + Next i + NbLettersDiff = C.Count +End Function diff --git a/Task/Binary-digits/Ceylon/binary-digits.ceylon b/Task/Binary-digits/Ceylon/binary-digits.ceylon new file mode 100644 index 0000000000..c3c95b0fc5 --- /dev/null +++ b/Task/Binary-digits/Ceylon/binary-digits.ceylon @@ -0,0 +1,9 @@ + shared void run() { + + void printBinary(Integer integer) => + print(Integer.format(integer, 2)); + + printBinary(5); + printBinary(50); + printBinary(9k); + } diff --git a/Task/Binary-digits/Elena/binary-digits.elena b/Task/Binary-digits/Elena/binary-digits.elena index 43588f656b..c986cb9dde 100644 --- a/Task/Binary-digits/Elena/binary-digits.elena +++ b/Task/Binary-digits/Elena/binary-digits.elena @@ -1,10 +1,10 @@ import system'routines. import extensions. -program = +public program = [ (5,50,9000) forEach(:n) [ - console printLine(n toLiteral base:2). + console printLine(n toLiteral(2)). ]. ]. diff --git a/Task/Binary-digits/Julia/binary-digits.julia b/Task/Binary-digits/Julia/binary-digits.julia index b7379ba6d3..5386da1153 100644 --- a/Task/Binary-digits/Julia/binary-digits.julia +++ b/Task/Binary-digits/Julia/binary-digits.julia @@ -1,3 +1,9 @@ -for i in [0, 5, 50, 9000] - println(i, " => ", bin(i)) +for n in (0, 5, 50, 9000) + @printf("%6i → %s\n", n, bin(n)) +end + +# with pad +println("\nwith pad") +for n in (0, 5, 50, 9000) + @printf("%6i → %s\n", n, bin(n, 20)) end diff --git a/Task/Binary-digits/PowerBASIC/binary-digits.powerbasic b/Task/Binary-digits/PowerBASIC/binary-digits.powerbasic new file mode 100644 index 0000000000..03731b28e0 --- /dev/null +++ b/Task/Binary-digits/PowerBASIC/binary-digits.powerbasic @@ -0,0 +1,12 @@ +#COMPILE EXE +#DIM ALL +#COMPILER PBCC 6 + +FUNCTION PBMAIN () AS LONG +LOCAL i, d() AS DWORD +REDIM d(2) +ARRAY ASSIGN d() = 5, 50, 9000 + FOR i = 0 TO 2 + PRINT STR$(d(i)) & ": " & BIN$(d(i)) & " (" & BIN$(d(i), 32) & ")" + NEXT i +END FUNCTION diff --git a/Task/Binary-digits/Red/binary-digits.red b/Task/Binary-digits/Red/binary-digits.red new file mode 100644 index 0000000000..cbaf98df41 --- /dev/null +++ b/Task/Binary-digits/Red/binary-digits.red @@ -0,0 +1,7 @@ +Red [] + +foreach number [5 50 9000] [ + ;; any returns first not false value, used to cut leading zeroes + binstr: form any [find enbase/base to-binary number 2 "1" "0"] + print reduce [ pad/left number 5 binstr ] +] diff --git a/Task/Binary-digits/VBA/binary-digits.vba b/Task/Binary-digits/VBA/binary-digits.vba new file mode 100644 index 0000000000..6b79bf8375 --- /dev/null +++ b/Task/Binary-digits/VBA/binary-digits.vba @@ -0,0 +1,38 @@ +Option Explicit + +Sub Main_Dec2bin() +Dim Nb As Long +Nb = 5 + Debug.Print "The decimal value " & Nb & " should produce an output of : " & DecToBin(Nb) + Debug.Print "The decimal value " & Nb & " should produce an output of : " & DecToBin2(Nb) +Nb = 50 + Debug.Print "The decimal value " & Nb & " should produce an output of : " & DecToBin(Nb) + Debug.Print "The decimal value " & Nb & " should produce an output of : " & DecToBin2(Nb) +Nb = 9000 + Debug.Print "The decimal value " & Nb & " should produce an output of : " & DecToBin(Nb) + Debug.Print "The decimal value " & Nb & " should produce an output of : " & DecToBin2(Nb) +End Sub + +Function DecToBin(ByVal Number As Long) As String +Dim strTemp As String + + Do While Number > 1 + strTemp = Number - 2 * (Number \ 2) & strTemp + Number = Number \ 2 + Loop + DecToBin = Number & strTemp +End Function + +Function DecToBin2(ByVal Number As Long, Optional Places As Long) As String + If Number > 511 Then + DecToBin2 = "Error : Number is too large ! (Number must be < 511)" + ElseIf Number < -512 Then + DecToBin2 = "Error : Number is too small ! (Number must be > -512)" + Else + If Places = 0 Then + DecToBin2 = WorksheetFunction.Dec2Bin(Number) + Else + DecToBin2 = WorksheetFunction.Dec2Bin(Number, Places) + End If + End If +End Function diff --git a/Task/Binary-digits/Visual-Basic/binary-digits.vb b/Task/Binary-digits/Visual-Basic/binary-digits.vb new file mode 100644 index 0000000000..752b90f22f --- /dev/null +++ b/Task/Binary-digits/Visual-Basic/binary-digits.vb @@ -0,0 +1,34 @@ +Public Function Bin(ByVal l As Long) As String +Dim i As Long + If l Then + If l And &H80000000 Then 'negative number + Bin = "1" & String$(31, "0") + l = l And (Not &H80000000) + + For i = 0 To 30 + If l And (2& ^ i) Then + Mid$(Bin, Len(Bin) - i) = "1" + End If + Next i + + Else 'positive number + Do While l + If l Mod 2 Then + Bin = "1" & Bin + Else + Bin = "0" & Bin + End If + l = l \ 2 + Loop + End If + Else + Bin = "0" 'zero + End If +End Function + +'testing: +Public Sub Main() + Debug.Print "5: " & Bin(5) + Debug.Print "50: " & Bin(50) + Debug.Print "9000: " & Bin(9000) +End Sub diff --git a/Task/Binary-search/C++/binary-search-1.cpp b/Task/Binary-search/C++/binary-search-1.cpp index 15eeca49e9..6212b421a5 100644 --- a/Task/Binary-search/C++/binary-search-1.cpp +++ b/Task/Binary-search/C++/binary-search-1.cpp @@ -1,24 +1,22 @@ -template -int binsearch(const T array[], int len, T what) -{ - if (len == 0) return -1; - int mid = len / 2; - if (array[mid] == what) return mid; - if (array[mid] < what) { - int result = binsearch(array+mid+1, len-(mid+1), what); - if (result == -1) return -1; - else return result + mid+1; - } - if (array[mid] > what) - return binsearch(array, mid, what); +template int binsearch(const T array[], int low, int high, T value) { + if (high < low) { + return -1; + } + auto mid = (low + high) / 2; + if (value < array[mid]) { + return binsearch(array, low, mid - 1, value); + } else if (value > array[mid]) { + return binsearch(array, mid + 1, high, value); + } + return mid; } #include int main() { int array[] = {2, 3, 5, 6, 8}; - int result1 = binsearch(array, sizeof(array)/sizeof(int), 4), - result2 = binsearch(array, sizeof(array)/sizeof(int), 8); + int result1 = binsearch(array, 0, sizeof(array)/sizeof(int), 4), + result2 = binsearch(array, 0, sizeof(array)/sizeof(int), 8); if (result1 == -1) std::cout << "4 not found!" << std::endl; else std::cout << "4 found at " << result1 << std::endl; if (result2 == -1) std::cout << "8 not found!" << std::endl; diff --git a/Task/Binary-search/Julia/binary-search-1.julia b/Task/Binary-search/Julia/binary-search-1.julia index 23fb98a5b3..4c59166e22 100644 --- a/Task/Binary-search/Julia/binary-search-1.julia +++ b/Task/Binary-search/Julia/binary-search-1.julia @@ -1,15 +1,15 @@ -function binary_search(l, value) +function binarysearch(lst::Vector{T}, val::T) where T low = 1 - high = length(l) - while low <= high - mid = int((low+high)/2) - if l[mid] > value - high = mid-1 - elseif l[mid] < value - low = mid+1 + high = length(lst) + while low ≤ high + mid = (low + high) ÷ 2 + if lst[mid] > val + high = mid - 1 + elseif lst[mid] < val + low = mid + 1 else - return mid + return mid end end - return -1 + return 0 end diff --git a/Task/Binary-search/Julia/binary-search-2.julia b/Task/Binary-search/Julia/binary-search-2.julia index 38aaa40a12..4f646279ff 100644 --- a/Task/Binary-search/Julia/binary-search-2.julia +++ b/Task/Binary-search/Julia/binary-search-2.julia @@ -1,10 +1,18 @@ -function binary_search(l, value, low = 1, high = -1) - high == -1 && (high = length(l)) - l==[] && (return -1) - low >= high && - ((low > high || l[low] != value) ? (return -1) : return low) - mid = int((low+high)/2) - l[mid] > value ? (return binary_search(l, value, low, mid-1)) : - l[mid] < value ? (return binary_search(l, value, mid+1, high)) : - return mid +function binarysearch(lst::Vector{T}, value::T, low=1, high=length(lst)) where T + if isempty(lst) return 0 end + if low ≥ high + if low > high || lst[low] != value + return 0 + else + return low + end + end + mid = (low + high) ÷ 2 + if lst[mid] > value + return binarysearch(lst, value, low, mid-1) + elseif lst[mid] < value + return binarysearch(lst, value, mid+1, high) + else + return mid + end end diff --git a/Task/Binary-search/N-t-roff/binary-search.n b/Task/Binary-search/N-t-roff/binary-search.n new file mode 100644 index 0000000000..250f435f95 --- /dev/null +++ b/Task/Binary-search/N-t-roff/binary-search.n @@ -0,0 +1,38 @@ +.de end +.. +.de array +. nr \\$1.c 0 1 +. de \\$1.push end +. nr \\$1..\\\\n+[\\$1.c] \\\\$1 +. end +. de \\$1.pushln end +. if \\\\n(.$>0 .\\$1.push \\\\$1 +. if \\\\n(.$>1 \{ \ +. shift +. \\$1.pushln \\\\$@ +\} +. end +.. +. +.de binarysearch +. nr min 1 +. nr max \\n[\\$1.c] +. nr guess \\n[min]+\\n[max]/2 +. while !\\n[\\$1..\\n[guess]]=\\$2 \{ \ +. ie \\n[\\$1..\\n[guess]]<\\$2 .nr min \\n[guess]+1 +. el .nr max \\n[guess]-1 +. +. if \\n[min]>\\n[max] \{ +. nr guess 0 +. break +. \} +. nr guess \\n[min]+\\n[max]/2 +. \} +\\n[guess] +.. +.array a +.a.pushln 1 4 9 16 25 36 49 64 81 100 121 144 +.binarysearch a 100 +.br +.ie \n[guess]=0 The item \fBdoesn't exist\fP. +.el The item \fBdoes exist\fP. diff --git a/Task/Binary-search/PARI-GP/binary-search.pari b/Task/Binary-search/PARI-GP/binary-search-1.pari similarity index 100% rename from Task/Binary-search/PARI-GP/binary-search.pari rename to Task/Binary-search/PARI-GP/binary-search-1.pari diff --git a/Task/Binary-search/PARI-GP/binary-search-2.pari b/Task/Binary-search/PARI-GP/binary-search-2.pari new file mode 100644 index 0000000000..229d2c9626 --- /dev/null +++ b/Task/Binary-search/PARI-GP/binary-search-2.pari @@ -0,0 +1,24 @@ +binarysearch(v, x) = { + local( + minm = 1, + maxm = length(v), + guess = floor(maxm/2+minm/2) + ); + + while(v[guess] != x, + if(v[guess] < x, minm = guess + 1, maxm = guess - 1); + if(minm > maxm, + guess = 0; + break + ); + guess = floor(maxm/2+minm/2) + ); + + return(guess); +} + +idx = binarysearch([1,4,9,16,25,36,49,64,81,100,121,144], 121); +if(idx, \ + print("Item exists on index ", idx), \ + print("Item does not exist anywhere.") \ +) diff --git a/Task/Binary-search/Rust/binary-search-1.rust b/Task/Binary-search/Rust/binary-search-1.rust new file mode 100644 index 0000000000..95ea4b3ac1 --- /dev/null +++ b/Task/Binary-search/Rust/binary-search-1.rust @@ -0,0 +1,3 @@ +let arr = ["a", "bc", "def", "ghij"]; +arr.binary_search(&"a"); // Search lexicographically +arr.binary_search_by(|e| e.len().cmp(&1)); // Search by length diff --git a/Task/Binary-search/Rust/binary-search-2.rust b/Task/Binary-search/Rust/binary-search-2.rust new file mode 100644 index 0000000000..fe980c5e0d --- /dev/null +++ b/Task/Binary-search/Rust/binary-search-2.rust @@ -0,0 +1,18 @@ +use std::cmp::Ordering::*; +fn binary_search(arr: &[T], elem: &T) -> Option +{ + let mut size = arr.len(); + let mut base = 0; + + while size > 0 { + size /= 2; + let mid = base + size; + base = match arr[mid].cmp(elem) { + Less => mid, + Greater => base, + Equal => return Some(mid) + }; + } + + None +} diff --git a/Task/Binary-search/Rust/binary-search.rust b/Task/Binary-search/Rust/binary-search.rust deleted file mode 100644 index 4a4bd8563e..0000000000 --- a/Task/Binary-search/Rust/binary-search.rust +++ /dev/null @@ -1,17 +0,0 @@ -fn bin_search(sar : &[T], v : &T) -> Option { - let mut lowi=0; - let mut highi=sar.len(); - loop { - if lowi>=highi { - return None; - } - let mi=lowi+(highi-lowi)/2; - if sar[mi].lt(v) { - lowi=mi+1; - } else if sar[mi].gt(v) { - highi=mi; - } else { - return Some(mi); - } - } -} diff --git a/Task/Binary-strings/Java/binary-strings-1.java b/Task/Binary-strings/Java/binary-strings-1.java new file mode 100644 index 0000000000..fc8f4a729d --- /dev/null +++ b/Task/Binary-strings/Java/binary-strings-1.java @@ -0,0 +1,118 @@ +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; + +public class MutableByteString { + + private byte[] bytes; + private int length; + + public MutableByteString(byte... bytes) { + setInternal(bytes); + } + + public int length() { + return length; + } + + public boolean isEmpty() { + return length == 0; + } + + public byte get(int index) { + return bytes[check(index)]; + } + + public void set(byte[] bytes) { + setInternal(bytes); + } + + public void set(int index, byte b) { + bytes[check(index)] = b; + } + + public void append(byte b) { + if (length >= bytes.length) { + int len = 2 * bytes.length; + if (len < 0) + len = Integer.MAX_VALUE; + bytes = Arrays.copyOf(bytes, len); + } + bytes[length] = b; + length++; + } + + public MutableByteString substring(int from, int to) { + return new MutableByteString(Arrays.copyOfRange(bytes, from, to)); + } + + public void replace(byte[] from, byte[] to) { + ByteArrayOutputStream copy = new ByteArrayOutputStream(); + if (from.length == 0) { + for (byte b : bytes) { + copy.write(to, 0, to.length); + copy.write(b); + } + copy.write(to, 0, to.length); + } else { + for (int i = 0; i < length; i++) { + if (regionEquals(i, from)) { + copy.write(to, 0, to.length); + i += from.length - 1; + } else { + copy.write(bytes[i]); + } + } + } + set(copy.toByteArray()); + } + + public boolean regionEquals(int offset, MutableByteString other, int otherOffset, int len) { + if (Math.max(offset, otherOffset) + len < 0) + return false; + if (offset + len > length || otherOffset + len > other.length()) + return false; + for (int i = 0; i < len; i++) { + if (bytes[offset + i] != other.get(otherOffset + i)) + return false; + } + return true; + } + + public String toHexString() { + char[] hex = new char[2 * length]; + for (int i = 0; i < length; i++) { + hex[2 * i] = "0123456789abcdef".charAt(bytes[i] >> 4 & 0x0F); + hex[2 * i + 1] = "0123456789abcdef".charAt(bytes[i] & 0x0F); + } + return new String(hex); + } + + public String toStringUtf8() { + return new String(bytes, 0, length, StandardCharsets.UTF_8); + } + + private void setInternal(byte[] bytes) { + this.bytes = bytes.clone(); + this.length = bytes.length; + } + + private boolean regionEquals(int offset, byte[] other) { + int len = other.length; + if (offset < 0 || offset + len < 0) + return false; + if (offset + len > length) + return false; + for (int i = 0; i < len; i++) { + if (bytes[offset + i] != other[i]) + return false; + } + return true; + } + + private int check(int index) { + if (index < 0 || index >= length) + throw new IndexOutOfBoundsException(String.valueOf(index)); + return index; + } +} diff --git a/Task/Binary-strings/Java/binary-strings-2.java b/Task/Binary-strings/Java/binary-strings-2.java new file mode 100644 index 0000000000..997033280b --- /dev/null +++ b/Task/Binary-strings/Java/binary-strings-2.java @@ -0,0 +1,60 @@ +import static org.hamcrest.CoreMatchers.is; + +import java.nio.charset.StandardCharsets; +import org.junit.Assert; +import org.junit.Test; + +public class MutableByteStringTest { + + @Test + public void testReplaceEmpty() { + MutableByteString str = new MutableByteString("hello".getBytes(StandardCharsets.UTF_8)); + str.replace(new byte[]{}, new byte[]{'-'}); + + Assert.assertThat(str.toStringUtf8(), is("-h-e-l-l-o-")); + } + + @Test + public void testReplaceMultiple() { + MutableByteString str = new MutableByteString("hello".getBytes(StandardCharsets.UTF_8)); + str.replace(new byte[]{'l'}, new byte[]{'1', '2', '3'}); + + Assert.assertThat(str.toStringUtf8(), is("he123123o")); + } + + @Test + public void testToHexString() { + MutableByteString str = new MutableByteString("hello".getBytes(StandardCharsets.UTF_8)); + + Assert.assertThat(str.toHexString(), is("68656c6c6f")); + } + + @Test + public void testAppend() { + MutableByteString str = new MutableByteString("hello".getBytes(StandardCharsets.UTF_8)); + str.append((byte) ','); + str.append((byte) ' '); + str.append((byte) 'w'); + str.append((byte) 'o'); + str.append((byte) 'r'); + str.append((byte) 'l'); + str.append((byte) 'd'); + + Assert.assertThat(str.toStringUtf8(), is("hello, world")); + } + @Test + public void testSubstring() { + MutableByteString str = new MutableByteString("hello, world".getBytes(StandardCharsets.UTF_8)); + + Assert.assertThat(str.substring(0, 5).toStringUtf8(), is("hello")); + Assert.assertThat(str.substring(7, 12).toStringUtf8(), is("world")); + } + + @Test + public void testRegionEquals() { + MutableByteString str = new MutableByteString("hello".getBytes(StandardCharsets.UTF_8)); + + Assert.assertThat(str.regionEquals(0, new MutableByteString(new byte[]{'h'}), 0, 1), is(true)); + Assert.assertThat(str.regionEquals(0, new MutableByteString(new byte[]{'h'}), 0, 2), is(false)); + } +} diff --git a/Task/Binary-strings/Lingo/binary-strings.lingo b/Task/Binary-strings/Lingo/binary-strings.lingo new file mode 100644 index 0000000000..9acbff0d3e --- /dev/null +++ b/Task/Binary-strings/Lingo/binary-strings.lingo @@ -0,0 +1,60 @@ +-- String creation and destruction +foo = "Hello world!" -- created by assignment; destruction via garbage collection + +-- Strings are binary safe +put numtochar(0) into char 6 of foo +put chartonum(foo.char[6]) +-- 0 +put str.char[7..foo.length] +-- "world!" + +-- String cloning and copying +bar = foo -- copies foo contents to bar + +-- String comparison +put (foo=bar) -- TRUE +put (foo<>bar) -- FALSE + +-- Check if a string is empty +put (foo=EMPTY) +put (foo="") +put (foo.length=0) + +-- Append a byte to a string +put "X" after foo +put chartonum(88) after foo + +-- Extract a substring from a string +put foo.char[3..5] + +-- Replace every occurrence of a byte (or a string) in a string with another string + +---------------------------------------- +-- Replace in string +-- @param {string} stringToFind +-- @param {string} stringToInsert +-- @param {string} input +-- @return {string} +---------------------------------------- +on replaceAll (stringToFind, stringToInsert, input) + output = "" + findLen = stringToFind.length - 1 + repeat while TRUE + currOffset = offset(stringToFind, input) + if currOffset=0 then exit repeat + put input.char[1..currOffset] after output + delete the last char of output + put stringToInsert after output + delete input.char[1..(currOffset + findLen)] + end repeat + put input after output + return output +end + +put replaceAll("o", "X", foo) + +-- Join strings (4x the same result) +foo = "Hello " & "world!" +foo = "Hello" & numtochar(32) & "world!" +foo = "Hello" & SPACE & "world!" +foo = "Hello" && "world!" diff --git a/Task/Binary-strings/Perl-6/binary-strings.pl6 b/Task/Binary-strings/Perl-6/binary-strings.pl6 index f0170d1a94..29874d9429 100644 --- a/Task/Binary-strings/Perl-6/binary-strings.pl6 +++ b/Task/Binary-strings/Perl-6/binary-strings.pl6 @@ -41,7 +41,7 @@ class ByteStr { } # A couple of operators for our new type: -multi infix:(ByteStr $x, ByteStr $y) { $x.bytes cmp $y.bytes } +multi infix:(ByteStr $x, ByteStr $y) { $x.bytes.join cmp $y.bytes.join } multi infix:<~> (ByteStr $x, ByteStr $y) { ByteStr.new(:bytes(|$x.bytes, |$y.bytes)) } # create some byte strings (destruction not needed due to garbage collection) diff --git a/Task/Binary-strings/Red/binary-strings.red b/Task/Binary-strings/Red/binary-strings.red new file mode 100644 index 0000000000..8525c0d244 --- /dev/null +++ b/Task/Binary-strings/Red/binary-strings.red @@ -0,0 +1,18 @@ +Red [] +s: copy "abc" ;; string creation + +s: none ;; destruction +t: "Abc" +if t == "abc" [print "equal case"] ;; comparison , case sensitive +if t = "abc" [print "equal (case insensitive)"] ;; comparison , case insensitive +s: copy "" ;; copying string +if empty? s [print "string is empty "] ;; check if string is empty +append s #"a" ;; append byte +substr: copy/part at "1234" 3 2 ;; ~ substr ("1234" ,3,2) , red has 1 based indices ! +?? substr +s: replace/all "abcabcabc" "bc" "x" ;; replace all "bc" by "x" +?? s +s: append "hello " "world" ;; join 2 strings +?? s +s: rejoin ["hello " "world" " !"] ;; join multiple strings +?? s diff --git a/Task/Binary-strings/Rust/binary-strings.rust b/Task/Binary-strings/Rust/binary-strings.rust index 5dc8ea1105..2b78975250 100644 --- a/Task/Binary-strings/Rust/binary-strings.rust +++ b/Task/Binary-strings/Rust/binary-strings.rust @@ -1,72 +1,71 @@ use std::str; + fn main() { - //Create new string - let str = String::from("Hello world!"); - println!("{}", str); - assert!(str == "Hello world!", "Incorrect string text"); + // Create new string + let string = String::from("Hello world!"); + println!("{}", string); + assert_eq!(string, "Hello world!", "Incorrect string text"); - //Create and assign value to string + // Create and assign value to string let mut assigned_str = String::new(); - assert!(assigned_str == "", "Incorrect string creation"); - assigned_str.push_str("Text has been assigned!"); + assert_eq!(assigned_str, "", "Incorrect string creation"); + assigned_str += "Text has been assigned!"; println!("{}", assigned_str); - assert!(assigned_str == "Text has been assigned!","Incorrect string text"); + assert_eq!(assigned_str, "Text has been assigned!","Incorrect string text"); - //String comparison, compared lexicographically byte-wise - //same as the asserts above - if str == "Hello world!" && assigned_str == "Text has been assigned!" { + // String comparison, compared lexicographically byte-wise same as the asserts above + if string == "Hello world!" && assigned_str == "Text has been assigned!" { println!("Strings are equal"); } - //Cloning -> str can still be used after cloning - let clone_str = str.clone(); - println!("String is:{} and Clone string is: {}", str, clone_str); - assert!(clone_str == str, "Incorrect string creation"); + // Cloning -> string can still be used after cloning + let clone_str = string.clone(); + println!("String is:{} and Clone string is: {}", string, clone_str); + assert_eq!(clone_str, string, "Incorrect string creation"); - //Copying, str won't be usable anymore, accessing it will cause compiler failure - let copy_str = str; + // Copying, string won't be usable anymore, accessing it will cause compiler failure + let copy_str = string; println!("String copied now: {}", copy_str); - //Check if string is empty + // Check if string is empty let empty_str = String::new(); assert!(empty_str.is_empty(), "Error, string should be empty"); - //Append byte, Rust strings are a stream of UTF-8 bytes - let byte_vec = vec![65]; //contains A + // Append byte, Rust strings are a stream of UTF-8 bytes + let byte_vec = [65]; // contains A let byte_str = str::from_utf8(&byte_vec).unwrap(); - assert!(byte_str == "A", "Incorrect byte append"); + assert_eq!(byte_str, "A", "Incorrect byte append"); - //Substrings can be accessed through slices + // Substrings can be accessed through slices let test_str = "Blah String"; let mut sub_str = &test_str[0..11]; - assert!(sub_str == "Blah String", "Error in slicing"); + assert_eq!(sub_str, "Blah String", "Error in slicing"); sub_str = &test_str[1..5]; - assert!(sub_str == "lah ", "Error in slicing"); + assert_eq!(sub_str, "lah ", "Error in slicing"); sub_str = &test_str[3..]; - assert!(sub_str == "h String", "Error in slicing"); + assert_eq!(sub_str, "h String", "Error in slicing"); sub_str = &test_str[..2]; - assert!(sub_str == "Bl", "Error in slicing"); + assert_eq!(sub_str, "Bl", "Error in slicing"); - //String replace, note string is immutable + // String replace, note string is immutable let org_str = "Hello"; - assert!( org_str.replace("l", "a") == "Heaao", "Error in replacement"); - assert!( org_str.replace("ll", "r") == "Hero", "Error in replacement"); + assert_eq!(org_str.replace("l", "a"), "Heaao", "Error in replacement"); + assert_eq!(org_str.replace("ll", "r"), "Hero", "Error in replacement"); - //Joining strings requires a string and an &str or a two string one of which needs an & for coercion + // Joining strings requires a `String` and an &str or a two `String`s one of which needs an & for coercion let str1 = "Hi"; let str2 = " There"; let fin_str = str1.to_string() + str2; - assert!( fin_str == "Hi There", "Error in concatenation"); + assert_eq!(fin_str, "Hi There", "Error in concatenation"); - //Joining strings requires a string and an &str or two strings, one of which needs an & for coercion + // Joining strings requires a `String` and an &str or two `Strings`s, one of which needs an & for coercion let str1 = "Hi"; let str2 = " There"; let fin_str = str1.to_string() + str2; - assert!( fin_str == "Hi There", "Error in concatenation"); + assert_eq!(fin_str, "Hi There", "Error in concatenation"); - //Splits -- note Rust supports passing patterns to splits + // Splits -- note Rust supports passing patterns to splits let f_str = "Pooja and Sundar are up in Tumkur"; - let split_str: Vec<&str> = f_str.split(' ').collect(); - assert!( split_str == ["Pooja", "and", "Sundar", "are", "up", "in", "Tumkur"], "Error in string split"); - + let split_str: Vec<_> = f_str.split(' ').collect(); + assert_eq!(split_str, ["Pooja", "and", "Sundar", "are", "up", "in", "Tumkur"], "Error in string split"); } diff --git a/Task/Binary-strings/VBA/binary-strings-1.vba b/Task/Binary-strings/VBA/binary-strings-1.vba new file mode 100644 index 0000000000..4c3370e72a --- /dev/null +++ b/Task/Binary-strings/VBA/binary-strings-1.vba @@ -0,0 +1,4 @@ +'Set the string comparison method to Binary. +Option Compare Binary ' That is, "AAA" is less than "aaa". +' Set the string comparison method to Text. +Option Compare Text ' That is, "AAA" is equal to "aaa". diff --git a/Task/Binary-strings/VBA/binary-strings-10.vba b/Task/Binary-strings/VBA/binary-strings-10.vba new file mode 100644 index 0000000000..9bacffc163 --- /dev/null +++ b/Task/Binary-strings/VBA/binary-strings-10.vba @@ -0,0 +1,9 @@ +Sub Join_Strings() +Dim A$, B As String + + A = "Hello" + B = "world" + Debug.Print A & " " & B 'return : Hello world + 'If you're sure that A and B are Strings, you can use + instead of & : + Debug.Print A + " " + B 'return : Hello world +End Sub diff --git a/Task/Binary-strings/VBA/binary-strings-2.vba b/Task/Binary-strings/VBA/binary-strings-2.vba new file mode 100644 index 0000000000..883fb91f80 --- /dev/null +++ b/Task/Binary-strings/VBA/binary-strings-2.vba @@ -0,0 +1,5 @@ +Sub Creation_String_FirstWay() +Dim myString As String + 'Here, myString is created and equal "" + +End Sub '==> Here the string is destructed ! diff --git a/Task/Binary-strings/VBA/binary-strings-3.vba b/Task/Binary-strings/VBA/binary-strings-3.vba new file mode 100644 index 0000000000..b9410b9644 --- /dev/null +++ b/Task/Binary-strings/VBA/binary-strings-3.vba @@ -0,0 +1,9 @@ +Sub String_Assignment() +Dim myString$ + 'Here, myString is created and equal "" + + 'assignments : + myString = vbNullString 'return : "" + myString = "Hello World" 'return : "Hello World" + myString = String(12, "A") 'return : "AAAAAAAAAAAA" +End Sub diff --git a/Task/Binary-strings/VBA/binary-strings-4.vba b/Task/Binary-strings/VBA/binary-strings-4.vba new file mode 100644 index 0000000000..0e82759ca8 --- /dev/null +++ b/Task/Binary-strings/VBA/binary-strings-4.vba @@ -0,0 +1,28 @@ +Sub String_Comparison_FirstWay() +Dim A$, B$, C$ + + If A = B Then Debug.Print "A = B" + + A = "creation": B = "destruction": C = "CREATION" + + 'test equality : (operator =) + If A = B Then + Debug.Print A & " = " & B + 'used to Sort : (operator < and >) + ElseIf A > B Then + Debug.Print A & " > " & B + Else 'here : A < B + Debug.Print A & " < " & B + End If + + 'test if A is different from C + If A <> C Then Debug.Print A & " and " & B & " are differents." + 'same test without case-sensitive + If UCase(A) = UCase(C) Then Debug.Print A & " = " & C & " (no case-sensitive)" + + 'operator Like : + If A Like "*ation" Then Debug.Print A & " Like *ation" + If Not B Like "*ation" Then Debug.Print B & " Not Like *ation" + 'See Also : +'https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/like-operator +End Sub diff --git a/Task/Binary-strings/VBA/binary-strings-5.vba b/Task/Binary-strings/VBA/binary-strings-5.vba new file mode 100644 index 0000000000..01ec5f6299 --- /dev/null +++ b/Task/Binary-strings/VBA/binary-strings-5.vba @@ -0,0 +1,6 @@ +Sub String_Clone_Copy() +Dim A As String, B$ + A = "Hello world!" + 'cloning : + B = A +End Sub diff --git a/Task/Binary-strings/VBA/binary-strings-6.vba b/Task/Binary-strings/VBA/binary-strings-6.vba new file mode 100644 index 0000000000..ca8d2c6415 --- /dev/null +++ b/Task/Binary-strings/VBA/binary-strings-6.vba @@ -0,0 +1,23 @@ +Sub Check_Is_Empty() +Dim A As String, B As Variant + + Debug.Print IsEmpty(A) 'return False + Debug.Print IsEmpty(Null) 'return False + Debug.Print IsEmpty(B) 'return True ==> B is a Variant + + Debug.Print A = vbNullString 'return True + Debug.Print StrPtr(A) 'return 0 (zero) + + 'Press the OK button without enter a data in the InputBox : + A = InputBox("Enter your own String : ") + Debug.Print A = "" 'return True + Debug.Print IsEmpty(A) 'return False + Debug.Print StrPtr(A) = 0 'return False + + 'Press the cancel button (with or without enter a data in the InputBox) + A = InputBox("Enter your own String : ") + Debug.Print StrPtr(A) = 0 'return True + Debug.Print IsEmpty(A) 'return False + Debug.Print A = "" 'return True + 'Note : StrPtr is the only way to know if you cancel the inputbox +End Sub diff --git a/Task/Binary-strings/VBA/binary-strings-7.vba b/Task/Binary-strings/VBA/binary-strings-7.vba new file mode 100644 index 0000000000..35409ef27f --- /dev/null +++ b/Task/Binary-strings/VBA/binary-strings-7.vba @@ -0,0 +1,5 @@ +Sub Append_to_string() +Dim A As String + A = "Hello worl" + Debug.Print A & Chr(100) 'return : Hello world +End Sub diff --git a/Task/Binary-strings/VBA/binary-strings-8.vba b/Task/Binary-strings/VBA/binary-strings-8.vba new file mode 100644 index 0000000000..5a8b64d946 --- /dev/null +++ b/Task/Binary-strings/VBA/binary-strings-8.vba @@ -0,0 +1,6 @@ +Sub ExtractFromString() +Dim A$, B As String + A = "Hello world" + B = Mid(A, 3, 8) + Debug.Print B 'return : llo worl +End Sub diff --git a/Task/Binary-strings/VBA/binary-strings-9.vba b/Task/Binary-strings/VBA/binary-strings-9.vba new file mode 100644 index 0000000000..88804d6b12 --- /dev/null +++ b/Task/Binary-strings/VBA/binary-strings-9.vba @@ -0,0 +1,7 @@ +Sub ReplaceInString() +Dim A$, B As String, C$ + A = "Hello world" + B = Chr(108) ' "l" + C = " " + Debug.Print Replace(A, B, C) 'return : He o wor d +End Sub diff --git a/Task/Bitcoin-address-validation/00DESCRIPTION b/Task/Bitcoin-address-validation/00DESCRIPTION index 434d4e11c5..c930f1b0d8 100644 --- a/Task/Bitcoin-address-validation/00DESCRIPTION +++ b/Task/Bitcoin-address-validation/00DESCRIPTION @@ -1,26 +1,36 @@ {{omit from|Brlcad}} {{omit from|GUISS}} + +;Task: Write a program that takes a [[wp:bitcoin|bitcoin address]] as argument, and checks whether or not this address is valid. -A bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters 0, O, I and l. +A bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters: +:::*   0   zero +:::*   O   uppercase oh +:::*   I   uppercase eye +:::*   l   lowercase ell + With this encoding, a bitcoin address encodes 25 bytes: * the first byte is the version number, which will be zero for this task ; * the next twenty bytes are a [[RIPEMD-160]] digest, but you don't have to know that for this task: you can consider them a pure arbitrary data ; * the last four bytes are a checksum check. They are the first four bytes of a double [[SHA-256]] digest of the previous 21 bytes. + To check the bitcoin address, you must read the first twenty-one bytes, compute the checksum, and check that it corresponds to the last four bytes. The program can either return a boolean value or throw an exception when not valid. You can use a digest library for [[SHA-256]]. -Here is an example of a bitcoin address: -1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i +;Example of a bitcoin address: + + 1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i + -It does not belong to anyone. -It is part of the test suite of the bitcoin software. -You can change a few characters in this string and check that it will fail the test. +It doesn't belong to anyone and is part of the test suite of the bitcoin software. +
You can change a few characters in this string and check that it'll fail the test. +

diff --git a/Task/Bitcoin-address-validation/Delphi/bitcoin-address-validation.delphi b/Task/Bitcoin-address-validation/Delphi/bitcoin-address-validation.delphi new file mode 100644 index 0000000000..cc7624414b --- /dev/null +++ b/Task/Bitcoin-address-validation/Delphi/bitcoin-address-validation.delphi @@ -0,0 +1,64 @@ +uses + DCPsha256; + +type + TByteArray = array of Byte; + +function HashSHA256(const Input: TByteArray): TByteArray; +var + Hasher: TDCP_sha256; +begin + Hasher := TDCP_sha256.Create(nil); + try + Hasher.Init; + Hasher.Update(Input[0], Length(Input)); + SetLength(Result, Hasher.HashSize div 8); + Hasher.Final(Result[0]); + finally + Hasher.Free; + end; +end; + +function DecodeBase58(const Input: string): TByteArray; +const + Size = 25; + Alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; +var + C: Char; + I, J: Integer; +begin + SetLength(Result, Size); + + for C in Input do + begin + I := Pos(C, Alphabet) - 1; + + if I = -1 then + raise Exception.CreateFmt('Invalid character found: %s', [C]); + + for J := High(Result) downto 0 do + begin + I := I + (58 * Result[J]); + Result[J] := I mod 256; + I := I div 256; + end; + + if I <> 0 then + raise Exception.Create('Address too long'); + end; +end; + +procedure ValidateBitcoinAddress(const Address: string); +var + Hashed: TByteArray; + Decoded: TByteArray; +begin + if (Length(Address) < 26) or (Length(Address) > 35) then + raise Exception.Create('Wrong length'); + + Decoded := DecodeBase58(Address); + Hashed := HashSHA256(HashSHA256(Copy(Decoded, 0, 21))); + + if not CompareMem(@Decoded[21], @Hashed[0], 4) then + raise Exception.Create('Bad digest'); +end; diff --git a/Task/Bitcoin-address-validation/Haskell/bitcoin-address-validation.hs b/Task/Bitcoin-address-validation/Haskell/bitcoin-address-validation.hs index ae360d10e9..9ae1e4aa1b 100644 --- a/Task/Bitcoin-address-validation/Haskell/bitcoin-address-validation.hs +++ b/Task/Bitcoin-address-validation/Haskell/bitcoin-address-validation.hs @@ -1,45 +1,50 @@ -import Data.List (unfoldr, elemIndex) -import Data.Binary (Word8) -import Crypto.Hash.SHA256 (hash) -import Data.ByteString (unpack, pack) +import Control.Monad (when) +import Data.List (elemIndex) +import Data.Monoid ((<>)) +import qualified Data.ByteString as BS +import Data.ByteString (ByteString) + +import Crypto.Hash.SHA256 (hash) -- from package cryptohash -- Convert from base58 encoded value to Integer decode58 :: String -> Maybe Integer -decode58 = foldl (\v d -> (+) <$> ((58*) <$> v) <*> (fromIntegral <$> elemIndex d c58 )) $ Just 0 - where c58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" +decode58 = fmap combine . traverse parseDigit + where + combine = foldl (\acc digit -> 58 * acc + digit) 0 -- should be foldl', but this trips up the highlighting + parseDigit char = toInteger <$> elemIndex char c58 + c58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" --- Convert from base58 encoded value to list of bytes -toBytes :: Integer -> [Word8] -toBytes x = reverse $ unfoldr (\b -> if b == 0 then Nothing else Just (fromIntegral $ b `mod` 256, b `div` 256)) x +-- Convert from base58 encoded value to bytes +toBytes :: Integer -> ByteString +toBytes = BS.reverse . BS.pack . map (fromIntegral . (`mod` 256)) . takeWhile (> 0) . iterate (`div` 256) + +-- Check if the hash of the first 21 (padded) bytes matches the last 4 bytes +checksumValid :: ByteString -> Bool +checksumValid address = + let (value, checksum) = BS.splitAt 21 $ leftPad address + in and $ BS.zipWith (==) checksum $ hash $ hash $ value + where + leftPad bs = BS.replicate (25 - BS.length bs) 0 <> bs + +-- utility +withError :: e -> Maybe a -> Either e a +withError e = maybe (Left e) Right -- Check validity of base58 encoded bitcoin address. --- Result is either an error string (Left) or a validity bool (Right). -validityCheck :: String -> Either String Bool -validityCheck encodedAddress = - let d58 = decode58 encodedAddress - in case d58 of - Nothing -> Left "Invalid base 58 encoding" - Just ev -> - let address = toBytes ev - addressLength = length address - in if addressLength > 25 - then Left "Address length exceeds 25 bytes" - else - if addressLength < 4 - then Left "Address length less than 4 bytes" - else - let (bs,cs) = splitAt 21 $ replicate (25 - addressLength) 0 ++ address - in Right $ all (uncurry (==)) (zip cs $ unpack $ hash $ hash $ pack bs) +-- Result is either an error string (Left) or unit (Right ()). +validityCheck :: String -> Either String () +validityCheck encoded = do + num <- withError "Invalid base 58 encoding" $ decode58 encoded + let address = toBytes num + when (BS.length address > 25) $ Left "Address length exceeds 25 bytes" + when (BS.length address < 4) $ Left "Address length less than 4 bytes" + when (not $ checksumValid address) $ Left "Invalid checksum" -- Run one validity check and display results. validate :: String -> IO () -validate encodedAddress = - let vc = validityCheck encodedAddress - in case vc of - Left err -> - putStrLn $ show encodedAddress ++ " -> " ++ show err - Right validity -> - putStrLn $ show encodedAddress ++ " -> " ++ if validity then "Valid" else "Invalid" +validate encodedAddress = do + let result = either show (const "Valid") $ validityCheck encodedAddress + putStrLn $ show encodedAddress ++ " -> " ++ result -- Run some validity check tests. main :: IO () diff --git a/Task/Bitcoin-address-validation/Java/bitcoin-address-validation.java b/Task/Bitcoin-address-validation/Java/bitcoin-address-validation.java index 90525a5f31..e2c4c25222 100644 --- a/Task/Bitcoin-address-validation/Java/bitcoin-address-validation.java +++ b/Task/Bitcoin-address-validation/Java/bitcoin-address-validation.java @@ -1,3 +1,4 @@ +import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; @@ -9,7 +10,7 @@ public class BitcoinAddressValidator { public static boolean validateBitcoinAddress(String addr) { if (addr.length() < 26 || addr.length() > 35) return false; - byte[] decoded = decodeBase58(addr, 25); + byte[] decoded = decodeBase58To25Bytes(addr); if (decoded == null) return false; @@ -19,22 +20,19 @@ public class BitcoinAddressValidator { return Arrays.equals(Arrays.copyOfRange(hash2, 0, 4), Arrays.copyOfRange(decoded, 21, 25)); } - private static byte[] decodeBase58(String input, int len) { - byte[] output = new byte[len]; + private static byte[] decodeBase58To25Bytes(String input) { + BigInteger num = BigInteger.ZERO; for (char t : input.toCharArray()) { int p = ALPHABET.indexOf(t); if (p == -1) return null; - for (int j = len - 1; j >= 0; j--) { - p += 58 * (output[j] & 0xFF); - output[j] = (byte) (p % 256); - p /= 256; - } - if (p != 0) - return null; + num = num.multiply(BigInteger.valueOf(58)).add(BigInteger.valueOf(p)); } - return output; + byte[] result = new byte[25]; + byte[] numBytes = num.toByteArray(); + System.arraycopy(numBytes, 0, result, result.length - numBytes.length, numBytes.length); + return result; } private static byte[] sha256(byte[] data) { diff --git a/Task/Bitcoin-address-validation/Julia/bitcoin-address-validation.julia b/Task/Bitcoin-address-validation/Julia/bitcoin-address-validation.julia new file mode 100644 index 0000000000..adbe3741bc --- /dev/null +++ b/Task/Bitcoin-address-validation/Julia/bitcoin-address-validation.julia @@ -0,0 +1,38 @@ +using SHA + +bytes(n::Integer, l::Int) = collect(UInt8, (n >> 8i) & 0xFF for i in l-1:-1:0) + +function decodebase58(bc::String, l::Int) + digits = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" + num = big(0) + for c in bc + num = num * 58 + search(digits, c) - 1 + end + return bytes(num, l) +end + +function checkbcaddress(addr::String) + if !(25 ≤ length(addr) ≤ 35) return false end + bcbytes = decodebase58(addr, 25) + sha = sha256(sha256(bcbytes[1:end-4])) + return bcbytes[end-3:end] == sha[1:4] +end + +const addresses = Dict( + "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i" => true, + "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62j" => false, + "1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9" => true, + "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62X" => true, + "1ANNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i" => false, + "1A Na15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i" => false, + "BZbvjr" => false, + "i55j" => false, + "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62!" => false, + "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62iz" => false, + "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62izz" => false, + "1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nJ9" => false, + "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62I" => false) + +for (addr, corr) in addresses + println("Address: $addr\nExpected: $corr\tChecked: ", checkbcaddress(addr)) +end diff --git a/Task/Bitcoin-address-validation/Python/bitcoin-address-validation-1.py b/Task/Bitcoin-address-validation/Python/bitcoin-address-validation-1.py index 9163777603..cf6f8776ba 100644 --- a/Task/Bitcoin-address-validation/Python/bitcoin-address-validation-1.py +++ b/Task/Bitcoin-address-validation/Python/bitcoin-address-validation-1.py @@ -8,8 +8,11 @@ def decode_base58(bc, length): n = n * 58 + digits58.index(char) return n.to_bytes(length, 'big') def check_bc(bc): - bcbytes = decode_base58(bc, 25) - return bcbytes[-4:] == sha256(sha256(bcbytes[:-4]).digest()).digest()[:4] + try: + bcbytes = decode_base58(bc, 25) + return bcbytes[-4:] == sha256(sha256(bcbytes[:-4]).digest()).digest()[:4] + except Exception: + return False print(check_bc('1AGNa15ZQXAZUgFiqJ3i7Z2DPU2J6hW62i')) print(check_bc("17NdbrSGoUotzeGCcMMCqnFkEvLymoou9j")) diff --git a/Task/Bitcoin-address-validation/Scala/bitcoin-address-validation.scala b/Task/Bitcoin-address-validation/Scala/bitcoin-address-validation.scala new file mode 100644 index 0000000000..e8cf552893 --- /dev/null +++ b/Task/Bitcoin-address-validation/Scala/bitcoin-address-validation.scala @@ -0,0 +1,67 @@ +import java.security.MessageDigest +import java.util.Arrays.copyOfRange + +import scala.annotation.tailrec +import scala.math.BigInt + +object BitcoinAddressValidator extends App { + + private def bitcoinTestHarness(address: String, expected: Boolean): Unit = + assert(validateBitcoinAddress(address) == expected, s"Expected $expected for $address%s, but got ${!expected}.") + + private def validateBitcoinAddress(addr: String): Boolean = { + def sha256(data: Array[Byte]) = { + val md: MessageDigest = MessageDigest.getInstance("SHA-256") + md.update(data) + md.digest + } + + def decodeBase58To25Bytes(input: String): Option[Array[Byte]] = { + def ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" + + @tailrec + def loop(s: String, accu: BigInt): BigInt = { + if (s.isEmpty) accu + else { + val p = ALPHABET.indexOf(s.head) + if (p >= 0) loop(s.tail, accu * 58 + p) + else -1 + } + } + + val num = loop(input, 0) + if (num >= 0) { + val (result, numBytes) = (new Array[Byte](25), num.toByteArray) + System.arraycopy(numBytes, 0, result, result.length - numBytes.length, numBytes.length) + Some(result) + } + else None + } + + if (27 to 34 contains addr.length) { + val decoded = decodeBase58To25Bytes(addr) + if (decoded.isEmpty) false + else { + val hash1 = sha256(copyOfRange(decoded.get, 0, 21)) + copyOfRange(sha256(hash1), 0, 4) + .sameElements(copyOfRange(decoded.get, 21, 25)) + } + } else false + } // validateBitcoinAddress + + bitcoinTestHarness("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", true) + bitcoinTestHarness("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62j", false) + bitcoinTestHarness("1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9", true) + bitcoinTestHarness("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62X", false) + bitcoinTestHarness("1ANNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", false) + bitcoinTestHarness("1A Na15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i", false) + bitcoinTestHarness("BZbvjr", false) + bitcoinTestHarness("i55j", false) + bitcoinTestHarness("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62!", false) + bitcoinTestHarness("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62iz", false) + bitcoinTestHarness("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62izz", false) + bitcoinTestHarness("1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nJ9", false) + bitcoinTestHarness("1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62I", false) + println(s"Successfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart}ms]") + +} diff --git a/Task/Bitcoin-public-point-to-address/Julia/bitcoin-public-point-to-address-1.julia b/Task/Bitcoin-public-point-to-address/Julia/bitcoin-public-point-to-address-1.julia new file mode 100644 index 0000000000..c0a0d43532 --- /dev/null +++ b/Task/Bitcoin-public-point-to-address/Julia/bitcoin-public-point-to-address-1.julia @@ -0,0 +1,28 @@ +const digits = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" +function encodebase58(b::Vector{<:Integer}) + out = Vector{Char}(34) + for j in endof(out):-1:1 + local c::Int = 0 + for i in eachindex(b) + c = c * 256 + b[i] + b[i] = c ÷ 58 + c %= 58 + end + out[j] = digits[c + 1] + end + local i = 1 + while i < endof(out) && out[i] == '1' + i += 1 + end + return join(out[i:end]) +end + +const COINVER = 0x00 +function pubpoint2address(x::Vector{UInt8}, y::Vector{UInt8}) + c = vcat(0x04, x, y) + c = vcat(COINVER, digest("ripemd160", sha256(c))) + d = sha256(sha256(c)) + return encodebase58(vcat(c, d[1:4])) +end +pubpoint2address(x::AbstractString, y::AbstractString) = + pubpoint2address(hex2bytes(x), hex2bytes(y)) diff --git a/Task/Bitcoin-public-point-to-address/Julia/bitcoin-public-point-to-address-2.julia b/Task/Bitcoin-public-point-to-address/Julia/bitcoin-public-point-to-address-2.julia new file mode 100644 index 0000000000..29dd559049 --- /dev/null +++ b/Task/Bitcoin-public-point-to-address/Julia/bitcoin-public-point-to-address-2.julia @@ -0,0 +1,3 @@ +x = "50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352" +y = "2CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6" +println(pubpoint2address(x, y))) diff --git a/Task/Bitcoin-public-point-to-address/Perl-6/bitcoin-public-point-to-address.pl6 b/Task/Bitcoin-public-point-to-address/Perl-6/bitcoin-public-point-to-address.pl6 index f9f959bf1b..cf9a4dd975 100644 --- a/Task/Bitcoin-public-point-to-address/Perl-6/bitcoin-public-point-to-address.pl6 +++ b/Task/Bitcoin-public-point-to-address/Perl-6/bitcoin-public-point-to-address.pl6 @@ -1,4 +1,5 @@ -use SSL::Digest; +use Digest::SHA; +use Digest::RIPEMD; constant BASE58 = < 1 2 3 4 5 6 7 8 9 diff --git a/Task/Bitmap-B-zier-curves-Cubic/Julia/bitmap-b-zier-curves-cubic.julia b/Task/Bitmap-B-zier-curves-Cubic/Julia/bitmap-b-zier-curves-cubic.julia new file mode 100644 index 0000000000..320adca6ef --- /dev/null +++ b/Task/Bitmap-B-zier-curves-Cubic/Julia/bitmap-b-zier-curves-cubic.julia @@ -0,0 +1,20 @@ +using Images + +function cubicbezier!(xy::Matrix, + img::Matrix = fill(RGB(255.0, 255.0, 255.0), 17, 17), + col::ColorTypes.Color = convert(eltype(img), Gray(0.0)), + n::Int = 20) + t = collect(0:n) ./ n + M = hcat((1 .- t) .^ 3, # a + 3t .* (1 .- t) .^ 2, # b + 3t .^ 2 .* (1 .- t), # c + t .^ 3) # d + p = floor.(Int, M * xy) + for i in 1:n + drawline!(img, p[i, :]..., p[i+1, :]..., col) + end + return img +end + +xy = [16 1; 1 4; 3 16; 15 11] +cubicbezier!(xy) diff --git a/Task/Bitmap-B-zier-curves-Cubic/Kotlin/bitmap-b-zier-curves-cubic.kotlin b/Task/Bitmap-B-zier-curves-Cubic/Kotlin/bitmap-b-zier-curves-cubic.kotlin new file mode 100644 index 0000000000..4df33af5ea --- /dev/null +++ b/Task/Bitmap-B-zier-curves-Cubic/Kotlin/bitmap-b-zier-curves-cubic.kotlin @@ -0,0 +1,77 @@ +// Version 1.2.40 + +import java.awt.Color +import java.awt.Graphics +import java.awt.image.BufferedImage +import kotlin.math.abs +import java.io.File +import javax.imageio.ImageIO + +class Point(var x: Int, var y: Int) + +class BasicBitmapStorage(width: Int, height: Int) { + val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR) + + fun fill(c: Color) { + val g = image.graphics + g.color = c + g.fillRect(0, 0, image.width, image.height) + } + + fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB()) + + fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y)) + + fun drawLine(x0: Int, y0: Int, x1: Int, y1: Int, c: Color) { + val dx = abs(x1 - x0) + val dy = abs(y1 - y0) + val sx = if (x0 < x1) 1 else -1 + val sy = if (y0 < y1) 1 else -1 + var xx = x0 + var yy = y0 + var e1 = (if (dx > dy) dx else -dy) / 2 + var e2: Int + while (true) { + setPixel(xx, yy, c) + if (xx == x1 && yy == y1) break + e2 = e1 + if (e2 > -dx) { e1 -= dy; xx += sx } + if (e2 < dy) { e1 += dx; yy += sy } + } + } + + fun cubicBezier(p1: Point, p2: Point, p3: Point, p4: Point, clr: Color, n: Int) { + val pts = List(n + 1) { Point(0, 0) } + for (i in 0..n) { + val t = i.toDouble() / n + val u = 1.0 - t + val a = u * u * u + val b = 3.0 * t * u * u + val c = 3.0 * t * t * u + val d = t * t * t + pts[i].x = (a * p1.x + b * p2.x + c * p3.x + d * p4.x).toInt() + pts[i].y = (a * p1.y + b * p2.y + c * p3.y + d * p4.y).toInt() + setPixel(pts[i].x, pts[i].y, clr) + } + for (i in 0 until n) { + val j = i + 1 + drawLine(pts[i].x, pts[i].y, pts[j].x, pts[j].y, clr) + } + } +} + +fun main(args: Array) { + val width = 200 + val height = 200 + val bbs = BasicBitmapStorage(width, height) + with (bbs) { + fill(Color.cyan) + val p1 = Point(0, 149) + val p2 = Point(30, 50) + val p3 = Point(120, 130) + val p4 = Point(160, 30) + cubicBezier(p1, p2, p3, p4, Color.black, 20) + val cbFile = File("cubic_bezier.jpg") + ImageIO.write(image, "jpg", cbFile) + } +} diff --git a/Task/Bitmap-B-zier-curves-Cubic/Perl-6/bitmap-b-zier-curves-cubic.pl6 b/Task/Bitmap-B-zier-curves-Cubic/Perl-6/bitmap-b-zier-curves-cubic.pl6 new file mode 100644 index 0000000000..169fac1aaf --- /dev/null +++ b/Task/Bitmap-B-zier-curves-Cubic/Perl-6/bitmap-b-zier-curves-cubic.pl6 @@ -0,0 +1,99 @@ +class Pixel { has UInt ($.R, $.G, $.B) } +class Bitmap { + has UInt ($.width, $.height); + has Pixel @!data; + + method fill(Pixel $p) { + @!data = $p.clone xx ($!width*$!height) + } + method pixel( + $i where ^$!width, + $j where ^$!height + --> Pixel + ) is rw { @!data[$i + $j * $!width] } + + method set-pixel ($i, $j, Pixel $p) { + self.pixel($i, $j) = $p.clone; + } + method get-pixel ($i, $j) returns Pixel { + self.pixel($i, $j); + } + + method line(($x0 is copy, $y0 is copy), ($x1 is copy, $y1 is copy), $pix) { + my $steep = abs($y1 - $y0) > abs($x1 - $x0); + if $steep { + ($x0, $y0) = ($y0, $x0); + ($x1, $y1) = ($y1, $x1); + } + if $x0 > $x1 { + ($x0, $x1) = ($x1, $x0); + ($y0, $y1) = ($y1, $y0); + } + my $Δx = $x1 - $x0; + my $Δy = abs($y1 - $y0); + my $error = 0; + my $Δerror = $Δy / $Δx; + my $y-step = $y0 < $y1 ?? 1 !! -1; + my $y = $y0; + for $x0 .. $x1 -> $x { + if $steep { + self.set-pixel($y, $x, $pix); + } else { + self.set-pixel($x, $y, $pix); + } + $error += $Δerror; + if $error >= 0.5 { + $y += $y-step; + $error -= 1.0; + } + } + } + + method dot (($px, $py), $pix, $radius = 2) { + for $px - $radius .. $px + $radius -> $x { + for $py - $radius .. $py + $radius -> $y { + self.set-pixel($x, $y, $pix) if ( $px - $x + ($py - $y) * i ).abs <= $radius; + } + } + } + + method cubic ( ($x1, $y1), ($x2, $y2), ($x3, $y3), ($x4, $y4), $pix, $segments = 30 ) { + my @line-segments = map -> $t { + my \a = (1-$t)³; + my \b = $t * (1-$t)² * 3; + my \c = $t² * (1-$t) * 3; + my \d = $t³; + (a*$x1 + b*$x2 + c*$x3 + d*$x4).round(1),(a*$y1 + b*$y2 + c*$y3 + d*$y4).round(1) + }, (0, 1/$segments, 2/$segments ... 1); + for @line-segments.rotor(2=>-1) -> ($p1, $p2) { self.line( $p1, $p2, $pix) }; + } + + method data { @!data } +} + +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 color( $r, $g, $b) { Pixel.new(R => $r, G => $g, B => $b) } + +my Bitmap $b = Bitmap.new( width => 600, height => 400) but PPM; + +$b.fill( color(2,2,2) ); + +my @points = (85,390), (5,5), (580,370), (270,10); + +my %seen; +my $c = 0; +for @points.permutations -> @this { + %seen{@this.reverse.join.Str}++; + next if %seen{@this.join.Str}; + $b.cubic( |@this, color(255-$c,127,$c+=22) ); +} + +@points.map: { $b.dot( $_, color(255,0,0), 3 )} + +$*OUT.write: $b.P6; diff --git a/Task/Bitmap-B-zier-curves-Quadratic/Kotlin/bitmap-b-zier-curves-quadratic.kotlin b/Task/Bitmap-B-zier-curves-Quadratic/Kotlin/bitmap-b-zier-curves-quadratic.kotlin new file mode 100644 index 0000000000..409434c7c6 --- /dev/null +++ b/Task/Bitmap-B-zier-curves-Quadratic/Kotlin/bitmap-b-zier-curves-quadratic.kotlin @@ -0,0 +1,75 @@ +// Version 1.2.40 + +import java.awt.Color +import java.awt.Graphics +import java.awt.image.BufferedImage +import kotlin.math.abs +import java.io.File +import javax.imageio.ImageIO + +class Point(var x: Int, var y: Int) + +class BasicBitmapStorage(width: Int, height: Int) { + val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR) + + fun fill(c: Color) { + val g = image.graphics + g.color = c + g.fillRect(0, 0, image.width, image.height) + } + + fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB()) + + fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y)) + + fun drawLine(x0: Int, y0: Int, x1: Int, y1: Int, c: Color) { + val dx = abs(x1 - x0) + val dy = abs(y1 - y0) + val sx = if (x0 < x1) 1 else -1 + val sy = if (y0 < y1) 1 else -1 + var xx = x0 + var yy = y0 + var e1 = (if (dx > dy) dx else -dy) / 2 + var e2: Int + while (true) { + setPixel(xx, yy, c) + if (xx == x1 && yy == y1) break + e2 = e1 + if (e2 > -dx) { e1 -= dy; xx += sx } + if (e2 < dy) { e1 += dx; yy += sy } + } + } + + fun quadraticBezier(p1: Point, p2: Point, p3: Point, clr: Color, n: Int) { + val pts = List(n + 1) { Point(0, 0) } + for (i in 0..n) { + val t = i.toDouble() / n + val u = 1.0 - t + val a = u * u + val b = 2.0 * t * u + val c = t * t + pts[i].x = (a * p1.x + b * p2.x + c * p3.x).toInt() + pts[i].y = (a * p1.y + b * p2.y + c * p3.y).toInt() + setPixel(pts[i].x, pts[i].y, clr) + } + for (i in 0 until n) { + val j = i + 1 + drawLine(pts[i].x, pts[i].y, pts[j].x, pts[j].y, clr) + } + } +} + +fun main(args: Array) { + val width = 320 + val height = 320 + val bbs = BasicBitmapStorage(width, height) + with (bbs) { + fill(Color.cyan) + val p1 = Point(10, 100) + val p2 = Point(250, 270) + val p3 = Point(150, 20) + quadraticBezier(p1, p2, p3, Color.black, 20) + val qbFile = File("quadratic_bezier.jpg") + ImageIO.write(image, "jpg", qbFile) + } +} diff --git a/Task/Bitmap-B-zier-curves-Quadratic/Perl-6/bitmap-b-zier-curves-quadratic.pl6 b/Task/Bitmap-B-zier-curves-Quadratic/Perl-6/bitmap-b-zier-curves-quadratic.pl6 new file mode 100644 index 0000000000..7d58e83a13 --- /dev/null +++ b/Task/Bitmap-B-zier-curves-Quadratic/Perl-6/bitmap-b-zier-curves-quadratic.pl6 @@ -0,0 +1,99 @@ +class Pixel { has UInt ($.R, $.G, $.B) } +class Bitmap { + has UInt ($.width, $.height); + has Pixel @!data; + + method fill(Pixel $p) { + @!data = $p.clone xx ($!width*$!height) + } + method pixel( + $i where ^$!width, + $j where ^$!height + --> Pixel + ) is rw { @!data[$i + $j * $!width] } + + method set-pixel ($i, $j, Pixel $p) { + return if $j >= $!height; + self.pixel($i, $j) = $p.clone; + } + method get-pixel ($i, $j) returns Pixel { + self.pixel($i, $j); + } + + method line(($x0 is copy, $y0 is copy), ($x1 is copy, $y1 is copy), $pix) { + my $steep = abs($y1 - $y0) > abs($x1 - $x0); + if $steep { + ($x0, $y0) = ($y0, $x0); + ($x1, $y1) = ($y1, $x1); + } + if $x0 > $x1 { + ($x0, $x1) = ($x1, $x0); + ($y0, $y1) = ($y1, $y0); + } + my $Δx = $x1 - $x0; + my $Δy = abs($y1 - $y0); + my $error = 0; + my $Δerror = $Δy / $Δx; + my $y-step = $y0 < $y1 ?? 1 !! -1; + my $y = $y0; + for $x0 .. $x1 -> $x { + if $steep { + self.set-pixel($y, $x, $pix); + } else { + self.set-pixel($x, $y, $pix); + } + $error += $Δerror; + if $error >= 0.5 { + $y += $y-step; + $error -= 1.0; + } + } + } + + method dot (($px, $py), $pix, $radius = 2) { + for $px - $radius .. $px + $radius -> $x { + for $py - $radius .. $py + $radius -> $y { + self.set-pixel($x, $y, $pix) if ( $px - $x + ($py - $y) * i ).abs <= $radius; + } + } + } + + method quadratic ( ($x1, $y1), ($x2, $y2), ($x3, $y3), $pix, $segments = 30 ) { + my @line-segments = map -> $t { + my \a = (1-$t)²; + my \b = $t * (1-$t) * 2; + my \c = $t²; + (a*$x1 + b*$x2 + c*$x3).round(1),(a*$y1 + b*$y2 + c*$y3).round(1) + }, (0, 1/$segments, 2/$segments ... 1); + for @line-segments.rotor(2=>-1) -> ($p1, $p2) { self.line( $p1, $p2, $pix) }; + } + + method data { @!data } +} + +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 color( $r, $g, $b) { Pixel.new(R => $r, G => $g, B => $b) } + +my Bitmap $b = Bitmap.new( width => 600, height => 400) but PPM; + +$b.fill( color(2,2,2) ); + +my @points = (65,25), (85,380), (570,15); + +my %seen; +my $c = 0; +for @points.permutations -> @this { + %seen{@this.reverse.join.Str}++; + next if %seen{@this.join.Str}; + $b.quadratic( |@this, color(255-$c,127,$c+=80) ); +} + +@points.map: { $b.dot( $_, color(255,0,0), 3 )} + +$*OUT.write: $b.P6; diff --git a/Task/Bitmap-Bresenhams-line-algorithm/00DESCRIPTION b/Task/Bitmap-Bresenhams-line-algorithm/00DESCRIPTION index 58ed56e689..d9d92d559b 100644 --- a/Task/Bitmap-Bresenhams-line-algorithm/00DESCRIPTION +++ b/Task/Bitmap-Bresenhams-line-algorithm/00DESCRIPTION @@ -1,3 +1,3 @@ ;Task: -Using the data storage type defined [[Basic_bitmap_storage|on this page]] for raster graphics images, draw a line given two points with the [[wp:Bresenham's line algorithm|Bresenham's line algorithm]]. +Using the data storage type defined on the [[Bitmap]] page for raster graphics images, draw a line given two points with [[wp:Bresenham's line algorithm|Bresenham's line algorithm]].

diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Java/bitmap-bresenhams-line-algorithm.java b/Task/Bitmap-Bresenhams-line-algorithm/Java/bitmap-bresenhams-line-algorithm.java index 2f972c0178..fa103a7989 100644 --- a/Task/Bitmap-Bresenhams-line-algorithm/Java/bitmap-bresenhams-line-algorithm.java +++ b/Task/Bitmap-Bresenhams-line-algorithm/Java/bitmap-bresenhams-line-algorithm.java @@ -1,90 +1,112 @@ -import java.awt.*; -import javax.swing.*; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Graphics; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; +import javax.swing.WindowConstants; -public class Bresenham extends JFrame { +public class Bresenham { public static void main(String[] args) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - JFrame f = new Bresenham(); - f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - f.setVisible(true); - f.add(new BresenhamPanel(), BorderLayout.CENTER); - f.setTitle("Bresenham"); - f.setResizable(false); - f.pack(); - f.setLocationRelativeTo(null); - } - }); + SwingUtilities.invokeLater(Bresenham::run); + } + + private static void run() { + JFrame f = new JFrame(); + f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); + f.setTitle("Bresenham"); + + f.getContentPane().add(new BresenhamPanel()); + f.pack(); + + f.setLocationRelativeTo(null); + f.setVisible(true); } } class BresenhamPanel extends JPanel { - final int centerX, centerY; - public BresenhamPanel() { - int w = 600; - int h = 500; - centerX = w / 2; - centerY = h / 2; - setPreferredSize(new Dimension(w, h)); - setBackground(Color.white); + private final int pixelSize = 10; + + BresenhamPanel() { + setPreferredSize(new Dimension(600, 500)); + setBackground(Color.WHITE); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); - drawLine(g, 0, 0, 8, 19); // NNE - drawLine(g, 0, 0, 19, 8); // ENE - drawLine(g, 0, 0, 19, -8); // ESE - drawLine(g, 0, 0, 8, -19); // SSE - drawLine(g, 0, 0, -8, -19); // SSW - drawLine(g, 0, 0, -19, -8); // WSW - drawLine(g, 0, 0, -19, 8); // WNW - drawLine(g, 0, 0, -8, 19); // NNW + int w = (getWidth() - 1) / pixelSize; + int h = (getHeight() - 1) / pixelSize; + int maxX = (w - 1) / 2; + int maxY = (h - 1) / 2; + int x1 = -maxX, x2 = maxX * -2 / 3, x3 = maxX * 2 / 3, x4 = maxX; + int y1 = -maxY, y2 = maxY * -2 / 3, y3 = maxY * 2 / 3, y4 = maxY; + + drawLine(g, 0, 0, x3, y1); // NNE + drawLine(g, 0, 0, x4, y2); // ENE + drawLine(g, 0, 0, x4, y3); // ESE + drawLine(g, 0, 0, x3, y4); // SSE + drawLine(g, 0, 0, x2, y4); // SSW + drawLine(g, 0, 0, x1, y3); // WSW + drawLine(g, 0, 0, x1, y2); // WNW + drawLine(g, 0, 0, x2, y1); // NNW } private void plot(Graphics g, int x, int y) { + int w = (getWidth() - 1) / pixelSize; + int h = (getHeight() - 1) / pixelSize; + int maxX = (w - 1) / 2; + int maxY = (h - 1) / 2; + + int borderX = getWidth() - ((2 * maxX + 1) * pixelSize + 1); + int borderY = getHeight() - ((2 * maxY + 1) * pixelSize + 1); + int left = (x + maxX) * pixelSize + borderX / 2; + int top = (y + maxY) * pixelSize + borderY / 2; + g.setColor(Color.black); - g.drawOval(centerX + (x * 10), centerY + (-y * 10), 10, 10); + g.drawOval(left, top, pixelSize, pixelSize); } private void drawLine(Graphics g, int x1, int y1, int x2, int y2) { - // delta of exact value and rounded value of the dependant variable + // delta of exact value and rounded value of the dependent variable int d = 0; - int dy = Math.abs(y2 - y1); int dx = Math.abs(x2 - x1); + int dy = Math.abs(y2 - y1); - int dy2 = (dy << 1); // slope scaling factors to avoid floating - int dx2 = (dx << 1); // point + int dx2 = 2 * dx; // slope scaling factors to + int dy2 = 2 * dy; // avoid floating point int ix = x1 < x2 ? 1 : -1; // increment direction int iy = y1 < y2 ? 1 : -1; - if (dy <= dx) { - for (;;) { - plot(g, x1, y1); - if (x1 == x2) + int x = x1; + int y = y1; + + if (dx >= dy) { + while (true) { + plot(g, x, y); + if (x == x2) break; - x1 += ix; + x += ix; d += dy2; if (d > dx) { - y1 += iy; + y += iy; d -= dx2; } } } else { - for (;;) { - plot(g, x1, y1); - if (y1 == y2) + while (true) { + plot(g, x, y); + if (y == y2) break; - y1 += iy; + y += iy; d += dx2; if (d > dy) { - x1 += ix; + x += ix; d -= dy2; } } diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Julia/bitmap-bresenhams-line-algorithm.julia b/Task/Bitmap-Bresenhams-line-algorithm/Julia/bitmap-bresenhams-line-algorithm.julia index d5fae39810..eb12afe64a 100644 --- a/Task/Bitmap-Bresenhams-line-algorithm/Julia/bitmap-bresenhams-line-algorithm.julia +++ b/Task/Bitmap-Bresenhams-line-algorithm/Julia/bitmap-bresenhams-line-algorithm.julia @@ -1,23 +1,27 @@ -function line(img, x0::Int, y0::Int, x1::Int, y1::Int, col) - dx = int(abs(x1-x0)) - dy = int(abs(y1-y0)) +function drawline!(img::Matrix{T}, x0::Int, y0::Int, x1::Int, y1::Int, col::T) where T + δx = abs(x1 - x0) + δy = abs(y1 - y0) + δe = abs(δy / δx) + er = 0.0 - sx = x0 0.5 + y += 1 + er -= 1.0 + end + end - err = (dx>dy ? dx : -dy)/2 - - while true - @inbounds img[x0,y0]=col - if (x0==x1 && y0==y1); break; end - e2 = err; - if e2 > -dx - err -= dy - x0 += sx - end - if e2 < dy - err += dx - y0 += sy - end - end + return img end + +using Images + +img = fill(Gray(255.0), 5, 5); +println("\nImage:") +display(img); println() +drawline!(img, 1, 1, 5, 5, Gray(0.0)); +println("\nModified image:") +display(img); println() diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Perl-6/bitmap-bresenhams-line-algorithm.pl6 b/Task/Bitmap-Bresenhams-line-algorithm/Perl-6/bitmap-bresenhams-line-algorithm.pl6 index 3b8cb13788..3636e87424 100644 --- a/Task/Bitmap-Bresenhams-line-algorithm/Perl-6/bitmap-bresenhams-line-algorithm.pl6 +++ b/Task/Bitmap-Bresenhams-line-algorithm/Perl-6/bitmap-bresenhams-line-algorithm.pl6 @@ -1,3 +1,25 @@ +class Pixel { has UInt ($.R, $.G, $.B) } +class Bitmap { + has UInt ($.width, $.height); + has Pixel @!data; + + method fill(Pixel $p) { + @!data = $p.clone xx ($!width*$!height) + } + method pixel( + $i where ^$!width, + $j where ^$!height + --> Pixel + ) is rw { @!data[$i + $j * $!width] } + + method set-pixel ($i, $j, Pixel $p) { + self.pixel($i, $j) = $p.clone; + } + method get-pixel ($i, $j) returns Pixel { + self.pixel($i, $j); + } +} + sub line(Bitmap $bitmap, $x0 is copy, $x1 is copy, $y0 is copy, $y1 is copy) { my $steep = abs($y1 - $y0) > abs($x1 - $x0); if $steep { diff --git a/Task/Bitmap-Flood-fill/Julia/bitmap-flood-fill.julia b/Task/Bitmap-Flood-fill/Julia/bitmap-flood-fill.julia new file mode 100644 index 0000000000..f16ae75ea4 --- /dev/null +++ b/Task/Bitmap-Flood-fill/Julia/bitmap-flood-fill.julia @@ -0,0 +1,46 @@ +using Images, FileIO + +function floodfill!(img::Matrix{<:Color}, initnode::CartesianIndex{2}, target::Color, replace::Color) + img[initnode] != target && return img + # constants + north = CartesianIndex(-1, 0) + south = CartesianIndex( 1, 0) + east = CartesianIndex( 0, 1) + west = CartesianIndex( 0, -1) + + queue = [initnode] + while !isempty(queue) + node = pop!(queue) + if img[node] == target + wnode = node + enode = node + east + end + # Move west until color of node does not match target color + while checkbounds(Bool, img, wnode) && img[wnode] == target + img[wnode] = replace + if checkbounds(Bool, img, wnode + north) && img[wnode + north] == target + push!(queue, wnode + north) + end + if checkbounds(Bool, img, wnode + south) && img[wnode + south] == target + push!(queue, wnode + south) + end + wnode += west + end + # Move east until color of node does not match target color + while checkbounds(Bool, img, enode) && img[enode] == target + img[enode] = replace + if checkbounds(Bool, img, enode + north) && img[enode + north] == target + push!(queue, enode + north) + end + if checkbounds(Bool, img, enode + south) && img[enode + south] == target + push!(queue, enode + south) + end + enode += east + end + end + return img +end + +img = Gray{Bool}.(load("data/unfilledcircle.png")) +floodfill!(img, CartesianIndex(100, 100), Gray(false), Gray(true)) +save("data/filledcircle.png", img) diff --git a/Task/Bitmap-Histogram/Java/bitmap-histogram.java b/Task/Bitmap-Histogram/Java/bitmap-histogram.java index 5b1c3b96db..864b27e14d 100644 --- a/Task/Bitmap-Histogram/Java/bitmap-histogram.java +++ b/Task/Bitmap-Histogram/Java/bitmap-histogram.java @@ -1,163 +1,63 @@ -package bitmap; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import javax.imageio.ImageIO; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; -import java.util.Random; -import java.util.stream.Collectors; -import java.util.stream.Stream; +public enum ImageProcessing { + ; -/** -* Image processing functions such as histogram, grayscale,.. -* here we assume we have a YUV image. so we process only luma component Y -* the histogram can be called on luma pixel only (values from 0 to 255) -* greyscale is done with a constant middle value of FullRange / 2 = 127 -*/ -public class ImageProc { + public static void main(String[] args) throws IOException { + BufferedImage img = ImageIO.read(new File("example.png")); - static final private Integer MAX_VAL = 255; - static final private Integer MIN_VAL = 0; - static final private Integer MID_RANGE = (MAX_VAL - MIN_VAL) >> 1; + BufferedImage bwimg = toBlackAndWhite(img); - private static Integer[] lumaHist(Integer[] luma,Integer length) { - // from input length, select a number of classes (intervalles ) - // usually take sqrt(length) - if ((length == 0 )|| (luma == null)){ - return null; + ImageIO.write(bwimg, "png", new File("example-bw.png")); + } + + private static int luminance(int rgb) { + int r = (rgb >> 16) & 0xFF; + int g = (rgb >> 8) & 0xFF; + int b = rgb & 0xFF; + return (r + b + g) / 3; + } + + private static BufferedImage toBlackAndWhite(BufferedImage img) { + int width = img.getWidth(); + int height = img.getHeight(); + + int[] histo = computeHistogram(img); + + int median = getMedian(width * height, histo); + + BufferedImage bwimg = new BufferedImage(width, height, img.getType()); + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + bwimg.setRGB(x, y, luminance(img.getRGB(x, y)) >= median ? 0xFFFFFFFF : 0xFF000000); } - double stepd = Math.sqrt(length); - // define the interval width - int step = (int)stepd ; - Integer width = (int)(length / stepd); - // define step Lists containing only values in one interval - // done with a loop generating a new list that discard lower part - // the luma buff is fist sorted to split the array correctly - // only values greater than width are kept in a new list - - List interv[] = new ArrayList[step]; - Integer hist[] = new Integer[step]; - interv[0] = Arrays.stream(luma) - .parallel() - .sorted() - .filter(value -> value >= width) - .collect(Collectors.toList()); - hist[0] = length - interv[0].size(); - - // here due to a lambda expression limitation - // we can not modify the width value. (should be a final var) - // so we decrease each reaming values with width, and store in a new list - // the filter is than the same across iterations - // histogram is computed in the same loop: the number of data for the interval - // is equal to the previous list size minus the new list size - for (int i =1; i < step; i++){ - - interv[i] = interv[i-1].stream() - .map(value -> value -= width) - .filter(value -> value >= width) - .collect(Collectors.toList()); - hist[i] = interv[i-1].size() - interv[i].size(); - } - - return hist; - } - - private static Integer[] blackAndWhite(Integer[] luma,Integer length) { - - List bwPict ; - // compute the average value of the stream - // need to transform the List in List to transform in int !!! - - double average; - average = Stream.of(luma).map(i -> i.toString()) - .mapToInt(Integer::parseInt) - .average() - .getAsDouble(); - System.out.println("Average value : " +average); - // compare each value with the average - // if less set to 0 (black) if more, set to 255 (black) - bwPict= Arrays.stream(luma) - .parallel() - .map(value -> (value > average) ?MAX_VAL: MIN_VAL) - .collect(Collectors.toList()); - - Integer retPict[] = new Integer[bwPict.size()]; - return bwPict.toArray(retPict); } + return bwimg; + } - public static void main (String[] args) - { - Integer[] histo; - Integer img_y[] = new Integer[256]; - // generate ramdom values just for testing algo - Random r = new Random(); - for (int i=0;i< img_y.length; i++) { - img_y[i] = r.nextInt(MAX_VAL); + private static int[] computeHistogram(BufferedImage img) { + int width = img.getWidth(); + int height = img.getHeight(); + + int[] histo = new int[256]; + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + histo[luminance(img.getRGB(x, y))]++; } + } + return histo; + } - // ********* compute histogram ******************** - histo = lumaHist(img_y,img_y.length); - - System.out.println("histogram size =:" + histo.length ); - - int sum = 0; - for (int i=0; i< histo.length;i++) { - System.out.println("histo[" + i + "] =:" + histo[i]); - sum +=histo[i]; - } - // check results are ok - // first check nb of elments in histo is 256 - if (sum != img_y.length){ - System.out.println("Error in histogram processing!\n" - + "Numbers of value not coherent"); - } - Integer hist[] = new Integer[16]; - Arrays.fill(hist, 0); - for (int i=0;i< 256; i++) { - if (img_y[i] < 16) hist[0]++; - else if (img_y[i] < 32) hist[1]++; - else if (img_y[i] < 48) hist[2]++; - else if (img_y[i] < 64) hist[3]++; - else if (img_y[i] < 80) hist[4]++; - else if (img_y[i] < 96) hist[5]++; - else if (img_y[i] < 112) hist[6]++; - else if (img_y[i] < 128) hist[7]++; - else if (img_y[i] < 144) hist[8]++; - else if (img_y[i] < 160) hist[9]++; - else if (img_y[i] < 176) hist[10]++; - else if (img_y[i] < 192) hist[11]++; - else if (img_y[i] < 208) hist[12]++; - else if (img_y[i] < 224) hist[13]++; - else if (img_y[i] < 240) hist[14]++; - else hist[15]++; - - } - if (hist.length != histo.length) { - System.out.println("Error in histogram processing!\n" - + "histogram size is wrong "); - return; - } - else { - for (int i=0; i< histo.length;i++) { - if (!Objects.equals(hist[i], histo[i])) { - System.out.println("Error in histogram processing!\n" - + "values are different (interv= " + i - + " computed: " + histo[i] - + " theorical :" + hist[i] + "\n"); - return; - } - } - } - System.out.println("Test OK\n"); - - // ********* compute grayscale image ******************** - Integer pictBW[]; - pictBW = blackAndWhite(img_y,img_y.length); - - for (int i=0;i< img_y.length; i++) { - System.out.println("Original[" + i +"]:" + img_y[i] + - " BandW[" + i +"]:" +pictBW[i] ); - } - - } + private static int getMedian(int total, int[] histo) { + int median = 0; + int sum = 0; + for (int i = 0; i < histo.length && sum + histo[i] < total / 2; i++) { + sum += histo[i]; + median++; + } + return median; + } } diff --git a/Task/Bitmap-Histogram/Julia/bitmap-histogram.julia b/Task/Bitmap-Histogram/Julia/bitmap-histogram.julia index 549e8d8a3a..157b469468 100644 --- a/Task/Bitmap-Histogram/Julia/bitmap-histogram.julia +++ b/Task/Bitmap-Histogram/Julia/bitmap-histogram.julia @@ -1,15 +1,9 @@ -using Color, Images, FixedPointNumbers +using Images, FileIO -ima = imread("bitmap_histogram_in.jpg") -imb = convert(Image{Gray{Ufixed8}}, ima) +ima = load("data/lenna50.jpg") +imb = Gray.(ima) -# calculate histogram -a = map(x->x.val.i, imb.data) -(nothing, h) = hist(reshape(a, length(a)), -1:typemax(Uint8)) - -g = float(imb.data) -b = g .> median(g) -fill!(imb, Gray(0.0)) -imb[b] = Gray(1.0) - -imwrite(imb, "bitmap_histogram_out.png") +medcol = median(imb) +imb[imb .≤ medcol] = Gray(0.0) +imb[imb .> medcol] = Gray(1.0) +save("data/lennaGray.jpg", imb) diff --git a/Task/Bitmap-Histogram/Kotlin/bitmap-histogram.kotlin b/Task/Bitmap-Histogram/Kotlin/bitmap-histogram.kotlin new file mode 100644 index 0000000000..ec60bbebce --- /dev/null +++ b/Task/Bitmap-Histogram/Kotlin/bitmap-histogram.kotlin @@ -0,0 +1,61 @@ +// version 1.2.10 + +import java.io.File +import java.awt.image.BufferedImage +import javax.imageio.ImageIO + +const val BLACK = 0xff000000.toInt() +const val WHITE = 0xffffffff.toInt() + +fun luminance(argb: Int): Int { + val red = (argb shr 16) and 0xFF + val green = (argb shr 8) and 0xFF + val blue = argb and 0xFF + return (0.2126 * red + 0.7152 * green + 0.0722 * blue).toInt() +} + +val BufferedImage.histogram: IntArray + get() { + val lumCount = IntArray(256) + for (x in 0 until width) { + for (y in 0 until height) { + var argb = getRGB(x, y) + lumCount[luminance(argb)]++ + } + } + return lumCount + } + +fun findMedian(histogram: IntArray): Int { + var lSum = 0 + var rSum = 0 + var left = 0 + var right = 255 + do { + if (lSum < rSum) lSum += histogram[left++] + else rSum += histogram[right--] + } + while (left != right) + return left +} + +fun BufferedImage.toBlackAndWhite(median: Int) { + for (x in 0 until width) { + for (y in 0 until height) { + val argb = getRGB(x, y) + val lum = luminance(argb) + if (lum < median) + setRGB(x, y, BLACK) + else + setRGB(x, y, WHITE) + } + } +} + +fun main(args: Array) { + val image = ImageIO.read(File("Lenna100.jpg")) + val median = findMedian(image.histogram) + image.toBlackAndWhite(median) + val bwFile = File("Lenna_bw.jpg") + ImageIO.write(image, "jpg", bwFile) +} diff --git a/Task/Bitmap-Histogram/Perl-6/bitmap-histogram.pl6 b/Task/Bitmap-Histogram/Perl-6/bitmap-histogram.pl6 new file mode 100644 index 0000000000..fa9a0b9efc --- /dev/null +++ b/Task/Bitmap-Histogram/Perl-6/bitmap-histogram.pl6 @@ -0,0 +1,52 @@ +class Pixel { has UInt ($.R, $.G, $.B) } +class Bitmap { + has UInt ($.width, $.height); + has Pixel @.data; +} + +role PBM { + has @.BM; + method P4 returns Blob { + "P4\n{self.width} {self.height}\n".encode('ascii') + ~ Blob.new: self.BM + } +} + +sub getline ( $fh ) { + my $line = '#'; # skip comments when reading image file + $line = $fh.get while $line.substr(0,1) eq '#'; + $line; +} + +sub load-ppm ( $ppm ) { + my $fh = $ppm.IO.open( :enc('ISO-8859-1') ); + my $type = $fh.&getline; + my ($width, $height) = $fh.&getline.split: ' '; + my $depth = $fh.&getline; + Bitmap.new( width => $width.Int, height => $height.Int, + data => ( $fh.slurp.ords.rotor(3).map: + { Pixel.new(R => $_[0], G => $_[1], B => $_[2]) } ) + ) +} + +sub grayscale ( Bitmap $bmp ) { + map { (.R*0.2126 + .G*0.7152 + .B*0.0722).round(1) min 255 }, $bmp.data; +} + +sub histogram ( Bitmap $bmp ) { + my @gray = grayscale($bmp); + my $threshold = @gray.sum / @gray; + for @gray.rotor($bmp.width) { + my @row = $_.list; + @row.push(0) while @row % 8; + $bmp.BM.append: @row.rotor(8).map: { :2(($_ X< $threshold)».Numeric.join) } + } +} + +my $filename = './Lenna.ppm'; + +my Bitmap $b = load-ppm( $filename ) but PBM; + +histogram($b); + +'./Lenna-bw.pbm'.IO.open(:bin, :w).write: $b.P4; diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Julia/bitmap-midpoint-circle-algorithm.julia b/Task/Bitmap-Midpoint-circle-algorithm/Julia/bitmap-midpoint-circle-algorithm.julia new file mode 100644 index 0000000000..5b1e33d063 --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/Julia/bitmap-midpoint-circle-algorithm.julia @@ -0,0 +1,31 @@ +function drawcircle!(img::Matrix{T}, col::T, x0::Int, y0::Int, radius::Int) where T + x = radius - 1 + y = 0 + δx = δy = 1 + er = δx - (radius << 1) + + s = x + y + while x ≥ y + for opx in (+, -), opy in (+, -), el in (x, y) + @inbounds img[opx(x0, el) + 1, opy(y0, s - el) + 1] = col + end + if er ≤ 0 + y += 1 + er += δy + δy += 2 + end + if er > 0 + x -= 1 + δx += 2 + er += (-radius << 1) + δx + end + s = x + y + end + return img +end + +# Test +using Images + +img = fill(Gray(255.0), 25, 25); +drawcircle!(img, Gray(0.0), 12, 12, 12) diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Perl-6/bitmap-midpoint-circle-algorithm-1.pl6 b/Task/Bitmap-Midpoint-circle-algorithm/Perl-6/bitmap-midpoint-circle-algorithm-1.pl6 index f367e6940c..78ba0186ac 100644 --- a/Task/Bitmap-Midpoint-circle-algorithm/Perl-6/bitmap-midpoint-circle-algorithm-1.pl6 +++ b/Task/Bitmap-Midpoint-circle-algorithm/Perl-6/bitmap-midpoint-circle-algorithm-1.pl6 @@ -1,4 +1,27 @@ -use MONKEY_TYPING; +use MONKEY-TYPING; + +class Pixel { has UInt ($.R, $.G, $.B) } +class Bitmap { + has UInt ($.width, $.height); + has Pixel @!data; + + method fill(Pixel $p) { + @!data = $p.clone xx ($!width*$!height) + } + method pixel( + $i where ^$!width, + $j where ^$!height + --> Pixel + ) is rw { @!data[$i + $j * $!width] } + + method set-pixel ($i, $j, Pixel $p) { + self.pixel($i, $j) = $p.clone; + } + method get-pixel ($i, $j) returns Pixel { + self.pixel($i, $j); + } +} + augment class Pixel { method Str { "$.R $.G $.B" } } augment class Bitmap { method P3 { diff --git a/Task/Bitmap-PPM-conversion-through-a-pipe/Julia/bitmap-ppm-conversion-through-a-pipe.julia b/Task/Bitmap-PPM-conversion-through-a-pipe/Julia/bitmap-ppm-conversion-through-a-pipe.julia new file mode 100644 index 0000000000..427f04d7b9 --- /dev/null +++ b/Task/Bitmap-PPM-conversion-through-a-pipe/Julia/bitmap-ppm-conversion-through-a-pipe.julia @@ -0,0 +1,4 @@ +using Images, FileIO + +ppmimg = load("data/bitmapInputTest.ppm") +save("data/bitmapOutputTest.jpg", ppmimg) diff --git a/Task/Bitmap-PPM-conversion-through-a-pipe/Kotlin/bitmap-ppm-conversion-through-a-pipe.kotlin b/Task/Bitmap-PPM-conversion-through-a-pipe/Kotlin/bitmap-ppm-conversion-through-a-pipe.kotlin new file mode 100644 index 0000000000..fa8d4a95d3 --- /dev/null +++ b/Task/Bitmap-PPM-conversion-through-a-pipe/Kotlin/bitmap-ppm-conversion-through-a-pipe.kotlin @@ -0,0 +1,56 @@ +// Version 1.2.40 + +import java.awt.Color +import java.awt.Graphics +import java.awt.image.BufferedImage + +class BasicBitmapStorage(width: Int, height: Int) { + val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR) + + fun fill(c: Color) { + val g = image.graphics + g.color = c + g.fillRect(0, 0, image.width, image.height) + } + + fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB()) + + fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y)) +} + +fun main(args: Array) { + // create BasicBitmapStorage object + val width = 640 + val height = 640 + val bbs = BasicBitmapStorage(width, height) + for (y in 0 until height) { + for (x in 0 until width) { + val c = Color(x % 256, y % 256, (x * y) % 256) + bbs.setPixel(x, y, c) + } + } + + // now write the object in PPM format to ImageMagick's STDIN via a pipe + // so it can be converted to a .jpg file and written to disk + val pb = ProcessBuilder("convert", "-", "output_piped.jpg") + pb.directory(null) + pb.redirectInput(ProcessBuilder.Redirect.PIPE) + val buffer = ByteArray(width * 3) // write one line at a time + val proc = pb.start() + val pStdIn = proc.outputStream + pStdIn.use { + val header = "P6\n$width $height\n255\n".toByteArray() + with (it) { + write(header) + for (y in 0 until height) { + for (x in 0 until width) { + val c = bbs.getPixel(x, y) + buffer[x * 3] = c.red.toByte() + buffer[x * 3 + 1] = c.green.toByte() + buffer[x * 3 + 2] = c.blue.toByte() + } + write(buffer) + } + } + } +} diff --git a/Task/Bitmap-Read-a-PPM-file/Erlang/bitmap-read-a-ppm-file-1.erl b/Task/Bitmap-Read-a-PPM-file/Erlang/bitmap-read-a-ppm-file-1.erl new file mode 100644 index 0000000000..f2c7bc7bc3 --- /dev/null +++ b/Task/Bitmap-Read-a-PPM-file/Erlang/bitmap-read-a-ppm-file-1.erl @@ -0,0 +1,102 @@ +% This module provides basic operations on ppm files: +% Read from file, create ppm in memory (from generic bitmap) and save to file. +% Writing PPM files was introduced in roseta code task 'Bitmap/Write a PPM file' +% but the same code is included here to provide whole set of operations on ppm +% needed for purposes of this task. + +-module(ppm). + +-export([ppm/1, write/2, read/1]). + +% constants for writing ppm file +-define(WHITESPACE, <<10>>). +-define(SPACE, <<32>>). + +% constants for reading ppm file +-define(WHITESPACES, [9, 10, 13, 32]). +-define(PPM_HEADER, "P6"). + +% data structure introduced in task Bitmap (module ros_bitmap.erl) +-record(bitmap, { + mode = rgb, + pixels = nil, + shape = {0, 0} + }). + +%%%%%%%%% API %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% read ppm file from file +read(Filename) -> + {ok, File} = file:read_file(Filename), + parse(File). + +% create ppm image from bitmap record +ppm(Bitmap) -> + {Width, Height} = Bitmap#bitmap.shape, + Pixels = ppm_pixels(Bitmap), + Maxval = 255, % original ppm format maximum + list_to_binary([ + header(), width_and_height(Width, Height), maxval(Maxval), Pixels]). + +% write bitmap as ppm file +write(Bitmap, Filename) -> + Ppm = ppm(Bitmap), + {ok, File} = file:open(Filename, [binary, write]), + file:write(File, Ppm), + file:close(File). + +%%%%%%%%% Reading PPM %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +parse(Binary) -> + {?PPM_HEADER, Data} = get_next_token(Binary), + {Width, HeightAndRest} = get_next_token(Data), + {Height, MaxValAndRest} = get_next_token(HeightAndRest), + {_MaxVal, RawPixels} = get_next_token(MaxValAndRest), + Shape = {list_to_integer(Width), list_to_integer(Height)}, + Pixels = load_pixels(RawPixels), + #bitmap{pixels=Pixels, shape=Shape}. + +% load binary as a list of RGB triplets +load_pixels(Binary) when is_binary(Binary)-> + load_pixels([], Binary). +load_pixels(Acc, <<>>) -> + array:from_list(lists:reverse(Acc)); +load_pixels(Acc, <>) -> + load_pixels([<>|Acc], Rest). + +is_whitespace(Byte) -> + lists:member(Byte, ?WHITESPACES). + +% get next part of PPM file, skip whitespaces, and return the rest of a binary +get_next_token(Binary) -> + get_next_token("", true, Binary). +get_next_token(CurrentToken, false, <>) -> + case is_whitespace(Byte) of + true -> + {lists:reverse(CurrentToken), Rest}; + false -> + get_next_token([Byte | CurrentToken], false, Rest) + end; +get_next_token(CurrentToken, true, <>) -> + case is_whitespace(Byte) of + true -> + get_next_token(CurrentToken, true, Rest); + false -> + get_next_token([Byte | CurrentToken], false, Rest) + end. + +%%%%%%%%% Writing PPM %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +header() -> + [<<"P6">>, ?WHITESPACE]. + +width_and_height(Width, Height) -> + [encode_decimal(Width), ?SPACE, encode_decimal(Height), ?WHITESPACE]. + +maxval(Maxval) -> + [encode_decimal(Maxval), ?WHITESPACE]. + +ppm_pixels(Bitmap) -> + % 24 bit color depth + array:to_list(Bitmap#bitmap.pixels). + +encode_decimal(Number) -> + integer_to_list(Number). diff --git a/Task/Bitmap-Read-a-PPM-file/Erlang/bitmap-read-a-ppm-file-2.erl b/Task/Bitmap-Read-a-PPM-file/Erlang/bitmap-read-a-ppm-file-2.erl new file mode 100644 index 0000000000..8c66ef6d21 --- /dev/null +++ b/Task/Bitmap-Read-a-PPM-file/Erlang/bitmap-read-a-ppm-file-2.erl @@ -0,0 +1,3 @@ +Colorful = ppm:read("colorful.ppm"), +Gray = ros_bitmap:convert(ros_bitmap:convert(Colorful, grey), rgb), +ppm:write(Gray, "gray.ppm"), diff --git a/Task/Bitmap-Read-a-PPM-file/Julia/bitmap-read-a-ppm-file.julia b/Task/Bitmap-Read-a-PPM-file/Julia/bitmap-read-a-ppm-file.julia index 8f57b7b6fa..8bf4f7cd5a 100644 --- a/Task/Bitmap-Read-a-PPM-file/Julia/bitmap-read-a-ppm-file.julia +++ b/Task/Bitmap-Read-a-PPM-file/Julia/bitmap-read-a-ppm-file.julia @@ -1,13 +1,5 @@ -using Color, Images, FixedPointNumbers +using Images, FileIO, Netpbm -const M_RGB_Y = reshape(Color.M_RGB_XYZ[2,:], 3) - -function rgb2gray(img::Image) - g = red(img)*M_RGB_Y[1] + green(img)*M_RGB_Y[2] + blue(img)*M_RGB_Y[3] - g = clamp(g, 0.0, 1.0) - return grayim(g) -end - -ima = imread("bitmap_read_ppm_in.ppm") -imb = convert(Image{Gray{Ufixed8}}, ima) -imwrite(imb, "bitmap_read_ppm_out.png") +rgbimg = load("data/bitmapInputTest.ppm") +greyimg = Gray.(rgbimg) +save("data/bitmapOutputTest.ppm", greyimg) diff --git a/Task/Bitmap-Read-a-PPM-file/Kotlin/bitmap-read-a-ppm-file.kotlin b/Task/Bitmap-Read-a-PPM-file/Kotlin/bitmap-read-a-ppm-file.kotlin new file mode 100644 index 0000000000..0a23a53e70 --- /dev/null +++ b/Task/Bitmap-Read-a-PPM-file/Kotlin/bitmap-read-a-ppm-file.kotlin @@ -0,0 +1,130 @@ +// Version 1.2.40 + +import java.awt.Color +import java.awt.Graphics +import java.awt.image.BufferedImage +import java.io.FileInputStream +import java.io.PushbackInputStream +import java.io.File +import javax.imageio.ImageIO + +class BasicBitmapStorage(width: Int, height: Int) { + val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR) + + fun fill(c: Color) { + val g = image.graphics + g.color = c + g.fillRect(0, 0, image.width, image.height) + } + + fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB()) + + fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y)) + + fun toGrayScale() { + for (x in 0 until image.width) { + for (y in 0 until image.height) { + var rgb = image.getRGB(x, y) + val red = (rgb shr 16) and 0xFF + val green = (rgb shr 8) and 0xFF + val blue = rgb and 0xFF + val lumin = (0.2126 * red + 0.7152 * green + 0.0722 * blue).toInt() + rgb = (lumin shl 16) or (lumin shl 8) or lumin + image.setRGB(x, y, rgb) + } + } + } +} + +fun PushbackInputStream.skipComment() { + while (read().toChar() != '\n') {} +} + +fun PushbackInputStream.skipComment(buffer: ByteArray) { + var nl: Int + while (true) { + nl = buffer.indexOf(10) // look for newline at end of comment + if (nl != -1) break + read(buffer) // read another buffer full if newline not yet found + } + val len = buffer.size + if (nl < len - 1) unread(buffer, nl + 1, len - nl - 1) +} + +fun Byte.toUInt() = if (this < 0) 256 + this else this.toInt() + +fun main(args: Array) { + // use file, output.ppm, created in the Bitmap/Write a PPM file task + val pbis = PushbackInputStream(FileInputStream("output.ppm"), 80) + pbis.use { + with (it) { + val h1 = read().toChar() + val h2 = read().toChar() + val h3 = read().toChar() + if (h1 != 'P' || h2 != '6' || h3 != '\n') { + println("Not a P6 PPM file") + System.exit(1) + } + val sb = StringBuilder() + while (true) { + val r = read().toChar() + if (r == '#') { skipComment(); continue } + if (r == ' ') break // read until space reached + sb.append(r.toChar()) + } + val width = sb.toString().toInt() + sb.setLength(0) + while (true) { + val r = read().toChar() + if (r == '#') { skipComment(); continue } + if (r == '\n') break // read until new line reached + sb.append(r.toChar()) + } + val height = sb.toString().toInt() + sb.setLength(0) + while (true) { + val r = read().toChar() + if (r == '#') { skipComment(); continue } + if (r == '\n') break // read until new line reached + sb.append(r.toChar()) + } + val maxCol = sb.toString().toInt() + if (maxCol !in 0..255) { + println("Maximum color value is outside the range 0..255") + System.exit(1) + } + var buffer = ByteArray(80) + // get rid of any more opening comments before reading data + while (true) { + read(buffer) + if (buffer[0].toChar() == '#') { + skipComment(buffer) + } + else { + unread(buffer) + break + } + } + // read data + val bbs = BasicBitmapStorage(width, height) + buffer = ByteArray(width * 3) + var y = 0 + while (y < height) { + read(buffer) + for (x in 0 until width) { + val c = Color( + buffer[x * 3].toUInt(), + buffer[x * 3 + 1].toUInt(), + buffer[x * 3 + 2].toUInt() + ) + bbs.setPixel(x, y, c) + } + y++ + } + // convert to grayscale and save to a file + bbs.toGrayScale() + val grayFile = File("output_gray.jpg") + ImageIO.write(bbs.image, "jpg", grayFile) + } + } +} diff --git a/Task/Bitmap-Read-a-PPM-file/Perl-6/bitmap-read-a-ppm-file.pl6 b/Task/Bitmap-Read-a-PPM-file/Perl-6/bitmap-read-a-ppm-file.pl6 new file mode 100644 index 0000000000..5f77cfb471 --- /dev/null +++ b/Task/Bitmap-Read-a-PPM-file/Perl-6/bitmap-read-a-ppm-file.pl6 @@ -0,0 +1,36 @@ +class Pixel { has UInt ($.R, $.G, $.B) } +class Bitmap { + has UInt ($.width, $.height); + has Pixel @.data; +} + +role PGM { + has @.GS; + method P5 returns Blob { + "P5\n{self.width} {self.height}\n255\n".encode('ascii') + ~ Blob.new: self.GS + } +} + +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 grayscale ( Bitmap $bmp ) { + $bmp.GS = map { (.R*0.2126 + .G*0.7152 + .B*0.0722).round(1) min 255 }, $bmp.data; +} + +my $filename = './camelia.ppm'; + +my Bitmap $b = load-ppm( $filename ) but PGM; + +grayscale($b); + +'./camelia-gs.pgm'.IO.open(:bin, :w).write: $b.P5; diff --git a/Task/Bitmap-Read-a-PPM-file/REXX/bitmap-read-a-ppm-file.rexx b/Task/Bitmap-Read-a-PPM-file/REXX/bitmap-read-a-ppm-file.rexx new file mode 100644 index 0000000000..8647e5e92b --- /dev/null +++ b/Task/Bitmap-Read-a-PPM-file/REXX/bitmap-read-a-ppm-file.rexx @@ -0,0 +1,36 @@ +/*REXX program reads a PPM formatted image file, and creates a gray─scale image of it. */ +parse arg iFN oFN /*obtain optional argument from the CL.*/ +if iFN=='' | iFN=="," then iFN= 'Lenna50' /*Not specified? Then use the default.*/ +if oFN=='' | oFN=="," then oFN= 'greyscale' /* " " " " " " */ +iFID= iFN'.ppm'; oFID= oFN'.ppm' /*complete the input and output FIDs.*/ +call charin iFID, 1, 0 /*set the position of the input file. */ +y=charin(iFID, , copies(9, digits() ) ) /*read the entire input file ───► X */ +parse var y id 3 c 4 3 width height # pixels /*extract header info from the PPM hdr.*/ + LF= 'a'x /*define a comment separator (in hdr).*/ /* ◄─── LF delimiters & comments*/ +if c==LF then do; commentEND=pos(LF, y, 4) /*point to the last char in the comment*/ /* ◄─── LF delimiters & comments*/ + parse var y =(commentEND) +1 width height # pixels /* ◄─── LF delimiters & comments*/ + end /* ◄─── LF delimiters & comments*/ + /* [↓] has an alternative delimiter? */ /* ◄─── LF delimiters & comments*/ +z=pos(LF, height); if z\==0 then parse var height height =(z) +1 # pixels /* ◄─── LF delimiters & comments*/ +z=pos(LF, # ); if z\==0 then parse var # # =(z) +1 pixels /* ◄─── LF delimiters & comments*/ +chunk=4000 /*chunk size to be written at one time.*/ +LenPixels= length(pixels) + + do j=0 for 256; _=d2c(j); @._=j; @@.j=_ /*build two tables for fast conversions*/ + end /*j*/ + +call charout oFID, , 1 /*set the position of the output file. */ +call charout oFID, id || width height #' ' /*write the header followed by a blank.*/ +!=1 + do until !>=LenPixels; $= /*$: partial output string so far.*/ + do !=! by 3 for chunk /*chunk: # pixels converted at 1 time.*/ + parse var pixels =(!) r +1 g +1 b +1 /*obtain the next RGB of a PPM pixel.*/ + if r=='' then leave /*has the end─of─string been reached? */ + _=(.2126*@.r + .7152*@.g + .0722*@.b )%1 /*an integer RGB greyscale of a pixel. */ + $=$ || @@._ || @@._ || @@._ /*lump (grey) R G B pixels together. */ + end /*!*/ /* [↑] D2C converts decimal ───► char*/ + call charout oFID, $ /*write the next bunch of pixels. */ + end /*until*/ + +call charout oFID /*close the output file just to be safe*/ +say 'File ' oFID " was created." /*stick a fork in it, we're all done. */ diff --git a/Task/Bitmap-Read-an-image-through-a-pipe/Julia/bitmap-read-an-image-through-a-pipe.julia b/Task/Bitmap-Read-an-image-through-a-pipe/Julia/bitmap-read-an-image-through-a-pipe.julia new file mode 100644 index 0000000000..3a827dd900 --- /dev/null +++ b/Task/Bitmap-Read-an-image-through-a-pipe/Julia/bitmap-read-an-image-through-a-pipe.julia @@ -0,0 +1,4 @@ +using Images, FileIO + +img = load("data/bitmapOutputTest.jpg") +save("data/bitmapOutputTest.ppm", img) diff --git a/Task/Bitmap-Read-an-image-through-a-pipe/Kotlin/bitmap-read-an-image-through-a-pipe.kotlin b/Task/Bitmap-Read-an-image-through-a-pipe/Kotlin/bitmap-read-an-image-through-a-pipe.kotlin new file mode 100644 index 0000000000..ed6c6d3cd9 --- /dev/null +++ b/Task/Bitmap-Read-an-image-through-a-pipe/Kotlin/bitmap-read-an-image-through-a-pipe.kotlin @@ -0,0 +1,135 @@ +// Version 1.2.40 + +import java.awt.Color +import java.awt.Graphics +import java.awt.image.BufferedImage +import java.io.PushbackInputStream +import java.io.File +import javax.imageio.ImageIO + +class BasicBitmapStorage(width: Int, height: Int) { + val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR) + + fun fill(c: Color) { + val g = image.graphics + g.color = c + g.fillRect(0, 0, image.width, image.height) + } + + fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB()) + + fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y)) + + fun toGrayScale() { + for (x in 0 until image.width) { + for (y in 0 until image.height) { + var rgb = image.getRGB(x, y) + val red = (rgb shr 16) and 0xFF + val green = (rgb shr 8) and 0xFF + val blue = rgb and 0xFF + val lumin = (0.2126 * red + 0.7152 * green + 0.0722 * blue).toInt() + rgb = (lumin shl 16) or (lumin shl 8) or lumin + image.setRGB(x, y, rgb) + } + } + } +} + +fun PushbackInputStream.skipComment() { + while (read().toChar() != '\n') {} +} + +fun PushbackInputStream.skipComment(buffer: ByteArray) { + var nl: Int + while (true) { + nl = buffer.indexOf(10) // look for newline at end of comment + if (nl != -1) break + read(buffer) // read another buffer full if newline not yet found + } + val len = buffer.size + if (nl < len - 1) unread(buffer, nl + 1, len - nl - 1) +} + +fun Byte.toUInt() = if (this < 0) 256 + this else this.toInt() + +fun main(args: Array) { + // use file, output_piped.jpg, created in the + // Bitmap/PPM conversion through a pipe task + val pb = ProcessBuilder("convert", "output_piped.jpg", "ppm:-") + pb.directory(null) + pb.redirectOutput(ProcessBuilder.Redirect.PIPE) + val proc = pb.start() + val pStdOut = proc.inputStream + val pbis = PushbackInputStream(pStdOut, 80) + pbis.use { + with (it) { + val h1 = read().toChar() + val h2 = read().toChar() + val h3 = read().toChar() + if (h1 != 'P' || h2 != '6' || h3 != '\n') { + println("Not a P6 PPM file") + System.exit(1) + } + val sb = StringBuilder() + while (true) { + val r = read().toChar() + if (r == '#') { skipComment(); continue } + if (r == ' ') break // read until space reached + sb.append(r.toChar()) + } + val width = sb.toString().toInt() + sb.setLength(0) + while (true) { + val r = read().toChar() + if (r == '#') { skipComment(); continue } + if (r == '\n') break // read until new line reached + sb.append(r.toChar()) + } + val height = sb.toString().toInt() + sb.setLength(0) + while (true) { + val r = read().toChar() + if (r == '#') { skipComment(); continue } + if (r == '\n') break // read until new line reached + sb.append(r.toChar()) + } + val maxCol = sb.toString().toInt() + if (maxCol !in 0..255) { + println("Maximum color value is outside the range 0..255") + System.exit(1) + } + var buffer = ByteArray(80) + // get rid of any more opening comments before reading data + while (true) { + read(buffer) + if (buffer[0].toChar() == '#') { + skipComment(buffer) + } + else { + unread(buffer) + break + } + } + // read data + val bbs = BasicBitmapStorage(width, height) + buffer = ByteArray(width * 3) + var y = 0 + while (y < height) { + read(buffer) + for (x in 0 until width) { + val c = Color( + buffer[x * 3].toUInt(), + buffer[x * 3 + 1].toUInt(), + buffer[x * 3 + 2].toUInt() + ) + bbs.setPixel(x, y, c) + } + y++ + } + // convert to grayscale and save to a file + bbs.toGrayScale() + val grayFile = File("output_piped_gray.jpg") + ImageIO.write(bbs.image, "jpg", grayFile) + } + } +} diff --git a/Task/Bitmap-Read-an-image-through-a-pipe/Perl-6/bitmap-read-an-image-through-a-pipe.pl6 b/Task/Bitmap-Read-an-image-through-a-pipe/Perl-6/bitmap-read-an-image-through-a-pipe.pl6 new file mode 100644 index 0000000000..c8b919fe7e --- /dev/null +++ b/Task/Bitmap-Read-an-image-through-a-pipe/Perl-6/bitmap-read-an-image-through-a-pipe.pl6 @@ -0,0 +1,33 @@ +class Pixel { has UInt ($.R, $.G, $.B) } +class Bitmap { + has UInt ($.width, $.height); + has Pixel @.data; +} + +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 getline ( $proc ) { + my $line = '#'; # skip comment when reading a .png + $line = $proc.out.get while $line.substr(0,1) eq '#'; + $line; +} + +my $filename = './camelia.png'; + +my $proc = run 'convert', $filename, 'ppm:-', :enc('ISO-8859-1'), :out; + +my $type = getline($proc); +my ($width, $height) = getline($proc).split: ' '; +my $depth = getline($proc); + +my Bitmap $b = Bitmap.new( width => $width.Int, height => $height.Int) but PPM; + +$b.data = $proc.out.slurp.ords.rotor(3).map: + { Pixel.new(R => .[0], G => .[1], B => .[2]) }; + +'./camelia.ppm'.IO.open(:bin, :w).write: $b.P6; diff --git a/Task/Bitmap-Write-a-PPM-file/Erlang/bitmap-write-a-ppm-file.erl b/Task/Bitmap-Write-a-PPM-file/Erlang/bitmap-write-a-ppm-file.erl new file mode 100644 index 0000000000..bb685f7ab5 --- /dev/null +++ b/Task/Bitmap-Write-a-PPM-file/Erlang/bitmap-write-a-ppm-file.erl @@ -0,0 +1,45 @@ +-module(ppm). + +-export([ppm/1, write/2]). + +-define(WHITESPACE, <<10>>). +-define(SPACE, <<32>>). + +% data structure introduced in task Bitmap (module ros_bitmap.erl) +-record(bitmap, { + pixels = nil, + shape = {0, 0} + }). + +% create ppm image from bitmap record +ppm(Bitmap) -> + {Width, Height} = Bitmap#bitmap.shape, + Pixels = ppm_pixels(Bitmap), + Maxval = 255, % original ppm format maximum + list_to_binary([ + header(), width_and_height(Width, Height), maxval(Maxval), Pixels]). + +% write bitmap as ppm file +write(Bitmap, Filename) -> + Ppm = ppm(Bitmap), + {ok, File} = file:open(Filename, [binary, write]), + file:write(File, Ppm), + file:close(File). + +%%%%%%%%%%%% four parts of ppm file %%%%%%%%%%%%%%%%%%%%%% +header() -> + [<<"P6">>, ?WHITESPACE]. + +width_and_height(Width, Height) -> + [encode_decimal(Width), ?SPACE, encode_decimal(Height), ?WHITESPACE]. + +maxval(Maxval) -> + [encode_decimal(Maxval), ?WHITESPACE]. + +ppm_pixels(Bitmap) -> + % 24 bit color depth + array:to_list(Bitmap#bitmap.pixels). + +%%%%%%%%%%%% Internals %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +encode_decimal(Number) -> + integer_to_list(Number). diff --git a/Task/Bitmap-Write-a-PPM-file/Julia/bitmap-write-a-ppm-file.julia b/Task/Bitmap-Write-a-PPM-file/Julia/bitmap-write-a-ppm-file.julia new file mode 100644 index 0000000000..edc97106a1 --- /dev/null +++ b/Task/Bitmap-Write-a-PPM-file/Julia/bitmap-write-a-ppm-file.julia @@ -0,0 +1,11 @@ +using Images, FileIO + +h, w = 50, 70 +img = zeros(RGB{N0f8}, h, w) +img[10:40, 5:35] = colorant"skyblue" +for i in 26:50, j in (i-25):40 + img[i, j] = colorant"sienna1" +end + +save("data/bitmapWrite.ppm", img) +save("data/bitmapWrite.png", img) diff --git a/Task/Bitmap-Write-a-PPM-file/Kotlin/bitmap-write-a-ppm-file.kotlin b/Task/Bitmap-Write-a-PPM-file/Kotlin/bitmap-write-a-ppm-file.kotlin new file mode 100644 index 0000000000..855f002c27 --- /dev/null +++ b/Task/Bitmap-Write-a-PPM-file/Kotlin/bitmap-write-a-ppm-file.kotlin @@ -0,0 +1,52 @@ +// Version 1.2.40 + +import java.awt.Color +import java.awt.Graphics +import java.awt.image.BufferedImage +import java.io.FileOutputStream + +class BasicBitmapStorage(width: Int, height: Int) { + val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR) + + fun fill(c: Color) { + val g = image.graphics + g.color = c + g.fillRect(0, 0, image.width, image.height) + } + + fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB()) + + fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y)) +} + +fun main(args: Array) { + // create BasicBitmapStorage object + val width = 640 + val height = 640 + val bbs = BasicBitmapStorage(width, height) + for (y in 0 until height) { + for (x in 0 until width) { + val c = Color(x % 256, y % 256, (x * y) % 256) + bbs.setPixel(x, y, c) + } + } + + // now write it to a PPM file + val fos = FileOutputStream("output.ppm") + val buffer = ByteArray(width * 3) // write one line at a time + fos.use { + val header = "P6\n$width $height\n255\n".toByteArray() + with (it) { + write(header) + for (y in 0 until height) { + for (x in 0 until width) { + val c = bbs.getPixel(x, y) + buffer[x * 3] = c.red.toByte() + buffer[x * 3 + 1] = c.green.toByte() + buffer[x * 3 + 2] = c.blue.toByte() + } + write(buffer) + } + } + } +} diff --git a/Task/Bitmap-Write-a-PPM-file/REXX/bitmap-write-a-ppm-file.rexx b/Task/Bitmap-Write-a-PPM-file/REXX/bitmap-write-a-ppm-file.rexx index a484e1be8d..2be353649c 100644 --- a/Task/Bitmap-Write-a-PPM-file/REXX/bitmap-write-a-ppm-file.rexx +++ b/Task/Bitmap-Write-a-PPM-file/REXX/bitmap-write-a-ppm-file.rexx @@ -1,17 +1,21 @@ -/*REXX program to write a PPM formatted image file, P6 (binary). */ -oFID = 'IMAGE.PPM' /*name of the output file. */ -green = '00 ff 00'x -image. = green /*define all IMAGE RGB's to green*/ - width = 20 /*define the width of IMAGE. */ -height = 20 /* " " height " " */ - sep = '9'x -call put 'P6'width||sep||height||sep||255||sep /*write header info.*/ - - do j =1 for width - do k=1 for height - call put image.j.k /*write IMAGE, 3 bytes at a time.*/ - end /*k*/ - end /*j*/ -exit /*stick a fork in it, we're done.*/ -/*─────────────────────────────────────subroutines──────────────────────*/ -put: call charout oFID,arg(1); return /*write out character(s) to file.*/ +/*REXX program writes a PPM formatted image file, also known as a P6 (binary) file. */ +green = 00ff00 /*define a pixel with the color green. */ +parse arg oFN width height color . /*obtain optional arguments from the CL*/ +if oFN=='' | oFN=="," then oFN='IMAGE' /*Not specified? Then use the default.*/ +if width=='' | width=="," then width= 20 /* " " " " " " */ +if height=='' | height=="," then height= 20 /* " " " " " " */ +if color=='' | color=="," then color= green /* " " " " " " */ +oFID= oFN'.PPM' /*define oFID by adding an extension.*/ + @. = x2c(color) /*set all pixels of image a hex color. */ + $ = '9'x /*define the separator (in the header).*/ + # = 255 /* " " max value for all colors. */ +call charout oFID, , 1 /*set the position of the file's output*/ +call charout oFID,'P6'width || $ || height || $ || # || $ /*write file header info. */ +_= + do j =1 for width + do k=1 for height; _=_ || @.j.k /*write the PPM file, 1 pixel at a time*/ + end /*k*/ /* ↑ a pixel contains three bytes, */ + end /*j*/ /* └────which defines the pixel's color*/ +call charout oFID, _ /*write the image's raster to the file.*/ +call charout oFID /*close the output file just to be safe*/ + /*stick a fork in it, we're all done. */ diff --git a/Task/Bitmap/Java/bitmap-1.java b/Task/Bitmap/Java/bitmap-1.java index 5ba6fe42e3..76a65f41dc 100644 --- a/Task/Bitmap/Java/bitmap-1.java +++ b/Task/Bitmap/Java/bitmap-1.java @@ -3,34 +3,29 @@ import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; -public class BasicBitmapStorage -{ - private BufferedImage image; +public class BasicBitmapStorage { - public BasicBitmapStorage(final int width, final int height) - { - image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR); - } + private final BufferedImage image; - public void fill(final Color c) - { - Graphics g = image.getGraphics(); - g.setColor(c); - g.fillRect(0, 0, image.getWidth(), image.getHeight()); - } + public BasicBitmapStorage(int width, int height) { + image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + } - public void setPixel(final int x, final int y, final Color c) - { - image.setRGB(x, y, c.getRGB()); - } + public void fill(Color c) { + Graphics g = image.getGraphics(); + g.setColor(c); + g.fillRect(0, 0, image.getWidth(), image.getHeight()); + } - public Color getPixel(final int x, final int y) - { - return new Color(image.getRGB(x, y)); - } + public void setPixel(int x, int y, Color c) { + image.setRGB(x, y, c.getRGB()); + } - public Image getImage() - { - return image; - } + public Color getPixel(int x, int y) { + return new Color(image.getRGB(x, y)); + } + + public Image getImage() { + return image; + } } diff --git a/Task/Bitmap/Java/bitmap-2.java b/Task/Bitmap/Java/bitmap-2.java index 9f647f775a..5c5d407582 100644 --- a/Task/Bitmap/Java/bitmap-2.java +++ b/Task/Bitmap/Java/bitmap-2.java @@ -1,19 +1,22 @@ +import static org.junit.Assert.assertEquals; + import java.awt.Color; -import junit.framework.TestCase; +import org.junit.Test; -public class BasicBitmapStorageTest extends TestCase -{ - public static final int WIDTH = 640, HEIGHT = 480; +public class BasicBitmapStorageTest { - BasicBitmapStorage bbs = new BasicBitmapStorage(WIDTH, HEIGHT); + @Test + public void testHappy() { + int width = 640; + int height = 480; - public void testHappy() - { - bbs.fill(Color.cyan); - bbs.setPixel(WIDTH / 2, HEIGHT / 2, Color.BLACK); - Color c1 = bbs.getPixel(WIDTH / 2, HEIGHT / 2); - Color c2 = bbs.getPixel(20, 20); - assertEquals(Color.BLACK, c1); - assertEquals(Color.CYAN, c2); - } + BasicBitmapStorage bbs = new BasicBitmapStorage(width, height); + bbs.fill(Color.CYAN); + bbs.setPixel(width / 2, height / 2, Color.BLACK); + Color c1 = bbs.getPixel(width / 2, height / 2); + Color c2 = bbs.getPixel(20, 20); + + assertEquals(Color.BLACK, c1); + assertEquals(Color.CYAN, c2); + } } diff --git a/Task/Bitmap/Julia/bitmap.julia b/Task/Bitmap/Julia/bitmap.julia new file mode 100644 index 0000000000..1467a9453d --- /dev/null +++ b/Task/Bitmap/Julia/bitmap.julia @@ -0,0 +1,24 @@ +using Images, Colors + +Base.hex(p::RGB{T}) where T = join(hex(c(p), 2) for c in (red, green, blue)) +function showhex(m::Matrix{RGB{T}}, pad::Integer=4) where T + for r in 1:size(m, 1) + println(" " ^ pad, join(hex.(m[r, :]), " ")) + end +end + +w, h = 5, 7 +cback = RGB(1, 0, 1) +cfore = RGB(0, 1, 0) + +img = Array{RGB{N0f8}}(h, w); +println("Uninitialized image:") +showhex(img) + +fill!(img, cback) +println("\nImage filled with background color:") +showhex(img) + +img[2, 3] = cfore +println("\nImage with a pixel set for foreground color:") +showhex(img) diff --git a/Task/Bitmap/Maple/bitmap.maple b/Task/Bitmap/Maple/bitmap.maple new file mode 100644 index 0000000000..c09fcaa799 --- /dev/null +++ b/Task/Bitmap/Maple/bitmap.maple @@ -0,0 +1,23 @@ +allocateImg := proc(width, height) + return Array(1..width, 1..height, 1..3); +end proc: +fillColor := proc(img, rgb::list) + local i; + for i from 1 to 3 do + img[..,..,i] := map(x->rgb[i], img[..,..,i]): + end do: +end proc: +setColor := proc(x, y, img, rgb::list) + local i: + for i from 1 to 3 do + img[x,y,i] := rgb[i]: + end do: +end proc: +getColor := proc(x,y,img) + local rgb,i: + rgb := Array(1..3): + for i from 1 to 3 do + rgb(i) := img[x,y,i]: + end do: + return rgb: +end proc: diff --git a/Task/Bitmap/Perl-6/bitmap.pl6 b/Task/Bitmap/Perl-6/bitmap.pl6 index e5f1f66533..1bf117941a 100644 --- a/Task/Bitmap/Perl-6/bitmap.pl6 +++ b/Task/Bitmap/Perl-6/bitmap.pl6 @@ -10,7 +10,7 @@ class Bitmap { $i where ^$!width, $j where ^$!height --> Pixel - ) is rw { @!data[$i*$!height + $j] } + ) is rw { @!data[$i + $j * $!width] } method set-pixel ($i, $j, Pixel $p) { self.pixel($i, $j) = $p.clone; diff --git a/Task/Bitmap/REXX/bitmap-1.rexx b/Task/Bitmap/REXX/bitmap-1.rexx index 826dc27c7f..ff5b039b32 100644 --- a/Task/Bitmap/REXX/bitmap-1.rexx +++ b/Task/Bitmap/REXX/bitmap-1.rexx @@ -2,36 +2,36 @@ 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.*/ -image.= /*"allocate" an "array" to nulls. */ -call RGBfill red /*set the entire image to red. */ -call RGBset 10, 40, blue /*set a pixel to blue. */ - -x=10; y=40; pix=RGBget(x, y) /*get the color of a pixel. */ -hexv = c2x(pix) /*get hex value of pix's color. */ -binv = x2b(hexv) /* " binary " " " " */ - -say 'pixel' x","y '=' binv /*show the binary value of 20,50 */ -bin3v = left(binv, 8) substr(binv, 9, 8) right(binv, 8) -say 'pixel' x","y '=' bin3v /*show again, but with spaces. */ +@. = /*define entire @. array to nulls. */ + x=10; y=40 /*set pixel's coördinates. */ +call RGBfill red /*set the entire image to red. */ +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. */ +binV = x2b(hexV) /* " binary " " " " */ +bin3V = left(binV, 8) substr(binV, 9, 8) right(binV, 8) +hex3V = left(hexV, 2) substr(hexV, 3, 2) right(hexV, 2) +xy= '(' || x","y')' /*create a handy─dandy literal for SAY.*/ +say xy ' pixel in binary: ' binV /*show the binary value of 20,50 */ +say xy ' pixel in binary: ' bin3V /*show again, but with spaces. */ say /*show a blank between binary and hex. */ -say 'pixel' x","y '=' hexv /*show again, but in hexadecimal. */ -hex3v = left(hexv, 2) substr(hexv, 3, 2) right(hexv, 2) -say 'pixel' x","y '=' hex3v /*show again, but with spaces. */ +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.*/ +say /*show a blank. */ +say 'The file image.PPM was created.' /*inform user that a file was created. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -RGBfill: procedure expose image.; image.=arg(1); return +RGBfill: @.=arg(1); return /*fill image with a color.*/ +RGBget: parse arg px,py; return @.px.py /*get a pixel's color. */ +RGBset: parse arg px,py,p$; @.px.py=p$; return /*set " " " */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -RGBget: procedure expose image.; parse arg Xpixel,Ypixel -return image.Xpixel.Ypixel /*obtain and return the pixel's color. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -RGBraster: procedure expose image.; parse arg Xsize,Ysize,color; RGB= - do x=1 to Xsize; _= /*build raster one line at a time. */ - do y=1 to Ysize /* " a line " pixel " " " */ - _=_ || image.x.y /*append single pixel to the line. */ - end /*y*/ /* [↑] all done building a line. */ - RGB=RGB || _ /*append a single line to raster. */ - end /*x*/ /* [↑] all done building raster. */ -r return RGB /*return RGB raster to the invoker. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -RGBset: procedure expose image.; parse arg Xpixel,Ypixel,color - image.Xpixel.Ypixel=color; return /*define pixel, return to the invoker. */ +PPMwrite: parse arg oFN, width, height /*obtain output filename, width, height*/ + oFID= oFN'.PPM'; $='9'x; #=255 /*fileID; separator; max color value.*/ + call charout oFID, , 1 /*set the position of the file's output*/ + call charout oFID,'P6'width || $ || height || $ || # || $ /*write hdr info.*/ + do j=1 for width + do k=1 for height; call charout oFID, @.j.k + end /*k*/ /* ↑ write the PPM file, ··· */ + end /*j*/ /* └───────── ··· one pixel at a time.*/ + call charout oFID; return /*close the output file just to be safe*/ diff --git a/Task/Bitwise-IO/Kotlin/bitwise-io.kotlin b/Task/Bitwise-IO/Kotlin/bitwise-io.kotlin new file mode 100644 index 0000000000..d942d46aee --- /dev/null +++ b/Task/Bitwise-IO/Kotlin/bitwise-io.kotlin @@ -0,0 +1,84 @@ +// version 1.2.31 + +import java.io.File + +class BitFilter(val f: File, var accu: Int = 0, var bits: Int = 0) { + + private val bw = f.bufferedWriter() + private val br = f.bufferedReader() + + fun write(buf: ByteArray, start: Int, _nBits: Int, _shift: Int) { + var nBits = _nBits + var index = start + _shift / 8 + var shift = _shift % 8 + + while (nBits != 0 || bits >= 8) { + while (bits >= 8) { + bits -= 8 + bw.write(accu ushr bits) + accu = accu and ((1 shl bits) - 1) + } + while (bits < 8 && nBits != 0) { + val b = buf[index].toInt() + accu = (accu shl 1) or (((128 ushr shift) and b) ushr (7 - shift)) + nBits-- + bits++ + if (++shift == 8) { shift = 0; index++ } + } + } + } + + fun read(buf: ByteArray, start: Int, _nBits: Int, _shift: Int) { + var nBits = _nBits + var index = start + _shift / 8 + var shift = _shift % 8 + + while (nBits != 0) { + while (bits != 0 && nBits != 0) { + val mask = 128 ushr shift + if ((accu and (1 shl (bits - 1))) != 0) + buf[index] = (buf[index].toInt() or mask).toByte() + else + buf[index] = (buf[index].toInt() and mask.inv()).toByte() + nBits-- + bits-- + if (++shift >= 8) { shift = 0; index++ } + } + if (nBits == 0) break + accu = (accu shl 8) or br.read() + bits += 8 + } + } + + fun closeWriter() { + if (bits != 0) { + accu = (accu shl (8 - bits)) + bw.write(accu) + } + bw.close() + accu = 0 + bits = 0 + } + + fun closeReader() { + br.close() + accu = 0 + bits = 0 + } +} + +fun main(args: Array) { + val s = "abcdefghijk".toByteArray(Charsets.UTF_8) + val f = File("test.bin") + val bf = BitFilter(f) + + /* for each byte in s, write 7 bits skipping 1 */ + for (i in 0 until s.size) bf.write(s, i, 7, 1) + bf.closeWriter() + + /* read 7 bits and expand to each byte of s2 skipping 1 bit */ + val s2 = ByteArray(s.size) + for (i in 0 until s2.size) bf.read(s2, i, 7, 1) + bf.closeReader() + println(String(s2, Charsets.UTF_8)) +} diff --git a/Task/Bitwise-IO/Python/bitwise-io-1.py b/Task/Bitwise-IO/Python/bitwise-io-1.py index d84dab75e8..0f818d3962 100644 --- a/Task/Bitwise-IO/Python/bitwise-io-1.py +++ b/Task/Bitwise-IO/Python/bitwise-io-1.py @@ -4,10 +4,16 @@ class BitWriter(object): self.bcount = 0 self.out = f + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.flush() + def __del__(self): try: self.flush() - except ValueError: # I/O operation on closed file + except ValueError: # I/O operation on closed file. pass def _writebit(self, bit): @@ -35,6 +41,12 @@ class BitReader(object): self.bcount = 0 self.read = 0 + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + pass + def _readbit(self): if not self.bcount: a = self.input.read(1) @@ -56,22 +68,22 @@ class BitReader(object): if __name__ == '__main__': import os import sys - # determine module name from this file's name and import it + # Determine this module's name from it's file name and import it. module_name = os.path.splitext(os.path.basename(__file__))[0] bitio = __import__(module_name) with open('bitio_test.dat', 'wb') as outfile: - writer = bitio.BitWriter(outfile) - chars = '12345abcde' - for ch in chars: - writer.writebits(ord(ch), 7) + with bitio.BitWriter(outfile) as writer: + chars = '12345abcde' + for ch in chars: + writer.writebits(ord(ch), 7) with open('bitio_test.dat', 'rb') as infile: - reader = bitio.BitReader(infile) - chars = [] - while True: - x = reader.readbits(7) - if reader.read == 0: - break - chars.append(chr(x)) - print(''.join(chars)) + with bitio.BitReader(infile) as reader: + chars = [] + while True: + x = reader.readbits(7) + if not reader.read: # End-of-file? + break + chars.append(chr(x)) + print(''.join(chars)) diff --git a/Task/Bitwise-IO/Python/bitwise-io-2.py b/Task/Bitwise-IO/Python/bitwise-io-2.py index 05bed4bf76..8cfae13337 100644 --- a/Task/Bitwise-IO/Python/bitwise-io-2.py +++ b/Task/Bitwise-IO/Python/bitwise-io-2.py @@ -6,3 +6,4 @@ c = sys.stdin.read(1) while len(c) > 0: o.writebits(ord(c), 7) c = sys.stdin.read(1) +o.flush() diff --git a/Task/Bitwise-operations/Befunge/bitwise-operations.bf b/Task/Bitwise-operations/Befunge/bitwise-operations.bf new file mode 100644 index 0000000000..6cffc7fe14 --- /dev/null +++ b/Task/Bitwise-operations/Befunge/bitwise-operations.bf @@ -0,0 +1,21 @@ +> v MCR >v + 1 2 3 4 5 6>61g-:| 8 9 + >&&\481p >88*61p371p >:61g\`!:68*+71g81gp| 7 >61g2/61p71g1+71pv + >v>v>v>v < > ^ +>#A 1 $^ ^ < + B 6^ < + ^>^>^>^1 C |!`5p18:+1g18$ < + ^ 9 p#p17*93p189p150 < >61g71g81gg+71g81gpv D + >071g81gp v ^ < + AND >+2\`!#^_> v + XOR +2% #^_> v + OR +1\`!#^_> v + NOT ! #^_> v + LSHFT 0 #^_>48*71g3+81gp v + RSHFT $ 48*71g3+81gp #^_>v E + END v #^_> >61g2*61pv + @ F + v_^# `2:< + >71g81gg.48*71g2+81gp79*1-71g2+81g1+pv + ^ <_v#!`2p15:+1g15p18+1g18< +^ < G diff --git a/Task/Bitwise-operations/Elena/bitwise-operations.elena b/Task/Bitwise-operations/Elena/bitwise-operations.elena index f32cfd3dde..2f697d0e38 100644 --- a/Task/Bitwise-operations/Elena/bitwise-operations.elena +++ b/Task/Bitwise-operations/Elena/bitwise-operations.elena @@ -13,7 +13,7 @@ extension testOp ] } -program = +public program = [ console readLineTo(Integer new); bitwiseTest(console readLineTo(Integer new)). ]. diff --git a/Task/Boolean-values/APL/boolean-values.apl b/Task/Boolean-values/APL/boolean-values.apl new file mode 100644 index 0000000000..ee0c1e802f --- /dev/null +++ b/Task/Boolean-values/APL/boolean-values.apl @@ -0,0 +1,4 @@ + 1 ^ 1 +1 + 1 ^ 0 +0 diff --git a/Task/Box-the-compass/Befunge/box-the-compass.bf b/Task/Box-the-compass/Befunge/box-the-compass.bf new file mode 100644 index 0000000000..d286f20a8d --- /dev/null +++ b/Task/Box-the-compass/Befunge/box-the-compass.bf @@ -0,0 +1,15 @@ +>>::"}"9**\4+3%79*9*5-*79*9*5--+:5>>>06p:55+%68*+v +^_@#!`*84:+1_06g:v>55+,^>/5+55+/48*::::,,,,%:1+.9,:06p48*\-0v +|p60-1<|:#,_>>>_08g1-^W|S>"-htroN"0"htron yb tsewhtroN"0v +#v"est-northwest"0"Northwest by west"0"Northwest"< +N>"W"0"htron yb tseW"0"tseW"0"htuos yb tseW"0"ts"v +#v0"Southwest"0"Southwest by west"0"West-southwe"< +S>"htuos yb tsewhtuoS"0"tsewhtuos-htuoS"0"tsew y"v +#v"h-southeast"0"South by east"0"South"0"South b"< +E>"tuoS"0"htuos yb tsaehtuoS"0"tsaehtuoS"0"tsae "v +#v"East by south"0"East-southeast"0"Southeast by"< +W>0"tsaE"0"htron yb tsaE"0"tsaehtron-tsaE"0"tsae"v +#v"rtheast by north"0"Northeast"0"Northeast by "<< +^>"oN"0"tsaehtron-htroN"0"tsae yb htroN"0"htroN"01 diff --git a/Task/Box-the-compass/Julia/box-the-compass.julia b/Task/Box-the-compass/Julia/box-the-compass.julia index b2fb2abce3..cd46704eef 100644 --- a/Task/Box-the-compass/Julia/box-the-compass.julia +++ b/Task/Box-the-compass/Julia/box-the-compass.julia @@ -1,18 +1,15 @@ -# v0.6 - function degree2compasspoint(d::Float64)::String - const MAJORS = ("north", "east", "south", "ovest", "north", "east", "south", "ovest") - const QUART1 = ("N", "N by E", "N-NE", "NE by N", "NE", "NE by E", "E-NE", "E by N") - const QUART2 = tuple((replace(p, "NE", "EN") for p in QUART1)...) + 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") 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 + 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)) end diff --git a/Task/Box-the-compass/Modula-2/box-the-compass.mod2 b/Task/Box-the-compass/Modula-2/box-the-compass.mod2 new file mode 100644 index 0000000000..96bf64fa92 --- /dev/null +++ b/Task/Box-the-compass/Modula-2/box-the-compass.mod2 @@ -0,0 +1,82 @@ +MODULE BoxTheCompass; +FROM FormatString IMPORT FormatString; +FROM RealStr IMPORT RealToStr; +FROM Terminal IMPORT WriteString,WriteLn,Write,ReadChar; + +PROCEDURE expand(cp : ARRAY OF CHAR); +VAR i : INTEGER = 0; +BEGIN + WHILE cp[i] # 0C DO + IF i=0 THEN + CASE cp[i] OF + 'N': WriteString("North") | + 'E': WriteString("East") | + 'S': WriteString("South") | + 'W': WriteString("West") | + 'b': WriteString(" by ") + ELSE + WriteString("-"); + END; + ELSE + CASE cp[i] OF + 'N': WriteString("north") | + 'E': WriteString("east") | + 'S': WriteString("south") | + 'W': WriteString("west") | + 'b': WriteString(" by ") + ELSE + WriteString("-"); + END; + END; + INC(i) + END; +END expand; + +PROCEDURE FormatReal(r : REAL); +VAR + buf : ARRAY[0..63] OF CHAR; + u,v : INTEGER; + w : REAL; +BEGIN + u := TRUNC(r); + w := r - FLOAT(u); + v := TRUNC(100.0 * w); + + FormatString("%6i.%'02i", buf, u, v); + WriteString(buf); +END FormatReal; + +VAR + cp : ARRAY[0..31] OF ARRAY[0..4] OF CHAR = { + "N", "NbE", "N-NE", "NEbN", "NE", "NEbE", "E-NE", "EbN", + "E", "EbS", "E-SE", "SEbE", "SE", "SEbS", "S-SE", "SbE", + "S", "SbW", "S-SW", "SWbS", "SW", "SWbW", "W-SW", "WbS", + "W", "WbN", "W-NW", "NWbW", "NW", "NWbN", "N-NW", "NbW" + }; + buf : ARRAY[0..63] OF CHAR; + i,index : INTEGER; + heading : REAL; +BEGIN + WriteString("Index Degrees Compass point"); + WriteLn; + WriteString("----- ------- -------------"); + WriteLn; + FOR i:=0 TO 32 DO + index := i MOD 32; + heading := FLOAT(i) * 11.25; + CASE i MOD 3 OF + 1: heading := heading + 5.62; | + 2: heading := heading - 5.62; + ELSE + (* empty *) + END; + FormatString("%2i ", buf, index+1); + WriteString(buf); + FormatReal(heading); + WriteString(" "); + expand(cp[index]); + WriteLn + END; + + ReadChar +END BoxTheCompass. diff --git a/Task/Box-the-compass/Ring/box-the-compass.ring b/Task/Box-the-compass/Ring/box-the-compass.ring new file mode 100644 index 0000000000..8f3eeb0ee3 --- /dev/null +++ b/Task/Box-the-compass/Ring/box-the-compass.ring @@ -0,0 +1,32 @@ +# Project : Box the compass +# Date : 2017/12/31 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +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"] + +degrees = [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] + +for i = 1 to len(degrees) + j = floor((degrees[i] + 5.625) / 11.25) + if j > 31 + j = j - 32 + ok + see "" + degrees[i] + " " + j + " " + if j != 0 + see "" + names[j+1] + nl + else + see "" + names[len(names)] + nl + ok +next diff --git a/Task/Break-OO-privacy/OCaml/break-oo-privacy.ocaml b/Task/Break-OO-privacy/OCaml/break-oo-privacy.ocaml new file mode 100644 index 0000000000..7c31bd221e --- /dev/null +++ b/Task/Break-OO-privacy/OCaml/break-oo-privacy.ocaml @@ -0,0 +1,33 @@ +class point x y = + object + val mutable x = x + val mutable y = y + method print = Printf.printf "(%d, %d)\n" x y + method dance = + x <- x + Random.int 3 - 1; + y <- y + Random.int 3 - 1 + end + +type evil_point { + blah : int; + blah2 : int; + mutable x : int; + mutable y : int; +} + +let evil_reset p = + let ep = Obj.magic p in + ep.x <- 0; + ep.y <- 0 + +let () = + let p = new point 0 0 in + p#print; + p#dance; + p#print; + p#dance; + p#print; + let (_, _, x, y) : int * int * int * int = Obj.magic p in + Printf.printf "Broken coord: (%d, %d)\n" x y; + evil_reset p + p#print diff --git a/Task/Brownian-tree/Julia/brownian-tree.julia b/Task/Brownian-tree/Julia/brownian-tree.julia index 3b4b0196a4..98f0772a2a 100644 --- a/Task/Brownian-tree/Julia/brownian-tree.julia +++ b/Task/Brownian-tree/Julia/brownian-tree.julia @@ -1,43 +1,42 @@ -using Color, Images, FixedPointNumbers +using Images, FileIO -const W = 512 -const W0 = W>>1 -const H = 512 -const H0 = H>>1 -const N = iceil(1.0*W*H) -const SIDESTICK = false +function main(h::Integer, w::Integer, side::Bool=false) + W0 = w >> 1 + H0 = h >> 1 + @inline function motecolor(x::Integer, y::Integer) + h = clamp(180 * (atan2(y - H0, x - W0) / π + 1.0), 0.0, 360.0) + return HSV(h, 0.5, 0.5) + end - -function motecolor(x::Int, y::Int) - h = clamp(180*(atan2(y-H0, x-W0)/pi + 1.0), 0.0, 360.0) - return HSV(h, 0.5, 0.5) -end - -img = Image(zeros(RGB{Ufixed8}, H, W)) -img["x", W0, "y", H0] = RGB(1, 1, 1) -isfree = trues(W, H) -isfree[W0, H0] = false -for i in 1:N - x = rand(1:W) - y = rand(1:H) - isfree[x, y] || continue - mc = motecolor(x, y) - for j in 1:10^3 - xp = x + rand(-1:1) - yp = y + rand(-1:1) - iscontained = 0 < xp <= W && 0 < yp <= H - if iscontained && isfree[xp, yp] - x = xp - y = yp - continue - else - if SIDESTICK || (iscontained && !isfree[xp, yp]) - isfree[x, y] = false - img["x", x, "y", y] = mc + img = zeros(RGB{N0f8}, h, w) + img[H0, W0] = RGB(1, 1, 1) + free = trues(h, w) + free[H0, W0] = false + for i in eachindex(img) + x = rand(1:h) + y = rand(1:w) + free[x, y] || continue + mc = motecolor(x, y) + for j in 1:1000 + xp = x + rand(-1:1) + yp = y + rand(-1:1) + contained = checkbounds(Bool, img, xp, yp) + if contained && free[xp, yp] + x, y = xp, yp + continue + else + if side || (contained && !free[xp, yp]) + free[x, y] = false + img[x, y] = mc + end + break end - break end end + return img end -imwrite(img, "brownian_tree.png") +imgnoside = main(256, 256) +imgwtside = main(256, 256, true) +save("data/browniantree_noside.jpg", imgnoside) +save("data/browniantree_wtside.jpg", imgwtside) diff --git a/Task/Brownian-tree/Perl-6/brownian-tree.pl6 b/Task/Brownian-tree/Perl-6/brownian-tree.pl6 index dcb96b3b36..3f9551d901 100644 --- a/Task/Brownian-tree/Perl-6/brownian-tree.pl6 +++ b/Task/Brownian-tree/Perl-6/brownian-tree.pl6 @@ -59,14 +59,9 @@ for ^particlenum -> $progress { } } set($x,$y); - display if $progress %% 50; if $spawnradius < mid && abs(($x|$y) - mid) > $spawnradius - 5 { $spawnradius = $spawnradius + 1; } } -say ""; display; -say ""; -say "time elapsed: ", (now - BEGIN { now }).Num.fmt("%.2f"), " seconds"; -say ""; diff --git a/Task/Brownian-tree/Ring/brownian-tree.ring b/Task/Brownian-tree/Ring/brownian-tree.ring new file mode 100644 index 0000000000..0a35440ec6 --- /dev/null +++ b/Task/Brownian-tree/Ring/brownian-tree.ring @@ -0,0 +1,102 @@ +# Project : Brownian tree +# Date : 2018/02/16 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + + +load "stdlib.ring" +load "guilib.ring" + +paint = null + +new qapp + { + win1 = new qwidget() { + setwindowtitle("") + setgeometry(100,100,800,600) + label1 = new qlabel(win1) { + setgeometry(10,10,800,600) + settext("") + } + new qpushbutton(win1) { + setgeometry(150,500,100,30) + settext("draw") + setclickevent("draw()") + } + show() + } + exec() + } + +func draw + p1 = new qpicture() + color = new qcolor() { + setrgb(0,0,255,255) + } + pen = new qpen() { + setcolor(color) + setwidth(1) + } + paint = new qpainter() { + begin(p1) + color = new qcolor() + color.setrgb(255,0,0,255) + pen = new qpen() { + setcolor(color) + setwidth(1)} + setpen(pen) + + browniantree() + + endpaint() + } + label1 { setpicture(p1) show() } + return + +func browniantree() + numparticles = 3000 + canvas = newlist(210,210) + canvas[randomf() * 100][randomf() * 200] = 1 + for i = 1 to numparticles + x = floor((randomf() * 199)) + 1 + y = floor((randomf() * 199)) + 1 + if x = 1 + x = 2 + ok + if y = 1 + y = 2 + ok + while canvas[x+1][y+1]+canvas[x][y+1]+canvas[x+1][y]+canvas[x-1][y-1]+canvas[x-1][y]+canvas[x][y-1] = 0 + x = x + floor((randomf() * 2)) + 1 + y = y + floor((randomf() * 2)) + 1 + if x = 1 + x = 2 + ok + if y = 1 + y = 2 + ok + if x < 1 or x > 200 or y < 1 or y > 200 + x = floor((randomf() * 199)) + 1 + y = floor((randomf() * 199)) + 1 + if x = 1 + x = 2 + ok + if y = 1 + y = 2 + ok + ok + end + canvas[x][y] = 1 + paint.drawpoint(x,y) + paint.drawpoint(x,y+1) + paint.drawpoint(x,y+2) + next + +func randomf() + decimals(10) + str = "0." + for i = 1 to 10 + nr = random(9) + str = str + string(nr) + next + return number(str) diff --git a/Task/Brownian-tree/Sidef/brownian-tree.sidef b/Task/Brownian-tree/Sidef/brownian-tree.sidef new file mode 100644 index 0000000000..934cb51e84 --- /dev/null +++ b/Task/Brownian-tree/Sidef/brownian-tree.sidef @@ -0,0 +1,78 @@ +const size = 100 +const mid = size>>1 +const particlenum = 1000 + +var map = [] +var spawnradius = 5 + +func set(x, y) { + map[x][y] = 1 +} + +func get(x, y) { + map[x][y] \\ 0 +} + +set(mid, mid) + +var blocks = [ + " ", + "\N{UPPER HALF BLOCK}", + "\N{LOWER HALF BLOCK}", + "\N{FULL BLOCK}" +] + +func block(a, b) { + blocks[2*b + a] +} + +func display { + 0..size `by` 2 -> map {|y| + 0..size -> map {|x| + if ([x, y].all { .-mid < spawnradius }) { + block(get(x, y), get(x, y+1)) + } else { " " } + }.join + }.join("\n").say +} + +for progress in (^particlenum) { + var (x=0, y=0) + + var reset = { + do { + (x, y) = ( + (mid-spawnradius .. mid+spawnradius -> pick), + [mid-spawnradius, mid+spawnradius] -> pick + ) + (x, y) = (y, x) if (1.rand < 0.5) + } while(get(x, y)) + } + + reset.run + + while ([[-1, 0, 1]]*2 -> cartesian.any {|pair| + get(x+pair[0], y+pair[1]) + } -> not) { + x = [x-1, x, x+1].pick + y = [y-1, y, y+1].pick + + if (1.rand < 0.25) { + x = (x >= mid ? (x-1) : (x+1)) + y = (y >= mid ? (y-1) : (y+1)) + } + + if ([x,y].any { .-mid > spawnradius }) { + reset.run + } + } + + set(x, y) + display() if (progress %% 50) + + if ((spawnradius < mid) && [x,y].any { .-mid > spawnradius-5 }) { + ++spawnradius + } +} + +display() diff --git a/Task/Bulls-and-cows-Player/Julia/bulls-and-cows-player-1.julia b/Task/Bulls-and-cows-Player/Julia/bulls-and-cows-player-1.julia new file mode 100644 index 0000000000..297eef0755 --- /dev/null +++ b/Task/Bulls-and-cows-Player/Julia/bulls-and-cows-player-1.julia @@ -0,0 +1,28 @@ +countbulls(a, b) = sum([a[i] == b[i] for i in 1:length(a)]) +countcows(a, b) = sum([a[i] == b[j] for i in 1:length(a), j in 1:length(b) if i != j]) +validate(a, b) = typeof(a) == Int && typeof(b) == Int && a >= 0 && b >= 0 && a + b < 5 + +function doguess() + poss = [a for a in collect(Base.product(1:9,1:9,1:9,1:9)) if length(unique(a))[1]==4] + while(length(poss) > 0) + ans = rand(poss, 1)[1] + while true + println("My guess: $(ans[1])$(ans[2])$(ans[3])$(ans[4]). How many bulls and cows?") + regres = match(r"\D*(\d+)\D*(\d+)", readline()) + bul, cow = parse(Int,regres[1]), parse(Int,regres[2]) + if(validate(bul, cow)) + break + else + println("Please enter an integer each for bulls and cows.") + end + end + if(bul == 4) + return ans + end + filter!(i -> (countbulls(ans,i), countcows(ans, i)) == (bul, cow), poss) + end + Base.throw("ERROR: No solutions found. Inconsistent scoring by other player?") +end + +answ = doguess() +println("The winning pick: $(answ[1])$(answ[2])$(answ[3])$(answ[4])") diff --git a/Task/Bulls-and-cows-Player/Julia/bulls-and-cows-player-2.julia b/Task/Bulls-and-cows-Player/Julia/bulls-and-cows-player-2.julia new file mode 100644 index 0000000000..a99a5a1d1b --- /dev/null +++ b/Task/Bulls-and-cows-Player/Julia/bulls-and-cows-player-2.julia @@ -0,0 +1,15 @@ +My guess: 9517. How many bulls and cows? +0 1 +My guess: 3285. How many bulls and cows? +1 1 +My guess: 4298. How many bulls and cows? +0 2 +My guess: 2465. How many bulls and cows? +0 2 +My guess: 3926. How many bulls and cows? +2 0 +My guess: 3724. How many bulls and cows? +3 0 +My guess: 3124. How many bulls and cows? +4 0 +The winning pick: 3124 diff --git a/Task/Bulls-and-cows-Player/Perl-6/bulls-and-cows-player.pl6 b/Task/Bulls-and-cows-Player/Perl-6/bulls-and-cows-player.pl6 index 960d9b911e..086b1d3857 100644 --- a/Task/Bulls-and-cows-Player/Perl-6/bulls-and-cows-player.pl6 +++ b/Task/Bulls-and-cows-Player/Perl-6/bulls-and-cows-player.pl6 @@ -1,7 +1,7 @@ # we use the [] reduction meta operator along with the Cartesian Product # operator X to create the Cartesian Product of four times [1..9] and then get # all the elements where the number of unique digits is four. -my @candidates = ([X] [1..9] xx 4).tree.grep: *.uniq == 4; +my @candidates = ([X] [1..9] xx 4).grep: *.unique == 4; repeat { my $guess = @candidates.pick; diff --git a/Task/Bulls-and-cows-Player/REXX/bulls-and-cows-player.rexx b/Task/Bulls-and-cows-Player/REXX/bulls-and-cows-player.rexx index 34482cd70c..e157fe4d42 100644 --- a/Task/Bulls-and-cows-Player/REXX/bulls-and-cows-player.rexx +++ b/Task/Bulls-and-cows-Player/REXX/bulls-and-cows-player.rexx @@ -1,60 +1,52 @@ /*REXX program plays the Bulls & Cows game with CBLFs (Carbon Based Life Forms). */ -call gen@ /*generate all the possibilities. */ -call # /*get the first guess for the game. */ +parse arg ? .; if datatype(?,'W') then call random ,,? /*Random seed? Make repeatable*/ +L=1234; H=9876; call gen@ /*generate all possibilities. */ + do forever; g=random(L,H); if @.g\==. then leave /*obtain a random 1st guess. */ + end /*forever*/ /* [↑] obtain rand 1st guess.*/ +$$1= '───── How many bulls and cows were guessed with '; $$2=" ? [─── or QUIT]" + do until #()<2 | bull==4; say; call ask /*examine @ list; get answer.*/ + do ?=L to H; if @.?==. then iterate /*is this already eliminated ?*/ + call bull# ?,g /*obtain bulls and cows count.*/ + if bull\==bulls | cow\==cows then @.?=. /*eliminate this possibility. */ + end /*?*/ + end /*until*/ - do tries=1 until #()<2 | bull==4; say - call prompter - do ?=L to H /*traipse through the whole list. */ - if @.?==. then iterate /*was this choice already eliminated ? */ - call bull# ?,g /*obtain the bulls and cows count. */ - if bull\==bulls | cow\==cows then @.?=. /*eliminate choice. */ - end /*?*/ - call # - end /*tries*/ - -if #==0 then do; call serr "At least one of your responses was invalid."; exit; end -say; say " ╔═════════════════════════════════════════════════╗" - say " ║ ║" - say " ║ Your secret Bulls and Cows number is: " g " ║" - say " ║ ║" - say " ╚═════════════════════════════════════════════════╝"; say -say tries 'tries.' +if #==0 then do; call serr "At least one of your responses was invalid."; exit; end +say; say " ╔═════════════════════════════════════════════════╗" + say " ║ ║" + say " ║ Your secret Bulls and Cows number is: " g " ║" + say " ║ ║" + say " ╚═════════════════════════════════════════════════╝"; say exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -#: #=0; do k=L to H; if @.k==. then iterate; #=#+1; g=k; end; return # -gen@: @.=.; L=1234; H=9876; do j=L to H; if genOK() then @.j=j; end; return -genOK: if pos(0, j)\==0 then return 0; return \rep() -rep: do k=1 for 3; if pos(substr(j,k,1),j,k+1)\==0 then return 1; end; return 0 -serr: say; say pad '***error*** ' ! arg(1); return +#: #=0; do k=L to H; if @.k==. then iterate; #=#+1; g=k; end; return # +gen@: @.=.; do j=L to H; if \rep() & pos(0, j)==0 then @.j=j; end; return +rep: do k=1 for 3; if pos(substr(j, k, 1), j, k+1)\==0 then return 1; end; return 0 +serr: say; say '───── ***error*** ' ! arg(1); return /*──────────────────────────────────────────────────────────────────────────────────────*/ -bull#: parse arg n,q; L=length(n); bulls=0; cows=0 /*initialize some vars.*/ - do j=1 for L; if substr(n,j,1) \== substr(q,j,1) then iterate - bulls=bulls+1 /*bump the bull counter. */ - q=overlay(.,q,j) /*disallow this for a cow count.*/ +bull#: parse arg n,q; w=length(n); bulls=0 /*W: # digits in N; bull cntr=0 */ + do j=1 for w; if substr(n, j, 1) \== substr(q, j, 1) then iterate + bulls=bulls+1; q=overlay(., q, j) /*bump counter; disallow for cow*/ end /*j*/ /* [↑] bull count═══════════════*/ - - do k=1 for L; _=substr(n,k,1); if pos(_, q)==0 then iterate - cows=cows + 1 /*bump the cow counter. */ - q=translate(q, , _) /*this allows for multiple digits*/ + cows=0 /*set the number of cows to zero.*/ + do k=1 for w; _=substr(n, k, 1); if pos(_, q)==0 then iterate + cows=cows + 1; q=translate(q, , _) /*bump counter; allow multiple #*/ end /*k*/ /* [↑] cow count═══════════════*/ return /*──────────────────────────────────────────────────────────────────────────────────────*/ -prompter: pad= '─────' /*define PAD characters for msgs.*/ - do forever; say - say pad "How many bulls and cows were guessed with " g '? [─── or QUIT]' - pull x 1 bull cow _ . /*PULL capitalizes the arguments.*/ - if abbrev('QUIT', x, 1) then exit /*the user wants to quit playing.*/ - select - when bull=='' then != "no numbers were entered." - when cow =='' then != "not enough numbers were entered." - when _\=='' then != "too many numbers entered: " x - when \datatype(bull, 'W') then != "1st number (bulls) not an integer: " bull - when \datatype(cow , 'W') then != "2nd number (cows) not an integer: " cow - when bull <0 | bull >4 then != "1st number (bulls) not 0 ──► 4: " bull - when cow <0 | cow >4 then != "2nd number (cows) not 0 ──► 4: " cow - when bull + cow > 4 then != "sum of bulls and cows can't be > 4: " x - otherwise != - end /*select*/ - if !\=='' then do; call serr; iterate; end /*prompt the user and try again. */ - bull=bull/1; cow=cow/1; return /*normalize bulls & cows numbers.*/ - end /*forever*/ +ask: do forever; say $$1 g $$2; pull x 1 bull cow . /*display prompt; obtain answer.*/ + select /* [↑] PULL capitalizes the args*/ + when abbrev('QUIT', x, 1) then exit /*the user wants to quit playing.*/ + when bull == '' then != "no numbers were entered." + when cow == '' then != "not enough numbers were entered." + when words(x) > 2 then != "too many numbers entered: " x + when \datatype(bull, 'W') then != "1st number (bulls) not an integer: " bull + when \datatype(cow , 'W') then != "2nd number (cows) not an integer: " cow + when bull <0 | bull >4 then != "1st number (bulls) not 0 ──► 4: " bull + when cow <0 | cow >4 then != "2nd number (cows) not 0 ──► 4: " cow + when bull + cow > 4 then != "sum of bulls and cows can't be > 4: " x + otherwise != + end /*select*/ + if !\=='' then do; call serr; iterate; end /*prompt the user and try again. */ + bull=bull/1; cow=cow/1; return /*normalize bulls & cows numbers.*/ + end /*forever*/ diff --git a/Task/Bulls-and-cows-Player/Ring/bulls-and-cows-player.ring b/Task/Bulls-and-cows-Player/Ring/bulls-and-cows-player.ring new file mode 100644 index 0000000000..20eb362dfd --- /dev/null +++ b/Task/Bulls-and-cows-Player/Ring/bulls-and-cows-player.ring @@ -0,0 +1,75 @@ +# Project : Bulls and cows/Player +# Date : 2017/11/21 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +secret = "" +while len(secret) != 4 + c = char(48 + random(9)) + if substr(secret, c) = 0 + secret = secret + c + ok +end +see "secret = " + secret + nl + +possible = "" +for i = 1234 to 9876 + possible = possible + string(i) +next + +see "guess a four-digit number with no digit used twice." + nl +guesses = 0 +while true + bulls = 0 + cows = 0 + if len(possible) = 4 + guess = possible + else + guess = substr(possible, 4*random(len(possible) / 4) - 3, 4) + ok + see "computer guesses " + guess + nl + guesses = guesses + 1 + if guess = secret + see "correctly guessed after " + guesses + " guesses!" + nl + exit + ok + if len(guess) = 4 + count(secret, guess, bulls, cows) + ok + i = 1 + testbulls = 0 + testcows = 0 + while i <= len(possible) + temp = substr(possible, i, 4) + if len(guess) = 4 + count(temp, guess, testbulls, testcows) + ok + if bulls=testbulls + if cows=testcows + i = i + 4 + ok + else + possible = left(possible, i-1) + substr(possible, i+4) + ok + end + if substr(possible, secret) = 0 + exit + ok +end + +func count(secret, guess, bulls, cows) + bulls = 0 + cows = 0 + for nr = 1 to 4 + c = secret[nr] + if guess != 0 + if guess[nr] = c + bulls = bulls + 1 + if substr(guess, c) > 0 + cows = cows + 1 + ok + ok + ok + next + see "giving " + bulls + " bull(s) and " + cows + " cow(s)." + nl + return [bulls, cows] diff --git a/Task/Bulls-and-cows-Player/VBA/bulls-and-cows-player.vba b/Task/Bulls-and-cows-Player/VBA/bulls-and-cows-player.vba new file mode 100644 index 0000000000..bca62b12a3 --- /dev/null +++ b/Task/Bulls-and-cows-Player/VBA/bulls-and-cows-player.vba @@ -0,0 +1,105 @@ +Option Explicit + +Sub Main_Bulls_And_Cows_Player() +Dim collSoluces As New Collection, Elem As Variant, Soluce As String +Dim strNumber As String, cpt As Byte, p As Byte +Dim i As Byte, Bulls() As Boolean, NbBulls As Byte, Cows As Byte, Poss As Long +Const NUMBER_OF_DIGITS As Byte = 4 + + strNumber = CreateNb(NUMBER_OF_DIGITS) + Debug.Print "TOSS : " & StrConv(strNumber, vbUnicode) + Debug.Print "---------- START ------------" + Set collSoluces = CollOfPossibleNumbers + Poss = collSoluces.Count + For Each Elem In collSoluces + 'Debug.Print "Number of possibilities : " & Poss + Debug.Print "Attempt : " & StrConv(Elem, vbUnicode) + NbBulls = 0: Soluce = Elem + ReDim Bulls(NUMBER_OF_DIGITS - 1) + For i = 1 To NUMBER_OF_DIGITS + If IsBull(strNumber, Mid(Elem, i, 1), i) Then + Bulls(i - 1) = True: NbBulls = NbBulls + 1 + RemoveIfNotBull collSoluces, Mid(Elem, i, 1), i + End If + Next i + Cows = 0 + For i = 1 To NUMBER_OF_DIGITS + If Not Bulls(i - 1) Then + If IsCow(collSoluces, strNumber, Mid(Elem, i, 1), p) Then + If Not Bulls(p - 1) Then Cows = Cows + 1 + End If + End If + Next i + Poss = collSoluces.Count + Debug.Print "Bulls : " & NbBulls & ", Cows : " & Cows + If Poss = 1 Then Exit For + Next + Debug.Print "---------- THE END ------------" + Debug.Print "TOSS WAS : " & StrConv(strNumber, vbUnicode) & " We found : " & StrConv(Soluce, vbUnicode) +End Sub + +Function CreateNb(NbDigits As Byte) As String +Dim myColl As New Collection +Dim strTemp As String +Dim bytAlea As Byte + + Randomize + Do + bytAlea = Int((Rnd * 9) + 1) + On Error Resume Next + myColl.Add CStr(bytAlea), CStr(bytAlea) + If Err <> 0 Then + On Error GoTo 0 + Else + strTemp = strTemp & CStr(bytAlea) + End If + Loop While Len(strTemp) < NbDigits + CreateNb = strTemp +End Function + +Function CollOfPossibleNumbers() As Collection +Dim TempColl As New Collection +Dim x As String +Dim i As Long +Dim Flag As Boolean +Dim b As Byte + + For i = 1234 To 9876 + Flag = False + For b = 1 To 4 + x = CStr(i) + If Len(Replace(x, Mid(x, b, 1), "")) < 3 Then + Flag = True: Exit For + End If + Next + If Not Flag Then TempColl.Add x, x + Next i + Set CollOfPossibleNumbers = TempColl +End Function + +Function IsBull(strgNb As String, Digit As String, place As Byte) As Boolean + IsBull = (Mid(strgNb, place, 1) = Digit) +End Function + +Function IsCow(C As Collection, strgNb As String, Digit As String, place As Byte) As Boolean + If (InStr(strgNb, Digit) > 0) Then + IsCow = True: place = InStr(strgNb, Digit) + RemoveIfNotCow C, Digit + End If +End Function + +Sub RemoveIfNotBull(C As Collection, Digit As String, place As Byte) +Dim E As Variant + + For Each E In C + If Mid(E, place, 1) <> Digit Then C.Remove E + Next +End Sub + +Sub RemoveIfNotCow(C As Collection, Digit As String) +Dim E As Variant + + For Each E In C + If (InStr(E, Digit) = 0) Then C.Remove E + Next +End Sub diff --git a/Task/Bulls-and-cows/Ceylon/bulls-and-cows.ceylon b/Task/Bulls-and-cows/Ceylon/bulls-and-cows.ceylon index ad4c6a1040..ec86ab3bea 100644 --- a/Task/Bulls-and-cows/Ceylon/bulls-and-cows.ceylon +++ b/Task/Bulls-and-cows/Ceylon/bulls-and-cows.ceylon @@ -1,70 +1,70 @@ import ceylon.random { - - DefaultRandom + DefaultRandom } shared void run() { - - value random = DefaultRandom(); - - function generateDigits() => - random.elements(1..9).distinct.take(4).sequence(); - - function validate(String guess) { - variable value ok = true; - if(!guess.every((Character element) => element.digit)) { - print("numbers only, please"); - ok = false; - } - if('0' in guess) { - print("only 1 to 9, please"); - ok = false; - } - if(guess.distinct.shorterThan(guess.size)) { - print("no duplicates, please"); - ok = false; - } - if(guess.size != 4) { - print("4 digits please"); - ok = false; - } - return ok; - } - function score({Integer*} target, {Integer*} guess) { - variable value bulls = 0; - variable value cows = 0; - for([a, b] in zipPairs(target, guess)) { - if(a == b) { - bulls++; - } else if(target.contains(b)) { - cows++; - } - } - return [bulls, cows]; - } - - while(true) { - value digits = generateDigits(); - print("I have chosen my four digits, please guess what they are. - Use only the digits 1 to 9 with no duplicates and enter them with no spaces. eg 1234 - Enter q or Q to quit."); - while(true) { - if(exists line = process.readLine()) { - if(line.uppercased == "Q") { - return; - } - if(validate(line)) { - value guessDigits = line.map((Character element) => parseInteger(element.string)).coalesced; - value [bulls, cows] = score(digits, guessDigits); - if(bulls == 4) { - print("You win!"); - break; - } else { - print("Bulls: ``bulls``, Cows: ``cows``"); - } - } - } - } - } + value random = DefaultRandom(); + + function generateDigits() => + random.elements(1..9).distinct.take(4).sequence(); + + function validate(String guess) { + variable value ok = true; + if (!guess.every((Character element) => element.digit)) { + print("numbers only, please"); + ok = false; + } + if ('0' in guess) { + print("only 1 to 9, please"); + ok = false; + } + if (guess.distinct.shorterThan(guess.size)) { + print("no duplicates, please"); + ok = false; + } + if (guess.size != 4) { + print("4 digits please"); + ok = false; + } + return ok; + } + + function score({Integer*} target, {Integer*} guess) { + variable value bulls = 0; + variable value cows = 0; + for ([a, b] in zipPairs(target, guess)) { + if (a == b) { + bulls++; + } else if (target.contains(b)) { + cows++; + } + } + return [bulls, cows]; + } + + while (true) { + value digits = generateDigits(); + print("I have chosen my four digits, please guess what they are. + Use only the digits 1 to 9 with no duplicates and enter them with no spaces. eg 1234 + Enter q or Q to quit."); + while (true) { + if (exists line = process.readLine()) { + if (line.uppercased == "Q") { + return; + } + if (validate(line)) { + value guessDigits = line.map((Character element) => Integer.parse(element.string)).narrow(); + value [bulls, cows] = score(digits, guessDigits); + if (bulls == 4) { + print("You win!"); + break; + } + else { + print("Bulls: ``bulls``, Cows: ``cows``"); + } + } + } + } + } } diff --git a/Task/Bulls-and-cows/Elena/bulls-and-cows.elena b/Task/Bulls-and-cows/Elena/bulls-and-cows.elena index 673fb94fb0..d1931d7936 100644 --- a/Task/Bulls-and-cows/Elena/bulls-and-cows.elena +++ b/Task/Bulls-and-cows/Elena/bulls-and-cows.elena @@ -28,7 +28,7 @@ class GameMaster var aBulls := Integer new:0. if (aGuess length != 4) - [ aBulls append int:(-1). ]; + [ aBulls append(-1). ]; [ try(0 to:3 do(:i) [ @@ -40,17 +40,17 @@ class GameMaster [ InvalidArgumentException new; raise. ]. // check duplicates - var duplicate := aGuess seekEach(:x)((x == ch)and:$(x equal reference:ch; not)). - if ($nil != duplicate) + var duplicate := aGuess seekEach(:x)((x == ch)&&(x equalReference:ch; inverted)). + if (nil != duplicate) [ InvalidArgumentException new; raise. ]. if (aNumber == theNumbers[i]) - [ aBulls append int:1 ]; + [ aBulls append(1) ]; [ (theNumbers ifExists:aNumber) - ? [ aCows append int:1 ]. + ? [ aCows append(1) ]. ]. ]) { @@ -65,7 +65,7 @@ class GameMaster -1 [ console printLine:"Not a valid guess.". ^ true ]; 4 [ console printLine:"Congratulations! You have won!". ^ false ]; ! [ - theAttempt append int:1. + theAttempt append(1). console printLine("Your Score is ",aBulls," bulls and ",aCows," cows"). @@ -74,7 +74,7 @@ class GameMaster ] } -program = +public program = [ var aGameMaster := GameMaster new. 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 c6ba98c0e3..5b9d62536f 100644 --- a/Task/Bulls-and-cows/REXX/bulls-and-cows-1.rexx +++ b/Task/Bulls-and-cows/REXX/bulls-and-cows-1.rexx @@ -1,24 +1,23 @@ -/*REXX program scores the Bulls & Cows game with CBLFs (Carbon Based Life Forms). */ -?=; do until length(?)==4 /*generate a unique four-digit number. */ - r=random(1, 9) /*change 1──► 0 to allow a zero digit*/ +/*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.*/ -id= '──────── [Bulls & Cows] ' +$= '──────── [Bulls & Cows] ' do until bulls==4; say /*play until guessed or enters "QUIT".*/ - say id '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. */ + 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 id @ 'bull's(bulls) "and" cows 'cow's(cows). + 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 " ┌─────────────────────────────────────────┐" @@ -28,4 +27,4 @@ say 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. */ +s: if arg(1)==1 then return ''; return "s" /*this function handles pluralization. */ diff --git a/Task/Bulls-and-cows/Ring/bulls-and-cows.ring b/Task/Bulls-and-cows/Ring/bulls-and-cows.ring new file mode 100644 index 0000000000..2d50ebccce --- /dev/null +++ b/Task/Bulls-and-cows/Ring/bulls-and-cows.ring @@ -0,0 +1,42 @@ +# Project : Bulls and cows +# Date : 2017/11/19 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +secret = "" +while len(secret) != 4 + c = char(48 + random(9)) + if substr(secret, c) = 0 + secret = secret + c + ok +end + +see "guess a four-digit number with no digit used twice." +guesses = 0 +guess = "" +while true + guess = "" + while len(guess) != 4 + see "enter your guess: " + give guess + if len(guess) != 4 + see "must be a four-digit number" + nl + ok + end + guesses = guesses + 1 + if guess = secret + see "you won after " + guesses + " guesses!" + exit + ok + bulls = 0 + cows = 0 + for i = 1 to 4 + c = secret[i] + if guess[i] = c + bulls = bulls + 1 + but substr(guess, c) > 0 + cows = cows + 1 + ok + next + see "you got " + bulls + " bull(s) and " + cows + " cow(s)." + nl +end diff --git a/Task/Bulls-and-cows/VBA/bulls-and-cows.vba b/Task/Bulls-and-cows/VBA/bulls-and-cows.vba new file mode 100644 index 0000000000..723f301ad3 --- /dev/null +++ b/Task/Bulls-and-cows/VBA/bulls-and-cows.vba @@ -0,0 +1,73 @@ +Option Explicit + +Sub Main_Bulls_and_cows() +Dim strNumber As String, strInput As String, strMsg As String, strTemp As String +Dim boolEnd As Boolean +Dim lngCpt As Long +Dim i As Byte, bytCow As Byte, bytBull As Byte +Const NUMBER_OF_DIGITS As Byte = 4 +Const MAX_LOOPS As Byte = 25 'the max of lines supported by MsgBox + + strNumber = Create_Number(NUMBER_OF_DIGITS) + Do + bytBull = 0: bytCow = 0: lngCpt = lngCpt + 1 + If lngCpt > MAX_LOOPS Then strMsg = "Max of loops... Sorry you loose!": Exit Do + strInput = AskToUser(NUMBER_OF_DIGITS) + If strInput = "Exit Game" Then strMsg = "User abort": Exit Do + For i = 1 To Len(strNumber) + If Mid(strNumber, i, 1) = Mid(strInput, i, 1) Then + bytBull = bytBull + 1 + ElseIf InStr(strNumber, Mid(strInput, i, 1)) > 0 Then + bytCow = bytCow + 1 + End If + Next i + If bytBull = Len(strNumber) Then + boolEnd = True: strMsg = "You win in " & lngCpt & " loops!" + Else + strTemp = strTemp & vbCrLf & "With : " & strInput & " ,you have : " & bytBull & " bulls," & bytCow & " cows." + MsgBox strTemp + End If + Loop While Not boolEnd + MsgBox strMsg +End Sub + +Function Create_Number(NbDigits As Byte) As String +Dim myColl As New Collection +Dim strTemp As String +Dim bytAlea As Byte + + Randomize + Do + bytAlea = Int((Rnd * 9) + 1) + On Error Resume Next + myColl.Add CStr(bytAlea), CStr(bytAlea) + If Err <> 0 Then + On Error GoTo 0 + Else + strTemp = strTemp & CStr(bytAlea) + End If + Loop While Len(strTemp) < NbDigits + Create_Number = strTemp +End Function + +Function AskToUser(NbDigits As Byte) As String +Dim boolGood As Boolean, strIn As String, i As Byte, NbDiff As Byte + + Do While Not boolGood + strIn = InputBox("Enter your number (" & NbDigits & " digits)", "Number") + If StrPtr(strIn) = 0 Then strIn = "Exit Game": Exit Do + If strIn <> "" Then + If Len(strIn) = NbDigits Then + NbDiff = 0 + For i = 1 To Len(strIn) + If Len(Replace(strIn, Mid(strIn, i, 1), "")) < NbDigits - 1 Then + NbDiff = 1 + Exit For + End If + Next i + If NbDiff = 0 Then boolGood = True + End If + End If + Loop + AskToUser = strIn +End Function diff --git a/Task/CRC-32/Julia/crc-32.julia b/Task/CRC-32/Julia/crc-32.julia index ed17de8403..fb6e0e6953 100644 --- a/Task/CRC-32/Julia/crc-32.julia +++ b/Task/CRC-32/Julia/crc-32.julia @@ -1,28 +1,27 @@ -function crc32(crc::Int, str::ASCIIString) - table = zeros(Uint32, 256) +function crc32(crc::Int, str::String) + table = zeros(UInt32, 256) - for i=0:255 - temp = i - - for j=0:7 - if temp & 1 == 1 - temp >>= 1 - temp $= 0xedb88320 + for i in 0:255 + tmp = i + for j in 0:7 + if tmp & 1 == 1 + tmp >>= 1 + tmp ⊻= 0xedb88320 else - temp >>= 1 + tmp >>= 1 end end - table[i + 1] = temp + table[i + 1] = tmp end - crc $= 0xffffffff + crc ⊻= 0xffffffff - for i in map(Uint32, collect(str)) - crc = (crc >> 8) $ table[(crc & 0xff) $ i + 1] + for i in UInt32.(collect(str)) + crc = (crc >> 8) ⊻ table[(crc & 0xff) ⊻ i + 1] end - crc $ 0xffffffff + crc ⊻ 0xffffffff end str = "The quick brown fox jumps over the lazy dog" diff --git a/Task/CSV-data-manipulation/Factor/csv-data-manipulation.factor b/Task/CSV-data-manipulation/Factor/csv-data-manipulation.factor new file mode 100644 index 0000000000..496e349d7b --- /dev/null +++ b/Task/CSV-data-manipulation/Factor/csv-data-manipulation.factor @@ -0,0 +1,10 @@ +USING: csv io.encodings.utf8 kernel math.parser sequences ; +IN: rosetta-code.csv-manipulation + +: append-sum ( seq -- seq' ) + dup [ string>number ] map-sum number>string suffix ; + +: csv-sums ( seq -- seq' ) + [ 0 = [ "SUM" suffix ] [ append-sum ] if ] map-index ; + +"example.csv" utf8 [ file>csv csv-sums ] [ csv>file ] 2bi diff --git a/Task/CSV-data-manipulation/Perl-6/csv-data-manipulation-1.pl6 b/Task/CSV-data-manipulation/Perl-6/csv-data-manipulation-1.pl6 index 5b2bcb585f..2b88751666 100644 --- a/Task/CSV-data-manipulation/Perl-6/csv-data-manipulation-1.pl6 +++ b/Task/CSV-data-manipulation/Perl-6/csv-data-manipulation-1.pl6 @@ -1,7 +1,7 @@ my $csvfile = './whatever.csv'; my $fh = open($csvfile, :r); my @header = $fh.get.split(','); -my @csv = map {[.split(',')]}, $fh.lines; +my @csv = map {[.split(',')]>>.Num}, $fh.lines; close $fh; my $out = open($csvfile, :w); diff --git a/Task/CSV-data-manipulation/Perl-6/csv-data-manipulation-2.pl6 b/Task/CSV-data-manipulation/Perl-6/csv-data-manipulation-2.pl6 index e2092e5444..5dbb372200 100644 --- a/Task/CSV-data-manipulation/Perl-6/csv-data-manipulation-2.pl6 +++ b/Task/CSV-data-manipulation/Perl-6/csv-data-manipulation-2.pl6 @@ -1,5 +1,5 @@ use Text::CSV; my $csvfile = './whatever.csv'; -my @csv = Text::CSV.parse-file($file); -modify(@csv); # do whatever; +my @csv = Text::CSV.parse-file($csvfile); +# modify(@csv); # do whatever; csv-write-file( @csv, :file($csvfile) ); diff --git a/Task/CSV-data-manipulation/Red/csv-data-manipulation-1.red b/Task/CSV-data-manipulation/Red/csv-data-manipulation-1.red new file mode 100644 index 0000000000..43ba06a134 --- /dev/null +++ b/Task/CSV-data-manipulation/Red/csv-data-manipulation-1.red @@ -0,0 +1,4 @@ +>>filein: read/lines %file.csv +>>data: copy [] +>>foreach item filein [append/only data split item ","] +; [["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"]] diff --git a/Task/CSV-data-manipulation/Red/csv-data-manipulation-2.red b/Task/CSV-data-manipulation/Red/csv-data-manipulation-2.red new file mode 100644 index 0000000000..caf8b0fc9d --- /dev/null +++ b/Task/CSV-data-manipulation/Red/csv-data-manipulation-2.red @@ -0,0 +1,6 @@ +>>forall data [either (index? data) = 1[ + append data/1 "SUM" +][ + append data/1 to string! + (to integer! data/1/1) + (to integer! data/1/2) + (to integer! data/1/3) + (to integer! data/1/4) + (to integer! data/1/5) +]] diff --git a/Task/CSV-data-manipulation/Red/csv-data-manipulation-3.red b/Task/CSV-data-manipulation/Red/csv-data-manipulation-3.red new file mode 100644 index 0000000000..25c8d311e6 --- /dev/null +++ b/Task/CSV-data-manipulation/Red/csv-data-manipulation-3.red @@ -0,0 +1,8 @@ +>>foreach item data [append item/6 "^/" repeat c 5 [append item/:c ","]] +>> print data +C1, C2, C3, C4, C5, SUM +1, 5, 9, 13, 17, 45 +2, 6, 10, 14, 18, 50 +3, 7, 11, 15, 19, 55 +4, 8, 12, 16, 20, 60 +>>write fileout.csv form data diff --git a/Task/CSV-data-manipulation/Stata/csv-data-manipulation.stata b/Task/CSV-data-manipulation/Stata/csv-data-manipulation.stata index 3cac3dc728..951b6f87bf 100644 --- a/Task/CSV-data-manipulation/Stata/csv-data-manipulation.stata +++ b/Task/CSV-data-manipulation/Stata/csv-data-manipulation.stata @@ -1,4 +1,4 @@ -import delimited input.csv, clear +import delim input.csv, clear replace c5=c3+c4 drop if mod(c3,3)==0 -export delimited using output.csv, replace +export delim output.csv, replace diff --git a/Task/CSV-to-HTML-translation/Factor/csv-to-html-translation-1.factor b/Task/CSV-to-HTML-translation/Factor/csv-to-html-translation-1.factor new file mode 100644 index 0000000000..ca6619490f --- /dev/null +++ b/Task/CSV-to-HTML-translation/Factor/csv-to-html-translation-1.factor @@ -0,0 +1,31 @@ +USING: combinators csv io kernel sequences strings ; +IN: rosetta-code.csv-to-html + +CONSTANT: input + +"Character,Speech +The multitude,The messiah! Show us the messiah! +Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away! +The multitude,Who are you? +Brians mother,I'm his mother; that's who! +The multitude,Behold his mother! Behold his mother!" + +: escape-chars ( seq -- seq' ) + [ + { + { CHAR: & [ "&" ] } + { CHAR: ' [ "'" ] } + { CHAR: < [ "<" ] } + { CHAR: > [ ">" ] } + [ 1string ] + } case + ] { } map-as concat ; + +: tag ( str tag -- str ) + [ "<" ">" surround ] [ "" surround ] bi surround ; + +: csv>table ( seq -- str ) + [ [ "td" tag ] map concat "tr" tag " " prepend ] map + { "" } prepend { "
" } append "\n" join ; + +input escape-chars string>csv csv>table print diff --git a/Task/CSV-to-HTML-translation/Factor/csv-to-html-translation-2.factor b/Task/CSV-to-HTML-translation/Factor/csv-to-html-translation-2.factor new file mode 100644 index 0000000000..c9d491103a --- /dev/null +++ b/Task/CSV-to-HTML-translation/Factor/csv-to-html-translation-2.factor @@ -0,0 +1,8 @@ + + + + + + + +
CharacterSpeech
The multitudeThe messiah! Show us the messiah!
Brians mother<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitudeWho are you?
Brians motherI'm his mother; that's who!
The multitudeBehold his mother! Behold his mother!
diff --git a/Task/CSV-to-HTML-translation/Forth/csv-to-html-translation-1.fth b/Task/CSV-to-HTML-translation/Forth/csv-to-html-translation-1.fth new file mode 100644 index 0000000000..b59459c399 --- /dev/null +++ b/Task/CSV-to-HTML-translation/Forth/csv-to-html-translation-1.fth @@ -0,0 +1,22 @@ +: BEGIN-COLUMN ." " ; +: END-COLUMN ." " ; + +: BEGIN-ROW ." " BEGIN-COLUMN ; +: END-ROW END-COLUMN ." " CR ; + +: CSV2HTML + ." " CR BEGIN-ROW + BEGIN KEY DUP #EOF <> WHILE + CASE + 10 OF END-ROW BEGIN-ROW ENDOF + [CHAR] , OF END-COLUMN BEGIN-COLUMN ENDOF + [CHAR] < OF ." <" ENDOF + [CHAR] > OF ." >" ENDOF + [CHAR] & OF ." &" ENDOF + DUP EMIT + ENDCASE + REPEAT + END-ROW ."
" CR +; + +CSV2HTML BYE diff --git a/Task/CSV-to-HTML-translation/Forth/csv-to-html-translation-2.fth b/Task/CSV-to-HTML-translation/Forth/csv-to-html-translation-2.fth new file mode 100644 index 0000000000..0964db10ff --- /dev/null +++ b/Task/CSV-to-HTML-translation/Forth/csv-to-html-translation-2.fth @@ -0,0 +1,8 @@ + + + + + + + +
CharacterSpeech
The multitudeThe messiah! Show us the messiah!
Brians mother<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitudeWho are you?
Brians motherI'm his mother; that's who!
The multitudeBehold his mother! Behold his mother!
diff --git a/Task/CSV-to-HTML-translation/Go/csv-to-html-translation-1.go b/Task/CSV-to-HTML-translation/Go/csv-to-html-translation-1.go index b65171cc92..4cb35fcbd1 100644 --- a/Task/CSV-to-HTML-translation/Go/csv-to-html-translation-1.go +++ b/Task/CSV-to-HTML-translation/Go/csv-to-html-translation-1.go @@ -5,6 +5,7 @@ import ( "encoding/csv" "fmt" "html/template" + "strings" ) var c = `Character,Speech @@ -27,7 +28,7 @@ func csvToHtml(c string) (string, error) { if err != nil { return "", err } - var b bytes.Buffer + var b strings.Builder err = template.Must(template.New("").Parse(` {{range .}} {{range .}}{{end}} {{end}}
{{.}}
diff --git a/Task/CSV-to-HTML-translation/Go/csv-to-html-translation-2.go b/Task/CSV-to-HTML-translation/Go/csv-to-html-translation-2.go index ba30c892c3..6aeea2a2a4 100644 --- a/Task/CSV-to-HTML-translation/Go/csv-to-html-translation-2.go +++ b/Task/CSV-to-HTML-translation/Go/csv-to-html-translation-2.go @@ -6,6 +6,7 @@ import ( "flag" "fmt" "html/template" + "strings" ) var csvStr = `Character,Speech @@ -34,7 +35,7 @@ func csvToHtml(csvStr string, headings bool) (string, error) { if headings { tStr = tHeadings } - var b bytes.Buffer + var b strings.Builder err = template.Must(template.New("").Parse(tStr)).Execute(&b, data) return b.String(), err } diff --git a/Task/CSV-to-HTML-translation/Maple/csv-to-html-translation.maple b/Task/CSV-to-HTML-translation/Maple/csv-to-html-translation.maple new file mode 100644 index 0000000000..5b6d65d7eb --- /dev/null +++ b/Task/CSV-to-HTML-translation/Maple/csv-to-html-translation.maple @@ -0,0 +1,28 @@ + #A translation of the C code posted +html_table := proc(str) + local char; + printf("\n\n\n
"); + for char in str do + if char = "\n" then + printf("
") + elif char = "," then + printf("") + elif char = "<" then + printf("<") + elif char = ">" then + printf(">") + elif char = "&" then + printf("&") + else + printf(char) + end if; + end do; + printf("
"); +end proc; + +html_table("Character,Speech +The multitude,The messiah! Show us the messiah! +Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away! +The multitude,Who are you? +Brians mother,I'm his mother; that's who! +The multitude,Behold his mother! Behold his mother!"); diff --git a/Task/CSV-to-HTML-translation/Red/csv-to-html-translation.red b/Task/CSV-to-HTML-translation/Red/csv-to-html-translation.red new file mode 100644 index 0000000000..469e18de4c --- /dev/null +++ b/Task/CSV-to-HTML-translation/Red/csv-to-html-translation.red @@ -0,0 +1,39 @@ +Red [] + +csv: {Character,Speech +The multitude,The messiah! Show us the messiah! +Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away! +The multitude,Who are you? +Brians mother,I'm his mother; that's who! +The multitude,Behold his mother! Behold his mother!} + +add2html: func [ bl ] [append html rejoin bl ] ;; helper function to add block data to html string + +;;---------------------------------------------------------------------- +csv2html: func ["function to generate string with html table from csv data file" +;;---------------------------------------------------------------------- + s [string!] "input .csv data" +][ +arr: split s newline ;; generate array (series) from string +html: copy "^/" ;; init html string + +forall arr [ ;; i use forall here so that i can test for head? of series ... + either head? arr [ append html ""] + [ append html ""] + replace/all first arr "<" "<" ;; escape "<" and ">" characters + replace/all first arr ">" ">" + foreach col split first arr "," [ + either head? arr [ + add2html ['] + ][ + add2html ['] + ] + ] + add2html [' newline] +] +return add2html ['
col ' col '
] +] +;;---------------------------------------------------------------------- + +print csv2html csv ;; call function +write %data.html csv2html csv ;; write to file diff --git a/Task/Caesar-cipher/Applesoft-BASIC/caesar-cipher.applesoft b/Task/Caesar-cipher/Applesoft-BASIC/caesar-cipher.applesoft new file mode 100644 index 0000000000..caef9c56cc --- /dev/null +++ b/Task/Caesar-cipher/Applesoft-BASIC/caesar-cipher.applesoft @@ -0,0 +1,42 @@ +100 INPUT ""; T$ + +110 LET K% = RND(1) * 25 + 1 +120 PRINT "ENCODED WITH "; +130 GOSUB 200ENCODED + +140 LET K% = 26 - K% +150 PRINT "DECODED WITH "; +160 GOSUB 200DECODED + +170 END + +REM ENCODED/DECODED +200 PRINT "CAESAR " K%; +210 LET K$(1) = " (ROT-13)" +220 PRINT K$(K% = 13) +230 GOSUB 300CAESAR +240 PRINT T$ +250 RETURN + +REM CAESAR T$ K% +300 FOR I = 1 TO LEN(T$) +310 LET C$ = MID$(T$, I, 1) +320 GOSUB 400ENCODE +330 LET L = I - 1 +340 LET T$(0) = MID$(T$, 1, L) +350 LET L = I + 1 +360 LET T$ = C$ + MID$(T$, L) +370 LET T$ = T$(0) + T$ +380 NEXT I +390 RETURN + +REM ENCODE C$ K% +400 LET C = ASC(C$) +410 LET L = (C > 95) * 32 +420 LET C = C - L +430 IF C < 65 THEN RETURN +440 IF C > 90 THEN RETURN +450 LET C = C + K% +460 IF C > 90 THEN C = C - 26 +470 LET C$ = CHR$(C + L) +480 RETURN diff --git a/Task/Caesar-cipher/Astro/caesar-cipher.astro b/Task/Caesar-cipher/Astro/caesar-cipher.astro index 12a4706887..9b6b670bbb 100644 --- a/Task/Caesar-cipher/Astro/caesar-cipher.astro +++ b/Task/Caesar-cipher/Astro/caesar-cipher.astro @@ -1,8 +1,8 @@ fun caesar(s, k, decode: false): if decode: k = 26 - k - join(char((ord(c) - 65 + k) % 26 + 65) | c in s.upper() where "a" <= c <= "A") + char({(ord(c) - 65 + k) mod 26 + 65) | c in s.upper() where "a" <= c <= "A"}).join() let msg = "The quick brown fox jumped over the lazy dogs" print msg let enc = caesar(msg, 11) -print ..(enc) ..(caesar(enc, 11, decode: true)) +print~(enc)~(caesar(enc, 11, decode: true)) diff --git a/Task/Caesar-cipher/COBOL/caesar-cipher-1.cobol b/Task/Caesar-cipher/COBOL/caesar-cipher-1.cobol new file mode 100644 index 0000000000..af62e5229c --- /dev/null +++ b/Task/Caesar-cipher/COBOL/caesar-cipher-1.cobol @@ -0,0 +1,37 @@ + identification division. + program-id. caesar. + data division. + 1 msg pic x(50) + value "The quick brown fox jumped over the lazy dog.". + 1 offset binary pic 9(4) value 7. + 1 from-chars pic x(52). + 1 to-chars pic x(52). + 1 tabl. + 2 pic x(26) value "abcdefghijklmnopqrstuvwxyz". + 2 pic x(26) value "ABCDEFGHIJKLMNOPQRSTUVWXYZ". + 2 pic x(26) value "abcdefghijklmnopqrstuvwxyz". + 2 pic x(26) value "ABCDEFGHIJKLMNOPQRSTUVWXYZ". + procedure division. + begin. + display msg + perform encrypt + display msg + perform decrypt + display msg + stop run + . + + encrypt. + move tabl (1:52) to from-chars + move tabl (1 + offset:52) to to-chars + inspect msg converting from-chars + to to-chars + . + + decrypt. + move tabl (1 + offset:52) to from-chars + move tabl (1:52) to to-chars + inspect msg converting from-chars + to to-chars + . + end program caesar. diff --git a/Task/Caesar-cipher/COBOL/caesar-cipher.cobol b/Task/Caesar-cipher/COBOL/caesar-cipher-2.cobol similarity index 100% rename from Task/Caesar-cipher/COBOL/caesar-cipher.cobol rename to Task/Caesar-cipher/COBOL/caesar-cipher-2.cobol diff --git a/Task/Caesar-cipher/Clojure/caesar-cipher.clj b/Task/Caesar-cipher/Clojure/caesar-cipher-1.clj similarity index 100% rename from Task/Caesar-cipher/Clojure/caesar-cipher.clj rename to Task/Caesar-cipher/Clojure/caesar-cipher-1.clj diff --git a/Task/Caesar-cipher/Clojure/caesar-cipher-2.clj b/Task/Caesar-cipher/Clojure/caesar-cipher-2.clj new file mode 100644 index 0000000000..7cd38c44d1 --- /dev/null +++ b/Task/Caesar-cipher/Clojure/caesar-cipher-2.clj @@ -0,0 +1,7 @@ +(defn encode [k s] + (let [f #(take 26 (drop %3 (cycle (range (int %1) (inc (int %2)))))) + a #(map char (concat (f \a \z %) (f \A \Z %)))] + (apply str (replace (zipmap (a 0) (a k)) s)))) + +(defn decode [k s] + (encode (- 26 k) s)) diff --git a/Task/Caesar-cipher/Crystal/caesar-cipher.crystal b/Task/Caesar-cipher/Crystal/caesar-cipher.crystal new file mode 100644 index 0000000000..3e7c66942d --- /dev/null +++ b/Task/Caesar-cipher/Crystal/caesar-cipher.crystal @@ -0,0 +1,11 @@ +class String + ALPHABET = ("A".."Z").to_a + + def caesar_cipher(num) + self.tr(ALPHABET.join, ALPHABET.rotate(num).join) + end +end + +# demo +encrypted = "THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG".caesar_cipher(5) +decrypted = encrypted.caesar_cipher(-5) diff --git a/Task/Caesar-cipher/Elena/caesar-cipher.elena b/Task/Caesar-cipher/Elena/caesar-cipher.elena index f9fed07b5a..dca3fc46ed 100644 --- a/Task/Caesar-cipher/Elena/caesar-cipher.elena +++ b/Task/Caesar-cipher/Elena/caesar-cipher.elena @@ -1,6 +1,7 @@ import system'routines. import system'math. import extensions. +import extensions'text. const Letters = "abcdefghijklmnopqrstuvwxyz". const BigLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ". @@ -12,16 +13,18 @@ class Encrypting :: Enumerator object theKey. object theEnumerator. - constructor new key:aKey text:aText + constructor key:aKey text:aText [ theKey := aKey. theEnumerator := aText enumerator. ] - next => theEnumerator. + bool next => theEnumerator. reset => theEnumerator. + enumerable => theEnumerator. + get [ var aChar := theEnumerator get. @@ -48,13 +51,13 @@ class Encrypting :: Enumerator extension encryptOp { encrypt : aKey - = Encrypting new key:aKey text:self; summarize(String new). + = Encrypting key:aKey text:self; summarize(StringWriter new). decrypt :aKey - = Encrypting new key(26 - aKey) text:self; summarize(String new). + = Encrypting key(26 - aKey) text:self; summarize(StringWriter new). } -program = +public program = [ console printLine("Original text :",TestText). diff --git a/Task/Caesar-cipher/Factor/caesar-cipher.factor b/Task/Caesar-cipher/Factor/caesar-cipher.factor new file mode 100644 index 0000000000..b47e03a788 --- /dev/null +++ b/Task/Caesar-cipher/Factor/caesar-cipher.factor @@ -0,0 +1,18 @@ +USING: io kernel locals math sequences unicode.categories ; +IN: rosetta-code.caesar-cipher + +:: cipher ( n s -- s' ) + [| c | + c Letter? [ + c letter? CHAR: a CHAR: A ? :> a + c a - n + 26 mod a + + ] + [ c ] if + ] :> shift + s [ shift call ] map ; + +: encrypt ( n s -- s' ) cipher ; +: decrypt ( n s -- s' ) [ 26 swap - ] dip cipher ; + +11 "Esp bftnv mczhy qzi ufxapo zgpc esp wlkj ozr." decrypt print +11 "The quick brown fox jumped over the lazy dog." encrypt print diff --git a/Task/Caesar-cipher/JavaScript/caesar-cipher-1.js b/Task/Caesar-cipher/JavaScript/caesar-cipher-1.js index 7aad4c2a83..44f68eb7d2 100644 --- a/Task/Caesar-cipher/JavaScript/caesar-cipher-1.js +++ b/Task/Caesar-cipher/JavaScript/caesar-cipher-1.js @@ -1,5 +1,5 @@ function caesar (text, shift) { - return text.toUpperCase().replace(/[^A-Z]/g,'').replace(/[A-Z]/g, function(a) { + return text.toUpperCase().replace(/[^A-Z]/g,'').replace(/./g, function(a) { return String.fromCharCode(65+(a.charCodeAt(0)-65+shift)%26); }); } diff --git a/Task/Caesar-cipher/JavaScript/caesar-cipher-2.js b/Task/Caesar-cipher/JavaScript/caesar-cipher-2.js index 5333e06810..3d30b7a5ac 100644 --- a/Task/Caesar-cipher/JavaScript/caesar-cipher-2.js +++ b/Task/Caesar-cipher/JavaScript/caesar-cipher-2.js @@ -1,5 +1,5 @@ var caesar = (text, shift) => text .toUpperCase() .replace(/[^A-Z]/g, '') - .replace(/[A-Z]/g, a => + .replace(/./g, a => String.fromCharCode(65 + (a.charCodeAt(0) - 65 + shift) % 26)); diff --git a/Task/Caesar-cipher/Julia/caesar-cipher.julia b/Task/Caesar-cipher/Julia/caesar-cipher.julia index c431d87362..43ad79cc5f 100644 --- a/Task/Caesar-cipher/Julia/caesar-cipher.julia +++ b/Task/Caesar-cipher/Julia/caesar-cipher.julia @@ -1,18 +1,15 @@ -function rot(s::String, key::Integer) - map(s) do c - if 'a' <= c <= 'z' - char( mod(c - 'a' + key, 26) + 'a') - elseif 'A' <= c <= 'Z' - char( mod(c - 'A' + key, 26) + 'A') - else - c - end +function rot(ch::Char, key::Integer) + if key < 1 || key > 25 end + if isalpha(ch) + shft = ifelse(islower(ch), 'a', 'A') + ch = (ch - shft + key) % 26 + shft end + return ch end +rot(str::AbstractString, key::Integer) = map(x -> rot(x, key), str) +msg = "The five boxing wizards jump quickly" key = 3 -txt = "The five boxing wizards jump quickly" +invkey = 26 - 3 -println("Original: ", txt); -println("Encrypted: ", rot(txt, key)) -println("Decrypted: ", rot(rot(txt, key), 26 - key)) +println("# original: $msg\n encrypted: $(rot(msg, key))\n decrypted: $(rot(rot(msg, key), invkey))") diff --git a/Task/Caesar-cipher/Modula-2/caesar-cipher.mod2 b/Task/Caesar-cipher/Modula-2/caesar-cipher.mod2 new file mode 100644 index 0000000000..21e7a4baa3 --- /dev/null +++ b/Task/Caesar-cipher/Modula-2/caesar-cipher.mod2 @@ -0,0 +1,77 @@ +MODULE CaesarCipher; +FROM Conversions IMPORT IntToStr; +FROM Terminal IMPORT WriteString, WriteLn, ReadChar; + +TYPE String = ARRAY[0..64] OF CHAR; + +PROCEDURE Encrypt(p : String; key : CARDINAL) : String; +VAR e : String; +VAR i,t : CARDINAL; +VAR c : CHAR; +BEGIN + FOR i:=0 TO HIGH(p) DO + IF p[i]=0C THEN BREAK; END; + + t := ORD(p[i]); + IF (p[i]>='A') AND (p[i]<='Z') THEN + t := t + key; + IF t>ORD('Z') THEN + t := t - 26; + END; + ELSIF (p[i]>='a') AND (p[i]<='z') THEN + t := t + key; + IF t>ORD('z') THEN + t := t - 26; + END; + END; + e[i] := CHR(t); + END; + RETURN e; +END Encrypt; + +PROCEDURE Decrypt(p : String; key : CARDINAL) : String; +VAR e : String; +VAR i,t : CARDINAL; +VAR c : CHAR; +BEGIN + FOR i:=0 TO HIGH(p) DO + IF p[i]=0C THEN BREAK; END; + + t := ORD(p[i]); + IF (p[i]>='A') AND (p[i]<='Z') THEN + t := t - key; + IF t='a') AND (p[i]<='z') THEN + t := t - key; + IF t + +cipher = "pack my box with five dozen liquor jugs" +abc = "abcdefghijklmnopqrstuvwxyz" +see "text is to be encrypted:" + nl +see cipher+ nl + nl +str = "" +key = random(24) + 1 +see "key = " + key + nl + nl +see "encrypted:" + nl +caesarencode(cipher, key) +see str + nl + nl +cipher = str +see "decrypted again:" + nl +caesardecode(cipher, key) +see str + nl + +func caesarencode(cipher, key) + str = "" + for n = 1 to len(cipher) + if cipher[n] != " " + pos = substr(abc, cipher[n]) + if pos + key < len(abc) + str = str + abc[pos + key] + else + if (pos+key)-len(abc) != 0 + str = str + abc[(pos+key)%len(abc)] + else + str = str +abc[key+pos] + ok + ok + else + str = str + " " + ok + next + return str + +func caesardecode(cipher, key) + str = "" + for n= 1 to len(cipher) + if cipher[n] != " " + pos = substr(abc, cipher[n]) + if (pos - key) > 0 and pos != key + str = str + abc[pos - key] + loop + else + if pos = key + str = str + char(122) + else + str = str + abc[len(abc)-(key-pos)] + ok + ok + else + str = str + " " + ok + next + return str diff --git a/Task/Caesar-cipher/Stata/caesar-cipher.stata b/Task/Caesar-cipher/Stata/caesar-cipher.stata new file mode 100644 index 0000000000..823b54b67f --- /dev/null +++ b/Task/Caesar-cipher/Stata/caesar-cipher.stata @@ -0,0 +1,11 @@ +function caesar(s, k) { + u = ascii(s) + i = selectindex(u:>=65 :& u:<=90) + if (length(i)>0) u[i] = mod(u[i]:+(k-65), 26):+65 + i = selectindex(u:>=97 :& u:<=122) + if (length(i)>0) u[i] = mod(u[i]:+(k-97), 26):+97 + return(char(u)) +} + +caesar("layout", 20) + fusion diff --git a/Task/Caesar-cipher/VBA/caesar-cipher.vba b/Task/Caesar-cipher/VBA/caesar-cipher.vba new file mode 100644 index 0000000000..9fa212493d --- /dev/null +++ b/Task/Caesar-cipher/VBA/caesar-cipher.vba @@ -0,0 +1,34 @@ +Option Explicit + +Sub Main_Caesar() +Dim ch As String + ch = Caesar_Cipher("CAESAR: Who is it in the press that calls on me? I hear a tongue, shriller than all the music, Cry 'Caesar!' Speak; Caesar is turn'd to hear.", 14) + Debug.Print ch + Debug.Print Caesar_Cipher(ch, -14) +End Sub + +Function Caesar_Cipher(sText As String, lngNumber As Long) As String +Dim Tbl, strGlob As String, strTemp As String, i As Long, bytAscii As Byte + Const MAJ As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + Const NB_LETTERS As Byte = 26 + Const DIFFASCIIMAJ As Byte = 65 - NB_LETTERS + Const DIFFASCIIMIN As Byte = 97 - NB_LETTERS + + strTemp = sText + If lngNumber < NB_LETTERS And lngNumber > NB_LETTERS * -1 Then + strGlob = String(NB_LETTERS * 4, " ") + LSet strGlob = MAJ & MAJ & MAJ + Tbl = Split(StrConv(strGlob, vbUnicode), Chr(0)) + For i = 1 To Len(strTemp) + If Mid(strTemp, i, 1) Like "[a-zA-Z]" Then + bytAscii = Asc(Mid(strTemp, i, 1)) + If Mid(strTemp, i, 1) = Tbl(bytAscii - DIFFASCIIMAJ) Then + Mid(strTemp, i) = Tbl(bytAscii - DIFFASCIIMAJ + lngNumber) + Else + Mid(strTemp, i) = LCase(Tbl(bytAscii - DIFFASCIIMIN + lngNumber)) + End If + End If + Next i + End If + Caesar_Cipher = strTemp +End Function diff --git a/Task/Calendar---for-REAL-programmers/BaCon/calendar---for-real-programmers.bacon b/Task/Calendar---for-REAL-programmers/BaCon/calendar---for-real-programmers.bacon new file mode 100644 index 0000000000..cd1f607d4d --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/BaCon/calendar---for-real-programmers.bacon @@ -0,0 +1,33 @@ +DECLARE MON$[] = { "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" } +DECLARE MON[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } +Y$ = "1969" +' Leap year +INCR MON[1], IIF(MOD(VAL(Y$), 4) = 0 OR MOD(VAL(Y$), 100) = 0 AND MOD(VAL(Y$), 400) <> 0, 1, 0) +PRINT ALIGN$("[SNOOPY HERE]", 132, 2) +PRINT ALIGN$(Y$, 132, 2) +FOR NR = 0 TO 11 + ROW = 3 + GOTOXY 1+(NR %6)*22, ROW+(NR/6)*9 + PRINT ALIGN$(MON$[NR], 21, 2); + INCR ROW + GOTOXY 1+(NR %6)*22, ROW+(NR/6)*9 + PRINT ALIGN$("MO TU WE TH FR SA SU", 21, 2); + INCR ROW + ' Each day + FOR D = 1 TO MON[NR] + ' Zeller + J = VAL(LEFT$(Y$, 2)) + K = VAL(MID$(Y$, 3, 2)) + M = NR+1 + IF NR < 2 THEN + INCR M, 12 + DECR K + END IF + H = (D + ((M+1)*26)/10 + K + (K/4) + (J/4) + 5*J) + DAYNR = MOD(H, 7) - 2 + IF DAYNR < 0 THEN INCR DAYNR, 7 + IF DAYNR = 0 AND D > 1 THEN INCR ROW + GOTOXY 1+(NR %6)*22+DAYNR*3, ROW+(NR/6)*9 + PRINT D; + NEXT +NEXT 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 52f44c9773..80b3991cd0 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 @@ -15,18 +15,18 @@ class CalendarMonthPrinter object theYear. object theRow. - constructor new year:aYear month:aMonth + constructor year:aYear month:aMonth [ theMonth := aMonth. theYear := aYear. - theLine := TextBuffer new. - theRow := Integer new int:0. + theLine := TextBuilder new. + theRow := Integer new(0). ] writeTitle [ - theRow set:0. - theDate := Date new year(theYear int) month(theMonth int) day:1. + theRow value := 0. + theDate := Date new(theYear, theMonth, 1). DayNames forEach(:aName) [ theLine print(" ",aName) ] ] @@ -39,38 +39,43 @@ class CalendarMonthPrinter [ theLine write:" " length((theDate dayOfWeek == 0)iif(7,theDate dayOfWeek) - 1). - control do: [ theLine write:(theDate day; literal) paddingLeft:3 with:$32. - - theDate := theDate add days:1. + theDate := theDate addDays:1. ] - until:$((theDate month != theMonth)or:$(theDate dayOfWeek == 1)). + repeatUntil:$((theDate month != theMonth)||(theDate dayOfWeek == 1)). ]. int aLength := theLine length. if (aLength < 21) [ theLine write:" " length(21 - aLength). ]. - theRow append int:1. + theRow append(1). ] - indexer = Indexer:: + indexer = BaseIndexer:: { - available = theRow < 7. + bool available = theRow < 7. - readIndexTo vint:anIndex [ anIndex int := theRow ] + readIndexTo(ref anIndex) [ theRow readValueTo(anIndex) ] - writeIndex int:anIndex + writeIndex(int anIndex) [ if (anIndex <= theRow) - [ $owner writeTitle ]. + [ self writeTitle ]. while (anIndex > theRow) - [ $owner writeLine ] + [ self writeLine ] ] - get = $owner. + appendIndex(int anIndex) + <= writeIndex(theRow value + anIndex). + + readLengthTo(ref retVal) [ retVal value := 7 ] + + get = self. + + set : o [ NotSupportedException new; raise ] }. printTitleTo : anOutput @@ -91,7 +96,7 @@ class Calendar constructor new : aYear [ - theYear := aYear int. + theYear := aYear. theRowLength := 3. ] @@ -103,17 +108,16 @@ class Calendar anOutput writeLine; writeLine. var aRowCount := 12 / theRowLength. - var Months := Array new length:aRowCount; populate(:i) - (Array new length:theRowLength; + var Months := Array new(aRowCount); populate(:i) + (Array new:theRowLength; populate(:j) - ( CalendarMonthPrinter new year(theYear int) month(i * theRowLength + j + 1))). + ( CalendarMonthPrinter year:theYear month(i * theRowLength + j + 1))). Months forEach(:aRow) [ aRow forEach(:aMonth) [ aMonth printTitleTo:anOutput. - anOutput write:" ". ]. @@ -124,7 +128,6 @@ class Calendar aLine forEach(:aPrinter) [ aPrinter printTo:anOutput. - anOutput write:" " ]. @@ -134,7 +137,7 @@ class Calendar ] } -program = +public program = [ var aCalender := Calendar new(console write:"ENTER THE YEAR:"; readLineTo(Integer new)). diff --git a/Task/Calendar---for-REAL-programmers/Icon/calendar---for-real-programmers-1.icon b/Task/Calendar---for-REAL-programmers/Icon/calendar---for-real-programmers-1.icon index 8d97ab5b6b..dfd73bd518 100644 --- a/Task/Calendar---for-REAL-programmers/Icon/calendar---for-real-programmers-1.icon +++ b/Task/Calendar---for-REAL-programmers/Icon/calendar---for-real-programmers-1.icon @@ -5,7 +5,7 @@ $define ISLEAPYEAR IsLeapYear $define JULIAN julian PROCEDURE MAIN(A) -PRINTCALENDAR(\A$<1$>|1969) + PRINTCALENDAR(\A$<1$>|1969) END PROCEDURE PRINTCALENDAR(YEAR) @@ -23,7 +23,7 @@ PROCEDURE PRINTCALENDAR(YEAR) WRITES(" ") EVERY I := 1 TO COLS DO { WRITES(CENTER(MONS$,24)) - M$ := CREATE CALENDARFORMATWEEK(1969,MON + I) + M$ := CREATE CALENDARFORMATWEEK(YEAR,MON + I) $) WRITE() EVERY 1 TO 7 DO $( @@ -34,15 +34,16 @@ PROCEDURE PRINTCALENDAR(YEAR) WRITE() $) $) + RETURN END PROCEDURE CALENDARFORMATWEEK(YEAR,M) -STATIC D -INITIAL D := $<31,28,31,30,31,30,31,31,30,31,30,31$> + STATIC D + INITIAL D := $<31,28,31,30,31,30,31,31,30,31,30,31$> -EVERY SUSPEND "SU"|"MO"|"TU"|"WE"|"TH"|"FR"|"SA" -EVERY 1 TO (DAY := (JULIAN(M,1,YEAR)+1)%7) DO SUSPEND "" -EVERY SUSPEND 1 TO D$ DO DAY +:= 1 -IF M = 2 & ISLEAPYEAR(YEAR) THEN SUSPEND (DAY +:= 1, 29) -EVERY DAY TO (6*7) DO SUSPEND "" + EVERY SUSPEND "SU"|"MO"|"TU"|"WE"|"TH"|"FR"|"SA" + EVERY 1 TO (DAY := (JULIAN(M,1,YEAR)+1)%7) DO SUSPEND "" + EVERY SUSPEND 1 TO D$ DO DAY +:= 1 + IF M = 2 & ISLEAPYEAR(YEAR) THEN SUSPEND (DAY +:= 1, 29) + EVERY DAY TO (6*7) DO SUSPEND "" END diff --git a/Task/Calendar---for-REAL-programmers/Icon/calendar---for-real-programmers-2.icon b/Task/Calendar---for-REAL-programmers/Icon/calendar---for-real-programmers-2.icon index 7d0c1f509e..b06c1d6669 100644 --- a/Task/Calendar---for-REAL-programmers/Icon/calendar---for-real-programmers-2.icon +++ b/Task/Calendar---for-REAL-programmers/Icon/calendar---for-real-programmers-2.icon @@ -23,3 +23,5 @@ $define LINK link $define IF if $define THEN then $define BY by +$define DATETIME datetime +$define RETURN return diff --git a/Task/Calendar---for-REAL-programmers/Python/calendar---for-real-programmers.py b/Task/Calendar---for-REAL-programmers/Python/calendar---for-real-programmers.py index 7a153f50a7..02df339141 100644 --- a/Task/Calendar---for-REAL-programmers/Python/calendar---for-real-programmers.py +++ b/Task/Calendar---for-REAL-programmers/Python/calendar---for-real-programmers.py @@ -2,4 +2,4 @@ import subprocess px = subprocess.Popen(['python', '-c', 'import calendar; calendar.prcal(1969)'], stdout=subprocess.PIPE) cal = px.communicate()[0] -print cal.upper() +print (cal.upper()) diff --git a/Task/Calendar---for-REAL-programmers/UNIX-Shell/calendar---for-real-programmers.sh b/Task/Calendar---for-REAL-programmers/UNIX-Shell/calendar---for-real-programmers.sh new file mode 100644 index 0000000000..0eb4b353a2 --- /dev/null +++ b/Task/Calendar---for-REAL-programmers/UNIX-Shell/calendar---for-real-programmers.sh @@ -0,0 +1 @@ +cal -m 1969 | tr a-z A-Z diff --git a/Task/Calendar/BaCon/calendar.bacon b/Task/Calendar/BaCon/calendar.bacon new file mode 100644 index 0000000000..950da8ba5e --- /dev/null +++ b/Task/Calendar/BaCon/calendar.bacon @@ -0,0 +1,33 @@ +DECLARE month$[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" } +DECLARE month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } +year$ = "1969" +' Leap year +INCR month[1], IIF(MOD(VAL(year$), 4) = 0 OR MOD(VAL(year$), 100) = 0 AND MOD(VAL(year$), 400) <> 0, 1, 0) +PRINT ALIGN$("[SNOOPY HERE]", 132, 2) +PRINT ALIGN$(year$, 132, 2) +FOR nr = 0 TO 11 + row = 3 + GOTOXY 1+(nr %6)*22, row+(nr/6)*9 + PRINT ALIGN$(month$[nr], 21, 2); + INCR row + GOTOXY 1+(nr %6)*22, row+(nr/6)*9 + PRINT ALIGN$("Mo Tu We Th Fr Sa Su", 21, 2); + INCR row + ' Each day + FOR day = 1 TO month[nr] + ' Zeller + J = VAL(LEFT$(year$, 2)) + K = VAL(MID$(year$, 3, 2)) + m = nr+1 + IF nr < 2 THEN + INCR m, 12 + DECR K + END IF + h = (day + ((m+1)*26)/10 + K + (K/4) + (J/4) + 5*J) + daynr = MOD(h, 7) - 2 + IF daynr < 0 THEN INCR daynr, 7 + IF daynr = 0 AND day > 1 THEN INCR row + GOTOXY 1+(nr %6)*22+daynr*3, row+(nr/6)*9 + PRINT day; + NEXT +NEXT diff --git a/Task/Calendar/Go/calendar.go b/Task/Calendar/Go/calendar.go new file mode 100644 index 0000000000..80a1ab470b --- /dev/null +++ b/Task/Calendar/Go/calendar.go @@ -0,0 +1,71 @@ +package main + +import ( + "fmt" + "time" +) + +const pageWidth = 80 + +func main() { + printCal(1969) +} + +func printCal(year int) { + thisDate := time.Date(year, 1, 1, 1, 1, 1, 1, time.UTC) + var ( + dayArr [12][7][6]int // month, weekday, week + month, lastMonth time.Month + weekInMonth, dayInMonth int + ) + for thisDate.Year() == year { + if month = thisDate.Month(); month != lastMonth { + weekInMonth = 0 + dayInMonth = 1 + } + weekday := thisDate.Weekday() + if weekday == 0 && dayInMonth > 1 { + weekInMonth++ + } + dayArr[int(month)-1][weekday][weekInMonth] = thisDate.Day() + lastMonth = month + dayInMonth++ + thisDate = thisDate.Add(time.Hour * 24) + } + centre := fmt.Sprintf("%d", pageWidth/2) + fmt.Printf("%"+centre+"s\n\n", "[SNOOPY]") + centre = fmt.Sprintf("%d", pageWidth/2-2) + fmt.Printf("%"+centre+"d\n\n", year) + months := [12]string{ + " January ", " February", " March ", " April ", + " May ", " June ", " July ", " August ", + "September", " October ", " November", " December"} + days := [7]string{"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"} + for qtr := 0; qtr < 4; qtr++ { + for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { // Month names + fmt.Printf(" %s ", months[qtr*3+monthInQtr]) + } + fmt.Println() + for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { // Day names + for day := 0; day < 7; day++ { + fmt.Printf(" %s", days[day]) + } + fmt.Printf(" ") + } + fmt.Println() + for weekInMonth = 0; weekInMonth < 6; weekInMonth++ { + for monthInQtr := 0; monthInQtr < 3; monthInQtr++ { + for day := 0; day < 7; day++ { + if dayArr[qtr*3+monthInQtr][day][weekInMonth] == 0 { + fmt.Printf(" ") + } else { + fmt.Printf("%3d", dayArr[qtr*3+monthInQtr][day][weekInMonth]) + } + } + fmt.Printf(" ") + } + fmt.Println() + } + fmt.Println() + } +} diff --git a/Task/Calendar/Icon/calendar.icon b/Task/Calendar/Icon/calendar.icon index b4849be329..456c10e4a5 100644 --- a/Task/Calendar/Icon/calendar.icon +++ b/Task/Calendar/Icon/calendar.icon @@ -1,5 +1,5 @@ procedure main(A) -printCalendar(\A[1]|1969) + printCalendar(\A[1]|1969) end procedure printCalendar(year) #: Print a 3 column x 80 char calendar @@ -12,12 +12,12 @@ procedure printCalendar(year) #: Print a 3 column x 80 char calendar write(center("[Snoopy Picture]",cols * 24 + 4)) # mandatory .. write(center(year,cols * 24 + 4), "\n") # ... headers - M := list(cols) # coexpr container + M := list(cols) # coexpr container every mon := 0 to 9 by cols do { # go through months by cols writes(" ") every i := 1 to cols do { writes(center(mons[mon+i],24)) # header months - M[i] := create CalendarFormatWeek(1969,mon + i) # formatting coexpr + M[i] := create CalendarFormatWeek(year,mon + i) # formatting coexpr } write() every 1 to 7 do { # 1 to max rows @@ -28,17 +28,18 @@ procedure printCalendar(year) #: Print a 3 column x 80 char calendar write() } } + return end link datetime procedure CalendarFormatWeek(year,m) #: Format Week for Calendar -static D -initial D := [31,28,31,30,31,30,31,31,30,31,30,31] + static D + initial D := [31,28,31,30,31,30,31,31,30,31,30,31] -every suspend "Su"|"Mo"|"Tu"|"We"|"Th"|"Fr"|"Sa" # header -every 1 to (d := (julian(m,1,year)+1)%7) do suspend "" # lead day alignment -every suspend 1 to D[m] do d +:= 1 # days -if m = 2 & IsLeapYear(year) then suspend (d +:= 1, 29) # LY adjustment -every d to (6*7) do suspend "" # trailer alignment + every suspend "Su"|"Mo"|"Tu"|"We"|"Th"|"Fr"|"Sa" # header + every 1 to (d := (julian(m,1,year)+1)%7) do suspend "" # lead day alignment + every suspend 1 to D[m] do d +:= 1 # days + if m = 2 & IsLeapYear(year) then suspend (d +:= 1, 29) # LY adjustment + every d to (6*7) do suspend "" # trailer alignment end diff --git a/Task/Calendar/PowerShell/calendar.psh b/Task/Calendar/PowerShell/calendar.psh new file mode 100644 index 0000000000..4e9a027847 --- /dev/null +++ b/Task/Calendar/PowerShell/calendar.psh @@ -0,0 +1,36 @@ +Param([int]$Year = 1969) +Begin { + $COL_WIDTH = 21 + $COLS = 3 + $MONTH_COUNT = 12 + $MONTH_LINES = 9 + + Function CenterStr([string]$s, [int]$lineSize) { + $padSize = [int](($lineSize - $s.Length) / 2) + ($(if ($padSize -gt 0) { ' ' * $padSize } else { '' }) + $s).PadRight($lineSize,' ') + } + + Function MonthLines([int]$month) { + $dt = [System.DateTime]::new($Year, $month, 1) + $line = CenterStr $dt.ToString("MMMM") $COL_WIDTH + $line += 'Su Mo Tu We Th Fr Sa' + $line += $(' ' * $dt.DayOfWeek.value__) + $line += (-join ($(1..$($dt.AddMonths(1).AddDays(-1).Day)) | %{ $("" + $_).PadLeft(3) })) + $line = $line.PadRight($MONTH_LINES * $COL_WIDTH) + New-Object –TypeName PSObject –Prop(@{ + 'Lines'=(0..($MONTH_LINES - 1)) | %{ $_ * $COL_WIDTH } | %{ -join $line[$_..($_ + $COL_WIDTH - 1)] } + 'Dt'=$dt}) + } +} +Process { + Write-Output (CenterStr $Year ($COL_WIDTH * $COLS + 4)) + $(0..($MONTH_COUNT / $COLS - 1)) | %{ + $fm = $_ * $COLS + $monthNums = $fm..($fm + $COLS - 1) | %{ $_ + 1 } + $months = $monthNums | %{ MonthLines $_ } + $(0..($MONTH_LINES - 1)) | %{ + $ml = $_ + Write-Output $(-join ($(0..($COLS - 1)) | %{ $(if ($_ -eq 0) { '' } else {' '}) + $months[$_].Lines[$ml] })) + } + } +} diff --git a/Task/Calendar/Ring/calendar.ring b/Task/Calendar/Ring/calendar.ring new file mode 100644 index 0000000000..b046866518 --- /dev/null +++ b/Task/Calendar/Ring/calendar.ring @@ -0,0 +1,159 @@ +# Project : Calendar +# Date : 2018/06/05 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +load "guilib.ring" +load "stdlib.ring" + +new qapp + { + win1 = new qwidget() { + + day = list(12) + pos = newlist(12,37) + month = list(12) + week = list(7) + weekday = list(7) + button = newlist(7,6) + monthsnames = list(12) + week = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] + months = ["January", "February", "March", "April", "May", "June", "July", + "August", "September", "October", "November", "December"] + daysnew = [[5,1], [6,2], [7,3], [1,4], [2,5], [3,6], [4,7]] + mo = [4,0,0,3,5,1,3,6,2,4,0,2] + mon = [31,28,31,30,31,30,31,31,30,31,30,31] + m2 = (((1969-1900)%7) + floor((1969 - 1900)/4) % 7) % 7 + for n = 1 to 12 + month[n] = (mo[n] + m2) % 7 + x = (month[n] + 1) % 7 + 1 + for m = 1 to len(daysnew) + if daysnew[m][1] = x + nr = m + ok + next + day[n] = daysnew[nr][2] + next + for m = 1 to 12 + for n = 1 to day[m] - 1 + pos[m][n] = " " + next + next + for m = 1 to 12 + for n = day[m] to 37 + if n < (mon[m] + day[m]) + pos[m][n] = n - day[m] + 1 + else + pos[m][n] = " " + ok + next + next + setwindowtitle("Calendar") + setgeometry(100,100,650,800) + label1 = new qlabel(win1) { + setgeometry(10,10,800,600) + settext("") + } + year = new qpushbutton(win1) + { + setgeometry(280,20,60,20) + year.settext("1969") + } + for n = 1 to 4 + nr = (n-1)*3+1 + showmonths(nr) + next + for n = 1 to 12 + showweeks(n) + next + for n = 1 to 12 + showdays(n) + next + show() + } + exec() + } + +func showmonths(m) + for n = m to m + 2 + monthsnames[n] = new qpushbutton(win1) + { + if n%3 = 1 + col = 120 + rownr = floor(n/3) + if rownr = 0 + rownr = n/3 + ok + if n = 1 + row = 40 + else + row = 40+rownr*180 + ok + else + colnr = n%3 + if colnr = 0 + colnr = 3 + ok + rownr = floor(n/3) + if n%3 = 0 + rownr = floor(n/3)-1 + ok + col = 120 + (colnr-1)*160 + row = 40 + rownr*180 + ok + setgeometry(col,row,60,20) + monthsnames[n].settext(months[n]) + } + next + +func showweeks(n) + for m = 1 to 7 + col = m%7 + if col = 0 col = 7 ok + weekday[m] = new qpushbutton(win1) + { + colnr = n % 3 + if colnr = 0 + colnr = 3 + ok + rownr = floor(n/3) + if n%3 = 0 + rownr = floor(n/3)-1 + ok + colbegin = 60 + (colnr-1)*160 + rowbegin = 60 + (rownr)*180 + setgeometry(colbegin+col*20,rowbegin,20,20) + weekday[m].settext(week[m]) + } + next + +func showdays(ind) + rownr = floor(ind/3) + if ind%3 = 0 + rownr = floor(ind/3)-1 + ok + rowbegin = 60+rownr*180 + for m = 1 to 6 + for n = 1 to 7 + col = n%7 + if col = 0 col = 7 ok + row = m + button[n][m] = new qpushbutton(win1) + { + if ind%3 = 1 + colbegin = 60 + elseif ind%3 = 2 + colbegin = 220 + else + colbegin = 380 + ok + setgeometry(colbegin+col*20,rowbegin+row*20,20,20) + nr = (m-1)*7+n + if nr <= 37 + if pos[ind][nr] != " " + button[n][m].settext(string(pos[ind][nr])) + ok + ok + } + next + next diff --git a/Task/Call-a-foreign-language-function/Julia/call-a-foreign-language-function-1.julia b/Task/Call-a-foreign-language-function/Julia/call-a-foreign-language-function-1.julia new file mode 100644 index 0000000000..518829d0f6 --- /dev/null +++ b/Task/Call-a-foreign-language-function/Julia/call-a-foreign-language-function-1.julia @@ -0,0 +1,3 @@ +p = ccall(:strdup, Ptr{Cuchar}, (Ptr{Cuchar},), "Hello world") +@show unsafe_string(p) # "Hello world" +ccall(:free, Void, (Ptr{Cuchar},), p) diff --git a/Task/Call-a-foreign-language-function/Julia/call-a-foreign-language-function-2.julia b/Task/Call-a-foreign-language-function/Julia/call-a-foreign-language-function-2.julia new file mode 100644 index 0000000000..c0c1bf666f --- /dev/null +++ b/Task/Call-a-foreign-language-function/Julia/call-a-foreign-language-function-2.julia @@ -0,0 +1,3 @@ +using PyCall +@pyimport math +@show math.cos(1) # 0.5403023058681398 diff --git a/Task/Call-a-foreign-language-function/Julia/call-a-foreign-language-function.julia b/Task/Call-a-foreign-language-function/Julia/call-a-foreign-language-function.julia deleted file mode 100644 index 8b22d32024..0000000000 --- a/Task/Call-a-foreign-language-function/Julia/call-a-foreign-language-function.julia +++ /dev/null @@ -1,7 +0,0 @@ -julia> p = ccall(:strdup, Ptr{Uint8}, (Ptr{Uint8},), "Hello world") -Ptr{Uint8} @0x000000011731bde0 - -julia> bytestring(p) # convert pointer back to a native Julia string -"Hello world" - -julia> ccall(:free, Void, (Ptr{Uint8},), p) diff --git a/Task/Call-a-foreign-language-function/Scala/call-a-foreign-language-function.scala b/Task/Call-a-foreign-language-function/Scala/call-a-foreign-language-function.scala new file mode 100644 index 0000000000..757aa666c3 --- /dev/null +++ b/Task/Call-a-foreign-language-function/Scala/call-a-foreign-language-function.scala @@ -0,0 +1,7 @@ +object JNIDemo { + try System.loadLibrary("JNIDemo") + + private def callStrdup(s: String) + + println(callStrdup("Hello World!")) +} diff --git a/Task/Call-a-function-in-a-shared-library/Kotlin/call-a-function-in-a-shared-library-1.kotlin b/Task/Call-a-function-in-a-shared-library/Kotlin/call-a-function-in-a-shared-library-1.kotlin new file mode 100644 index 0000000000..224e741eea --- /dev/null +++ b/Task/Call-a-function-in-a-shared-library/Kotlin/call-a-function-in-a-shared-library-1.kotlin @@ -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/Kotlin/call-a-function-in-a-shared-library-2.kotlin b/Task/Call-a-function-in-a-shared-library/Kotlin/call-a-function-in-a-shared-library-2.kotlin new file mode 100644 index 0000000000..0f6df9e0c9 --- /dev/null +++ b/Task/Call-a-function-in-a-shared-library/Kotlin/call-a-function-in-a-shared-library-2.kotlin @@ -0,0 +1,34 @@ +// Kotlin Native version 0.5 + +import kotlinx.cinterop.* +import platform.posix.* +import platform.linux.* + +typealias Func = (String)-> Int + +var handle = 0 + +fun myOpenImage(s: String): Int { + fprintf(stderr, "internal openImage opens %s...\n", s) + return handle++ +} + +fun main(args: Array) { + var imgHandle: Int + val imglib = dlopen("./fakeimglib.so", RTLD_LAZY) + if (imglib != null) { + val fp = dlsym(imglib, "openimage") + if (fp != null) { + val extOpenImage: CPointer> = fp.reinterpret() + imgHandle = extOpenImage("fake.img") + } + else { + imgHandle = myOpenImage("fake.img") + } + dlclose(imglib) + } + else { + imgHandle = myOpenImage("fake.img") + } + println("opened with handle $imgHandle") +} diff --git a/Task/Call-a-function-in-a-shared-library/Perl-6/call-a-function-in-a-shared-library.pl6 b/Task/Call-a-function-in-a-shared-library/Perl-6/call-a-function-in-a-shared-library.pl6 index f44629e09d..244b7419ee 100644 --- a/Task/Call-a-function-in-a-shared-library/Perl-6/call-a-function-in-a-shared-library.pl6 +++ b/Task/Call-a-function-in-a-shared-library/Perl-6/call-a-function-in-a-shared-library.pl6 @@ -2,8 +2,8 @@ use NativeCall; constant libX11 = '/usr/lib/x86_64-linux-gnu/libX11.so.6'; -sub XOpenDisplay(Str $s --> Int) is native(libX11) {*} -sub XCloseDisplay(Int $i --> Int) is native(libX11) {*} +sub XOpenDisplay(Str $s --> int32) is native(libX11) {*} +sub XCloseDisplay(int32 $i --> int32) is native(libX11) {*} if try my $d = XOpenDisplay ":0.0" { say "ID = $d"; diff --git a/Task/Call-a-function-in-a-shared-library/Python/call-a-function-in-a-shared-library.py b/Task/Call-a-function-in-a-shared-library/Python/call-a-function-in-a-shared-library-1.py similarity index 100% rename from Task/Call-a-function-in-a-shared-library/Python/call-a-function-in-a-shared-library.py rename to Task/Call-a-function-in-a-shared-library/Python/call-a-function-in-a-shared-library-1.py diff --git a/Task/Call-a-function-in-a-shared-library/Python/call-a-function-in-a-shared-library-2.py b/Task/Call-a-function-in-a-shared-library/Python/call-a-function-in-a-shared-library-2.py new file mode 100644 index 0000000000..a7787bd849 --- /dev/null +++ b/Task/Call-a-function-in-a-shared-library/Python/call-a-function-in-a-shared-library-2.py @@ -0,0 +1,7 @@ +>>> import ctypes +>>> # libc = ctypes.cdll.msvcrt # Windows +>>> # libc = ctypes.CDLL('libc.dylib') # Mac +>>> libc = ctypes.CDLL('libc.so') # Linux and most other *nix +>>> libc.printf(b'hi there, %s\n', b'world') +hi there, world. +17 diff --git a/Task/Call-a-function-in-a-shared-library/Python/call-a-function-in-a-shared-library-3.py b/Task/Call-a-function-in-a-shared-library/Python/call-a-function-in-a-shared-library-3.py new file mode 100644 index 0000000000..310caabe52 --- /dev/null +++ b/Task/Call-a-function-in-a-shared-library/Python/call-a-function-in-a-shared-library-3.py @@ -0,0 +1,10 @@ +>>> from cffi import FFI +>>> ffi = FFI() +>>> ffi.cdef(""" +... int printf(const char *format, ...); // copy-pasted from the man page +... """) +>>> C = ffi.dlopen(None) # loads the entire C namespace +>>> arg = ffi.new("char[]", b"world") # equivalent to C code: char arg[] = "world"; +>>> C.printf(b"hi there, %s.\n", arg) # call printf +hi there, world. +17 diff --git a/Task/Call-a-function/ARM-Assembly/call-a-function.arm b/Task/Call-a-function/ARM-Assembly/call-a-function.arm new file mode 100644 index 0000000000..6e899b056c --- /dev/null +++ b/Task/Call-a-function/ARM-Assembly/call-a-function.arm @@ -0,0 +1,171 @@ +/* ARM assembly Raspberry PI */ +/* program callfonct.s */ + +/* Constantes */ +.equ STDOUT, 1 +.equ WRITE, 4 +.equ EXIT, 1 + +/***********************/ +/* Initialized data */ +/***********************/ +.data +szMessage: .asciz "Hello. \n" @ message +szRetourLigne: .asciz "\n" +szMessResult: .ascii "Resultat : " @ message result +sMessValeur: .fill 12, 1, ' ' + .asciz "\n" +/***********************/ +/* No Initialized data */ +/***********************/ +.bss +iValeur: .skip 4 @ reserve 4 bytes in memory + +.text +.global main +main: + ldr r0,=szMessage @ adresse of message short program + bl affichageMess @ call function with 1 parameter (r0) + + @ call function with parameters in register + mov r0,#5 + mov r1,#10 + bl fonction1 @ call function with 2 parameters (r0,r1) + ldr r1,=sMessValeur @ result in r0 + bl conversion10S @ call function with 2 parameter (r0,r1) + ldr r0,=szMessResult + bl affichageMess @ call function with 1 parameter (r0) + + @ call function with parameters on stack + mov r0,#5 + mov r1,#10 + push {r0,r1} + bl fonction2 @ call function with 2 parameters on the stack + @ result in r0 + ldr r1,=sMessValeur + bl conversion10S @ call function with 2 parameter (r0,r1) + ldr r0,=szMessResult + bl affichageMess @ call function with 1 parameter (r0) + + + /* end of program */ + mov r0, #0 @ return code + mov r7, #EXIT @ request to exit program + swi 0 @ perform the system call + +/******************************************************************/ +/* call function parameter in register */ +/******************************************************************/ +/* r0 value one */ +/* r1 value two */ +/* return in r0 */ +fonction1: + push {fp,lr} /* save des 2 registres */ + push {r1,r2} /* save des autres registres */ + mov r2,#20 + mul r0,r2 + add r0,r0,r1 + pop {r1,r2} /* restaur des autres registres */ + pop {fp,lr} /* restaur des 2 registres */ + bx lr /* retour procedure */ + +/******************************************************************/ +/* call function parameter in the stack */ +/******************************************************************/ +/* return in r0 */ +fonction2: + push {fp,lr} /* save des 2 registres */ + add fp,sp,#8 /* address parameters in the stack*/ + push {r1,r2} /* save des autres registres */ + ldr r0,[fp] + ldr r1,[fp,#4] + mov r2,#-20 + mul r0,r2 + add r0,r0,r1 + pop {r1,r2} /* restaur des autres registres */ + pop {fp,lr} /* restaur des 2 registres */ + add sp,#8 /* very important, for stack aligned */ + bx lr /* retour procedure */ + +/******************************************************************/ +/* affichage des messages avec calcul longueur */ +/******************************************************************/ +/* r0 contient l adresse du message */ +affichageMess: + push {fp,lr} /* save des 2 registres */ + push {r0,r1,r2,r7} /* save des autres registres */ + mov r2,#0 /* compteur longueur */ +1: /*calcul de la longueur */ + ldrb r1,[r0,r2] /* recup octet position debut + indice */ + cmp r1,#0 /* si 0 c est fini */ + beq 1f + add r2,r2,#1 /* sinon on ajoute 1 */ + b 1b +1: /* donc ici r2 contient la longueur du message */ + mov r1,r0 /* adresse du message en r1 */ + mov r0,#STDOUT /* code pour écrire sur la sortie standard Linux */ + mov r7, #WRITE /* code de l appel systeme 'write' */ + swi #0 /* appel systeme */ + pop {r0,r1,r2,r7} /* restaur des autres registres */ + pop {fp,lr} /* restaur des 2 registres */ + bx lr /* retour procedure */ +/***************************************************/ +/* conversion registre en décimal signé */ +/***************************************************/ +/* r0 contient le registre */ +/* r1 contient l adresse de la zone de conversion */ +conversion10S: + push {fp,lr} /* save des 2 registres frame et retour */ + push {r0-r5} /* save autres registres */ + mov r2,r1 /* debut zone stockage */ + mov r5,#'+' /* par defaut le signe est + */ + cmp r0,#0 /* nombre négatif ? */ + movlt r5,#'-' /* oui le signe est - */ + mvnlt r0,r0 /* et inversion en valeur positive */ + addlt r0,#1 + + mov r4,#10 /* longueur de la zone */ +1: /* debut de boucle de conversion */ + bl divisionpar10 /* division */ + add r1,#48 /* ajout de 48 au reste pour conversion ascii */ + strb r1,[r2,r4] /* stockage du byte en début de zone r5 + la position r4 */ + sub r4,r4,#1 /* position précedente */ + cmp r0,#0 + bne 1b /* boucle si quotient different de zéro */ + strb r5,[r2,r4] /* stockage du signe à la position courante */ + subs r4,r4,#1 /* position précedente */ + blt 100f /* si r4 < 0 fin */ + /* sinon il faut completer le debut de la zone avec des blancs */ + mov r3,#' ' /* caractere espace */ +2: + strb r3,[r2,r4] /* stockage du byte */ + subs r4,r4,#1 /* position précedente */ + bge 2b /* boucle si r4 plus grand ou egal a zero */ +100: /* fin standard de la fonction */ + pop {r0-r5} /*restaur des autres registres */ + pop {fp,lr} /* restaur des 2 registres frame et retour */ + bx lr + +/***************************************************/ +/* division par 10 signé */ +/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/* +/* and http://www.hackersdelight.org/ */ +/***************************************************/ +/* r0 contient le dividende */ +/* r0 retourne le quotient */ +/* r1 retourne le reste */ +divisionpar10: + /* r0 contains the argument to be divided by 10 */ + push {r2-r4} /* save autres registres */ + mov r4,r0 + ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */ + smull r1, r2, r3, r0 /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */ + mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */ + mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */ + add r0, r2, r1 /* r0 <- r2 + r1 */ + add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */ + sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */ + pop {r2-r4} + bx lr /* leave function */ + .align 4 +.Ls_magic_number_10: .word 0x66666667 diff --git a/Task/Call-a-function/Elena/call-a-function-1.elena b/Task/Call-a-function/Elena/call-a-function-1.elena new file mode 100644 index 0000000000..acac31882a --- /dev/null +++ b/Task/Call-a-function/Elena/call-a-function-1.elena @@ -0,0 +1,2 @@ +var c0 := [ console writeLine("No argument provided") ]. +var c2 := (:a:b)[ console printLine("Arguments ",a," and ",b," provided") ]. diff --git a/Task/Call-a-function/Elena/call-a-function-2.elena b/Task/Call-a-function/Elena/call-a-function-2.elena new file mode 100644 index 0000000000..3ab4361423 --- /dev/null +++ b/Task/Call-a-function/Elena/call-a-function-2.elena @@ -0,0 +1 @@ + c0(). diff --git a/Task/Call-a-function/Elena/call-a-function-3.elena b/Task/Call-a-function/Elena/call-a-function-3.elena new file mode 100644 index 0000000000..9c272e6d62 --- /dev/null +++ b/Task/Call-a-function/Elena/call-a-function-3.elena @@ -0,0 +1 @@ + c2(2,4). diff --git a/Task/Call-a-function/Elena/call-a-function-4.elena b/Task/Call-a-function/Elena/call-a-function-4.elena new file mode 100644 index 0000000000..4e83fc1708 --- /dev/null +++ b/Task/Call-a-function/Elena/call-a-function-4.elena @@ -0,0 +1,3 @@ + var exch := (:x)>[ x value := 2 ]. + var a := 1. + exch(&a). diff --git a/Task/Call-a-function/Factor/call-a-function-1.factor b/Task/Call-a-function/Factor/call-a-function-1.factor new file mode 100644 index 0000000000..257cc5642c --- /dev/null +++ b/Task/Call-a-function/Factor/call-a-function-1.factor @@ -0,0 +1 @@ +foo diff --git a/Task/Call-a-function/Factor/call-a-function-2.factor b/Task/Call-a-function/Factor/call-a-function-2.factor new file mode 100644 index 0000000000..257cc5642c --- /dev/null +++ b/Task/Call-a-function/Factor/call-a-function-2.factor @@ -0,0 +1 @@ +foo diff --git a/Task/Call-a-function/Factor/call-a-function-3.factor b/Task/Call-a-function/Factor/call-a-function-3.factor new file mode 100644 index 0000000000..443845a2d4 --- /dev/null +++ b/Task/Call-a-function/Factor/call-a-function-3.factor @@ -0,0 +1,2 @@ +"a" "b" "c" 3 narray +! { "a" "b" "c" } diff --git a/Task/Call-a-function/Factor/call-a-function-4.factor b/Task/Call-a-function/Factor/call-a-function-4.factor new file mode 100644 index 0000000000..3d2bf732cd --- /dev/null +++ b/Task/Call-a-function/Factor/call-a-function-4.factor @@ -0,0 +1,6 @@ + + "jack@aol.com" >>from + { "jill@aol.com" } >>to + "Hello there" >>subject + body >>body +send-email diff --git a/Task/Call-a-function/Factor/call-a-function-5.factor b/Task/Call-a-function/Factor/call-a-function-5.factor new file mode 100644 index 0000000000..4e854595ca --- /dev/null +++ b/Task/Call-a-function/Factor/call-a-function-5.factor @@ -0,0 +1 @@ +\ foo diff --git a/Task/Call-a-function/Factor/call-a-function-6.factor b/Task/Call-a-function/Factor/call-a-function-6.factor new file mode 100644 index 0000000000..3f2d091773 --- /dev/null +++ b/Task/Call-a-function/Factor/call-a-function-6.factor @@ -0,0 +1 @@ +{ foo } [ foo ] diff --git a/Task/Call-a-function/Factor/call-a-function-7.factor b/Task/Call-a-function/Factor/call-a-function-7.factor new file mode 100644 index 0000000000..257cc5642c --- /dev/null +++ b/Task/Call-a-function/Factor/call-a-function-7.factor @@ -0,0 +1 @@ +foo diff --git a/Task/Call-a-function/Factor/call-a-function-8.factor b/Task/Call-a-function/Factor/call-a-function-8.factor new file mode 100644 index 0000000000..6a59e6832b --- /dev/null +++ b/Task/Call-a-function/Factor/call-a-function-8.factor @@ -0,0 +1 @@ +\ foo primitive? diff --git a/Task/Call-a-function/Factor/call-a-function-9.factor b/Task/Call-a-function/Factor/call-a-function-9.factor new file mode 100644 index 0000000000..b22e50cea1 --- /dev/null +++ b/Task/Call-a-function/Factor/call-a-function-9.factor @@ -0,0 +1,2 @@ +{ 1 2 3 } 2 [ - ] curry map . +! { -1 0 1 } diff --git a/Task/Call-a-function/Fortress/call-a-function.fortress b/Task/Call-a-function/Fortress/call-a-function.fortress new file mode 100644 index 0000000000..ce1258f102 --- /dev/null +++ b/Task/Call-a-function/Fortress/call-a-function.fortress @@ -0,0 +1,38 @@ +component call_a_function + export Executable + (* Declaring test functions that allow the various ways to call functions in Fortress to be demonstrated. *) + addition(i:ZZ32, j:ZZ32): ZZ32 = i+j + addition(i:ZZ32): ZZ32 = i+1 + + (* Strings are concatenated by using a space as an infix operator. *) + addition(i:String, j:String): String = i j + + printAString(s:String): () = println(s) + + (* Functions can be passed to other functions as arguments. When passing a function as an argument, the argument's type should be + represented as follows: "typeOfArgument(s)->returnType," which, in this case, is "String->()." You could also technically use the + "Any" type, but that isn't type-safe. *) + printAString(s:String, f:String->()) = f(s) + + (* Defined functions can then be called as follows. *) + var x:ZZ32 = addition(1, 2) + var str:String = addition("This is ", "another string.") + + run() = do + (* You can call built-in functions the same way that you call functions that you define. *) + println("x at start: " x) + + x := addition(x, 2) + + println("x at middle: " x) + + printAString("This " "is " "a " "string.") + printAString(str) + printAString("\nThis is a string that is being printed by a function of the same name \nthat takes a function as an argument.\n", + printAString) + + x := addition(4) + + println("x at end: " x) + end +end diff --git a/Task/Call-a-function/Julia/call-a-function.julia b/Task/Call-a-function/Julia/call-a-function.julia new file mode 100644 index 0000000000..373329f136 --- /dev/null +++ b/Task/Call-a-function/Julia/call-a-function.julia @@ -0,0 +1,90 @@ +# Calling a function that requires no arguments: +f() = print("Hello world!") +f() + + +# Calling a function with a fixed number of arguments: +function f(x, y, z) + x*y - z^2 +end + +f(3, 4, 2) + + +# Calling a function with optional arguments: +# Note Julia uses multiple dispatch based on argument number and type, so +# f() is always different from f(x) unless default arguments are used, as in: + +pimultiple(mult=1.0) = pi * mult # so pimultiple() defaults to pi * (1.0) or pi + + +# Calling a function with a variable number of arguments: + +f(a,b,x...) = reduce(+, 0, x) - a - b + + +# here a and b are single arguments, but x is a tuple of x plus whatever follows x, so: +a = b = c = d = e = 3 +f(a,b,c) # x within the function is (c) so == 0 + c - a - b +f(a,b,c,d,e) # x is a tuple == (c,d,e) so == (0 + c + d + e) - a - b +f(a,b) # x is () so == 0 - a - b + + +# Calling a function with named arguments: +# Functions with keyword arguments are defined using a semicolon in the function signature, +# as in +# function plot(x, y; style="solid", width=1, color="black") +# +# When the function is called, the semicolon is optional, so plot here can be +# either called with plot(x, y, width=2) or less commonly as plot(x, y; width=2). + + +# Using a function in statement context: +# Any function can be used as a variable by its name. + +circlearea(x) = x^2 * pi +map(circlearea, [r1, r2, r3, r4]) + + +# Using a function in first-class context within an expression: +cylindervolume = circlearea(r) * h + + +# Obtaining the return value of a function: +radius = 2.5 +area = circlearea(2.5) + + +# Distinguishing built-in functions and user-defined functions: +# Julia does not attempt to distinguish these in any special way, +# but at the REPL command line there is ? help available for builtin +# functions that would not generally be available for the user-defined ones. + + +# Distinguishing subroutines and functions: +# All subroutines are called functions in Julia, regardless of whether they return values. + + +# Stating whether arguments are passed by value or by reference: +# As in Python, all arguments are passed by pointer reference, but assignment to a passed argument +# only changes the variable within the function. Assignment to the values referenced by the argument +## DOES however change those values. For instance: + +a = 3 +b = [3] +c = [3] + +function f(x, y) + a = 0 + b[1] = 0 + c = [0] +end # a and c are now unchanged but b = [0] + + +# Is partial application possible and how: +# In Julia, there are many different ways to compose functions. In particular, +# Julia has an "arrow" operator -> that may be used to curry other functions. + +f(a, b) = a^2 + a + b +v = [4, 6, 8] +map(x -> f(x, 10), v) # v = [30, 52, 82] diff --git a/Task/Call-an-object-method/C++/call-an-object-method.cpp b/Task/Call-an-object-method/C++/call-an-object-method.cpp index 16ce9e564a..f8f2274fea 100644 --- a/Task/Call-an-object-method/C++/call-an-object-method.cpp +++ b/Task/Call-an-object-method/C++/call-an-object-method.cpp @@ -3,3 +3,6 @@ MyClass::method(someParameter); // Instance myInstance.method(someParameter); + +// Pointer +MyPointer->method(someParameter); diff --git a/Task/Call-an-object-method/Elena/call-an-object-method.elena b/Task/Call-an-object-method/Elena/call-an-object-method.elena new file mode 100644 index 0000000000..9bf9c893a1 --- /dev/null +++ b/Task/Call-an-object-method/Elena/call-an-object-method.elena @@ -0,0 +1 @@ + console printLine("Hello"," ","World!"). diff --git a/Task/Call-an-object-method/VBA/call-an-object-method-1.vba b/Task/Call-an-object-method/VBA/call-an-object-method-1.vba new file mode 100644 index 0000000000..5f1b27e421 --- /dev/null +++ b/Task/Call-an-object-method/VBA/call-an-object-method-1.vba @@ -0,0 +1,13 @@ +Option Explicit + +Sub Method_1(Optional myStr As String) +Dim strTemp As String + If myStr <> "" Then strTemp = myStr + Debug.Print strTemp +End Sub + +Static Sub Method_2(Optional myStr As String) +Dim strTemp As String + If myStr <> "" Then strTemp = myStr + Debug.Print strTemp +End Sub diff --git a/Task/Call-an-object-method/VBA/call-an-object-method-2.vba b/Task/Call-an-object-method/VBA/call-an-object-method-2.vba new file mode 100644 index 0000000000..8792d7edc6 --- /dev/null +++ b/Task/Call-an-object-method/VBA/call-an-object-method-2.vba @@ -0,0 +1,9 @@ +Option Explicit + +Sub test() +Dim Obj As New myObject + Obj.Method_1 "Hello to you" + Obj.Method_2 "What is your name ?" + Obj.Method_1 + Obj.Method_2 +End Sub diff --git a/Task/Canny-edge-detector/Julia/canny-edge-detector.julia b/Task/Canny-edge-detector/Julia/canny-edge-detector.julia new file mode 100644 index 0000000000..2b3121b94d --- /dev/null +++ b/Task/Canny-edge-detector/Julia/canny-edge-detector.julia @@ -0,0 +1,3 @@ +using Images + +canny_edges = canny(img, sigma = 1.4, upperThreshold = 0.80, lowerThreshold = 0.20) diff --git a/Task/Carmichael-3-strong-pseudoprimes/Go/carmichael-3-strong-pseudoprimes.go b/Task/Carmichael-3-strong-pseudoprimes/Go/carmichael-3-strong-pseudoprimes.go new file mode 100644 index 0000000000..4679282c5d --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/Go/carmichael-3-strong-pseudoprimes.go @@ -0,0 +1,48 @@ +package main + +import "fmt" + +// Use this rather than % for negative integers +func mod(n, m int) int { + return ((n % m) + m) % m +} + +func isPrime(n int) bool { + if n < 2 { return false } + if n % 2 == 0 { return n == 2 } + if n % 3 == 0 { return n == 3 } + d := 5 + for d * d <= n { + if n % d == 0 { return false } + d += 2 + if n % d == 0 { return false } + d += 4 + } + return true +} + +func carmichael(p1 int) { + for h3 := 2; h3 < p1; h3++ { + for d := 1; d < h3 + p1; d++ { + if (h3 + p1) * (p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3 { + p2 := 1 + (p1 - 1) * (h3 + p1) / d + if !isPrime(p2) { continue } + p3 := 1 + p1 * p2 / h3 + if !isPrime(p3) { continue } + if p2 * p3 % (p1 - 1) != 1 { continue } + c := p1 * p2 * p3 + fmt.Printf("%2d %4d %5d %d\n", p1, p2, p3, c) + } + } + } +} + +func main() { + fmt.Println("The following are Carmichael munbers for p1 <= 61:\n") + fmt.Println("p1 p2 p3 product") + fmt.Println("== == == =======") + + for p1 := 2; p1 <= 61; p1++ { + if isPrime(p1) { carmichael(p1) } + } +} diff --git a/Task/Carmichael-3-strong-pseudoprimes/J/carmichael-3-strong-pseudoprimes.j b/Task/Carmichael-3-strong-pseudoprimes/J/carmichael-3-strong-pseudoprimes.j new file mode 100644 index 0000000000..982bf25edf --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/J/carmichael-3-strong-pseudoprimes.j @@ -0,0 +1,6 @@ +q =: (,"0 1~ >:@i.@<:@+/"1)&.>@(,&.>"0 1~ >:@i.)&.>@I.@(1&p:@i.)@>: +f1 =: (0: = {. | <:@{: * 1&{ + {:) *. ((1&{ | -@*:@{:) = 1&{ | {.) +f2 =: 1: = <:@{. | ({: * 1&{) +p2 =: 0:`((* 1&p:)@(<.@(1: + <:@{: * {. %~ 1&{ + {:)))@.f1 +p3 =: 3:$0:`((* 1&p:)@({: , {. , (<.@>:@(1&{ %~ {. * {:))))@.(*@{.)@(p2 , }.) +(-. 3:$0:)@(((*"0 f2)@p3"1)@;@;@q) 61 diff --git a/Task/Carmichael-3-strong-pseudoprimes/Julia/carmichael-3-strong-pseudoprimes-1.julia b/Task/Carmichael-3-strong-pseudoprimes/Julia/carmichael-3-strong-pseudoprimes-1.julia index 85c36fc988..73742d9080 100644 --- a/Task/Carmichael-3-strong-pseudoprimes/Julia/carmichael-3-strong-pseudoprimes-1.julia +++ b/Task/Carmichael-3-strong-pseudoprimes/Julia/carmichael-3-strong-pseudoprimes-1.julia @@ -1,19 +1,21 @@ -function carmichael{T<:Integer}(pmax::T) - 0 < pmax || throw(DomainError()) - car = T[] +using Primes + +function carmichael(pmax::Integer) + if pmax ≤ 0 throw(DomainError("pmax must be strictly positive")) end + car = Vector{typeof(pmax)}(0) for p in primes(pmax) for h₃ in 2:(p-1) - m = (p - 1)*(h₃ + p) - pmh = mod(-p^2, h₃) + m = (p - 1) * (h₃ + p) + pmh = mod(-p ^ 2, h₃) for Δ in 1:(h₃+p-1) - m%Δ==0 && Δ%h₃==pmh || continue - q = div(m, Δ) + 1 - isprime(q) || continue - r = div((p*q - 1), h₃) + 1 - isprime(r) && mod(q*r, (p-1))==1 || continue + if m % Δ != 0 || Δ % h₃ != pmh continue end + q = m ÷ Δ + 1 + if !isprime(q) continue end + r = (p * q - 1) ÷ h₃ + 1 + if !isprime(r) || mod(q * r, p - 1) == 1 continue end append!(car, [p, q, r]) end end end - reshape(car, 3, div(length(car), 3)) + return reshape(car, 3, length(car) ÷ 3) end diff --git a/Task/Carmichael-3-strong-pseudoprimes/Julia/carmichael-3-strong-pseudoprimes-2.julia b/Task/Carmichael-3-strong-pseudoprimes/Julia/carmichael-3-strong-pseudoprimes-2.julia index 727ab57be2..7a247f775f 100644 --- a/Task/Carmichael-3-strong-pseudoprimes/Julia/carmichael-3-strong-pseudoprimes-2.julia +++ b/Task/Carmichael-3-strong-pseudoprimes/Julia/carmichael-3-strong-pseudoprimes-2.julia @@ -1,15 +1,14 @@ hi = 61 car = carmichael(hi) -curp = 0 -tcnt = 0 -print("Carmichael 3 (p\u00d7q\u00d7r) Pseudoprimes, up to p = ", hi, ":") +curp = tcnt = 0 +print("Carmichael 3 (p×q×r) pseudoprimes, up to p = $hi:") for j in sortperm(1:size(car)[2], by=x->(car[1,x], car[2,x], car[3,x])) - p, q, r = car[:,j] - c = prod(car[:,j]) + p, q, r = car[:, j] + c = prod(car[:, j]) if p != curp curp = p - print(@sprintf("\n\np = %d\n ", p)) + @printf("\n\np = %d\n ", p) tcnt = 0 end if tcnt == 4 @@ -18,6 +17,6 @@ for j in sortperm(1:size(car)[2], by=x->(car[1,x], car[2,x], car[3,x])) else tcnt += 1 end - print(@sprintf("p\u00d7%d\u00d7%d = %d ", q, r, c)) + @printf("p× %d × %d = %d ", q, r, c) end println("\n\n", size(car)[2], " results in total.") diff --git a/Task/Carmichael-3-strong-pseudoprimes/REXX/carmichael-3-strong-pseudoprimes.rexx b/Task/Carmichael-3-strong-pseudoprimes/REXX/carmichael-3-strong-pseudoprimes.rexx new file mode 100644 index 0000000000..10f1908ac0 --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/REXX/carmichael-3-strong-pseudoprimes.rexx @@ -0,0 +1,39 @@ +/*REXX program calculates Carmichael 3─strong pseudoprimes (up to and including N). */ +numeric digits 18 /*handle big dig #s (9 is the default).*/ +parse arg N .; if N=='' then N=61 /*allow user to specify for the search.*/ +tell= N>0; N=abs(N) /*N>0? Then display Carmichael numbers*/ +#=0 /*number of Carmichael numbers so far. */ +@.=0; @.2=1; @.3=1; @.5=1; @.7=1; @.11=1; @.13=1; @.17=1; @.19=1; @.23=1; @.29=1; @.31=1 + /*[↑] prime number memoization array. */ + do p=3 to N by 2; pm=p-1; bot=0; top=0 /*step through some (odd) prime numbers*/ + if \isPrime(p) then iterate; nps=-p*p /*is P a prime? No, then skip it.*/ + !.=0 /*the list of Carmichael #'s (so far).*/ + do h3=2 to pm; g=h3+p /*find Carmichael #s for this prime. */ + gPM=g*pm; npsH3=((nps//h3)+h3)//h3 /*define a couple of shortcuts for pgm.*/ + /* [↓] perform some weeding of D values*/ + do d=1 for g-1; if gPM//d \== 0 then iterate + if npsH3 \== d//h3 then iterate + q=1+gPM%d; if \isPrime(q) then iterate + r=1+p*q%h3; if q*r//pm\==1 then iterate + if \isPrime(r) then iterate + #=#+1; !.q=r /*bump Carmichael counter; add to array*/ + if bot==0 then bot=q; bot=min(bot,q); top=max(top,q) + end /*d*/ + end /*h3*/ + $= /*display a list of some Carmichael #s.*/ + do j=bot to top by 2 while tell; if !.j\==0 then $=$ p"∙"j'∙'!.j + end /*j*/ + + if $\=='' then say 'Carmichael number: ' strip($) + end /*p*/ +say +say '──────── ' # " Carmichael numbers found." +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +isPrime: parse arg x; if @.x then return 1 /*X a known prime?*/ + if x<37 then return 0; if x//2==0 then return 0; if x// 3==0 then return 0 + parse var x '' -1 _; if _==5 then return 0; if x// 7==0 then return 0 + do k=11 by 6 until k*k>x; if x// k ==0 then return 0 + if x//(k+2)==0 then return 0 + end /*i*/ + @.x=1; return 1 diff --git a/Task/Carmichael-3-strong-pseudoprimes/Ring/carmichael-3-strong-pseudoprimes.ring b/Task/Carmichael-3-strong-pseudoprimes/Ring/carmichael-3-strong-pseudoprimes.ring new file mode 100644 index 0000000000..d57d667f5a --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/Ring/carmichael-3-strong-pseudoprimes.ring @@ -0,0 +1,46 @@ +# Project : Carmichael 3 strong pseudoprimes +# Date : 2017/11/29 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +see "The following are Carmichael munbers for p1 <= 61:" + nl +see "p1 p2 p3 product" + nl + +for p = 2 to 61 + carmichael3(p) +next + +func carmichael3(p1) + if isprime(p1) = 0 return ok + for h3 = 1 to p1 -1 + t1 = (h3 + p1) * (p1 -1) + t2 = (-p1 * p1) % h3 + if t2 < 0 + t2 = t2 + h3 + ok + for d = 1 to h3 + p1 -1 + if t1 % d = 0 and t2 = (d % h3) + p2 = 1 + (t1 / d) + if isprime(p2) = 0 + loop + ok + p3 = 1 + floor((p1 * p2 / h3)) + if isprime(p3) = 0 or ((p2 * p3) % (p1 -1)) != 1 + loop + ok + see "" + p1 + " " + p2 + " " + p3 + " " + p1*p2*p3 + nl + ok + next + next + +func isprime(num) + if (num <= 1) return 0 ok + if (num % 2 = 0) and num != 2 + return 0 + ok + for i = 3 to floor(num / 2) -1 step 2 + if (num % i = 0) + return 0 + ok + next + return 1 diff --git a/Task/Case-sensitivity-of-identifiers/Elena/case-sensitivity-of-identifiers.elena b/Task/Case-sensitivity-of-identifiers/Elena/case-sensitivity-of-identifiers.elena index 0ba1066c14..72354c38c4 100644 --- a/Task/Case-sensitivity-of-identifiers/Elena/case-sensitivity-of-identifiers.elena +++ b/Task/Case-sensitivity-of-identifiers/Elena/case-sensitivity-of-identifiers.elena @@ -1,6 +1,6 @@ import extensions. -program = +public program = [ var dog := "Benjamin". var Dog := "Samba". diff --git a/Task/Case-sensitivity-of-identifiers/Factor/case-sensitivity-of-identifiers.factor b/Task/Case-sensitivity-of-identifiers/Factor/case-sensitivity-of-identifiers.factor new file mode 100644 index 0000000000..d80379625b --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/Factor/case-sensitivity-of-identifiers.factor @@ -0,0 +1,8 @@ +USING: formatting locals ; +IN: scratchpad +[let + "Benjamin" :> dog + "Samba" :> Dog + "Bernie" :> DOG + { dog Dog DOG } "There are three dogs named %s, %s, and %s." vprintf +] diff --git a/Task/Case-sensitivity-of-identifiers/Julia/case-sensitivity-of-identifiers.julia b/Task/Case-sensitivity-of-identifiers/Julia/case-sensitivity-of-identifiers.julia index 38ea5769ca..ebf155ad4d 100644 --- a/Task/Case-sensitivity-of-identifiers/Julia/case-sensitivity-of-identifiers.julia +++ b/Task/Case-sensitivity-of-identifiers/Julia/case-sensitivity-of-identifiers.julia @@ -1,8 +1,6 @@ -dog = "Benjamin" -Dog = "Samba" -DOG = "Bernie" +dog, Dog, DOG = "Benjamin", "Samba", "Bernie" -if is(dog, Dog) +if dog === Dog println("There is only one dog, ", DOG) else println("The three dogs are: ", dog, ", ", Dog, " and ", DOG) diff --git a/Task/Casting-out-nines/Ring/casting-out-nines.ring b/Task/Casting-out-nines/Ring/casting-out-nines.ring new file mode 100644 index 0000000000..035b3655fb --- /dev/null +++ b/Task/Casting-out-nines/Ring/casting-out-nines.ring @@ -0,0 +1,40 @@ +# Project : Casting out nines +# Date : 2018/03/24 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : + +co9(1, 10, 99, [1,9,45,55,99]) +co9(1, 10, 1000, [1,9,45,55,99,297,703,999]) + +func co9(start,base,lim,kaprekars) +c1=0 +c2=0 +s = [] +for k = start to lim + c1 = c1 + 1 + if k % (base-1) = (k*k) % (base-1) + c2 = c2 + 1 + add(s,k) + ok +next +msg = "Valid subset" + nl +for i = 1 to len(kaprekars) + if not find(s,kaprekars[i]) + msg = "***Invalid***" + nl + exit + ok +next +showarray(s) +see "Kaprekar numbers:" + nl +showarray(kaprekars) +see msg +see "Trying " + c2 + " numbers instead of " + c1 + " saves " + (100-(c2/c1)*100) + "%" + nl + nl + +func showarray(vect) + see "{" + svect = "" + for n = 1 to len(vect) + svect = svect + vect[n] + ", " + next + svect = left(svect, len(svect) - 2) + see svect + "}" + nl diff --git a/Task/Casting-out-nines/Sidef/casting-out-nines.sidef b/Task/Casting-out-nines/Sidef/casting-out-nines.sidef new file mode 100644 index 0000000000..b545aa3c7d --- /dev/null +++ b/Task/Casting-out-nines/Sidef/casting-out-nines.sidef @@ -0,0 +1,23 @@ +func cast_out(base = 10, min = 1, max = (base**2 - 1)) { + + var b9 = base-1 + var ran = b9.range.grep {|n| n%b9 == (n*n % b9) } + + var x = min//b9 + var r = [] + + loop { + ran.each {|n| + var k = (b9*x + n) + return r if (k > max) + r << k if (k >= min) + } + ++x + } + + return r +} + +say cast_out().join(' ') +say cast_out(16).join(' ') +say cast_out(17).join(' ') diff --git a/Task/Catalan-numbers-Pascals-triangle/00DESCRIPTION b/Task/Catalan-numbers-Pascals-triangle/00DESCRIPTION index c11c3855c6..5cdc2860c4 100644 --- a/Task/Catalan-numbers-Pascals-triangle/00DESCRIPTION +++ b/Task/Catalan-numbers-Pascals-triangle/00DESCRIPTION @@ -3,9 +3,10 @@ Print out the first   '''15'''   Catalan numbers by extracting them fr ;See: -*   [http://milan.milanovic.org/math/english/fibo/fibo4.html Catalan Numbers and the Pascal Triangle].     This method enables calculation of Catalan Numbers using only addition and subtraction.
    '''The (above) link is broken.''' +*   [https://archive.is/0IrNp Catalan Numbers and the Pascal Triangle].     This method enables calculation of Catalan Numbers using only addition and subtraction. + *   [http://mathworld.wolfram.com/CatalansTriangle.html Catalan's Triangle] for a Number Triangle that generates Catalan Numbers using only addition. - +*   Sequence [http://oeis.org/A000108 A000108] on OEIS has a lot of information on Catalan Numbers. ;Related Tasks: [[Pascal's triangle]] diff --git a/Task/Catalan-numbers-Pascals-triangle/Factor/catalan-numbers-pascals-triangle.factor b/Task/Catalan-numbers-Pascals-triangle/Factor/catalan-numbers-pascals-triangle.factor new file mode 100644 index 0000000000..d003bcd727 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Factor/catalan-numbers-pascals-triangle.factor @@ -0,0 +1,14 @@ +USING: arrays grouping io kernel math prettyprint sequences ; +IN: rosetta-code.catalan-pascal + +: next-row ( seq -- seq' ) + 2 clump [ sum ] map 1 prefix 1 suffix ; + +: pascal ( n -- seq ) + 1 - { { 1 } } swap [ dup last next-row suffix ] times ; + +15 2 * pascal [ length odd? ] filter [ + dup length 1 = [ 1 ] + [ dup midpoint@ dup 1 + 2array swap nths first2 - ] if + pprint bl +] each drop diff --git a/Task/Catalan-numbers-Pascals-triangle/Go/catalan-numbers-pascals-triangle.go b/Task/Catalan-numbers-Pascals-triangle/Go/catalan-numbers-pascals-triangle.go new file mode 100644 index 0000000000..a6e0bbaae3 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Go/catalan-numbers-pascals-triangle.go @@ -0,0 +1,18 @@ +package main + +import "fmt" + +func main() { + const n = 15 + t := [n + 2]uint64{0, 1} + for i := 1; i <= n; i++ { + for j := i; j > 1; j-- { + t[j] += t[j-1] + } + t[i+1] = t[i] + for j := i + 1; j > 1; j-- { + t[j] += t[j-1] + } + fmt.Printf("%2d : %d\n", i, t[i+1]-t[i]) + } +} diff --git a/Task/Catalan-numbers-Pascals-triangle/OCaml/catalan-numbers-pascals-triangle.ocaml b/Task/Catalan-numbers-Pascals-triangle/OCaml/catalan-numbers-pascals-triangle.ocaml new file mode 100644 index 0000000000..1b195e4ee9 --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/OCaml/catalan-numbers-pascals-triangle.ocaml @@ -0,0 +1,12 @@ +let catalan : int ref = ref 0 in +Printf.printf "%d ," 1 ; +for i = 2 to 9 do +let nm : int ref = ref 1 in +let den : int ref = ref 1 in +for k = 2 to i do +nm := (!nm)*(i+k); +den := (!den)*k; +catalan := (!nm)/(!den) ; +done; +print_int (!catalan); print_string "," ; +done;; diff --git a/Task/Catalan-numbers-Pascals-triangle/Oforth/catalan-numbers-pascals-triangle.oforth b/Task/Catalan-numbers-Pascals-triangle/Oforth/catalan-numbers-pascals-triangle.oforth index e9f782c14e..822b292642 100644 --- a/Task/Catalan-numbers-Pascals-triangle/Oforth/catalan-numbers-pascals-triangle.oforth +++ b/Task/Catalan-numbers-Pascals-triangle/Oforth/catalan-numbers-pascals-triangle.oforth @@ -1,2 +1,7 @@ -: pascal(n) [ 1 ] #[ dup 0 + 0 rot + zipWith(#+) ] times(n) ; -: catalan(n) pascal(n 2 * ) at(n 1+) n 1+ / ; +import: mapping + +: pascal( n -- [] ) + [ 1 ] n #[ dup [ 0 ] + [ 0 ] rot + zipWith( #+ ) ] times ; + +: catalan( n -- m ) + n 2 * pascal at( n 1+ ) n 1+ / ; diff --git a/Task/Catalan-numbers-Pascals-triangle/Scala/catalan-numbers-pascals-triangle.scala b/Task/Catalan-numbers-Pascals-triangle/Scala/catalan-numbers-pascals-triangle.scala new file mode 100644 index 0000000000..5eeb4d6b2d --- /dev/null +++ b/Task/Catalan-numbers-Pascals-triangle/Scala/catalan-numbers-pascals-triangle.scala @@ -0,0 +1,5 @@ +def catalan(n: Int): Int = + if (n <= 1) 1 + else (0 until n).map(i => catalan(i) * catalan(n - i - 1)).sum + +(1 to 15).map(catalan(_)) diff --git a/Task/Catalan-numbers/360-Assembly/catalan-numbers.360 b/Task/Catalan-numbers/360-Assembly/catalan-numbers.360 index 1db03f7569..b9d443a5b0 100644 --- a/Task/Catalan-numbers/360-Assembly/catalan-numbers.360 +++ b/Task/Catalan-numbers/360-Assembly/catalan-numbers.360 @@ -1,4 +1,4 @@ -CATALAN CSECT +CATALAN CSECT 08/09/2015 USING CATALAN,R15 LA R7,1 c=1 LA R6,1 i=1 diff --git a/Task/Catalan-numbers/BBC-BASIC/catalan-numbers.bbc b/Task/Catalan-numbers/BBC-BASIC/catalan-numbers.bbc index 403c2ec92d..9c9a7afd47 100644 --- a/Task/Catalan-numbers/BBC-BASIC/catalan-numbers.bbc +++ b/Task/Catalan-numbers/BBC-BASIC/catalan-numbers.bbc @@ -1,8 +1,7 @@ - FOR i% = 1 TO 15 - PRINT FNcatalan(i%) - NEXT - END - - DEF FNcatalan(n%) - IF n% = 0 THEN = 1 - = 2 * (2 * n% - 1) * FNcatalan(n% - 1) / (n% + 1) + 10 FOR i% = 1 TO 15 + 20 PRINT FNcatalan(i%) + 30 NEXT + 40 END + 50 DEF FNcatalan(n%) + 60 IF n% = 0 THEN = 1 + 70 = 2 * (2 * n% - 1) * FNcatalan(n% - 1) / (n% + 1) diff --git a/Task/Catalan-numbers/Julia/catalan-numbers.julia b/Task/Catalan-numbers/Julia/catalan-numbers.julia index 09b82cd1a0..e9980b7656 100644 --- a/Task/Catalan-numbers/Julia/catalan-numbers.julia +++ b/Task/Catalan-numbers/Julia/catalan-numbers.julia @@ -1 +1,4 @@ -Catalan(n::Integer) = div(binomial(2n, n), n+1) +catalannum(n::Integer) = binomial(2n, n) ÷ (n + 1) + +@show catalannum.(1:15) +@show catalannum(big(100)) diff --git a/Task/Catalan-numbers/Logo/catalan-numbers.logo b/Task/Catalan-numbers/Logo/catalan-numbers.logo new file mode 100644 index 0000000000..1309ef009a --- /dev/null +++ b/Task/Catalan-numbers/Logo/catalan-numbers.logo @@ -0,0 +1,11 @@ +to factorial :n + output ifelse [less? :n 1] 1 [product :n factorial difference :n 1] +end +to choose :n :r + output quotient factorial :n product factorial :r factorial difference :n :r +end +to catalan :n + output product (quotient sum :n 1) choose product 2 :n :n +end + +repeat 15 [print catalan repcount] diff --git a/Task/Catalan-numbers/MATLAB/catalan-numbers-1.m b/Task/Catalan-numbers/MATLAB/catalan-numbers-1.m index 07ec109bca..22d433f6d1 100644 --- a/Task/Catalan-numbers/MATLAB/catalan-numbers-1.m +++ b/Task/Catalan-numbers/MATLAB/catalan-numbers-1.m @@ -1,4 +1,4 @@ -function n = catalanNumbers(n) +function n = catalanNumber(n) for i = (1:length(n)) n(i) = (1/(n(i)+1))*nchoosek(2*n(i),n(i)); end diff --git a/Task/Catalan-numbers/MATLAB/catalan-numbers-2.m b/Task/Catalan-numbers/MATLAB/catalan-numbers-2.m index 9315ee385e..36d85232ee 100644 --- a/Task/Catalan-numbers/MATLAB/catalan-numbers-2.m +++ b/Task/Catalan-numbers/MATLAB/catalan-numbers-2.m @@ -1,3 +1,3 @@ function n = catalanNumbers(n) - n = arrayfun(@(n)prod(n+1:2*n)/prod(1:n+1), n); + n = [1 cumprod((2:4:4*n-6) ./ (2:n))]; end diff --git a/Task/Catalan-numbers/MATLAB/catalan-numbers-3.m b/Task/Catalan-numbers/MATLAB/catalan-numbers-3.m index db449e504a..092b7cafcd 100644 --- a/Task/Catalan-numbers/MATLAB/catalan-numbers-3.m +++ b/Task/Catalan-numbers/MATLAB/catalan-numbers-3.m @@ -1,10 +1,10 @@ ->> catalanNumbers(14) +>> catalanNumber(14) ans = 2674440 ->> catalanNumbers((0:17))' +>> catalanNumbers(18)' ans = diff --git a/Task/Catalan-numbers/Modula-2/catalan-numbers.mod2 b/Task/Catalan-numbers/Modula-2/catalan-numbers.mod2 new file mode 100644 index 0000000000..565fe2d7cb --- /dev/null +++ b/Task/Catalan-numbers/Modula-2/catalan-numbers.mod2 @@ -0,0 +1,65 @@ +MODULE CatalanNumbers; +FROM FormatString IMPORT FormatString; +FROM Terminal IMPORT WriteString,WriteLn,ReadChar; + +PROCEDURE binomial(m,n : LONGCARD) : LONGCARD; +VAR r,d : LONGCARD; +BEGIN + r := 1; + d := m - n; + IF d>n THEN + n := d; + d := m - n; + END; + WHILE m>n DO + r := r * m; + DEC(m); + WHILE (d>1) AND NOT (r MOD d # 0) DO + r := r DIV d; + DEC(d) + END + END; + RETURN r +END binomial; + +PROCEDURE catalan1(n : LONGCARD) : LONGCARD; +BEGIN + RETURN binomial(2*n,n) DIV (1+n) +END catalan1; + +PROCEDURE catalan2(n : LONGCARD) : LONGCARD; +VAR i,sum : LONGCARD; +BEGIN + IF n>1 THEN + sum := 0; + FOR i:=0 TO n-1 DO + sum := sum + catalan2(i) * catalan2(n - 1 - i) + END; + RETURN sum + ELSE + RETURN 1 + END +END catalan2; + +PROCEDURE catalan3(n : LONGCARD) : LONGCARD; +BEGIN + IF n#0 THEN + RETURN 2 *(2 * n - 1) * catalan3(n - 1) DIV (1 + n) + ELSE + RETURN 1 + END +END catalan3; + +VAR + blah : LONGCARD = 123; + buf : ARRAY[0..63] OF CHAR; + i : LONGCARD; +BEGIN + FormatString("\tdirect\tsumming\tfrac\n", buf); + WriteString(buf); + FOR i:=0 TO 15 DO + FormatString("%u\t%u\t%u\t%u\n", buf, i, catalan1(i), catalan2(i), catalan3(i)); + WriteString(buf) + END; + ReadChar +END CatalanNumbers. diff --git a/Task/Catalan-numbers/OCaml/catalan-numbers.ocaml b/Task/Catalan-numbers/OCaml/catalan-numbers.ocaml index 1b195e4ee9..82a899be4f 100644 --- a/Task/Catalan-numbers/OCaml/catalan-numbers.ocaml +++ b/Task/Catalan-numbers/OCaml/catalan-numbers.ocaml @@ -1,12 +1,54 @@ -let catalan : int ref = ref 0 in -Printf.printf "%d ," 1 ; -for i = 2 to 9 do -let nm : int ref = ref 1 in -let den : int ref = ref 1 in -for k = 2 to i do -nm := (!nm)*(i+k); -den := (!den)*k; -catalan := (!nm)/(!den) ; -done; -print_int (!catalan); print_string "," ; -done;; +let imp_catalan n = + let return = ref 1 in + for i = 1 to n do + return := !return * 2 * (2 * i - 1) / (i + 1) + done; + !return + +let rec catalan = function + | 0 -> 1 + | n -> catalan (n - 1) * 2 * (2 * n - 1) / (n + 1) + +let memoize f = + let cache = Hashtbl.create 20 in + fun n -> + match Hashtbl.find_opt cache n with + | None -> + let x = f n in + Hashtbl.replace cache n x; + x + | Some x -> x + +let catalan_cache = Hashtbl.create 20 + +let rec memo_catalan n = + if n = 0 then 1 else + match Hashtbl.find_opt catalan_cache n with + | None -> + let x = memo_catalan (n - 1) * 2 * (2 * n - 1) / (n + 1) in + Hashtbl.replace catalan_cache n x; + x + | Some x -> x + +let () = + if not !Sys.interactive then + let bench label f n times = + let start = Unix.gettimeofday () in + begin + for i = 1 to times do f n done; + let stop = Unix.gettimeofday () in + Printf.printf "%s (%d runs) : %.3f\n" + label times (stop -. start) + end in + let show f g h f' n = + for i = 0 to n do + Printf.printf "%2d %7d %7d %7d %7d\n" + i (f i) (g i) (h i) (f' i) + done + in + List.iter (fun (l, f) -> bench l f 15 10_000_000) + ["imperative", imp_catalan; + "recursive", catalan; + "hand-memoized", memo_catalan; + "memoized", (memoize catalan)]; + show imp_catalan catalan memo_catalan (memoize catalan) 15 diff --git a/Task/Catalan-numbers/Oforth/catalan-numbers.oforth b/Task/Catalan-numbers/Oforth/catalan-numbers.oforth index 1fdd5cc832..ff612e4ec5 100644 --- a/Task/Catalan-numbers/Oforth/catalan-numbers.oforth +++ b/Task/Catalan-numbers/Oforth/catalan-numbers.oforth @@ -1 +1,2 @@ -: catalan(n) n ifZero: [ 1 ] else: [ catalan(n 1-) 2 n * 1- * 2 * n 1+ / ] ; +: catalan( n -- m ) + n ifZero: [ 1 ] else: [ catalan( n 1- ) 2 n * 1- * 2 * n 1+ / ] ; diff --git a/Task/Catalan-numbers/Perl-6/catalan-numbers-2.pl6 b/Task/Catalan-numbers/Perl-6/catalan-numbers-2.pl6 index fa95984dc4..67f631389c 100644 --- a/Task/Catalan-numbers/Perl-6/catalan-numbers-2.pl6 +++ b/Task/Catalan-numbers/Perl-6/catalan-numbers-2.pl6 @@ -1 +1,5 @@ constant Catalan = 1, |[\*] (2, 6 ... *) Z/ 2 .. *; + + +# In both cases, the sixteen first values can be seen with: +.say for Catalan[^16]; diff --git a/Task/Catalan-numbers/R/catalan-numbers.r b/Task/Catalan-numbers/R/catalan-numbers.r index 67ac88e7a1..d2af252fec 100644 --- a/Task/Catalan-numbers/R/catalan-numbers.r +++ b/Task/Catalan-numbers/R/catalan-numbers.r @@ -1,4 +1,4 @@ catalan <- function(n) choose(2*n, n)/(n + 1) -catalan(1:15) -# [1] 1 2 5 14 42 132 429 1430 4862 -#[10] 16796 58786 208012 742900 2674440 9694845 +catalan(0:15) + [1] 1 1 2 5 14 42 132 429 1430 +[10] 4862 16796 58786 208012 742900 2674440 9694845 diff --git a/Task/Catalan-numbers/Scala/catalan-numbers.scala b/Task/Catalan-numbers/Scala/catalan-numbers.scala index 3fd82d209f..009f8eeb59 100644 --- a/Task/Catalan-numbers/Scala/catalan-numbers.scala +++ b/Task/Catalan-numbers/Scala/catalan-numbers.scala @@ -3,7 +3,7 @@ object Catalan { def catalan(n: BigInt) = factorial(2 * n) / (factorial(n + 1) * factorial(n)) def main(args: Array[String]) { - for (n <- 1 to 15) { + for (n <- 0 to 15) { println("catalan(" + n + ") = " + catalan(n)) } } diff --git a/Task/Catalan-numbers/Stata/catalan-numbers.stata b/Task/Catalan-numbers/Stata/catalan-numbers.stata new file mode 100644 index 0000000000..c23867ed7c --- /dev/null +++ b/Task/Catalan-numbers/Stata/catalan-numbers.stata @@ -0,0 +1,5 @@ +clear +set obs 15 +gen catalan=1 in 1 +replace catalan=catalan[_n-1]*2*(2*_n-3)/_n in 2/l +list, noobs noh diff --git a/Task/Catamorphism/Elena/catamorphism.elena b/Task/Catamorphism/Elena/catamorphism.elena index 3dd9565c03..c9b69636c6 100644 --- a/Task/Catamorphism/Elena/catamorphism.elena +++ b/Task/Catamorphism/Elena/catamorphism.elena @@ -3,9 +3,9 @@ import system'routines. import extensions. import extensions'text. -program = +public program = [ - var numbers := 1 repeat till:10 each(:n)( n ); summarize(ArrayList new). + var numbers := 1 to:10 repeat(:n)( n ); summarize(ArrayList new). var summary := numbers accumulate(Variable new:0) with(:a:b)( a + b ). diff --git a/Task/Catamorphism/Factor/catamorphism.factor b/Task/Catamorphism/Factor/catamorphism.factor new file mode 100644 index 0000000000..407df204e4 --- /dev/null +++ b/Task/Catamorphism/Factor/catamorphism.factor @@ -0,0 +1 @@ +{ 1 2 4 6 10 } 0 [ + ] reduce . diff --git a/Task/Catamorphism/Fortran/catamorphism-1.f b/Task/Catamorphism/Fortran/catamorphism-1.f new file mode 100644 index 0000000000..1a0aaf20d3 --- /dev/null +++ b/Task/Catamorphism/Fortran/catamorphism-1.f @@ -0,0 +1,9 @@ + SUBROUTINE FOLD(t,F,i,ist,lst) + INTEGER t + BYNAME F + DO i = ist,lst + t = F + END DO + END SUBROUTINE FOLD !Result in temp. + + temp = a(1); CALL FOLD(temp,temp*a(i),i,2,N) diff --git a/Task/Catamorphism/Fortran/catamorphism-2.f b/Task/Catamorphism/Fortran/catamorphism-2.f new file mode 100644 index 0000000000..87476c9eb3 --- /dev/null +++ b/Task/Catamorphism/Fortran/catamorphism-2.f @@ -0,0 +1,53 @@ + INTEGER FUNCTION IFOLD(F,A,N) !"Catamorphism"... + INTEGER F !We're working only with integers. + EXTERNAL F !This is a function, not an array. + INTEGER A(*) !An 1-D array, of unspecified size. + INTEGER N !The number of elements. + INTEGER I !A stepper. + IFOLD = 0 !A default value. + IF (N.LE.0) RETURN !Dodge silly invocations. + IFOLD = A(1) !The function is to have two arguments. + IF (N.EQ.1) RETURN !So, if there is only one element, silly. + DO I = 2,N !Otherwise, stutter along the array. + IFOLD = F(IFOLD,A(I)) !Applying the function. + END DO !On to the next element. + END FUNCTION IFOLD!Thus, F(A(1),A(2)), or F(F(A(1),A(2)),A(3)), or F(F(F(A(1),A(2)),A(3)),A(4)), etc. + + INTEGER FUNCTION IADD(I,J) + INTEGER I,J + IADD = I + J + END FUNCTION IADD + + INTEGER FUNCTION IMUL(I,J) + INTEGER I,J + IMUL = I*J + END FUNCTION IMUL + + INTEGER FUNCTION IDIV(I,J) + INTEGER I,J + IDIV = I/J + END FUNCTION IDIV + + INTEGER FUNCTION IVID(I,J) + INTEGER I,J + IVID = J/I + END FUNCTION IVID + + PROGRAM POKE + INTEGER ENUFF + PARAMETER (ENUFF = 6) + INTEGER A(ENUFF) + PARAMETER (A = (/1,2,3,4,5,6/)) + INTEGER MSG + EXTERNAL IADD,IMUL,IDIV,IVID !Warn that these are the names of functions. + + MSG = 6 !Standard output. + WRITE (MSG,1) ENUFF,A + 1 FORMAT ('To apply a function in the "catamorphic" style ', + 1 "to the ",I0," values ",/,(20I3)) + + WRITE (MSG,*) "Iadd",IFOLD(IADD,A,ENUFF) + WRITE (MSG,*) "Imul",IFOLD(IMUL,A,ENUFF) + WRITE (MSG,*) "Idiv",IFOLD(IDIV,A,ENUFF) + WRITE (MSG,*) "Ivid",IFOLD(IVID,A,ENUFF) + END PROGRAM POKE diff --git a/Task/Catamorphism/J/catamorphism-3.j b/Task/Catamorphism/J/catamorphism-3.j new file mode 100644 index 0000000000..01d6937cee --- /dev/null +++ b/Task/Catamorphism/J/catamorphism-3.j @@ -0,0 +1,4 @@ +1 * 2 * 3 * 20 +1 * 2 * 60 +1 * 120 +120 diff --git a/Task/Catamorphism/Perl-6/catamorphism-2.pl6 b/Task/Catamorphism/Perl-6/catamorphism-2.pl6 index f00c19588f..acaaf6514f 100644 --- a/Task/Catamorphism/Perl-6/catamorphism-2.pl6 +++ b/Task/Catamorphism/Perl-6/catamorphism-2.pl6 @@ -1,3 +1,4 @@ +my @list = 1..10; say reduce &infix:<+>, @list; say reduce &infix:<*>, @list; say reduce &infix:<~>, @list; diff --git a/Task/Catamorphism/Python/catamorphism-1.py b/Task/Catamorphism/Python/catamorphism-1.py index bac5e8a046..15cfb6321a 100644 --- a/Task/Catamorphism/Python/catamorphism-1.py +++ b/Task/Catamorphism/Python/catamorphism-1.py @@ -1,3 +1,4 @@ +>>> # Python 2.X >>> from operator import add >>> listoflists = [['the', 'cat'], ['sat', 'on'], ['the', 'mat']] >>> help(reduce) diff --git a/Task/Catamorphism/Python/catamorphism-2.py b/Task/Catamorphism/Python/catamorphism-2.py index 543f12c042..1dc1b545fd 100644 --- a/Task/Catamorphism/Python/catamorphism-2.py +++ b/Task/Catamorphism/Python/catamorphism-2.py @@ -1,3 +1,5 @@ +# Python 3.X + from functools import reduce from operator import add, mul diff --git a/Task/Catamorphism/R/catamorphism-1.r b/Task/Catamorphism/R/catamorphism-1.r new file mode 100644 index 0000000000..4a21515b85 --- /dev/null +++ b/Task/Catamorphism/R/catamorphism-1.r @@ -0,0 +1,2 @@ +Reduce('+', c(2,30,400,5000)) +5432 diff --git a/Task/Catamorphism/R/catamorphism-2.r b/Task/Catamorphism/R/catamorphism-2.r new file mode 100644 index 0000000000..9404deec10 --- /dev/null +++ b/Task/Catamorphism/R/catamorphism-2.r @@ -0,0 +1,2 @@ +Reduce(function(a,b){c(a,0,b)}, c(2,3,4,5)) +2 0 3 0 4 0 5 diff --git a/Task/Catamorphism/R/catamorphism-3.r b/Task/Catamorphism/R/catamorphism-3.r new file mode 100644 index 0000000000..2e72431793 --- /dev/null +++ b/Task/Catamorphism/R/catamorphism-3.r @@ -0,0 +1,2 @@ +Reduce(paste0, unlist(strsplit("freedom", NULL)), accum=T) +"f" "fr" "fre" "free" "freed" "freedo" "freedom" diff --git a/Task/Catamorphism/R/catamorphism-4.r b/Task/Catamorphism/R/catamorphism-4.r new file mode 100644 index 0000000000..1798772611 --- /dev/null +++ b/Task/Catamorphism/R/catamorphism-4.r @@ -0,0 +1,3 @@ +Reduce(function(x,acc){if (0==x%%3) c(x*x,acc) else acc}, 0:22, + init=c(), right=T) + 0 9 36 81 144 225 324 441 diff --git a/Task/Catamorphism/REXX/catamorphism.rexx b/Task/Catamorphism/REXX/catamorphism.rexx index 16b1aead65..743065b307 100644 --- a/Task/Catamorphism/REXX/catamorphism.rexx +++ b/Task/Catamorphism/REXX/catamorphism.rexx @@ -1,36 +1,36 @@ /*REXX program demonstrates a method for catamorphism for some simple functions. */ @list= 1 2 3 4 5 6 7 8 9 10 - say 'show:' fold(@list, "show") - say ' sum:' fold(@list, "+" ) - say 'prod:' fold(@list, "*" ) - say ' cat:' fold(@list, "||" ) - say ' min:' fold(@list, "min" ) - say ' max:' fold(@list, "max" ) - say ' avg:' fold(@list, "avg" ) - say ' GCD:' fold(@list, "GCD" ) - say ' LCM:' fold(@list, "LCM" ) + say 'list:' fold(@list, "list") + say ' sum:' fold(@list, "+" ) + say 'prod:' fold(@list, "*" ) + say ' cat:' fold(@list, "||" ) + say ' min:' fold(@list, "min" ) + say ' max:' fold(@list, "max" ) + say ' avg:' fold(@list, "avg" ) + say ' GCD:' fold(@list, "GCD" ) + say ' LCM:' fold(@list, "LCM" ) exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -fold: procedure; parse arg z; arg ,f; z=space(z); BIFs='MIN MAX LCM GCD' - za=translate(z, f, ' '); zf=f"("translate(z, ',' , " ")')' - if f=='+' | f=="*" then interpret "return" za - if f=='||' then return space(z, 0) - if f=='AVG' then interpret "return" fold(z, '+') "/" words(z) - if wordpos(f,BIFs)\==0 then interpret "return" zf - if f=='SHOW' then return z - return 'illegal function:' arg(2) +fold: procedure; parse arg z; arg ,f; z=space(z); BIFs='MIN MAX LCM GCD' + za=translate(z, f, ' '); zf=f"("translate(z, ',' , " ")')' + if f=='+' | f=="*" then interpret "return" za + if f=='||' then return space(z, 0) + if f=='AVG' then interpret "return" fold(z, '+') "/" words(z) + if wordpos(f, BIFs)\==0 then interpret "return" zf + if f=='LIST' | f=="SHOW" then return z + return 'illegal function:' arg(2) /*──────────────────────────────────────────────────────────────────────────────────────*/ GCD: procedure; $=; do j=1 for arg(); $=$ arg(j); end /*j*/ parse var $ x z .; if x=0 then x=z /* [↑] build a list of arguments.*/ x=abs(x) - do k=2 to words($); y=abs(word($,k)); if y==0 then iterate - do until _==0; _=x//y; x=y; y=_; end /*until*/ + do k=2 to words($); y=abs(word($, k)); if y=0 then iterate + do until _=0; _=x//y; x=y; y=_; end /*until*/ end /*k*/ return x /*──────────────────────────────────────────────────────────────────────────────────────*/ LCM: procedure; $=; do j=1 for arg(); $=$ arg(j); end /*j*/ - x=abs(word($,1)) /* [↑] build a list of arguments.*/ - do k=2 to words($); !=abs(word($,k)); if !==0 then return 0 - x=x*! / GCD(x,!) /*have GCD do the heavy lifting.*/ - end /*k*/ + x=abs(word($, 1)) /* [↑] build a list of arguments.*/ + do k=2 to words($); !=abs(word($, k)); if !=0 then return 0 + x=x*! / GCD(x, !) /*have GCD do the heavy lifting.*/ + end /*k*/ return x diff --git a/Task/Catamorphism/Scala/catamorphism.scala b/Task/Catamorphism/Scala/catamorphism.scala new file mode 100644 index 0000000000..cacda729b1 --- /dev/null +++ b/Task/Catamorphism/Scala/catamorphism.scala @@ -0,0 +1,9 @@ +object Main extends App { + val a = Seq(1, 2, 3, 4, 5) + println(s"Array : ${a.mkString(", ")}") + println(s"Sum : ${a.sum}") + println(s"Difference : ${a.reduce { (x, y) => x - y }}") + println(s"Product : ${a.product}") + println(s"Minimum : ${a.min}") + println(s"Maximum : ${a.max}") +} diff --git a/Task/Catamorphism/Swift/catamorphism.swift b/Task/Catamorphism/Swift/catamorphism.swift new file mode 100644 index 0000000000..fa81a5ea15 --- /dev/null +++ b/Task/Catamorphism/Swift/catamorphism.swift @@ -0,0 +1,5 @@ +let nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + +print(nums.reduce(0, +)) +print(nums.reduce(1, *)) +print(nums.reduce("", { $0 + String($1) })) diff --git a/Task/Catmull-Clark-subdivision-surface/Haskell/catmull-clark-subdivision-surface.hs b/Task/Catmull-Clark-subdivision-surface/Haskell/catmull-clark-subdivision-surface.hs new file mode 100644 index 0000000000..27afe8b4d3 --- /dev/null +++ b/Task/Catmull-Clark-subdivision-surface/Haskell/catmull-clark-subdivision-surface.hs @@ -0,0 +1,311 @@ +{-# LANGUAGE GeneralizedNewtypeDeriving #-} +{-# LANGUAGE ScopedTypeVariables #-} + +import Data.Array +import Data.Foldable (length, concat, sum) +import Data.List (genericLength) +import Data.Maybe (mapMaybe) +import Prelude hiding (length, concat, sum) +import qualified Data.Map.Strict as Map + +{- +A SimpleMesh consists of only vertices and faces that refer to them. +A Mesh extends the SimpleMesh to contain edges as well as references to +adjoining mesh components for each other component, such as a vertex +also contains what faces it belongs to. +An isolated edge can be represented as a degenerate face with 2 vertices. +Faces with 0 or 1 vertices can be thrown out, as they do not contribute to +the result (they can also propagate NaNs). +-} + +newtype VertexId = VertexId { getVertexId :: Int } deriving (Ix, Ord, Eq, Show) +newtype EdgeId = EdgeId { getEdgeId :: Int } deriving (Ix, Ord, Eq, Show) +newtype FaceId = FaceId { getFaceId :: Int } deriving (Ix, Ord, Eq, Show) + +data Vertex a = Vertex + { vertexPoint :: a + , vertexEdges :: [EdgeId] + , vertexFaces :: [FaceId] + } deriving Show + +data Edge = Edge + { edgeVertexA :: VertexId + , edgeVertexB :: VertexId + , edgeFaces :: [FaceId] + } deriving Show + +data Face = Face + { faceVertices :: [VertexId] + , faceEdges :: [EdgeId] + } deriving Show + +type VertexArray a = Array VertexId (Vertex a) +type EdgeArray = Array EdgeId Edge +type FaceArray = Array FaceId Face + +data Mesh a = Mesh + { meshVertices :: VertexArray a + , meshEdges :: EdgeArray + , meshFaces :: FaceArray + } deriving Show + +data SimpleVertex a = SimpleVertex { sVertexPoint :: a } deriving Show +data SimpleFace = SimpleFace { sFaceVertices :: [VertexId] } deriving Show + +type SimpleVertexArray a = Array VertexId (SimpleVertex a) +type SimpleFaceArray = Array FaceId SimpleFace + +data SimpleMesh a = SimpleMesh + { sMeshVertices :: SimpleVertexArray a + , sMeshFaces :: SimpleFaceArray + } deriving Show + +-- Generic helpers. +fmap1 :: Functor f => (t -> a -> b) -> (t -> f a) -> t -> f b +fmap1 g h x = fmap (g x) (h x) + +aZipWith :: Ix i1 => (a -> b -> e) -> Array i1 a -> Array i b -> Array i1 e +aZipWith f a b = listArray (bounds a) $ zipWith f (elems a) (elems b) + +average :: (Foldable f, Fractional a) => f a -> a +average xs = (sum xs) / (fromIntegral $ length xs) + +-- Intermediary point types for ultimately converting into a point `a`. +newtype FacePoint a = FacePoint { getFacePoint :: a } deriving Show +newtype EdgeCenterPoint a = EdgeCenterPoint { getEdgeCenterPoint :: a } deriving Show +newtype EdgePoint a = EdgePoint { getEdgePoint :: a } deriving Show +newtype VertexPoint a = VertexPoint { getVertexPoint :: a } deriving Show + +type FacePointArray a = Array FaceId (FacePoint a) +type EdgePointArray a = Array EdgeId (EdgePoint a) +type EdgeCenterPointArray a = Array EdgeId (EdgeCenterPoint a) +type IsEdgeHoleArray = Array EdgeId Bool +type VertexPointArray a = Array VertexId (VertexPoint a) + +-- Subdivision helpers. +facePoint :: Fractional a => Mesh a -> Face -> FacePoint a +facePoint mesh = FacePoint . average . (fmap $ vertexPointById mesh) . faceVertices + +allFacePoints :: Fractional a => Mesh a -> FacePointArray a +allFacePoints = fmap1 facePoint meshFaces + +vertexPointById :: Mesh a -> VertexId -> a +vertexPointById mesh = vertexPoint . (meshVertices mesh !) + +edgeCenterPoint :: Fractional a => Mesh a -> Edge -> EdgeCenterPoint a +edgeCenterPoint mesh (Edge ea eb _) + = EdgeCenterPoint . average $ fmap (vertexPointById mesh) [ea, eb] + +allEdgeCenterPoints :: Fractional a => Mesh a -> EdgeCenterPointArray a +allEdgeCenterPoints = fmap1 edgeCenterPoint meshEdges + +allIsEdgeHoles :: Mesh a -> IsEdgeHoleArray +allIsEdgeHoles = fmap ((< 2) . length . edgeFaces) . meshEdges + +edgePoint :: Fractional a => Edge -> FacePointArray a -> EdgeCenterPoint a -> EdgePoint a +edgePoint (Edge _ _ [_]) _ (EdgeCenterPoint ecp) = EdgePoint ecp +edgePoint (Edge _ _ faceIds) facePoints (EdgeCenterPoint ecp) + = EdgePoint $ average [ecp, average $ fmap (getFacePoint . (facePoints !)) faceIds] + +allEdgePoints :: Fractional a => Mesh a -> FacePointArray a -> EdgeCenterPointArray a -> EdgePointArray a +allEdgePoints mesh fps ecps = aZipWith (\e ecp -> edgePoint e fps ecp) (meshEdges mesh) ecps + +vertexPoint' :: Fractional a => Vertex a -> FacePointArray a -> EdgeCenterPointArray a -> IsEdgeHoleArray -> VertexPoint a +vertexPoint' vertex facePoints ecps iehs + | length faceIds == length edgeIds = VertexPoint newCoords + | otherwise = VertexPoint avgHoleEcps + where + newCoords = (oldCoords * m1) + (avgFacePoints * m2) + (avgMidEdges * m3) + oldCoords = vertexPoint vertex + avgFacePoints = average $ fmap (getFacePoint . (facePoints !)) faceIds + avgMidEdges = average $ fmap (getEdgeCenterPoint . (ecps !)) edgeIds + m1 = (n - 3) / n + m2 = 1 / n + m3 = 2 / n + n = genericLength faceIds + faceIds = vertexFaces vertex + edgeIds = vertexEdges vertex + avgHoleEcps = average . (oldCoords:) . fmap (getEdgeCenterPoint . (ecps !)) $ filter (iehs !) edgeIds + +allVertexPoints :: Fractional a => Mesh a -> FacePointArray a -> EdgeCenterPointArray a -> IsEdgeHoleArray -> VertexPointArray a +allVertexPoints mesh fps ecps iehs = fmap (\v -> vertexPoint' v fps ecps iehs) (meshVertices mesh) + +-- For each vertex in a face, generate a set of new faces from it with its vertex point, +-- neighbor edge points, and face point. The new faces will refer to vertices in the +-- combined vertex array. +newFaces :: Face -> FaceId -> Int -> Int -> [SimpleFace] +newFaces (Face vertexIds edgeIds) faceId epOffset vpOffset + = take (genericLength vertexIds) + $ zipWith3 newFace (cycle vertexIds) (cycle edgeIds) (drop 1 (cycle edgeIds)) + where + f = VertexId . (+ epOffset) . getEdgeId + newFace vid epA epB = SimpleFace + [ VertexId . (+ vpOffset) $ getVertexId vid + , f epA + , VertexId $ getFaceId faceId + , f epB] + +subdivide :: Fractional a => SimpleMesh a -> SimpleMesh a +subdivide simpleMesh + = SimpleMesh combinedVertices (listArray (FaceId 0, FaceId (genericLength faces - 1)) faces) + where + mesh = makeComplexMesh simpleMesh + fps = allFacePoints mesh + ecps = allEdgeCenterPoints mesh + eps = allEdgePoints mesh fps ecps + iehs = allIsEdgeHoles mesh + vps = allVertexPoints mesh fps ecps iehs + edgePointOffset = length fps + vertexPointOffset = edgePointOffset + length eps + combinedVertices + = listArray (VertexId 0, VertexId (vertexPointOffset + length vps - 1)) + . fmap SimpleVertex + $ concat [ fmap getFacePoint $ elems fps + , fmap getEdgePoint $ elems eps + , fmap getVertexPoint $ elems vps] + faces + = concat $ zipWith (\face fid -> newFaces face fid edgePointOffset vertexPointOffset) + (elems $ meshFaces mesh) (fmap FaceId [0..]) + +-- Transform to a Mesh by filling in the missing references and generating edges. +-- Faces can be updated with their edges, but must be ordered. +-- Edge and face order does not matter for vertices. +-- TODO: Discard degenerate faces (ones with 0 to 2 vertices/edges), +-- or we could transform these into single edges or vertices. +makeComplexMesh :: forall a. SimpleMesh a -> Mesh a +makeComplexMesh (SimpleMesh sVertices sFaces) = Mesh vertices edges faces + where + makeEdgesFromFace :: SimpleFace -> FaceId -> [Edge] + makeEdgesFromFace (SimpleFace vertexIds) fid + = take (genericLength vertexIds) + $ zipWith (\a b -> Edge a b [fid]) verts (drop 1 verts) + where + verts = cycle vertexIds + + edgeKey :: VertexId -> VertexId -> (VertexId, VertexId) + edgeKey a b = (min a b, max a b) + + sFacesList :: [SimpleFace] + sFacesList = elems sFaces + + fids :: [FaceId] + fids = fmap FaceId [0..] + + eids :: [EdgeId] + eids = fmap EdgeId [0..] + + faceEdges :: [[Edge]] + faceEdges = zipWith makeEdgesFromFace sFacesList fids + + edgeMap :: Map.Map (VertexId, VertexId) Edge + edgeMap + = Map.fromListWith (\(Edge a b fidsA) (Edge _ _ fidsB) -> Edge a b (fidsA ++ fidsB)) + . fmap (\edge@(Edge a b _) -> (edgeKey a b, edge)) + $ concat faceEdges + + edges :: EdgeArray + edges = listArray (EdgeId 0, EdgeId $ (Map.size edgeMap) - 1) $ Map.elems edgeMap + + edgeIdMap :: Map.Map (VertexId, VertexId) EdgeId + edgeIdMap = Map.fromList $ zipWith (\(Edge a b _) eid -> ((edgeKey a b), eid)) (elems edges) eids + + faceEdgeIds :: [[EdgeId]] + faceEdgeIds = fmap (mapMaybe (\(Edge a b _) -> Map.lookup (edgeKey a b) edgeIdMap)) faceEdges + + faces :: FaceArray + faces + = listArray (FaceId 0, FaceId $ (length sFaces) - 1) + $ zipWith (\(SimpleFace verts) edgeIds -> Face verts edgeIds) sFacesList faceEdgeIds + + vidsToFids :: Map.Map VertexId [FaceId] + vidsToFids + = Map.fromListWith (++) + . concat + $ zipWith (\(SimpleFace vertexIds) fid -> fmap (\vid -> (vid, [fid])) vertexIds) sFacesList fids + + vidsToEids :: Map.Map VertexId [EdgeId] + vidsToEids + = Map.fromListWith (++) + . concat + $ zipWith (\(Edge a b _) eid -> [(a, [eid]), (b, [eid])]) (elems edges) eids + + simpleToComplexVert :: SimpleVertex a -> VertexId -> Vertex a + simpleToComplexVert (SimpleVertex point) vid + = Vertex point + (Map.findWithDefault [] vid vidsToEids) + (Map.findWithDefault [] vid vidsToFids) + + vertices :: VertexArray a + vertices + = listArray (bounds sVertices) + $ zipWith simpleToComplexVert (elems sVertices) (fmap VertexId [0..]) + +pShowSimpleMesh :: Show a => SimpleMesh a -> String +pShowSimpleMesh (SimpleMesh vertices faces) + = "Vertices:\n" ++ (arrShow vertices sVertexPoint) + ++ "Faces:\n" ++ (arrShow faces (fmap getVertexId . sFaceVertices)) + where + arrShow a f = concatMap ((++ "\n") . show . (\(i, e) -> (i, f e))) . zip [0 :: Int ..] $ elems a + +-- Testing types. +data Point a = Point a a a deriving (Show) + +instance Functor Point where + fmap f (Point x y z) = Point (f x) (f y) (f z) + +zipPoint :: (a -> b -> c) -> Point a -> Point b -> Point c +zipPoint f (Point x y z) (Point x' y' z') = Point (f x x') (f y y') (f z z') + +instance Num a => Num (Point a) where + (+) = zipPoint (+) + (-) = zipPoint (-) + (*) = zipPoint (*) + negate = fmap negate + abs = fmap abs + signum = fmap signum + fromInteger i = let i' = fromInteger i in Point i' i' i' + +instance Fractional a => Fractional (Point a) where + recip = fmap recip + fromRational r = let r' = fromRational r in Point r' r' r' + +testCube :: SimpleMesh (Point Double) +testCube = SimpleMesh vertices faces + where + vertices = listArray (VertexId 0, VertexId 7) + $ fmap SimpleVertex + [ Point (-1) (-1) (-1) + , Point (-1) (-1) 1 + , Point (-1) 1 (-1) + , Point (-1) 1 1 + , Point 1 (-1) (-1) + , Point 1 (-1) 1 + , Point 1 1 (-1) + , Point 1 1 1] + faces = listArray (FaceId 0, FaceId 5) + $ fmap (SimpleFace . (fmap VertexId)) + [ [0, 4, 5, 1] + , [4, 6, 7, 5] + , [6, 2, 3, 7] + , [2, 0, 1, 3] + , [1, 5, 7, 3] + , [0, 2, 6, 4]] + +testCubeWithHole :: SimpleMesh (Point Double) +testCubeWithHole + = SimpleMesh (sMeshVertices testCube) (ixmap (FaceId 0, FaceId 4) id (sMeshFaces testCube)) + +testTriangle :: SimpleMesh (Point Double) +testTriangle = SimpleMesh vertices faces + where + vertices = listArray (VertexId 0, VertexId 2) + $ fmap SimpleVertex + [ Point 0 0 0 + , Point 0 0 1 + , Point 0 1 0] + faces = listArray (FaceId 0, FaceId 0) + $ fmap (SimpleFace . (fmap VertexId)) + [ [0, 1, 2]] + +main :: IO () +main = putStr . pShowSimpleMesh $ subdivide testCube diff --git a/Task/Character-codes/BASIC/character-codes-5.basic b/Task/Character-codes/BASIC/character-codes-5.basic new file mode 100644 index 0000000000..2c4bc355f5 --- /dev/null +++ b/Task/Character-codes/BASIC/character-codes-5.basic @@ -0,0 +1,4 @@ +10 REM THE ZX81 USES ITS OWN NON-ASCII CHARACTER SET +20 REM WHICH DOES NOT INCLUDE LOWER-CASE LETTERS +30 PRINT CODE "A" +40 PRINT CHR$ 38 diff --git a/Task/Character-codes/BASIC/character-codes-6.basic b/Task/Character-codes/BASIC/character-codes-6.basic new file mode 100644 index 0000000000..b429c2bcca --- /dev/null +++ b/Task/Character-codes/BASIC/character-codes-6.basic @@ -0,0 +1,4 @@ +10 CH = 65: REM IN PETSCII CODE FOR 'A' IS 65 +20 D$ = "B": REM D$ HOLDS THE CHARACTER 'B' +30 PRINT CHR$(CH): REM THIS PRINTS 'A' +40 PRINT ASC(D$): REM THIS PRINTS 66 diff --git a/Task/Character-codes/Elena/character-codes.elena b/Task/Character-codes/Elena/character-codes.elena index 70c73c48c8..45811efb1e 100644 --- a/Task/Character-codes/Elena/character-codes.elena +++ b/Task/Character-codes/Elena/character-codes.elena @@ -1,6 +1,6 @@ import extensions. -program = +public program = [ var ch := $97. diff --git a/Task/Character-codes/HolyC/character-codes.holyc b/Task/Character-codes/HolyC/character-codes.holyc new file mode 100644 index 0000000000..56ca554d51 --- /dev/null +++ b/Task/Character-codes/HolyC/character-codes.holyc @@ -0,0 +1,2 @@ +Print("%d\n", 'a'); /* prints "97" */ +Print("%c\n", 97); /* prints "a" */ diff --git a/Task/Character-codes/Julia/character-codes.julia b/Task/Character-codes/Julia/character-codes.julia index 1b59a08561..bf5d8c5ac3 100644 --- a/Task/Character-codes/Julia/character-codes.julia +++ b/Task/Character-codes/Julia/character-codes.julia @@ -1,2 +1,2 @@ -println(int('a')) -println(char(97)) +println(Int('a')) +println(Char(97)) diff --git a/Task/Character-codes/Red/character-codes.red b/Task/Character-codes/Red/character-codes.red new file mode 100644 index 0000000000..1bca69ca6a --- /dev/null +++ b/Task/Character-codes/Red/character-codes.red @@ -0,0 +1,5 @@ +Red [] +print to-integer first "a" ;; -> 97 +print to-integer #"a" ;; -> 97 +print to-binary "a" ;; -> #{61} +print to-char 97 ;; -> a diff --git a/Task/Character-codes/Stata/character-codes-1.stata b/Task/Character-codes/Stata/character-codes-1.stata new file mode 100644 index 0000000000..c1f316d03a --- /dev/null +++ b/Task/Character-codes/Stata/character-codes-1.stata @@ -0,0 +1,5 @@ +: ascii("α") + 1 2 + +-------------+ + 1 | 206 177 | + +-------------+ diff --git a/Task/Character-codes/Stata/character-codes-2.stata b/Task/Character-codes/Stata/character-codes-2.stata new file mode 100644 index 0000000000..51962cc797 --- /dev/null +++ b/Task/Character-codes/Stata/character-codes-2.stata @@ -0,0 +1,5 @@ +: ascii("We the People") + 1 2 3 4 5 6 7 8 9 10 11 12 13 + +-------------------------------------------------------------------------------+ + 1 | 87 101 32 116 104 101 32 80 101 111 112 108 101 | + +-------------------------------------------------------------------------------+ diff --git a/Task/Character-codes/Stata/character-codes-3.stata b/Task/Character-codes/Stata/character-codes-3.stata new file mode 100644 index 0000000000..9198765cd0 --- /dev/null +++ b/Task/Character-codes/Stata/character-codes-3.stata @@ -0,0 +1,2 @@ +: char((73,32,115,116,97,110,100,32,104,101,114,101)) + I stand here diff --git a/Task/Chat-server/Julia/chat-server.julia b/Task/Chat-server/Julia/chat-server.julia new file mode 100644 index 0000000000..55eab88606 --- /dev/null +++ b/Task/Chat-server/Julia/chat-server.julia @@ -0,0 +1,82 @@ +using HttpServer +using WebSockets + +const connections = Dict{Int,WebSocket}() +const usernames = Dict{Int,String}() + +function decodeMessage( msg ) + String(copy(msg)) +end + + +wsh = WebSocketHandler() do req, client + global connections + @show connections[client.id] = client + println("req is $req") + notifyonline = "Connection from user number $(client.id) is now online." + for (k,v) in connections + if k != client.id + try + write(v, notifyonline) + catch + continue + end + end + end + while true + try + msg = read(client) + catch + telloffline = "User $(usernames[client.id]) disconnected." + println(telloffline, "(The client id was $(client.id).)") + delete!(connections, client.id) + if haskey(usernames, client.id) + delete!(usernames, client.id) + end + for (k,v) in connections + try + write(v, telloffline) + catch + continue + end + end + return + end + msg = decodeMessage(msg) + if startswith(msg, "setusername:") + println("SETTING USERNAME: $msg") + usernames[client.id] = msg[13:end] + notifyusername = "User number $(client.id) chose $(usernames[client.id]) as name handle." + for (k,v) in connections + try + write(v, notifyusername) + catch + println("Caught exception writing to user $k") + continue + end + end + end + if startswith(msg, "say:") + println("EMITTING MESSAGE: $msg") + for (k,v) in connections + if k != client.id + try + write(v, (usernames[client.id] * ": " * msg[5:end])) + catch + println("Caught exception writing to user $k") + continue + end + end + end + end + end +end + +onepage = readstring(Pkg.dir("WebSockets","examples","chat-client.html")) +httph = HttpHandler() do req::Request, res::Response + Response(onepage) +end + +server = Server(httph, wsh) +println("Chat server listening on 8000...") +run(server,8000) diff --git a/Task/Chat-server/Perl-6/chat-server.pl6 b/Task/Chat-server/Perl-6/chat-server.pl6 index 9829864687..57c246e125 100644 --- a/Task/Chat-server/Perl-6/chat-server.pl6 +++ b/Task/Chat-server/Perl-6/chat-server.pl6 @@ -25,6 +25,12 @@ react { LAST { broadcast "--- %s left ---", $name; %connections{$name}:delete; + $conn.close ; + } + QUIT { + default { + say "oh no, $_"; + } } } } diff --git a/Task/Check-Machin-like-formulas/Perl-6/check-machin-like-formulas.pl6 b/Task/Check-Machin-like-formulas/Perl-6/check-machin-like-formulas.pl6 new file mode 100644 index 0000000000..1fcde0bf73 --- /dev/null +++ b/Task/Check-Machin-like-formulas/Perl-6/check-machin-like-formulas.pl6 @@ -0,0 +1,42 @@ +sub taneval ($coef, $f) { + return 0 if $coef == 0; + return $f if $coef == 1; + return -taneval(-$coef, $f) if $coef < 0; + + my $a = taneval($coef+>1, $f); + my $b = taneval($coef - $coef+>1, $f); + ($a+$b)/(1-$a*$b); +} + +sub tans (@xs) { + return taneval(@xs[0;0], @xs[0;1].FatRat) if @xs == 1; + + my $a = tans(@xs[0 .. (-1+@xs+>1)]); + my $b = tans(@xs[(-1+@xs+>1)+1 .. -1+@xs]); + ($a+$b)/(1-$a*$b); +} + +sub verify (@eqn) { + printf "%5s (%s)\n", (tans(@eqn) == 1) ?? "OK" !! "Error", + (map { "[{.[0]} {.[1].nude.join('/')}]" }, @eqn).join(' '); +} + +verify($_) for + ([[1,1/2], [1,1/3]], + [[2,1/3], [1,1/7]], + [[4,1/5], [-1,1/239]], + [[5,1/7], [2,3/79]], + [[5,29/278], [7,3/79]], + [[1,1/2], [1,1/5], [1,1/8]], + [[4,1/5], [-1,1/70], [1,1/99]], + [[5,1/7], [4,1/53], [2,1/4443]], + [[6,1/8], [2,1/57], [1,1/239]], + [[8,1/10], [-1,1/239], [-4,1/515]], + [[12,1/18], [8,1/57], [-5,1/239]], + [[16,1/21], [3,1/239], [4,3/1042]], + [[22,1/28], [2,1/443], [-5,1/1393], [-10,1/11018]], + [[22,1/38], [17,7/601], [10,7/8149]], + [[44,1/57], [7,1/239], [-12,1/682], [24,1/12943]], + [[88,1/172], [51,1/239], [32,1/682], [44,1/5357], [68,1/12943]], + [[88,1/172], [51,1/239], [32,1/682], [44,1/5357], [68,1/21944]] + ); diff --git a/Task/Check-that-file-exists/Elena/check-that-file-exists.elena b/Task/Check-that-file-exists/Elena/check-that-file-exists.elena index 617a8503f7..7c1597d1e8 100644 --- a/Task/Check-that-file-exists/Elena/check-that-file-exists.elena +++ b/Task/Check-that-file-exists/Elena/check-that-file-exists.elena @@ -7,7 +7,7 @@ extension op = self isAvailable; iif("exists","not found"). } -program = +public program = [ console printLine("input.txt file ",File new("input.txt"); validatePath). diff --git a/Task/Check-that-file-exists/HolyC/check-that-file-exists.holyc b/Task/Check-that-file-exists/HolyC/check-that-file-exists.holyc new file mode 100644 index 0000000000..cad406a818 --- /dev/null +++ b/Task/Check-that-file-exists/HolyC/check-that-file-exists.holyc @@ -0,0 +1,20 @@ +U0 FileExists(U8 *f) { + if (FileFind(f) && !IsDir(f)) { + Print("'%s' file exists.\n", f); + } else { + Print("'%s' file does not exist.\n", f); + } +} + +U0 DirExists(U8 *d) { + if (IsDir(d)) { + Print("'%s' directory exists.\n", d); + } else { + Print("'%s' directory does not exist.\n", d); + } +} + +FileExists("input.txt"); +FileExists("::/input.txt"); +DirExists("docs"); +DirExists("::/docs"); diff --git a/Task/Check-that-file-exists/Julia/check-that-file-exists.julia b/Task/Check-that-file-exists/Julia/check-that-file-exists.julia index f2cc07551d..cce93db096 100644 --- a/Task/Check-that-file-exists/Julia/check-that-file-exists.julia +++ b/Task/Check-that-file-exists/Julia/check-that-file-exists.julia @@ -1,4 +1,6 @@ -isfile("input.txt") -isfile("/input.txt") -isdir("docs") -isdir("/docs") +@show isfile("input.txt") +@show isfile("/input.txt") +@show isdir("docs") +@show isdir("/docs") +@show isfile("") +@show isfile("`Abdu'l-Bahá.txt") diff --git a/Task/Check-that-file-exists/PicoLisp/check-that-file-exists.l b/Task/Check-that-file-exists/PicoLisp/check-that-file-exists.l index 503ff761d7..9c7f4b0580 100644 --- a/Task/Check-that-file-exists/PicoLisp/check-that-file-exists.l +++ b/Task/Check-that-file-exists/PicoLisp/check-that-file-exists.l @@ -1,3 +1,20 @@ (if (info "file.txt") (prinl "Size: " (car @) " bytes, last modified " (stamp (cadr @) (cddr @))) (prinl "File doesn't exist") ) + +# for directory existing +# Nehal-Singhal 2018-05-25 + +(if (info "./docs") + (print 'exists) + (print 'doesNotExist))) + +# To verify if it's really a directory, (CAR of return value will be 'T'). +# abu 2018-05-25 + + (let I (info "./docs") + (prinl + (nond + (I "Does not exist") + ((=T (car I)) "Is not a directory") + (NIL "Directory exists") ) ) ) diff --git a/Task/Check-that-file-exists/Red/check-that-file-exists.red b/Task/Check-that-file-exists/Red/check-that-file-exists.red new file mode 100644 index 0000000000..5fa864d6fb --- /dev/null +++ b/Task/Check-that-file-exists/Red/check-that-file-exists.red @@ -0,0 +1,9 @@ +exists? %input.txt +exists? %docs/ +exists? %/c/input.txt +exists? %/c/docs/ +exists? %//input.txt +exists? %//docs/ + +>> exists? %`Abdu'l-Bahá.txt +== true diff --git a/Task/Check-that-file-exists/Stata/check-that-file-exists-3.stata b/Task/Check-that-file-exists/Stata/check-that-file-exists-3.stata index ab89fe27d7..37d7a2c5db 100644 --- a/Task/Check-that-file-exists/Stata/check-that-file-exists-3.stata +++ b/Task/Check-that-file-exists/Stata/check-that-file-exists-3.stata @@ -1,4 +1,4 @@ confirmdir docs -if !r(confirmdir) { +if !`r(confirmdir)' { * do something if the directory exists } diff --git a/Task/Check-that-file-exists/VBA/check-that-file-exists.vba b/Task/Check-that-file-exists/VBA/check-that-file-exists.vba new file mode 100644 index 0000000000..8a3bbef69b --- /dev/null +++ b/Task/Check-that-file-exists/VBA/check-that-file-exists.vba @@ -0,0 +1,18 @@ +Option Explicit + +Sub Main_File_Exists() +Dim myFile As String, myDirectory As String + + myFile = "Abdu'l-Bahá.txt" + myDirectory = "C:\" + Debug.Print File_Exists(myFile, myDirectory) +End Sub + +Function File_Exists(F As String, D As String) As Boolean + If F = "" Then + File_Exists = False + Else + D = IIf(Right(D, 1) = "\", D, D & "\") + File_Exists = (Dir(D & F) <> "") + End If +End Function diff --git a/Task/Check-that-file-exists/VBScript/check-that-file-exists.vb b/Task/Check-that-file-exists/VBScript/check-that-file-exists.vb index c40d6b023d..8b6e9daff3 100644 --- a/Task/Check-that-file-exists/VBScript/check-that-file-exists.vb +++ b/Task/Check-that-file-exists/VBScript/check-that-file-exists.vb @@ -1,24 +1,33 @@ -Set FSO=CreateObject("Scripting.FileSystemObject") +Set FSO = CreateObject("Scripting.FileSystemObject") + Function FileExists(strFile) -if FSO.fileExists(strFile) then -FileExists=true -else -FileExists=false -end if -end function + If FSO.FileExists(strFile) Then + FileExists = True + Else + FileExists = False + End If +End Function -Function folderExists(strFolder) -if FSO.folderExists(strFolder) then -folderExists=true -else -folderexists=false -end if -end function +Function FolderExists(strFolder) + If FSO.FolderExists(strFolder) Then + FolderExists = True + Else + Folderexists = False + End If +End Function -'''''usage (apostrophes indicate comments-this section will not be run)''''' -'if fileExists("C:\test.txt") then -'msgbox"It Exists!" -'else -'msgbox"awww" -'end if -'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' +'''''Usage (apostrophes indicate comments-this section will not be run)''''' +'If FileExists("C:\test.txt") Then +' MsgBox "It Exists!" +'Else +' Msgbox "awww" +'End If +'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' + +'Shorter version + +If CreateObject("Scripting.FileSystemObject").FileExists("d:\test.txt") Then + Wscript.Echo "File Exists" +Else + Wscript.Echo "File Does Not Exist") +End If diff --git a/Task/Check-that-file-exists/Visual-Basic/check-that-file-exists.vb b/Task/Check-that-file-exists/Visual-Basic/check-that-file-exists.vb new file mode 100644 index 0000000000..ec799df921 --- /dev/null +++ b/Task/Check-that-file-exists/Visual-Basic/check-that-file-exists.vb @@ -0,0 +1,16 @@ +'declarations: +Public Declare Function GetFileAttributes Lib "kernel32" _ + Alias "GetFileAttributesA" (ByVal lpFileName As String) As Long +Public Const INVALID_FILE_ATTRIBUTES As Long = -1 +Public Const ERROR_SHARING_VIOLATION As Long = 32& + +'implementation: +Public Function FileExists(ByVal Filename As String) As Boolean +Dim l As Long +l = GetFileAttributes(Filename) + If l <> INVALID_FILE_ATTRIBUTES Then + FileExists = ((l And vbDirectory) = 0) + ElseIf Err.LastDllError = ERROR_SHARING_VIOLATION Then + FileExists = True + End If +End Function diff --git a/Task/Checkpoint-synchronization/Go/checkpoint-synchronization-1.go b/Task/Checkpoint-synchronization/Go/checkpoint-synchronization-1.go new file mode 100644 index 0000000000..b85efd6a7d --- /dev/null +++ b/Task/Checkpoint-synchronization/Go/checkpoint-synchronization-1.go @@ -0,0 +1,34 @@ +package main + +import ( + "log" + "math/rand" + "sync" + "time" +) + +func worker(part string) { + log.Println(part, "worker begins part") + time.Sleep(time.Duration(rand.Int63n(1e6))) + log.Println(part, "worker completes part") + wg.Done() +} + +var ( + partList = []string{"A", "B", "C", "D"} + nAssemblies = 3 + wg sync.WaitGroup +) + +func main() { + rand.Seed(time.Now().UnixNano()) + for c := 1; c <= nAssemblies; c++ { + log.Println("begin assembly cycle", c) + wg.Add(len(partList)) + for _, part := range partList { + go worker(part) + } + wg.Wait() + log.Println("assemble. cycle", c, "complete") + } +} diff --git a/Task/Checkpoint-synchronization/Go/checkpoint-synchronization-2.go b/Task/Checkpoint-synchronization/Go/checkpoint-synchronization-2.go new file mode 100644 index 0000000000..3d1a457c8e --- /dev/null +++ b/Task/Checkpoint-synchronization/Go/checkpoint-synchronization-2.go @@ -0,0 +1,40 @@ +package main + +import ( + "log" + "math/rand" + "strings" + "time" +) + +func worker(part string, completed chan string) { + log.Println(part, "worker begins part") + time.Sleep(time.Duration(rand.Int63n(1e6))) + p := strings.ToLower(part) + log.Println(part, "worker completed", p) + completed <- p +} + +var ( + partList = []string{"A", "B", "C", "D"} + nAssemblies = 3 +) + +func main() { + rand.Seed(time.Now().UnixNano()) + completed := make([]chan string, len(partList)) + for i := range completed { + completed[i] = make(chan string) + } + for c := 1; c <= nAssemblies; c++ { + log.Println("begin assembly cycle", c) + for i, part := range partList { + go worker(part, completed[i]) + } + a := "" + for _, c := range completed { + a += <-c + } + log.Println(a, "assembled. cycle", c, "complete") + } +} diff --git a/Task/Checkpoint-synchronization/Go/checkpoint-synchronization-3.go b/Task/Checkpoint-synchronization/Go/checkpoint-synchronization-3.go new file mode 100644 index 0000000000..4f8b03faa2 --- /dev/null +++ b/Task/Checkpoint-synchronization/Go/checkpoint-synchronization-3.go @@ -0,0 +1,64 @@ +package main + +import ( + "log" + "math/rand" + "strings" + "sync" + "time" +) + +func worker(part string, completed chan string) { + log.Println(part, "worker running") + for { + select { + case <-start: + log.Println(part, "worker begins part") + time.Sleep(time.Duration(rand.Int63n(1e6))) + p := strings.ToLower(part) + log.Println(part, "worker completed", p) + completed <- p + <-reset + wg.Done() + case <-done: + log.Println(part, "worker stopped") + wg.Done() + return + } + } +} + +var ( + partList = []string{"A", "B", "C", "D"} + nAssemblies = 3 + start = make(chan int) + done = make(chan int) + reset chan int + wg sync.WaitGroup +) + +func main() { + rand.Seed(time.Now().UnixNano()) + completed := make([]chan string, len(partList)) + for i, part := range partList { + completed[i] = make(chan string) + go worker(part, completed[i]) + } + for c := 1; c <= nAssemblies; c++ { + log.Println("begin assembly cycle", c) + reset = make(chan int) + close(start) + a := "" + for _, c := range completed { + a += <-c + } + log.Println(a, "assembled. cycle", c, "complete") + wg.Add(len(partList)) + start = make(chan int) + close(reset) + wg.Wait() + } + wg.Add(len(partList)) + close(done) + wg.Wait() +} diff --git a/Task/Checkpoint-synchronization/Go/checkpoint-synchronization.go b/Task/Checkpoint-synchronization/Go/checkpoint-synchronization-4.go similarity index 100% rename from Task/Checkpoint-synchronization/Go/checkpoint-synchronization.go rename to Task/Checkpoint-synchronization/Go/checkpoint-synchronization-4.go diff --git a/Task/Checkpoint-synchronization/Kotlin/checkpoint-synchronization.kotlin b/Task/Checkpoint-synchronization/Kotlin/checkpoint-synchronization.kotlin new file mode 100644 index 0000000000..fffe473965 --- /dev/null +++ b/Task/Checkpoint-synchronization/Kotlin/checkpoint-synchronization.kotlin @@ -0,0 +1,60 @@ +// Version 1.2.41 + +import java.util.Random + +val rgen = Random() +var nWorkers = 0 +var nTasks = 0 + +class Worker(private val threadID: Int) : Runnable { + + @Synchronized + override fun run() { + try { + val workTime = rgen.nextInt(900) + 100L // 100..999 msec. + println("Worker $threadID will work for $workTime msec.") + Thread.sleep(workTime) + nFinished++ + println("Worker $threadID is ready") + } + catch (e: InterruptedException) { + println("Error: thread execution interrupted") + e.printStackTrace() + } + } + + companion object { + private var nFinished = 0 + + @Synchronized + fun checkPoint() { + while (nFinished != nWorkers) { + try { + Thread.sleep(10) + } + catch (e: InterruptedException) { + println("Error: thread execution interrupted") + e.printStackTrace() + } + } + nFinished = 0 // reset + } + } +} + +fun runTasks() { + for (i in 1..nTasks) { + println("\nStarting task number $i.") + // Create a thread for each worker and run it. + for (j in 1..nWorkers) Thread(Worker(j)).start() + Worker.checkPoint() // wait for all workers to finish the task + } +} + +fun main(args: Array) { + print("Enter number of workers to use: ") + nWorkers = readLine()!!.toInt() + print("Enter number of tasks to complete: ") + nTasks = readLine()!!.toInt() + runTasks() +} diff --git a/Task/Chinese-remainder-theorem/Factor/chinese-remainder-theorem.factor b/Task/Chinese-remainder-theorem/Factor/chinese-remainder-theorem.factor new file mode 100644 index 0000000000..1e38fe5ddb --- /dev/null +++ b/Task/Chinese-remainder-theorem/Factor/chinese-remainder-theorem.factor @@ -0,0 +1,2 @@ +USING: math.algebra prettyprint ; +{ 2 3 2 } { 3 5 7 } chinese-remainder . diff --git a/Task/Chinese-remainder-theorem/Julia/chinese-remainder-theorem.julia b/Task/Chinese-remainder-theorem/Julia/chinese-remainder-theorem.julia new file mode 100644 index 0000000000..f798e3f2ca --- /dev/null +++ b/Task/Chinese-remainder-theorem/Julia/chinese-remainder-theorem.julia @@ -0,0 +1,26 @@ +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 +end + +@show chineseremainder([3, 5, 7], [2, 3, 2]) diff --git a/Task/Chinese-remainder-theorem/Sidef/chinese-remainder-theorem.sidef b/Task/Chinese-remainder-theorem/Sidef/chinese-remainder-theorem.sidef index 7bd20060f0..7f1cac715f 100644 --- a/Task/Chinese-remainder-theorem/Sidef/chinese-remainder-theorem.sidef +++ b/Task/Chinese-remainder-theorem/Sidef/chinese-remainder-theorem.sidef @@ -1,18 +1,20 @@ func mul_inv(a, b) { - b == 1 && return 1; - var (b0, x0, x1) = (0, 0, 1); + b == 1 && return 1 + var (b0, x0, x1) = (0, 0, 1) while (a > 1) { - (a, b, x0, x1) = (b, a % b, x1 - x0*int(a / b), x0); - }; - x1 < 0 ? x1+b0 : x1; + (a, b, x0, x1) = (b, a % b, x1 - x0*int(a / b), x0) + } + x1 < 0 ? x1+b0 : x1 } func chinese_remainder(*n) { - var N = n«*»; + var N = n«*» func (*a) { n.range.map { |i| - var p = int(N / n[i]); - a[i] * mul_inv(p, n[i]) * p; + var p = int(N / n[i]) + a[i] * mul_inv(p, n[i]) * p }.sum } } + +say chinese_remainder(3, 5, 7)(2, 3, 2) diff --git a/Task/Cholesky-decomposition/Go/cholesky-decomposition-3.go b/Task/Cholesky-decomposition/Go/cholesky-decomposition-3.go index 7f20fd8514..cb66b8f9ff 100644 --- a/Task/Cholesky-decomposition/Go/cholesky-decomposition-3.go +++ b/Task/Cholesky-decomposition/Go/cholesky-decomposition-3.go @@ -3,13 +3,13 @@ package main import ( "fmt" - "github.com/gonum/matrix/mat64" + "gonum.org/v1/gonum/mat" ) func cholesky(order int, elements []float64) fmt.Formatter { - t := mat64.NewTriDense(order, false, nil) - t.Cholesky(mat64.NewSymDense(order, elements), false) - return mat64.Formatted(t) + var c mat.Cholesky + c.Factorize(mat.NewSymDense(order, elements)) + return mat.Formatted(c.LTo(nil)) } func main() { diff --git a/Task/Cholesky-decomposition/Mathematica/cholesky-decomposition.math b/Task/Cholesky-decomposition/Mathematica/cholesky-decomposition-1.math similarity index 100% rename from Task/Cholesky-decomposition/Mathematica/cholesky-decomposition.math rename to Task/Cholesky-decomposition/Mathematica/cholesky-decomposition-1.math diff --git a/Task/Cholesky-decomposition/Mathematica/cholesky-decomposition-2.math b/Task/Cholesky-decomposition/Mathematica/cholesky-decomposition-2.math new file mode 100644 index 0000000000..677359d300 --- /dev/null +++ b/Task/Cholesky-decomposition/Mathematica/cholesky-decomposition-2.math @@ -0,0 +1,6 @@ +chol[A_] := + Module[{L}, + L[k_, k_] := L[k, k] = Sqrt[A[[k, k]] - Sum[L[k, j]^2, {j, 1, k-1}]]; + L[i_, k_] := L[i, k] = L[k, k]^-1 (A[[i, k]] - Sum[L[i, j] L[k, j], {j, 1, k-1}]); + PadRight[Table[L[i, j], {i, Length[A]}, {j, i}]] + ] diff --git a/Task/Cholesky-decomposition/REXX/cholesky-decomposition.rexx b/Task/Cholesky-decomposition/REXX/cholesky-decomposition.rexx index da49f72c59..e6f2a0fd20 100644 --- a/Task/Cholesky-decomposition/REXX/cholesky-decomposition.rexx +++ b/Task/Cholesky-decomposition/REXX/cholesky-decomposition.rexx @@ -1,51 +1,49 @@ -/*REXX program performs the Cholesky decomposition on a square matrix. */ -niner = '25 15 -5' , /*define a 3x3 matrix. */ +/*REXX program performs the Cholesky decomposition on a square matrix & displays results*/ +niner = '25 15 -5' , /*define a 3x3 matrix with elements. */ '15 18 0' , '-5 0 11' call Cholesky niner -hexer = 18 22 54 42, /*define a 4x4 matrix. */ +hexer = 18 22 54 42, /*define a 4x4 matrix with elements. */ 22 70 86 62, 54 86 174 134, 42 62 134 106 call Cholesky hexer -exit /*stick a fork in it, we're all done. */ -/*────────────────────────────────────────────────────────────────────────────*/ -Cholesky: procedure; parse arg mat; say; say; call tell 'input matrix',mat - do r=1 for ord - do c=1 for r; $=0; do i=1 for c-1; $=$+!.r.i*!.c.i; end /*i*/ - if r=c then !.r.r=sqrt(!.r.r-$) - else !.r.c=1/!.c.c*(@.r.c-$) - end /*c*/ - end /*r*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +Cholesky: procedure; parse arg mat; say; say; call tell 'input array',mat + do r=1 for ord + do c=1 for r; $=0; do i=1 for c-1; $= $ + !.r.i * !.c.i; end /*i*/ + if r=c then !.r.r= sqrt(!.r.r - $) / 1 + else !.r.c= 1 / !.c.c * (@.r.c - $) + end /*c*/ + end /*r*/ call tell 'Cholesky factor',,!.,'─' return -/*────────────────────────────────────────────────────────────────────────────*/ -err: say; say; say '***error***!'; say; say arg(1); say; say; exit 13 -/*────────────────────────────────────────────────────────────────────────────*/ -tell: parse arg hdr,x,y,sep; #=0; if sep=='' then sep='═' - dPlaces= 5 /*# decimal places past the decimal point*/ - width =10 /*width of field used to display elements*/ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +err: say; say; say '***error***!'; say; say arg(1); say; say; exit 13 +/*──────────────────────────────────────────────────────────────────────────────────────*/ +tell: parse arg hdr,x,y,sep; #=0; if sep=='' then sep= '═' + dPlaces= 5 /*# dec. places past the decimal point.*/ + width =10 /*field width used to display elements.*/ if y=='' then !.=0 - else do row=1 for ord; do col=1 for ord; x=x !.row.col; end; end + else do row=1 for ord; do col=1 for ord; x=x !.row.col; end; end w=words(x) - do ord=1 until ord**2>=w; end /*a fast way to find matrix's order*/ + do ord=1 until ord**2>=w; end /*a fast way to find the matrix's order*/ say if ord**2\==w then call err "matrix elements don't form a square matrix." - say center(hdr, ((width+1)*w)%ord, sep) + say center(hdr, ((width + 1) * w) % ord, sep) say - do row=1 for ord; z= - do col=1 for ord; #=#+1 - @.row.col=word(x,#) - if col<=row then !.row.col=@.row.col - z=z right( format(@.row.col,, dPlaces) / 1, width) - end /*col*/ - say z + do row=1 for ord; z= + do col=1 for ord; #= # + 1 + @.row.col= word(x, #) + if col<=row then !.row.col= @.row.col + z=z right( format(@.row.col, , dPlaces) / 1, width) + end /*col*/ /* ↑↑↑ */ + say z /* └┴┴──◄──normalization for zero*/ end /*row*/ return -/*────────────────────────────────────────────────────────────────────────────*/ -sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=; m.=9 - numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end - parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2 - do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ - do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ - numeric digits d; return (g/1)i /*make complex if X < 0.*/ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); numeric digits; h=d+6 + numeric form; m.=9; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_ %2 + do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ + do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/; return g diff --git a/Task/Cholesky-decomposition/Ring/cholesky-decomposition.ring b/Task/Cholesky-decomposition/Ring/cholesky-decomposition.ring new file mode 100644 index 0000000000..c51e9d37af --- /dev/null +++ b/Task/Cholesky-decomposition/Ring/cholesky-decomposition.ring @@ -0,0 +1,45 @@ +# Project : Cholesky decomposition +# Date : 2017/11/12 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +load "stdlib.ring" +decimals(5) +m1 = [[25, 15, -5], + [15, 18, 0], + [-5, 0, 11]] +cholesky(m1) +printarray(m1) +see nl + +m2 = [[18, 22, 54, 42], + [22, 70, 86, 62], + [54, 86, 174, 134], + [42, 62, 134, 106]] +cholesky(m2) +printarray(m2) + +func cholesky(a) +l = newlist(len(a), len(a)) +for i = 1 to len(a) + for j = 1 to i + s = 0 + for k = 1 to j + s = s + l[i][k] * l[j][k] + next + if i = j + l[i][j] = sqrt(a[i][i] - s) + else + l[i][j] = (a[i][j] - s) / l[j][j] + ok + next +next +a = l + +func printarray(a) + for row = 1 to len(a) + for col = 1 to len(a) + see "" + a[row][col] + " " + next + see nl + next diff --git a/Task/Cholesky-decomposition/Scilab/cholesky-decomposition.scilab b/Task/Cholesky-decomposition/Scilab/cholesky-decomposition.scilab new file mode 100644 index 0000000000..1547c91f63 --- /dev/null +++ b/Task/Cholesky-decomposition/Scilab/cholesky-decomposition.scilab @@ -0,0 +1,19 @@ +a = [25 15 -5; 15 18 0; -5 0 11]; +chol(a) + ans = + + 5. 3. -1. + 0. 3. 1. + 0. 0. 3. + + +a = [18 22 54 42; 22 70 86 62; + 54 86 174 134; 42 62 134 106]; + +chol(a) + ans = + + 4.2426407 5.1854497 12.727922 9.8994949 + 0. 6.5659052 3.0460385 1.6245539 + 0. 0. 1.6497422 1.849711 + 0. 0. 0. 1.3926212 diff --git a/Task/Circles-of-given-radius-through-two-points/00DESCRIPTION b/Task/Circles-of-given-radius-through-two-points/00DESCRIPTION index ced8cafbf4..d921defc55 100644 --- a/Task/Circles-of-given-radius-through-two-points/00DESCRIPTION +++ b/Task/Circles-of-given-radius-through-two-points/00DESCRIPTION @@ -20,6 +20,11 @@ Given two points on a plane and a radius, usually two circles of given radius ca 0.1234, 0.9876 0.1234, 0.9876 0.0 -;Ref: -* [http://mathforum.org/library/drmath/view/53027.html Finding the Center of a Circle from 2 Points and Radius] from Math forum @ Drexel + +;Related task: +*   [[Total circles area]]. + + +;See also: +*   [http://mathforum.org/library/drmath/view/53027.html Finding the Center of a Circle from 2 Points and Radius] from Math forum @ Drexel

diff --git a/Task/Circles-of-given-radius-through-two-points/Fortran/circles-of-given-radius-through-two-points.f b/Task/Circles-of-given-radius-through-two-points/Fortran/circles-of-given-radius-through-two-points-1.f similarity index 85% rename from Task/Circles-of-given-radius-through-two-points/Fortran/circles-of-given-radius-through-two-points.f rename to Task/Circles-of-given-radius-through-two-points/Fortran/circles-of-given-radius-through-two-points-1.f index 074a027907..76560beafd 100644 --- a/Task/Circles-of-given-radius-through-two-points/Fortran/circles-of-given-radius-through-two-points.f +++ b/Task/Circles-of-given-radius-through-two-points/Fortran/circles-of-given-radius-through-two-points-1.f @@ -1,4 +1,5 @@ ! Implemented by Anant Dixit (Nov. 2014) +! Transpose elements in find_center to obtain correct results. R.N. McLean (Dec 2017) program circles implicit none double precision :: P1(2), P2(2), R @@ -92,13 +93,13 @@ end subroutine test_inputs subroutine find_center(P1,P2,R,Center) implicit none -double precision :: P1(2), P2(2), MP(2), Center(2,2), R, dm -MP = (P1+P2)/2.0d0 -dm = sqrt( (P1(1)-P2(1))**2 + (P1(2)-P2(2))**2 ) +double precision :: P1(2), P2(2), MP(2), Center(2,2), R, dm, dd +MP = (P1 + P2)/2.0d0 +dm = sqrt((P1(1) - P2(1))**2 + (P1(2) - P2(2))**2) +dd = sqrt(R**2 - (dm/2.0d0)**2) +Center(1,1) = MP(1) - dd*(P2(2) - P1(2))/dm +Center(1,2) = MP(2) + dd*(P2(1) - P1(1))/dm -Center(1,1) = MP(1) + sqrt(R**2 - (dm/2.0d0)**2)*(P2(2)-P1(2))/dm -Center(1,2) = MP(2) + sqrt(R**2 - (dm/2.0d0)**2)*(P2(1)-P1(1))/dm - -Center(2,1) = MP(1) - sqrt(R**2 - (dm/2.0d0)**2)*(P2(2)-P1(2))/dm -Center(2,2) = MP(2) - sqrt(R**2 - (dm/2.0d0)**2)*(P2(1)-P1(1))/dm +Center(2,1) = MP(1) + dd*(P2(2) - P1(2))/dm +Center(2,2) = MP(2) - dd*(P2(1) - P1(1))/dm end subroutine find_center diff --git a/Task/Circles-of-given-radius-through-two-points/Fortran/circles-of-given-radius-through-two-points-2.f b/Task/Circles-of-given-radius-through-two-points/Fortran/circles-of-given-radius-through-two-points-2.f new file mode 100644 index 0000000000..6935c17d2f --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Fortran/circles-of-given-radius-through-two-points-2.f @@ -0,0 +1,63 @@ + MODULE GEOMETRY !Limited scope. + CHARACTER*(*) SQUAWK(-3:2) !Holds a schedule of complaints. + PARAMETER (SQUAWK = (/ !According to what might go wrong. + 3 "No circles: points are more than 2R apart.", + 2 "Innumerable circles: co-incident points, R > 0.", + 1 "One 'circle', centred on the co-incident points. R is zero!", + o "No circles! R is negative!", + 1 "One circle: points are 2R apart.", + 2 "Two circles."/)) !This last is the hoped-for state. + CONTAINS !Now for the action. + SUBROUTINE BUBBLE(P,R,N) !Finds circles of radius R passing through two points. + COMPLEX P(2) !The two points. Results returned here. + REAL R !The specified radius. + INTEGER N !Indicates how many centres are valid. + COMPLEX MID,DP !Geometrical assistants. + DP = (P(2) - P(1))/2 !Or, the other way around. + D = ABS(DP) !Half the separation is useful. + IF (R.LT.0) THEN !Is the specified radius silly? + N = 0 !Yes. No circles, then. + ELSE IF (D.EQ.0) THEN !Any distance between the points? + IF (R.EQ.0) THEN !No. Zero radius? + N = -1 !Yes. So a degenerate "circle" of zero radius. + ELSE !A negative radius being tested for above, + N = -2 !A swirl of circles around the midpoint. + END IF !So much for co-incident points. + ELSE IF (D.GT.R) THEN !Points too far apart? + N = -3 !A circle of radius R can't reach them. + ELSE IF (D.EQ.R) THEN !Maximum separation for R? + N = 1 !Yes. The two circles lie atop each other. + P(1) = (P(1) + P(2))/2 !Both centres are on the midpoint, but N = 1. + ELSE !Finally, the ordinary case. + N = 2 !Two circles. + MID = (P(1) + P(2))/2 !Midway between the two points. + D = SQRT((R/D)**2 - 1) !Rescale vector DP. + P = MID + DP*CMPLX(0,(/+D,-D/)) !Array (0,+D), (0,-D) + END IF !P(1) = DP*CMPLX(0,+D) and P(2) = DP*CMPLX(0,-D) + END SUBROUTINE BUBBLE !Careful! P and N are modified. + END MODULE GEOMETRY !Not much. + + PROGRAM POKE !A tester. + USE GEOMETRY !Useful to I. Newton. + COMPLEX P(2) !A pair of points. + REAL PP(4) !Also a pair. + EQUIVALENCE (P,PP) !Since free-format input likes (x,y), not x,y + REAL R !This is not complex. + INTEGER MSG,IN !I/O unit numbers. + MSG = 6 !Standard output. + OPEN (MSG, RECL = 120) !For "formatted" files, this length is in characters. + IN = 10 !For the disc file holding the test data. + WRITE (MSG,1) !Announce. + 1 FORMAT ("Given two points and a radius, find the centres " + 1 "of circles of that radius passing through those points.") + + OPEN (IN,FILE="Circle.csv", STATUS = "OLD", ACTION="READ") !Have data, will compute. + 10 READ (IN,*,END = 20) PP,R !Get two points and a radius. + WRITE (MSG,*) !Set off. + WRITE (MSG,*) P,R !Show the input. + CALL BUBBLE(P,R,N) !Calculate. + WRITE (MSG,*) P(1:N),SQUAWK(N) !Show results. + GO TO 10 !Try it again. + + 20 CLOSE(IN) !Finihed with input. + END !Finished. diff --git a/Task/Circles-of-given-radius-through-two-points/Java/circles-of-given-radius-through-two-points.java b/Task/Circles-of-given-radius-through-two-points/Java/circles-of-given-radius-through-two-points.java new file mode 100644 index 0000000000..835faa1072 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Java/circles-of-given-radius-through-two-points.java @@ -0,0 +1,86 @@ +import java.util.Objects; + +public class Circles { + private static class Point { + private final double x, y; + + public Point(Double x, Double y) { + this.x = x; + this.y = y; + } + + public double distanceFrom(Point other) { + double dx = x - other.x; + double dy = y - other.y; + return Math.sqrt(dx * dx + dy * dy); + } + + @Override + public boolean equals(Object other) { + if (this == other) return true; + if (other == null || getClass() != other.getClass()) return false; + Point point = (Point) other; + return x == point.x && y == point.y; + } + + @Override + public String toString() { + return String.format("(%.4f, %.4f)", x, y); + } + } + + private static Point[] findCircles(Point p1, Point p2, double r) { + if (r < 0.0) throw new IllegalArgumentException("the radius can't be negative"); + if (r == 0.0 && p1 != p2) throw new IllegalArgumentException("no circles can ever be drawn"); + if (r == 0.0) return new Point[]{p1, p1}; + if (Objects.equals(p1, p2)) throw new IllegalArgumentException("an infinite number of circles can be drawn"); + double distance = p1.distanceFrom(p2); + double diameter = 2.0 * r; + if (distance > diameter) throw new IllegalArgumentException("the points are too far apart to draw a circle"); + Point center = new Point((p1.x + p2.x) / 2.0, (p1.y + p2.y) / 2.0); + if (distance == diameter) return new Point[]{center, center}; + double mirrorDistance = Math.sqrt(r * r - distance * distance / 4.0); + double dx = (p2.x - p1.x) * mirrorDistance / distance; + double dy = (p2.y - p1.y) * mirrorDistance / distance; + return new Point[]{ + new Point(center.x - dy, center.y + dx), + new Point(center.x + dy, center.y - dx) + }; + } + + public static void main(String[] args) { + Point[] p = new Point[]{ + new Point(0.1234, 0.9876), + new Point(0.8765, 0.2345), + new Point(0.0000, 2.0000), + new Point(0.0000, 0.0000) + }; + Point[][] points = new Point[][]{ + {p[0], p[1]}, + {p[2], p[3]}, + {p[0], p[0]}, + {p[0], p[1]}, + {p[0], p[0]}, + }; + double[] radii = new double[]{2.0, 1.0, 2.0, 0.5, 0.0}; + for (int i = 0; i < radii.length; ++i) { + Point p1 = points[i][0]; + Point p2 = points[i][1]; + double r = radii[i]; + System.out.printf("For points %s and %s with radius %f\n", p1, p2, r); + try { + Point[] circles = findCircles(p1, p2, r); + Point c1 = circles[0]; + Point c2 = circles[1]; + if (Objects.equals(c1, c2)) { + System.out.printf("there is just one circle with center at %s\n", c1); + } else { + System.out.printf("there are two circles with centers at %s and %s\n", c1, c2); + } + } catch (IllegalArgumentException ex) { + System.out.println(ex.getMessage()); + } + System.out.println(); + } + } +} diff --git a/Task/Circles-of-given-radius-through-two-points/Kotlin/circles-of-given-radius-through-two-points.kotlin b/Task/Circles-of-given-radius-through-two-points/Kotlin/circles-of-given-radius-through-two-points.kotlin new file mode 100644 index 0000000000..00657ea2ca --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Kotlin/circles-of-given-radius-through-two-points.kotlin @@ -0,0 +1,64 @@ +// version 1.1.51 + +typealias IAE = IllegalArgumentException + +class Point(val x: Double, val y: Double) { + fun distanceFrom(other: Point): Double { + val dx = x - other.x + val dy = y - other.y + return Math.sqrt(dx * dx + dy * dy ) + } + + override fun equals(other: Any?): Boolean { + if (other == null || other !is Point) return false + return (x == other.x && y == other.y) + } + + override fun toString() = "(%.4f, %.4f)".format(x, y) +} + +fun findCircles(p1: Point, p2: Point, r: Double): Pair { + if (r < 0.0) throw IAE("the radius can't be negative") + if (r == 0.0 && p1 != p2) throw IAE("no circles can ever be drawn") + if (r == 0.0) return p1 to p1 + if (p1 == p2) throw IAE("an infinite number of circles can be drawn") + val distance = p1.distanceFrom(p2) + val diameter = 2.0 * r + if (distance > diameter) throw IAE("the points are too far apart to draw a circle") + val center = Point((p1.x + p2.x) / 2.0, (p1.y + p2.y) / 2.0) + if (distance == diameter) return center to center + val mirrorDistance = Math.sqrt(r * r - distance * distance / 4.0) + val dx = (p2.x - p1.x) * mirrorDistance / distance + val dy = (p2.y - p1.y) * mirrorDistance / distance + return Point(center.x - dy, center.y + dx) to + Point(center.x + dy, center.y - dx) +} + +fun main(args: Array) { + val p = arrayOf( + Point(0.1234, 0.9876), + Point(0.8765, 0.2345), + Point(0.0000, 2.0000), + Point(0.0000, 0.0000) + ) + val points = arrayOf( + p[0] to p[1], p[2] to p[3], p[0] to p[0], p[0] to p[1], p[0] to p[0] + ) + val radii = doubleArrayOf(2.0, 1.0, 2.0, 0.5, 0.0) + for (i in 0..4) { + try { + val (p1, p2) = points[i] + val r = radii[i] + println("For points $p1 and $p2 with radius $r") + val (c1, c2) = findCircles(p1, p2, r) + if (c1 == c2) + println("there is just one circle with center at $c1") + else + println("there are two circles with centers at $c1 and $c2") + } + catch(ex: IllegalArgumentException) { + println(ex.message) + } + println() + } +} diff --git a/Task/Circles-of-given-radius-through-two-points/Modula-2/circles-of-given-radius-through-two-points.mod2 b/Task/Circles-of-given-radius-through-two-points/Modula-2/circles-of-given-radius-through-two-points.mod2 new file mode 100644 index 0000000000..649f531c84 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Modula-2/circles-of-given-radius-through-two-points.mod2 @@ -0,0 +1,118 @@ +MODULE Circles; +FROM EXCEPTIONS IMPORT AllocateSource,ExceptionSource,GetMessage,RAISE; +FROM FormatString IMPORT FormatString; +FROM LongMath IMPORT sqrt; +FROM LongStr IMPORT RealToStr; +FROM Terminal IMPORT WriteString,WriteLn,ReadChar; + +VAR + TextWinExSrc : ExceptionSource; + +TYPE + Point = RECORD + x,y : LONGREAL; + END; + Pair = RECORD + a,b : Point; + END; + +PROCEDURE Distance(p1,p2 : Point) : LONGREAL; +VAR dx,dy : LONGREAL; +BEGIN + dx := p1.x - p2.x; + dy := p1.y - p2.y; + RETURN sqrt(dx*dx + dy*dy) +END Distance; + +PROCEDURE Equal(p1,p2 : Point) : BOOLEAN; +BEGIN + RETURN (p1.x=p2.x) AND (p1.y=p2.y) +END Equal; + +PROCEDURE WritePoint(p : Point); +VAR buf : ARRAY[0..63] OF CHAR; +BEGIN + WriteString("("); + RealToStr(p.x, buf); + WriteString(buf); + WriteString(", "); + RealToStr(p.y, buf); + WriteString(buf); + WriteString(")"); +END WritePoint; + +PROCEDURE FindCircles(p1,p2 : Point; r : LONGREAL) : Pair; +VAR + distance,diameter,mirrorDistance,dx,dy : LONGREAL; + center : Point; +BEGIN + IF r < 0.0 THEN RAISE(TextWinExSrc, 0, "the radius can't be negative") END; + IF (r = 0.0) AND NOT Equal(p1,p2) THEN RAISE(TextWinExSrc, 0, "No circles can ever be drawn") END; + IF r = 0.0 THEN RETURN Pair{p1,p1} END; + IF Equal(p1,p2) THEN RAISE(TextWinExSrc, 0, "an infinite number of circles can be drawn") END; + distance := Distance(p1,p2); + diameter := 2.0 * r; + IF distance > diameter THEN RAISE(TextWinExSrc, 0, "the points are too far apart to draw a circle") END; + center := Point{(p1.x + p2.x) / 2.0, (p1.y + p2.y) / 2.0}; + IF distance = diameter THEN RETURN Pair{center, center} END; + mirrorDistance := sqrt(r * r - distance * distance / 4.0); + dx := (p2.x - p1.x) * mirrorDistance / distance; + dy := (p2.y - p1.y) * mirrorDistance / distance; + RETURN Pair{ + {center.x - dy, center.y + dx}, + {center.x + dy, center.y - dx} + } +END FindCircles; + +PROCEDURE Print(p1,p2 : Point; r : LONGREAL) : BOOLEAN; +VAR + buf : ARRAY[0..63] OF CHAR; + result : Pair; +BEGIN + WriteString("For points "); + WritePoint(p1); + WriteString(" and "); + WritePoint(p2); + WriteString(" with radius "); + RealToStr(r, buf); + WriteString(buf); + WriteLn; + + result := FindCircles(p1,p2,r); + IF Equal(result.a, result.b) THEN + WriteString("there is just one circle with the center at "); + WritePoint(result.a); + WriteLn; + ELSE + WriteString("there are two circles with centers at "); + WritePoint(result.a); + WriteString(" and "); + WritePoint(result.b); + WriteLn; + END; + WriteLn; + RETURN TRUE +EXCEPT + GetMessage(buf); + WriteString(buf); + WriteLn; + WriteLn; + RETURN FALSE +END Print; + +VAR p0,p1,p2,p3 : Point; +BEGIN + AllocateSource(TextWinExSrc); + p0 := Point{0.1234,0.9876}; + p1 := Point{0.8765,0.2345}; + p2 := Point{0.0000,2.0000}; + p3 := Point{0.0000,0.0000}; + + Print(p0,p1,2.0); + Print(p2,p3,1.0); + Print(p0,p0,2.0); + Print(p0,p1,0.5); + Print(p0,p0,0.0); + + ReadChar +END Circles. 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 3b43925b81..6108e284f3 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 @@ -12,19 +12,18 @@ say ' ════════ ════════ ═══════ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ 2circ: procedure; parse arg px py qx qy r .; x=(qx-px)/2; y=(qy-py)/2 - bx=px+x; by=py+y; pb=sqrt(x**2+y**2) + bx=px + x; by=py + y; pb=sqrt(x**2+y**2) if r = 0 then return 'radius of zero yields no circles.' if pb==0 then return 'coincident points give infinite circles.' if pb >r then return 'points are too far apart for the specified radius.' - cb=sqrt(r**2-pb**2); x1=y*cb/pb; y1=x*cb/pb + 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 the # with four decimal digits*/ - if pos(.,f)\==0 then f=strip(f,'T',0) /*strip trailing 0s if decimal point.*/ - return left(strip(f,'T',.), length(_)) /*maybe strip trailing decimal point.*/ +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. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ 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/Circles-of-given-radius-through-two-points/Ring/circles-of-given-radius-through-two-points.ring b/Task/Circles-of-given-radius-through-two-points/Ring/circles-of-given-radius-through-two-points.ring new file mode 100644 index 0000000000..313f656730 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Ring/circles-of-given-radius-through-two-points.ring @@ -0,0 +1,70 @@ +# Project : Circles of given radius through two points +# Date : 2018/01/05 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +decimals(4) +x1 = 0.1234 +y1 = 0.9876 +x2 = 0.8765 +y2 = 0.2345 +r = 2.0 +see "1 : " + x1 + " " + y1 + " " + x2 + " " + y2 + " " + r + nl +twocircles(x1, y1, x2, y2, r) + +x1 = 0.0000 +y1 = 2.0000 +x2 = 0.0000 +y2 = 0.0000 +r = 1.0 +see "2 : " + x1 + " " + y1 + " " + x2 + " " + y2 + " " + r + nl +twocircles(x1, y1, x2, y2, r) + +x1 = 0.1234 +y1 = 0.9876 +x2 = 0.1234 +y2 = 0.9876 +r = 2.0 +see "3 : " + x1 + " " + y1 + " " + x2 + " " + y2 + " " + r + nl +twocircles(x1, y1, x2, y2, r) + +x1 = 0.1234 +y1 = 0.9876 +x2 = 0.8765 +y2 = 0.2345 +r = 0.5 +see "4 : " + x1 + " " + y1 + " " + x2 + " " + y2 + " " + r + nl +twocircles(x1, y1, x2, y2, r) + +x1 = 0.1234 +y1 = 0.9876 +x2 = 0.1234 +y2 = 0.9876 +r= 0.0 +see "5 : " + x1 + " " + y1 + " " + x2 + " " + y2 + " " + r + nl +twocircles(x1, y1, x2, y2, r) + +func twocircles(x1, y1, x2, y2, r) + if x1=x2 and y1=y2 + if r=0 + see "It will be a single point (" + x1 + "," + y1 + ") of radius 0" + nl + nl + return + else + see "There are any number of circles via single point (" + x1 + "," + y1 + ") of radius " + r + nl + nl + return + ok + ok + r2 = sqrt(pow((x1-x2),2)+pow((y1-y2),2))/2 + if r round(-16) + } +} + +var input = [ + [0.1234 + 0.9876i, 0.8765 + 0.2345i, 2.0], + [0.0000 + 2.0000i, 0.0000 + 0.0000i, 1.0], + [0.1234 + 0.9876i, 0.1234 + 0.9876i, 2.0], + [0.1234 + 0.9876i, 0.8765 + 0.2345i, 0.5], + [0.1234 + 0.9876i, 0.1234 + 0.9876i, 0.0], +] + +input.each {|a| + say (a.join(', '), ': ', circles(a...).join(' and ')) +} diff --git a/Task/Circles-of-given-radius-through-two-points/Stata/circles-of-given-radius-through-two-points-1.stata b/Task/Circles-of-given-radius-through-two-points/Stata/circles-of-given-radius-through-two-points-1.stata new file mode 100644 index 0000000000..62ac1cc632 --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Stata/circles-of-given-radius-through-two-points-1.stata @@ -0,0 +1,19 @@ +real matrix centers(real colvector a, real colvector b, real scalar r) { + real matrix rot + real scalar d, u, v + d = norm(b-a) + if (r == 0 | d == 0) { + if (r == 0 & d == 0) { + return((a,a)) + } else { + return(J(2, 2, .)) + } + } else if (d <= 2*r) { + u = d/(2*r) + v = sqrt(1-u^2) + rot = u,-v\v,u + return((rot*(b-a),rot'*(b-a))*r/d:+a) + } else { + return(J(2, 2, .)) + } +} diff --git a/Task/Circles-of-given-radius-through-two-points/Stata/circles-of-given-radius-through-two-points-2.stata b/Task/Circles-of-given-radius-through-two-points/Stata/circles-of-given-radius-through-two-points-2.stata new file mode 100644 index 0000000000..a3437189dd --- /dev/null +++ b/Task/Circles-of-given-radius-through-two-points/Stata/circles-of-given-radius-through-two-points-2.stata @@ -0,0 +1,38 @@ +:a=0.1234\0.9876 +:b=0.8765\0.2345 +: centers(a,b,2) + 1 2 + +-------------------------------+ + 1 | 1.863111802 -.8632118017 | + 2 | 1.974211802 -.7521118017 | + +-------------------------------+ + +: centers((0\2),(0\0),1) + 1 2 + +---------+ + 1 | 0 0 | + 2 | 1 1 | + +---------+ + +: centers(a,a,2) +[symmetric] + 1 2 + +---------+ + 1 | . | + 2 | . . | + +---------+ + +: centers(a,b,0.5) +[symmetric] + 1 2 + +---------+ + 1 | . | + 2 | . . | + +---------+ + +: centers(a,a,0) + 1 2 + +-----------------+ + 1 | .1234 .1234 | + 2 | .9876 .9876 | + +-----------------+ diff --git a/Task/Classes/Elena/classes.elena b/Task/Classes/Elena/classes.elena index 89d9b6fc99..4c35ceab73 100644 --- a/Task/Classes/Elena/classes.elena +++ b/Task/Classes/Elena/classes.elena @@ -14,7 +14,7 @@ class MyClass ] } -program = +public program = [ // instantiate the class var instance := MyClass new. diff --git a/Task/Classes/Julia/classes.julia b/Task/Classes/Julia/classes.julia new file mode 100644 index 0000000000..12b8d6054a --- /dev/null +++ b/Task/Classes/Julia/classes.julia @@ -0,0 +1,20 @@ +abstract type Mammal end +habitat(::Mammal) = "planet Earth" + +struct Whale <: Mammal + mass::Float64 + habitat::String +end +Base.show(io::IO, ::Whale) = print(io, "a whale") +habitat(w::Whale) = w.habitat + +struct Wolf <: Mammal + mass::Float64 +end +Base.show(io::IO, ::Wolf) = print(io, "a wolf") + +arr = [Whale(1000, "ocean"), Wolf(50)] +println("Type of $arr is ", typeof(arr)) +for a in arr + println("Habitat of $a: ", habitat(a)) +end diff --git a/Task/Classes/Processing/classes-1 b/Task/Classes/Processing/classes-1 new file mode 100644 index 0000000000..333396b374 --- /dev/null +++ b/Task/Classes/Processing/classes-1 @@ -0,0 +1,17 @@ +class ProgrammingLanguage +{ + // instance variable: + private String name; + // constructor (let's use it to give the instance variable a value): + public ProgrammingLanguage(String name) + { + this.name = name; + // note use of "this" to distinguish the instance variable from the argument + } + // a method: + public void sayHello() + { + println("Hello from the programming language " + name); + // the method has no argument or local variable called "name", so we can omit the "this" + } +} diff --git a/Task/Classes/Processing/classes-2 b/Task/Classes/Processing/classes-2 new file mode 100644 index 0000000000..bc0bbfc2ed --- /dev/null +++ b/Task/Classes/Processing/classes-2 @@ -0,0 +1,5 @@ +// instantiate the class: +ProgrammingLanguage processing = new ProgrammingLanguage("Processing"); + +// call the method: +processing.sayHello(); diff --git a/Task/Closest-pair-problem/C++/closest-pair-problem.cpp b/Task/Closest-pair-problem/C++/closest-pair-problem.cpp index c855813fed..d0ecaf58ff 100644 --- a/Task/Closest-pair-problem/C++/closest-pair-problem.cpp +++ b/Task/Closest-pair-problem/C++/closest-pair-problem.cpp @@ -50,7 +50,7 @@ std::pair find_closest_optimized(const std::vector& x auto xR = std::vector(); std::copy(std::begin(xP), std::begin(xP) + (N / 2), std::back_inserter(xL)); std::copy(std::begin(xP) + (N / 2), std::end(xP), std::back_inserter(xR)); - auto xM = xP.at(N / 2).first; + auto xM = xP.at((N-1) / 2).first; auto yL = std::vector(); auto yR = std::vector(); std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yL), [&xM](const point_t& p) { diff --git a/Task/Closest-pair-problem/Maple/closest-pair-problem-1.maple b/Task/Closest-pair-problem/Maple/closest-pair-problem-1.maple new file mode 100644 index 0000000000..93d9aeac40 --- /dev/null +++ b/Task/Closest-pair-problem/Maple/closest-pair-problem-1.maple @@ -0,0 +1,70 @@ +ClosestPair := module() + +local + ModuleApply := proc(L::list,$) + local Lx, Ly, out; + Ly := sort(L, 'key'=(i->i[2]), 'output'='permutation'); + Lx := sort(L, 'key'=(i->i[1]), 'output'='permutation'); + out := Recurse(L, Lx, Ly, 1, numelems(L)); + return sqrt(out[1]), out[2]; + end proc; # ModuleApply + +local + BruteForce := proc(L, Lx, r1:=1, r2:=numelems(L), $) + local d, p, n, i, j; + d := infinity; + for i from r1 to r2-1 do + for j from i+1 to r2 do + n := dist( L[Lx[i]], L[Lx[j]] ); + if n < d then + d := n; + p := [ L[Lx[i]], L[Lx[j]] ]; + end if; + end do; # j + end do; # i + return (d, p); + end proc; # BruteForce + +local dist := (p, q)->(( (p[1]-q[1])^2+(p[2]-q[2])^2 )); + +local Recurse := proc(L, Lx, Ly, r1, r2) + local m, xm, rDist, rPair, lDist, lPair, minDist, minPair, S, i, j, Lyr, Lyl; + + if r2-r1 <= 3 then + return BruteForce(L, Lx, r1, r2); + end if; + + m := ceil((r2-r1)/2)+r1; + xm := (L[Lx[m]][1] + L[Lx[m-1]][1])/2; + + (Lyr, Lyl) := selectremove( i->L[i][1] < xm, Ly); + + (rDist, rPair) := thisproc(L, Lx, Lyr, r1, m-1); + (lDist, lPair) := thisproc(L, Lx, Lyl, m, r2); + + if rDist < lDist then + minDist := rDist; + minPair := rPair; + else + minDist := lDist; + minPair := lPair; + end if; + + S := [ seq( `if`(abs(xm - L[i][1])^2< minDist, L[i], NULL ), i in Ly ) ]; + + for i from 1 to nops(S)-1 do + for j from i+1 to nops(S) do + if abs( S[i][2] - S[j][2] )^2 >= minDist then + break; + elif dist(S[i], S[j]) < minDist then + minDist := dist(S[i], S[j]); + minPair := [S[i], S[j]]; + end if; + end do; + end do; + + return (minDist, minPair); + + end proc; #Recurse + +end module; #ClosestPair diff --git a/Task/Closest-pair-problem/Maple/closest-pair-problem-2.maple b/Task/Closest-pair-problem/Maple/closest-pair-problem-2.maple new file mode 100644 index 0000000000..d5baa0477d --- /dev/null +++ b/Task/Closest-pair-problem/Maple/closest-pair-problem-2.maple @@ -0,0 +1,3 @@ +> L := RandomTools:-Generate(list(list(float(range=0..1),2),512)): +> ClosestPair(L); + 0.002576770304, [[0.4265584800, 0.7443097852], [0.4240649736, 0.7449595321]] diff --git a/Task/Closest-pair-problem/Prolog/closest-pair-problem-1.pro b/Task/Closest-pair-problem/Prolog/closest-pair-problem-1.pro new file mode 100644 index 0000000000..be73633c1f --- /dev/null +++ b/Task/Closest-pair-problem/Prolog/closest-pair-problem-1.pro @@ -0,0 +1,30 @@ +% main predicate, find and print closest point +do_find_closest_points(Points) :- + points_closest(Points, points(point(X1,Y1),point(X2,Y2),Dist)), + format('Point 1 : (~p, ~p)~n', [X1,Y1]), + format('Point 1 : (~p, ~p)~n', [X2,Y2]), + format('Distance: ~p~n', [Dist]). + +% Find the distance between two points +distance(point(X1,Y1), point(X2,Y2), points(point(X1,Y1),point(X2,Y2),Dist)) :- + Dx is X2 - X1, + Dy is Y2 - Y1, + Dist is sqrt(Dx * Dx + Dy * Dy). + +% find the closest point that relatest to another point +point_closest(Points, Point, Closest) :- + select(Point, Points, Remaining), + maplist(distance(Point), Remaining, PointList), + foldl(closest, PointList, 0, Closest). + +% find the closest point/dist pair for all points +points_closest(Points, Closest) :- + maplist(point_closest(Points), Points, ClosestPerPoint), + foldl(closest, ClosestPerPoint, 0, Closest). + +% used by foldl to get the lowest point/distance combination +closest(points(P1,P2,Dist), 0, points(P1,P2,Dist)). +closest(points(_,_,Dist), points(P1,P2,Dist2), points(P1,P2,Dist2)) :- + Dist2 < Dist. +closest(points(P1,P2,Dist), points(_,_,Dist2), points(P1,P2,Dist)) :- + Dist =< Dist2. diff --git a/Task/Closest-pair-problem/Prolog/closest-pair-problem-2.pro b/Task/Closest-pair-problem/Prolog/closest-pair-problem-2.pro new file mode 100644 index 0000000000..b38a81cc56 --- /dev/null +++ b/Task/Closest-pair-problem/Prolog/closest-pair-problem-2.pro @@ -0,0 +1,12 @@ +do_find_closest_points([ + point(0.654682, 0.925557), + point(0.409382, 0.619391), + point(0.891663, 0.888594), + point(0.716629, 0.996200), + point(0.477721, 0.946355), + point(0.925092, 0.818220), + point(0.624291, 0.142924), + point(0.211332, 0.221507), + point(0.293786, 0.691701), + point(0.839186, 0.728260) +]). diff --git a/Task/Closest-pair-problem/REXX/closest-pair-problem.rexx b/Task/Closest-pair-problem/REXX/closest-pair-problem.rexx index 2436e35517..7c340d98b7 100644 --- a/Task/Closest-pair-problem/REXX/closest-pair-problem.rexx +++ b/Task/Closest-pair-problem/REXX/closest-pair-problem.rexx @@ -1,32 +1,30 @@ /*REXX program solves the closest pair of points problem (in two dimensions). */ parse arg N low high seed . /*obtain optional arguments from the CL*/ -if N=='' | N=="," then N= 100 /*Not specified? Then use the default.*/ -if low=='' | low=="," then low= 0 /* " " " " " " */ -if high=='' | high=="," then high=20000 /* " " " " " " */ -if datatype(seed,'W') then call random ,,seed /*seed for RANDOM (BIF) repeatability.*/ -w=length(high); w=w + (w//2==0) - /*╔══════════════════════╗*/ do j=1 for N /*generate N random points.*/ - /*║ generate N points. ║*/ @x.j=random(low,high) /* " a random X. */ - /*╚══════════════════════╝*/ @y.j=random(low,high) /* " " " Y. */ - end /*j*/ /*X and Y make the point*/ - A=1; B=2 /* [↓] MINDD is actually the unsquared*/ -minDD=(@x.A-@x.B)**2 + (@y.A-@y.B)**2 /*distance between the first two points*/ +if N=='' | N=="," then N= 100 /*Not specified? Then use the default.*/ +if low=='' | low=="," then low= 0 /* " " " " " " */ +if high=='' | high=="," then high= 20000 /* " " " " " " */ +if datatype(seed, 'W') then call random ,,seed /*seed for RANDOM (BIF) repeatability.*/ +w=length(high); w=w + (w//2==0) /*W: for aligning the output columns.*/ + /*╔══════════════════════╗*/ do j=1 for N /*generate N random points*/ + /*║ generate N points. ║*/ @x.j=random(low, high) /* " a random X */ + /*╚══════════════════════╝*/ @y.j=random(low, high) /* " " " Y */ + end /*j*/ /*X & Y make the point.*/ + A=1; B=2 /* [↓] MINDD is actually the squared*/ +minDD= (@x.A - @x.B)**2 + (@y.A - @y.B)**2 /*distance between the first two points*/ /* [↓] use of XJ & YJ speed things up.*/ - do j=1 for N-1; xj=@x.j; yj=@y.j /*find minimum distance between a ··· */ - do k=j+1 to N /* ··· point and all the other points.*/ - dd=(xj - @x.k)**2 + (yj - @y.k)**2 /*compute squared distance from points.*/ - if dd9; 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/Closest-pair-problem/Racket/closest-pair-problem-2.rkt b/Task/Closest-pair-problem/Racket/closest-pair-problem-2.rkt index 0963cfb6f3..e1719ae279 100644 --- a/Task/Closest-pair-problem/Racket/closest-pair-problem-2.rkt +++ b/Task/Closest-pair-problem/Racket/closest-pair-problem-2.rkt @@ -1,2 +1,97 @@ -Closest points: (0+1i 1+2i) -Distance: 1.4142135623730951 +#lang racket +(struct point (x y) #:transparent) + +(define (closest-pair ps) + (check-type ps) + (cond [(vector? ps) (if (> (vector-length ps) 1) + (closest-pair/sorted (vector-sort ps left?) + (vector-sort ps below?)) + (error 'closest-pair "2 or more points are needed" ps))] + [(sequence? ps) (closest-pair (for/vector ([x (in-sequences ps)]) x))] + [else (error 'closest-pair "closest pair only supports sequence types (excluding hash)")])) + +;; accept any sequence type except hash +;; any other exclusions needed? +(define (check-type ps) + (cond [(hash? ps) (error 'closest-pair "Hash tables are not supported")] + [(sequence? ps) #t] + [else (error 'closest-pair "Only sequence types are supported")])) + +;; vector -> vector -> list +(define (closest-pair/sorted Px Py) + (define L (vector-length Px)) + (cond [(= L 2) (vector->list Px)] + [(= L 3) (apply min-pair (combinations (vector->list Px) 2))] + [else (let*-values ([(Qx Rx) (vector-split-at Px (floor (/ L 2)))] + ; Rx-min is the left most point in Rx + [(Rx-min) (vector-ref Rx 0)] + ; instead of sorting Qx, Rx by y + ; - Qy are members of Py to left of Rx-min + ; - Ry are the remaining members of Py + [(Qy Ry) (vector-partition Py (curryr left? Rx-min))] + [(pair1) (closest-pair/sorted Qx Qy)] + [(pair2) (closest-pair/sorted Rx Ry)] + [(delta) (min (distance^2 pair1) (distance^2 pair2))] + [(pair3) (closest-split-pair Px Py delta)]) + ; pair3 is null when there are no split pairs closer than delta + (min-pair pair1 pair2 pair3))])) + +(define (closest-split-pair Px Py delta) + (define Lp (vector-length Px)) + (define x-mid (point-x (vector-ref Px (floor (/ Lp 2))))) + (define Sy (for/vector ([p (in-vector Py)] + #:when (< (abs (- (point-x p) x-mid)) delta)) + p)) + (define Ls (vector-length Sy)) + (define-values (_ best-pair) + (for*/fold ([new-best delta] + [new-best-pair null]) + ([i (in-range (sub1 Ls))] + [j (in-range (+ i 1) (min (+ i 7) Ls))] + [Sij (in-value (list (vector-ref Sy i) + (vector-ref Sy j)))] + [dij (in-value (distance^2 Sij))] + #:when (< dij new-best)) + (values dij Sij))) + best-pair) + +;; helper procedures + +;; same as partition except for vectors +;; it's critical to maintain the relative order of elements +(define (vector-partition Py pred) + (define-values (left right) + (for/fold ([Qy null] + [Ry null]) + ([p (in-vector Py)]) + (if (pred p) + (values (cons p Qy) Ry) + (values Qy (cons p Ry))))) + (values (list->vector (reverse left)) + (list->vector (reverse right)))) + +; is p1 (strictly) left of p2 +(define (left? p1 p2) (< (point-x p1) (point-x p2))) + +; is p1 (strictly) below of p2 +(define (below? p1 p2) (< (point-y p1) (point-y p2))) + +;; return the pair with minimum distance +(define (min-pair . pairs) + (argmin distance^2 pairs)) + +;; pairs are passed around as a list of 2 points +;; distance is only for comparison so no need to use sqrt +(define (distance^2 pair) + (cond [(null? pair) +inf.0] + [else (define a (first pair)) + (define b (second pair)) + (+ (sqr (- (point-x b) (point-x a))) + (sqr (- (point-y b) (point-y a))))])) + +; points on a quadratic curve, shuffled +(define points + (shuffle + (for/list ([ i (in-range 1000)]) (point i (* i i))))) +(match-define (list (point p1x p1y) (point p2x p2y)) (closest-pair points)) +(printf "Closest points on a quadratic curve (~a,~a) (~a,~a)\n" p1x p1y p2x p2y) diff --git a/Task/Closest-pair-problem/Racket/closest-pair-problem-3.rkt b/Task/Closest-pair-problem/Racket/closest-pair-problem-3.rkt new file mode 100644 index 0000000000..d7eb6f2517 --- /dev/null +++ b/Task/Closest-pair-problem/Racket/closest-pair-problem-3.rkt @@ -0,0 +1,4 @@ +Closest points: (0+1i 1+2i) +Distance: 1.4142135623730951 + +Closest points on a quadratic curve (0,0) (1,1) diff --git a/Task/Closest-pair-problem/VBA/closest-pair-problem.vba b/Task/Closest-pair-problem/VBA/closest-pair-problem.vba new file mode 100644 index 0000000000..c119febc6a --- /dev/null +++ b/Task/Closest-pair-problem/VBA/closest-pair-problem.vba @@ -0,0 +1,53 @@ +Option Explicit + +Private Type MyPoint + X As Single + Y As Single +End Type + +Private Type MyPair + p1 As MyPoint + p2 As MyPoint +End Type + +Sub Main() +Dim points() As MyPoint, i As Long, BF As MyPair, d As Single, Nb As Long +Dim T# +Randomize Timer + Nb = 10 + Do + ReDim points(1 To Nb) + For i = 1 To Nb + points(i).X = Rnd * Nb + points(i).Y = Rnd * Nb + Next + d = 1000000000000# +T = Timer + BF = BruteForce(points, d) + Debug.Print "For " & Nb & " points, runtime : " & Timer - T & " sec." + Debug.Print "point 1 : X:" & BF.p1.X & " Y:" & BF.p1.Y + Debug.Print "point 2 : X:" & BF.p2.X & " Y:" & BF.p2.Y + Debug.Print "dist : " & d + Debug.Print "--------------------------------------------------" + Nb = Nb * 10 + Loop While Nb <= 10000 +End Sub + +Private Function BruteForce(p() As MyPoint, mindist As Single) As MyPair +Dim i As Long, j As Long, d As Single, ClosestPair As MyPair + For i = 1 To UBound(p) - 1 + For j = i + 1 To UBound(p) + d = Dist(p(i), p(j)) + If d < mindist Then + mindist = d + ClosestPair.p1 = p(i) + ClosestPair.p2 = p(j) + End If + Next + Next + BruteForce = ClosestPair +End Function + +Private Function Dist(p1 As MyPoint, p2 As MyPoint) As Single + Dist = Sqr((p1.X - p2.X) ^ 2 + (p1.Y - p2.Y) ^ 2) +End Function diff --git a/Task/Closures-Value-capture/Elena/closures-value-capture.elena b/Task/Closures-Value-capture/Elena/closures-value-capture.elena index a56552550c..beab4dfc6d 100644 --- a/Task/Closures-Value-capture/Elena/closures-value-capture.elena +++ b/Task/Closures-Value-capture/Elena/closures-value-capture.elena @@ -1,8 +1,8 @@ import system'routines. -program = +public program = [ - var functions := Array new length:10; populate(:i)( [ ^ i * i ] ). + var functions := Array new(10); populate(:i)( [ ^ i * i ] ). - functions forEach(:func) [ console writeLine(func eval). ]. + functions forEach(:func) [ console writeLine(func()). ]. ]. diff --git a/Task/Closures-Value-capture/R/closures-value-capture-4.r b/Task/Closures-Value-capture/R/closures-value-capture-4.r new file mode 100644 index 0000000000..8a1f9f3d40 --- /dev/null +++ b/Task/Closures-Value-capture/R/closures-value-capture-4.r @@ -0,0 +1 @@ + evalq (x <- x + 1, parent.env(environment())) diff --git a/Task/Closures-Value-capture/R/closures-value-capture-5.r b/Task/Closures-Value-capture/R/closures-value-capture-5.r new file mode 100644 index 0000000000..48a35ec25d --- /dev/null +++ b/Task/Closures-Value-capture/R/closures-value-capture-5.r @@ -0,0 +1 @@ + x <<- x + 1 diff --git a/Task/Closures-Value-capture/REXX/closures-value-capture.rexx b/Task/Closures-Value-capture/REXX/closures-value-capture.rexx index cbcb915db9..1da8302707 100644 --- a/Task/Closures-Value-capture/REXX/closures-value-capture.rexx +++ b/Task/Closures-Value-capture/REXX/closures-value-capture.rexx @@ -1,13 +1,25 @@ /*REXX program has a list of ten functions, each returns its invocation (index) squared.*/ - - do j=1 for 9; ?=random(0, 9) /*invoke random functions nine times.*/ - interpret 'CALL .'? /*invoke a randomly selected function. */ - end /*j*/ /* [↑] the called function has no args*/ - -say 'The tenth invocation of .0 ───► ' .0() +parse arg seed base $ /*obtain optional arguments from the CL*/ +if datatype(seed, 'W') then call random ,,seed /*Not given? Use random start seed. */ +if base=='' | base="," then base=0 /* " " Use a zero─based list. */ +if $='' then $= 8 5 4 9 1 3 2 7 6 0 /* " " Use ordered function list*/ + /*the $ list must contain 10 functions.*/ +say 'the' word("zero one", base+1)'─based list is: ' $ /*show list of functions.*/ + /*BASED must be either 1 or 0. */ +?='.'random(0, 9) /*get a random name of a function. */ +interpret 'CALL' ? /*invoke a randomly selected function. */ +say 'function ' ? " returned " result /*display the value of random function.*/ exit /*stick a fork in it, we're all done. */ -/*───────────────────────────[Below is the closest thing to anonymous functions in REXX]*/ -.0: return .(); .1: return .(); .2: return .(); .3: return .(); .4: return .() -.5: return .(); .6: return .(); .7: return .(); .8: return .(); .9: return .() +/*────────────────────────[Below are the closest things to anonymous functions in REXX].*/ +.0: return .(0) /*function .0 ─── bump its counter. */ +.1: return .(1) /* ' .1 " " " " */ +.2: return .(2) /* ' .2 " " " " */ +.3: return .(3) /* ' .3 " " " " */ +.4: return .(4) /* ' .4 " " " " */ +.5: return .(5) /* ' .5 " " " " */ +.6: return .(6) /* ' .6 " " " " */ +.7: return .(7) /* ' .7 " " " " */ +.8: return .(8) /* ' .8 " " " " */ +.9: return .(9) /* ' .9 " " " " */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -.: if symbol('@')=="LIT" then @=0 /* ◄───handle very 1st invoke*/; @=@+1; return @*@ +.: arg #; _=wordpos(#,$); if _==0 then return 'not in the list.'; return (_-(\base))**2 diff --git a/Task/Closures-Value-capture/Red/closures-value-capture.red b/Task/Closures-Value-capture/Red/closures-value-capture.red new file mode 100644 index 0000000000..f3e60b6dc0 --- /dev/null +++ b/Task/Closures-Value-capture/Red/closures-value-capture.red @@ -0,0 +1,4 @@ +funs: collect [repeat i 10 [keep func [] reduce [i ** 2]]] + +>> funs/7 +== 49 diff --git a/Task/Collections/Elena/collections-1.elena b/Task/Collections/Elena/collections-1.elena index dfa8f709f0..0bd3ea867d 100644 --- a/Task/Collections/Elena/collections-1.elena +++ b/Task/Collections/Elena/collections-1.elena @@ -1,5 +1,11 @@ -// Creates and initializes a new Array +// Constant array var intArray := (1, 2, 3, 4, 5). +// Generic array var stringArr := Array new:5. stringArr[0] := "string". + +// Typified array +Array arr := V(5). +arr[0] := "a". +arr[1] := "b". diff --git a/Task/Collections/Elena/collections-2.elena b/Task/Collections/Elena/collections-2.elena index a4fa63743b..58d128ef16 100644 --- a/Task/Collections/Elena/collections-2.elena +++ b/Task/Collections/Elena/collections-2.elena @@ -1,5 +1,5 @@ //Create and initialize ArrayList -var myAl := ArrayList new; append:"Hello"; append:"World"; append:"!". +var myAl := system'collections'ArrayList new; append:"Hello"; append:"World"; append:"!". //Create and initialize List -var myList := List new; append:"Hello"; append:"World"; append:"!". +var myList := system'collections'List new; append:"Hello"; append:"World"; append:"!". diff --git a/Task/Collections/Elena/collections-3.elena b/Task/Collections/Elena/collections-3.elena index 8f24be9874..cc64ba6c6b 100644 --- a/Task/Collections/Elena/collections-3.elena +++ b/Task/Collections/Elena/collections-3.elena @@ -1,4 +1,4 @@ //Create a dictionary -var dict := Dictionary new. +var dict := system'collections'Dictionary new. dict["Hello"] := "World". dict["Key"] := "Value". diff --git a/Task/Collections/Gambas/collections.gambas b/Task/Collections/Gambas/collections.gambas new file mode 100644 index 0000000000..0640be9bff --- /dev/null +++ b/Task/Collections/Gambas/collections.gambas @@ -0,0 +1,10 @@ +Public Sub Main() +Dim siCount As Short +Dim cCollection As Collection = ["0": "zero", "1": "one", "2": "two", "3": "three", "4": "four", + "5": "five", "6": "six", "7": "seven", "8": "eight", "9": "nine"] + +For siCount = 0 To 9 + Print cCollection[Str(siCount)] +Next + +End diff --git a/Task/Collections/Julia/collections.julia b/Task/Collections/Julia/collections.julia new file mode 100644 index 0000000000..b0521db69d --- /dev/null +++ b/Task/Collections/Julia/collections.julia @@ -0,0 +1,9 @@ +julia> collection = [] +0-element Array{Any,1} + +julia> push!(collection, 1,2,4,7) +4-element Array{Any,1}: + 1 + 2 + 4 + 7 diff --git a/Task/Collections/Perl-6/collections-4.pl6 b/Task/Collections/Perl-6/collections-4.pl6 index 54e6ff9d1f..5ed46f7c27 100644 --- a/Task/Collections/Perl-6/collections-4.pl6 +++ b/Task/Collections/Perl-6/collections-4.pl6 @@ -1,2 +1,3 @@ +class Something { has $.foo; has $.bar }; my $obj = Something.new: foo => 1, bar => 2; my $newobj = $obj but role { has $.baz = 3 } # anonymous mixin diff --git a/Task/Color-of-a-screen-pixel/BaCon/color-of-a-screen-pixel.bacon b/Task/Color-of-a-screen-pixel/BaCon/color-of-a-screen-pixel.bacon new file mode 100644 index 0000000000..4061bac906 --- /dev/null +++ b/Task/Color-of-a-screen-pixel/BaCon/color-of-a-screen-pixel.bacon @@ -0,0 +1,4 @@ +INCLUDE canvas +FULLSCREEN +color = GETINK(100, 100, 4) +WAITKEY diff --git a/Task/Color-of-a-screen-pixel/REXX/color-of-a-screen-pixel.rexx b/Task/Color-of-a-screen-pixel/REXX/color-of-a-screen-pixel.rexx new file mode 100644 index 0000000000..46d64a221c --- /dev/null +++ b/Task/Color-of-a-screen-pixel/REXX/color-of-a-screen-pixel.rexx @@ -0,0 +1,21 @@ +/*REXX program obtains the cursor position (within it's window) and displays it's color.*/ +parse value cursor() with r c . /*get cursor's location in DOS screen. */ + +hue=scrRead(r, c, 1, 'A') /*get color of the cursor's location. */ +if hue=='00'x then color= 'black' /*or dark grey, dark gray. */ +if hue=='01'x then color= 'darkblue' +if hue=='02'x then color= 'darkgreen' +if hue=='03'x then color= 'darkturquoise' /*or dark cyan. */ +if hue=='04'x then color= 'darkred' /*or maroon. */ +if hue=='05'x then color= 'darkmagenta' /*or dark pink. */ +if hue=='06'x then color= 'orange' /*or dark yellow, orage, brown. */ +if hue=='07'x then color= 'gray' /*or grey, gray, dark white. */ +if hue=='08'x then color= 'gray' /*or grey, gray, dark white. */ +if hue=='09'x then color= 'blue' /*or bright blue. */ +if hue=='0A'x then color= 'green' /*or bright green. */ +if hue=='0B'x then color= 'turquoise' /*or bright turquoise, cyan, britecyan.*/ +if hue=='0C'x then color= 'red' /*or bright red. */ +if hue=='0D'x then color= 'magenta' /*or bright magenta, pink, brite pink. */ +if hue=='0E'x then color= 'yellow' /*or bright yellow. */ +if hue=='0F'x then color= 'white' /*or bright, brite white. */ +say 'screen location ('r","c') color is:' color /*display color of char at row, column.*/ diff --git a/Task/Color-of-a-screen-pixel/VBA/color-of-a-screen-pixel.vba b/Task/Color-of-a-screen-pixel/VBA/color-of-a-screen-pixel.vba new file mode 100644 index 0000000000..2db984c946 --- /dev/null +++ b/Task/Color-of-a-screen-pixel/VBA/color-of-a-screen-pixel.vba @@ -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-quantization/Kotlin/color-quantization.kotlin b/Task/Color-quantization/Kotlin/color-quantization.kotlin new file mode 100644 index 0000000000..760f09c852 --- /dev/null +++ b/Task/Color-quantization/Kotlin/color-quantization.kotlin @@ -0,0 +1,41 @@ +// Version 1.2.41 + +import java.io.BufferedReader +import java.io.InputStreamReader + +fun main(args: Array) { + // convert 'frog' to an image which uses only 16 colors, no dithering + val pb = ProcessBuilder( + "convert", + "Quantum_frog.png", + "-dither", + "None", + "-colors", + "16", + "Quantum_frog_16.png" + ) + pb.directory(null) + val proc = pb.start() + proc.waitFor() + + // now show the colors used + val pb2 = ProcessBuilder( + "convert", + "Quantum_frog_16.png", + "-format", + "%c", + "-depth", + "8", + "histogram:info:-" + ) + pb2.directory(null) + pb.redirectOutput(ProcessBuilder.Redirect.PIPE) + val proc2 = pb2.start() + val br = BufferedReader(InputStreamReader(proc2.inputStream)) + var clrNum = 0 + while (true) { + val line = br.readLine() ?: break + System.out.printf("%2d->%s\n", clrNum++, line) + } + br.close() +} diff --git a/Task/Color-quantization/Sidef/color-quantization.sidef b/Task/Color-quantization/Sidef/color-quantization.sidef new file mode 100644 index 0000000000..217e2fed96 --- /dev/null +++ b/Task/Color-quantization/Sidef/color-quantization.sidef @@ -0,0 +1,10 @@ +require('Image::Magick') + +func quantize_image(n = 16, input, output='output.png') { + var im = %O.new + im.Read(input) + im.Quantize(colors => n, dither => 1) # 1 = None + im.Write(output) +} + +quantize_image(input: 'Quantum_frog.png') diff --git a/Task/Colour-bars-Display/Julia/colour-bars-display.julia b/Task/Colour-bars-Display/Julia/colour-bars-display.julia new file mode 100644 index 0000000000..c4b946960c --- /dev/null +++ b/Task/Colour-bars-Display/Julia/colour-bars-display.julia @@ -0,0 +1,11 @@ +using Images + +colors = [colorant"black", colorant"red", colorant"green", colorant"darkblue", + colorant"purple", colorant"blue", colorant"yellow", colorant"white"] +wcol = 60 # width of each color bar +h, w = 150, wcol * length(colors) + 1 +img = Matrix{RGB{N0f8}}(h, w); +for (j, col) in zip(1:wcol:w, colors) + img[:, j:j+wcol] = col +end +save("data/colourbars.jpg", img) diff --git a/Task/Colour-pinstripe-Display/Python/colour-pinstripe-display.py b/Task/Colour-pinstripe-Display/Python/colour-pinstripe-display.py new file mode 100644 index 0000000000..3f5e2e080e --- /dev/null +++ b/Task/Colour-pinstripe-Display/Python/colour-pinstripe-display.py @@ -0,0 +1,34 @@ +from turtle import * + +colors = ["black", "red", "green", "blue", "magenta", "cyan", "yellow", "white"] + +# Middle of screen is 0,0 + +screen = getscreen() + +left_edge = -screen.window_width()//2 + +right_edge = screen.window_width()//2 + +quarter_height = screen.window_height()//4 + +half_height = quarter_height * 2 + +speed("fastest") + +for quarter in range(4): + pensize(quarter+1) + colornum = 0 + + min_y = half_height - ((quarter + 1) * quarter_height) + max_y = half_height - ((quarter) * quarter_height) + + for x in range(left_edge,right_edge,quarter+1): + penup() + pencolor(colors[colornum]) + colornum = (colornum + 1) % len(colors) + setposition(x,min_y) + pendown() + setposition(x,max_y) + +notused = input("Hit enter to continue: ") diff --git a/Task/Colour-pinstripe-Display/Ring/colour-pinstripe-display.ring b/Task/Colour-pinstripe-Display/Ring/colour-pinstripe-display.ring new file mode 100644 index 0000000000..7bc29fdad5 --- /dev/null +++ b/Task/Colour-pinstripe-Display/Ring/colour-pinstripe-display.ring @@ -0,0 +1,66 @@ +# Project : Colour pinstripe/Display +# Date : 2018/01/05 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +load "guilib.ring" + +paint = null + +new qapp + { + win1 = new qwidget() { + setwindowtitle("archimedean spiral") + setgeometry(100,100,500,600) + label1 = new qlabel(win1) { + setgeometry(10,10,400,400) + settext("") + } + new qpushbutton(win1) { + setgeometry(150,500,100,30) + settext("draw") + setclickevent("draw()") + } + show() + } + exec() + } + +func draw + p1 = new qpicture() + color = new qcolor() { + setrgb(0,0,255,255) + } + pen = new qpen() { + setcolor(color) + setwidth(1) + } + paint = new qpainter() { + begin(p1) + setpen(pen) + w = 100 + h = 100 + color = list(8) + color[1] = [0 ,0, 0] + color[2] = [255, 0, 0] + color[3] = [0, 255, 0] + color[4] = [0, 0, 255] + color[5] = [255, 0, 255] + color[6] = [0, 255, 255] + color[7] = [255, 255, 0] + color[8] = [255, 255, 255] + y = h*4 + for p = 1 to 4 + y = y - h + for x = 0 to w step 4*p + col = random(7) + 1 + color2 = new qcolor() + color2.setrgb(color[col][1],color[col][2],color[col][3],255) + mybrush = new qbrush() {setstyle(1) setcolor(color2)} + setbrush(mybrush) + paint.drawrect(x, y, 2*p, h) + next + next + endpaint() + } + label1 { setpicture(p1) show() } diff --git a/Task/Colour-pinstripe-Display/Sidef/colour-pinstripe-display.sidef b/Task/Colour-pinstripe-Display/Sidef/colour-pinstripe-display.sidef new file mode 100644 index 0000000000..51949a972a --- /dev/null +++ b/Task/Colour-pinstripe-Display/Sidef/colour-pinstripe-display.sidef @@ -0,0 +1,30 @@ +require('GD') + +func pinstripes(width = 1280, height = 720) { + + var im = %O.new(width, height) + var colors = [0, 255].variations_with_repetition(3) + + var paintcolors = colors.shuffle.map {|rgb| + im.colorAllocate(rgb...) + } + + var starty = 0 + var barheight = height//4 + + for barwidth in (1..4) { + for ( + var(startx = 0, colorindex = 0); + startx + barwidth <= width; + startx += barwidth + ) { + im.filledRectangle(startx, starty, startx+barwidth, + starty + barheight - 1, paintcolors[colorindex++ % 8]) + } + starty += barheight + } + + return im +} + +File('pinstripes.png').write(pinstripes().png, :raw) diff --git a/Task/Combinations-and-permutations/Common-Lisp/combinations-and-permutations.lisp b/Task/Combinations-and-permutations/Common-Lisp/combinations-and-permutations.lisp index acbc81c7af..48be90ee99 100644 --- a/Task/Combinations-and-permutations/Common-Lisp/combinations-and-permutations.lisp +++ b/Task/Combinations-and-permutations/Common-Lisp/combinations-and-permutations.lisp @@ -1,11 +1,16 @@ (defun combinations (n k) - (let ((num 1) - (den 1) ) - (dotimes (i k (/ num den)) - (setq num (* num (- n i)) den (* den (- k i))) ))) - + (cond ((or (< n k) (< k 0) (< n 0)) 0) + ((= k 0) 1) + (t (do* ((i 1 (1+ i)) + (m n (1- m)) + (a m (* a m)) + (b i (* b i))) + ((= i k) (/ a b)))))) (defun permutations (n k) - (let ((p 1)) - (dotimes (i k p) - (setq p (* p (- n i))) ))) + (cond ((or (< n k) (< k 0) (< n 0)) 0) + ((= k 0) 1) + (t (do* ((i 1 (1+ i)) + (m n (1- m)) + (a m (* a m))) + ((= i k) a))))) diff --git a/Task/Combinations-and-permutations/Go/combinations-and-permutations.go b/Task/Combinations-and-permutations/Go/combinations-and-permutations.go new file mode 100644 index 0000000000..9f9d5f3c2b --- /dev/null +++ b/Task/Combinations-and-permutations/Go/combinations-and-permutations.go @@ -0,0 +1,64 @@ +package main + +import ( + "fmt" + "math/big" +) + +func main() { + var n, p int64 + fmt.Printf("A sample of permutations from 1 to 12:\n") + for n = 1; n < 13; n++ { + p = n / 3 + fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p))) + } + fmt.Printf("\nA sample of combinations from 10 to 60:\n") + for n = 10; n < 61; n += 10 { + p = n / 3 + fmt.Printf("C(%d,%d) = %d\n", n, p, comb(big.NewInt(n), big.NewInt(p))) + } + fmt.Printf("\nA sample of permutations from 5 to 15000:\n") + nArr := [...]int64{5, 50, 500, 1000, 5000, 15000} + for _, n = range nArr { + p = n / 3 + fmt.Printf("P(%d,%d) = %d\n", n, p, perm(big.NewInt(n), big.NewInt(p))) + } + fmt.Printf("\nA sample of combinations from 100 to 1000:\n") + for n = 100; n < 1001; n += 100 { + p = n / 3 + fmt.Printf("C(%d,%d) = %d\n", n, p, comb(big.NewInt(n), big.NewInt(p))) + } +} + +func fact(n *big.Int) *big.Int { + if n.Sign() < 1 { + return big.NewInt(0) + } + r := big.NewInt(1) + i := big.NewInt(2) + for i.Cmp(n) < 1 { + r.Mul(r, i) + i.Add(i, big.NewInt(1)) + } + return r +} + +func perm(n, k *big.Int) *big.Int { + r := fact(n) + r.Div(r, fact(n.Sub(n, k))) + return r +} + +func comb(n, r *big.Int) *big.Int { + if r.Cmp(n) == 1 { + return big.NewInt(0) + } + if r.Cmp(n) == 0 { + return big.NewInt(1) + } + c := fact(n) + den := fact(n.Sub(n, r)) + den.Mul(den, fact(r)) + c.Div(c, den) + return c +} diff --git a/Task/Combinations-and-permutations/Stata/combinations-and-permutations.stata b/Task/Combinations-and-permutations/Stata/combinations-and-permutations.stata new file mode 100644 index 0000000000..99071839df --- /dev/null +++ b/Task/Combinations-and-permutations/Stata/combinations-and-permutations.stata @@ -0,0 +1,7 @@ +real scalar comb1(n, k) { + return(exp(lnfactorial(n)-lnfactorial(k)-lnfactorial(n-k))) +} + +real scalar perm(n, k) { + return(exp(lnfactorial(n)-lnfactorial(n-k))) +} diff --git a/Task/Combinations-with-repetitions/Common-Lisp/combinations-with-repetitions.lisp b/Task/Combinations-with-repetitions/Common-Lisp/combinations-with-repetitions.lisp new file mode 100644 index 0000000000..f19d507f92 --- /dev/null +++ b/Task/Combinations-with-repetitions/Common-Lisp/combinations-with-repetitions.lisp @@ -0,0 +1,8 @@ +(defun combinations (xs k) + (let ((x (car xs))) + (cond + ((null xs) nil) + ((= k 1) (mapcar #'list xs)) + (t (append (mapcar (lambda (ys) (cons x ys)) + (combinations xs (1- k))) + (combinations (cdr xs) k)))))) diff --git a/Task/Combinations-with-repetitions/Julia/combinations-with-repetitions.julia b/Task/Combinations-with-repetitions/Julia/combinations-with-repetitions.julia index 0189960c13..c7db19db50 100644 --- a/Task/Combinations-with-repetitions/Julia/combinations-with-repetitions.julia +++ b/Task/Combinations-with-repetitions/Julia/combinations-with-repetitions.julia @@ -1,4 +1,9 @@ -function combos_with_replacement(list, k) - n = length(list) - [[list[c[i]-i+1] for i=1:length(c)] for c in combinations([1:(n+k-1)],k)] +using Combinatorics + +l = ["iced", "jam", "plain"] +println("List: ", l, "\nCombinations:") +for c in with_replacement_combinations(l, 2) + println(c) end + +@show length(with_replacement_combinations(1:10, 3)) diff --git a/Task/Combinations-with-repetitions/REXX/combinations-with-repetitions-1.rexx b/Task/Combinations-with-repetitions/REXX/combinations-with-repetitions-1.rexx index 0f207aa6e7..ba5df8417f 100644 --- a/Task/Combinations-with-repetitions/REXX/combinations-with-repetitions-1.rexx +++ b/Task/Combinations-with-repetitions/REXX/combinations-with-repetitions-1.rexx @@ -1,21 +1,20 @@ -/*REXX pgm displays combination sets (with repetitions) for X things taken Y at a time.*/ -call RcombN 3, 2, 'iced,jam,plain' /*The 1st part of Rosetta Code task. */ -call RcombN -10, 3, 'Iced,jam,plain' /* " 2nd " " " " " */ +/*REXX pgm displays combination sets with repetitions for X things taken Y at a time*/ +call RcombN 3, 2, 'iced jam plain' /*The 1st part of Rosetta Code task. */ +call RcombN -10, 3, 'Iced jam plain' /* " 2nd " " " " " */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -RcombN: procedure; parse arg x,y,syms; tell= x>0; x=abs(x); z=x+1; pad=copies('─', 15) - syms=translate(syms, , ',') /*split symbols. */ - say pad x 'doughnut selection taken' y "at a time:" /*display title. */ - do i=1 for words(syms); $.i=word(syms, i) /*assign symbol. */ +RcombN: procedure; parse arg x,y,syms; tell= x>0; x=abs(x); z=x+1 /*X>0? Show combo*/ + say copies('─',15) x "doughnut selection taken" y 'at a time:' /*display title. */ + do i=1 for words(syms); $.i=word(syms, i) /*assign symbols.*/ end /*i*/ @.=1 /*assign default.*/ - do #=1; if tell then call show /*display combos?*/ - @.y=@.y+1; if @.y==z then if .(y-1) then leave /* ◄─── recursive*/ + do #=1; if tell then call show /*display combos?*/ + @.y=@.y + 1; if @.y==z then if .(y-1) then leave /* ◄─── recursive*/ end /*#*/ - say pad # 'combinations.'; say; say; say /*display answer.*/ - return /* [↑] and blanks*/ + say copies('═',15) # "combinations."; say; say /*display answer.*/ + return /*──────────────────────────────────────────────────────────────────────────────────────*/ -.: procedure expose @. y z; parse arg ?; if ?==0 then return 1; p=@.?+1 - if p==z then return .(?-1); do i=? to y; @.i=p; end /*i*/; return 0 +.: procedure expose @. y z; parse arg ?; if ?==0 then return 1; p=@.? +1 + if p==z then return .(? -1); do j=? to y; @.j=p; end /*j*/; return 0 /*──────────────────────────────────────────────────────────────────────────────────────*/ show: L=; do c=1 for y; _=@.c; L=L $._; end /*c*/; say L; return diff --git a/Task/Combinations-with-repetitions/Ring/combinations-with-repetitions.ring b/Task/Combinations-with-repetitions/Ring/combinations-with-repetitions.ring new file mode 100644 index 0000000000..6297379cca --- /dev/null +++ b/Task/Combinations-with-repetitions/Ring/combinations-with-repetitions.ring @@ -0,0 +1,66 @@ +# Project : Combinations with repetitions +# Date : 2017/10/29 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +n = 2 +k = 3 +temp = [] +comb = [] +num = com(n, k) +combinations(n, k) +comb = sortfirst(comb, 1) +see showarray(comb) + nl + +func combinations(n, k) +while true + temp = [] + for nr = 1 to k + tm = random(n-1) + 1 + add(temp, tm) + next + add(comb, temp) + for p = 1 to len(comb) - 1 + for q = p + 1 to len(comb) + if (comb[p][1] = comb[q][1]) and (comb[p][2] = comb[q][2]) and (comb[p][3] = comb[q][3]) + del(comb, p) + ok + next + next + if len(comb) = num + exit + ok +end + +func com(n, k) + res = pow(n, k) + return res + +func showarray(vect) + svect = "" + for nrs = 1 to len(vect) + svect = "[" + vect[nrs][1] + " " + vect[nrs][2] + " " + vect[nrs][3] + "]" + nl + see svect + next + +Func sortfirst(alist, ind) + aList = sort(aList,ind) + for n = 1 to len(alist)-1 + for m= n + 1 to len(aList) + if alist[n][1] = alist[m][1] and alist[m][2] < alist[n][2] + temp = alist[n] + alist[n] = alist[m] + alist[m] = temp + ok + next + next + for n = 1 to len(alist)-1 + for m= n + 1 to len(aList) + if alist[n][1] = alist[m][1] and alist[n][2] = alist[m][2] and alist[m][3] < alist[n][3] + temp = alist[n] + alist[n] = alist[m] + alist[m] = temp + ok + next + next + return aList diff --git a/Task/Combinations-with-repetitions/Stata/combinations-with-repetitions.stata b/Task/Combinations-with-repetitions/Stata/combinations-with-repetitions.stata new file mode 100644 index 0000000000..db95cc2feb --- /dev/null +++ b/Task/Combinations-with-repetitions/Stata/combinations-with-repetitions.stata @@ -0,0 +1,19 @@ +function combrep(v,k) { + n = cols(v) + a = J(comb(n+k-1,k),k,v[1]) + u = J(1,k,1) + for (i=2; 1; i++) { + for (j=k; j>0; j--) { + if (u[j]( n ) ]. -program = +public program = [ - var aNumbers := numbers eval:N. + var aNumbers := numbers(N). Combinator new:M of:aNumbers; forEach(:aRow) [ - console printLine:aRow + console printLine(aRow toLiteral) ]. console readChar. diff --git a/Task/Combinations/Glee/combinations-1.glee b/Task/Combinations/Glee/combinations-1.glee new file mode 100644 index 0000000000..c804ecac80 --- /dev/null +++ b/Task/Combinations/Glee/combinations-1.glee @@ -0,0 +1,5 @@ +5!3 >>> ,,\ + +$$(5!3) give all combinations of 3 out of 5 +$$(>>>) sorted up, +$$(,,\) printed with crlf delimiters. diff --git a/Task/Combinations/Glee/combinations-2.glee b/Task/Combinations/Glee/combinations-2.glee new file mode 100644 index 0000000000..cc9a8663c2 --- /dev/null +++ b/Task/Combinations/Glee/combinations-2.glee @@ -0,0 +1,11 @@ +Result: +1 2 3 +1 2 4 +1 2 5 +1 3 4 +1 3 5 +1 4 5 +2 3 4 +2 3 5 +2 4 5 +3 4 5 diff --git a/Task/Combinations/Julia/combinations.julia b/Task/Combinations/Julia/combinations-1.julia similarity index 100% rename from Task/Combinations/Julia/combinations.julia rename to Task/Combinations/Julia/combinations-1.julia diff --git a/Task/Combinations/Julia/combinations-2.julia b/Task/Combinations/Julia/combinations-2.julia new file mode 100644 index 0000000000..c63e0df482 --- /dev/null +++ b/Task/Combinations/Julia/combinations-2.julia @@ -0,0 +1,27 @@ +############################## +# COMBINATIONS OF 3 OUT OF 5 # +############################## + +# Set n and m +m = 5 +n = 3 + +# Prepare the boundary of the calculation. Only m - n numbers are changing in each position. +max_n = m - n + +#Prepare an array for result +result = zeros(Int64, n) + +function combinations(pos, val) # n, max_n and result are visible in the function + for i = val:max_n # from current value to the boundary + result[pos] = pos + i # fill the position of result + if pos < n # if combination isn't complete, + combinations(pos+1, i) # go to the next position + else + println(result) # combination is complete, print it + end + end +end + +combinations(1, 0) +end diff --git a/Task/Combinations/Modula-2/combinations.mod2 b/Task/Combinations/Modula-2/combinations.mod2 new file mode 100644 index 0000000000..66861d8446 --- /dev/null +++ b/Task/Combinations/Modula-2/combinations.mod2 @@ -0,0 +1,36 @@ +MODULE Combinations; +FROM STextIO IMPORT + WriteString, WriteLn; +FROM SWholeIO IMPORT + WriteInt; + +CONST + MMax = 3; + NMax = 5; + +VAR + Combination: ARRAY [0 .. MMax] OF CARDINAL; + +PROCEDURE Generate(M: CARDINAL); +VAR + N, I: CARDINAL; +BEGIN + IF (M > MMax) THEN + FOR I := 1 TO MMax DO + WriteInt(Combination[I], 1); + WriteString(' '); + END; + WriteLn; + ELSE + FOR N := 1 TO NMax DO + IF (M = 1) OR (N > Combination[M - 1]) THEN + Combination[M] := N; + Generate(M + 1); + END + END + END +END Generate; + +BEGIN + Generate(1); +END Combinations. diff --git a/Task/Combinations/PHP/combinations-1.php b/Task/Combinations/PHP/combinations-1.php index b16134bdd0..d6bc7fa29d 100644 --- a/Task/Combinations/PHP/combinations-1.php +++ b/Task/Combinations/PHP/combinations-1.php @@ -1,6 +1,5 @@ + +n = 5 +k = 3 +temp = [] +comb = [] +num = com(n, k) +while true + temp = [] + for n = 1 to 3 + tm = random(4) + 1 + add(temp, tm) + next + bool1 = (temp[1] = temp[2]) and (temp[1] = temp[3]) and (temp[2] = temp[3]) + bool2 = (temp[1] < temp[2]) and (temp[2] < temp[3]) + if not bool1 and bool2 + add(comb, temp) + ok + for p = 1 to len(comb) - 1 + for q = p + 1 to len(comb) + if (comb[p][1] = comb[q][1]) and (comb[p][2] = comb[q][2]) and (comb[p][3] = comb[q][3]) + del(comb, p) + ok + next + next + if len(comb) = num + exit + ok +end +comb = sortfirst(comb, 1) +see showarray(comb) + nl + +func com(n, k) + res1 = 1 + for n1 = n - k + 1 to n + res1 = res1 * n1 + next + res2 = 1 + for n2 = 1 to k + res2 = res2 * n2 + next + res3 = res1/res2 + return res3 + +func showarray(vect) + svect = "" + for nrs = 1 to len(vect) + svect = "[" + vect[nrs][1] + " " + vect[nrs][2] + " " + vect[nrs][3] + "]" + nl + see svect + next + +Func sortfirst(alist, ind) + aList = sort(aList,ind) + for n = 1 to len(alist)-1 + for m= n + 1 to len(aList) + if alist[n][1] = alist[m][1] and alist[m][2] < alist[n][2] + temp = alist[n] + alist[n] = alist[m] + alist[m] = temp + ok + next + next + for n = 1 to len(alist)-1 + for m= n + 1 to len(aList) + if alist[n][1] = alist[m][1] and alist[n][2] = alist[m][2] and alist[m][3] < alist[n][3] + temp = alist[n] + alist[n] = alist[m] + alist[m] = temp + ok + next + next + return aList diff --git a/Task/Combinations/Scala/combinations-4.scala b/Task/Combinations/Scala/combinations-4.scala index 10bc260850..7984df106d 100644 --- a/Task/Combinations/Scala/combinations-4.scala +++ b/Task/Combinations/Scala/combinations-4.scala @@ -1,2 +1,2 @@ -scala> (0 to 4 toList) combinations(3) toList -res1: List[List[Int]] = List(List(0, 1, 2), List(0, 1, 3), List(0, 1, 4), List(0, 2, 3), List(0, 2, 4), List(0, 3, 4), List(1, 2, 3), List(1, 2, 4), List(1, 3, 4), List(2, 3, 4)) +scala>(0 to 4).combinations(3).toList +res0: List[scala.collection.immutable.IndexedSeq[Int]] = List(Vector(0, 1, 2), Vector(0, 1, 3), Vector(0, 1, 4), Vector(0, 2, 3), Vector(0, 2, 4), Vector(0, 3, 4), Vector(1, 2, 3), Vector(1, 2, 4), Vector(1, 3, 4), Vector(2, 3, 4)) diff --git a/Task/Combinations/Stata/combinations-3.stata b/Task/Combinations/Stata/combinations-3.stata new file mode 100644 index 0000000000..87a838e53b --- /dev/null +++ b/Task/Combinations/Stata/combinations-3.stata @@ -0,0 +1,14 @@ +function combinations(n,k) { + a = J(comb(n,k),k,.) + u = 1..k + for (i=1; 1; i++) { + a[i,.] = u + for (j=k; j>0; j--) { + if (u[j]-j 0 Then ReDim MyArr(M) 'Case Option Base 1 + For i = LBound(MyArr) To UBound(MyArr) + MyArr(i) = i + Next i + i = IIf(LBound(MyArr) > 0, N, N - 1) + ReDim ArrResult(i, LBound(MyArr)) + Combine MyArr, N, LBound(MyArr), LBound(MyArr) + ReDim Preserve ArrResult(UBound(ArrResult, 1), UBound(ArrResult, 2) - 1) + 'In VBA Excel we can use Application.Transpose instead of personal Function Transposition + ArrResult = Transposition(ArrResult) +End Sub + +Private Sub Combine(MyArr As Variant, Nb As Long, Deb As Long, Ind As Long) +Dim i As Long, j As Long, N As Long + For i = Deb To UBound(MyArr, 1) + ArrResult(Ind, UBound(ArrResult, 2)) = MyArr(i) + N = IIf(LBound(ArrResult, 1) = 0, Nb - 1, Nb) + If Ind = N Then + ReDim Preserve ArrResult(UBound(ArrResult, 1), UBound(ArrResult, 2) + 1) + For j = LBound(ArrResult, 1) To UBound(ArrResult, 1) + ArrResult(j, UBound(ArrResult, 2)) = ArrResult(j, UBound(ArrResult, 2) - 1) + Next j + Else + Call Combine(MyArr, Nb, i + 1, Ind + 1) + End If + Next i +End Sub + +Private Function Transposition(ByRef MyArr As Variant) As Variant +Dim T, i As Long, j As Long + ReDim T(LBound(MyArr, 2) To UBound(MyArr, 2), LBound(MyArr, 1) To UBound(MyArr, 1)) + For i = LBound(MyArr, 1) To UBound(MyArr, 1) + For j = LBound(MyArr, 2) To UBound(MyArr, 2) + T(j, i) = MyArr(i, j) + Next j + Next i + Transposition = T + Erase T +End Function diff --git a/Task/Comma-quibbling/Astro/comma-quibbling.astro b/Task/Comma-quibbling/Astro/comma-quibbling.astro index 6c2216ce1f..19e849afd0 100644 --- a/Task/Comma-quibbling/Astro/comma-quibbling.astro +++ b/Task/Comma-quibbling/Astro/comma-quibbling.astro @@ -1,11 +1,6 @@ -fun commaQuibble(s): - result = "" - for (i, c) in enumerate(s): - if i > 0: - result += ", " if i < s[!0] else "and " - result += c - result = "{ $result }" +fun quibble(s): + let result = ' and '.join(s).replace(/ and /, ', ', len(s) - 1) + "{ $result }" -var s = [ [] ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"] ] - -for i in s: print commaQuibble i +let s = [ [] ["ABC"] ["ABC", "DEF"] ["ABC", "DEF", "G", "H"] ] +for i in s: print(quibble i) diff --git a/Task/Comma-quibbling/Factor/comma-quibbling.factor b/Task/Comma-quibbling/Factor/comma-quibbling.factor new file mode 100644 index 0000000000..e0bd3b6ad0 --- /dev/null +++ b/Task/Comma-quibbling/Factor/comma-quibbling.factor @@ -0,0 +1,20 @@ +USING: arrays combinators io kernel qw sequences ; +IN: rosetta-code.comma-quibble + +: wrap ( str -- {str} ) "{" prepend "}" append ; +: quibble-pair ( seq -- str ) " and " join wrap ; +: quibble-list ( seq -- str ) + [ but-last ] [ last ] bi [ ", " join ] dip 2array + quibble-pair ; +: comma-quibble ( seq -- ) dup length +{ + { 0 [ drop "{}" ] } + { 1 [ first wrap ] } + { 2 [ quibble-pair ] } + [ drop quibble-list ] +} case print ; + +{ } comma-quibble +qw{ ABC } comma-quibble +qw{ ABC DEF } comma-quibble +qw{ ABC DEF G H } comma-quibble diff --git a/Task/Comma-quibbling/Julia/comma-quibbling.julia b/Task/Comma-quibbling/Julia/comma-quibbling.julia index 3e6b4561c7..5bff41239b 100644 --- a/Task/Comma-quibbling/Julia/comma-quibbling.julia +++ b/Task/Comma-quibbling/Julia/comma-quibbling.julia @@ -1,4 +1,10 @@ -quibble(words) = - "{"* (isempty(words) ? "" : - length(words)==1? words[1] : - join(words[1:end-1],", ")*" and "*words[end]) *"}" +function quibble(arr::Array) + if isempty(arr) rst = "" else rst = "$(arr[end])" end + if length(arr) > 1 rst = join(arr[1:end-1], ", ") * " and " * rst end + return "{" * rst * "}" +end + +@show quibble([]) +@show quibble(["ABC"]) +@show quibble(["ABC", "DEF"]) +@show quibble(["ABC", "DEF", "G", "H"]) diff --git a/Task/Comma-quibbling/OCaml/comma-quibbling-1.ocaml b/Task/Comma-quibbling/OCaml/comma-quibbling-1.ocaml new file mode 100644 index 0000000000..a9b5269b09 --- /dev/null +++ b/Task/Comma-quibbling/OCaml/comma-quibbling-1.ocaml @@ -0,0 +1,17 @@ +open Printf + +let quibble list = + let rec aux = function + | a :: b :: c :: d :: rest -> a ^ ", " ^ aux (b :: c :: d :: rest) + | [a; b; c] -> sprintf "%s, %s and %s}" a b c + | [a; b] -> sprintf "%s and %s}" a b + | [a] -> sprintf "%s}" a + | [] -> "}" in + "{" ^ aux list + +let test () = + [[]; + ["ABC"]; + ["ABC"; "DEF"]; + ["ABC"; "DEF"; "G"; "H"]] + |> List.iter (fun list -> print_endline (quibble list)) diff --git a/Task/Comma-quibbling/OCaml/comma-quibbling-2.ocaml b/Task/Comma-quibbling/OCaml/comma-quibbling-2.ocaml new file mode 100644 index 0000000000..3498259342 --- /dev/null +++ b/Task/Comma-quibbling/OCaml/comma-quibbling-2.ocaml @@ -0,0 +1,15 @@ +open Core + +let quibble = function + | [| |] -> "{}" + | [| a |] -> sprintf "{%s}" a + | array -> + let last, rest = Array.last array, Array.slice array 0 (-1) in + sprintf "{%s and %s}" (String.concat_array ~sep:", " rest) last + +let test () = + [[||]; + [|"ABC"|]; + [|"ABC"; "DEF"|]; + [|"ABC"; "DEF"; "G"; "H"|]] + |> List.iter ~f:(fun list -> print_endline (quibble list)) diff --git a/Task/Comma-quibbling/Ring/comma-quibbling.ring b/Task/Comma-quibbling/Ring/comma-quibbling.ring new file mode 100644 index 0000000000..3e1e6996f0 --- /dev/null +++ b/Task/Comma-quibbling/Ring/comma-quibbling.ring @@ -0,0 +1,44 @@ +# Project : Comma Quibbling +# Date : 2017/11/12 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +text = list(4) +text[1] = "{}" +text[2] = "ABC" +text[3] = "ABC,DEF" +text[4] = "ABC,DEF,G,H" +comma(text) + +func comma(text) + listtext = [] + for n = 1 to 4 + listtext = str2list(substr(text[n], ",", nl)) + if n = 2 + see "{" + list2str(listtext) + "}" + nl + loop + ok + if len(listtext) = 1 + see "{}" + nl + loop + ok + str = "{" + for m = 1 to len(listtext)-1 + if len(listtext) = 2 + str = str + listtext[m] + " " + else + str = str + listtext[m] + ", " + ok + next + if len(listtext) = 2 + str = left(str, len(str)-1) + else + str = left(str, len(str)-2) + ok + if len(listtext) = 2 + str = str + " " + listtext[len(listtext)] + "}" + else + str = str + " and " + listtext[len(listtext)] + "}" + ok + see str + nl + next diff --git a/Task/Comma-quibbling/VBA/comma-quibbling.vba b/Task/Comma-quibbling/VBA/comma-quibbling.vba new file mode 100644 index 0000000000..c3edb6cdc1 --- /dev/null +++ b/Task/Comma-quibbling/VBA/comma-quibbling.vba @@ -0,0 +1,16 @@ +Option Explicit + +Sub Main() + Debug.Print Quibbling("") + Debug.Print Quibbling("ABC") + Debug.Print Quibbling("ABC, DEF") + Debug.Print Quibbling("ABC, DEF, G, H") + Debug.Print Quibbling("ABC, DEF, G, H, IJKLM, NO, PQRSTUV") +End Sub + +Private Function Quibbling(MyString As String) As String +Dim s As String, n As Integer + s = "{" & MyString & "}": n = InStrRev(s, ",") + If n > 0 Then s = Left(s, n - 1) & " and " & Right(s, Len(s) - (n + 1)) + Quibbling = s +End Function diff --git a/Task/Command-line-arguments/Elena/command-line-arguments.elena b/Task/Command-line-arguments/Elena/command-line-arguments.elena index cce089875e..85a474f03f 100644 --- a/Task/Command-line-arguments/Elena/command-line-arguments.elena +++ b/Task/Command-line-arguments/Elena/command-line-arguments.elena @@ -1,8 +1,8 @@ import system'routines. import extensions. -program = +public program = [ - 'program'arguments forEvery(:i) - [ console printLine("Argument ",i," is ",'program'arguments[i]) ] + program_arguments forEvery(:i) + [ console printLine("Argument ",i," is ",program_arguments[i]) ] ]. diff --git a/Task/Command-line-arguments/JavaScript/command-line-arguments-1.js b/Task/Command-line-arguments/JavaScript/command-line-arguments-1.js index e0e2318a6b..370d7d2df8 100644 --- a/Task/Command-line-arguments/JavaScript/command-line-arguments-1.js +++ b/Task/Command-line-arguments/JavaScript/command-line-arguments-1.js @@ -1,3 +1,3 @@ -var objArgs = WScript.Arguments; -for (var i = 0; i < objArgs.length; i++) - WScript.Echo(objArgs.Item(i)); +process.argv.forEach((val, index) => { + console.log(`${index}: ${val}`); +}); diff --git a/Task/Command-line-arguments/JavaScript/command-line-arguments-2.js b/Task/Command-line-arguments/JavaScript/command-line-arguments-2.js index 41b7a9dead..e0e2318a6b 100644 --- a/Task/Command-line-arguments/JavaScript/command-line-arguments-2.js +++ b/Task/Command-line-arguments/JavaScript/command-line-arguments-2.js @@ -1,4 +1,3 @@ -import System; -var argv:String[] = Environment.GetCommandLineArgs(); -for (var i in argv) - print(argv[i]); +var objArgs = WScript.Arguments; +for (var i = 0; i < objArgs.length; i++) + WScript.Echo(objArgs.Item(i)); diff --git a/Task/Command-line-arguments/JavaScript/command-line-arguments-3.js b/Task/Command-line-arguments/JavaScript/command-line-arguments-3.js index 7cc09fefe4..41b7a9dead 100644 --- a/Task/Command-line-arguments/JavaScript/command-line-arguments-3.js +++ b/Task/Command-line-arguments/JavaScript/command-line-arguments-3.js @@ -1,2 +1,4 @@ -for (var i = 0; i < arguments.length; i++) - print(arguments[i]); +import System; +var argv:String[] = Environment.GetCommandLineArgs(); +for (var i in argv) + print(argv[i]); diff --git a/Task/Command-line-arguments/JavaScript/command-line-arguments-4.js b/Task/Command-line-arguments/JavaScript/command-line-arguments-4.js new file mode 100644 index 0000000000..7cc09fefe4 --- /dev/null +++ b/Task/Command-line-arguments/JavaScript/command-line-arguments-4.js @@ -0,0 +1,2 @@ +for (var i = 0; i < arguments.length; i++) + print(arguments[i]); diff --git a/Task/Command-line-arguments/Klong/command-line-arguments.klong b/Task/Command-line-arguments/Klong/command-line-arguments.klong new file mode 100644 index 0000000000..69efff8b63 --- /dev/null +++ b/Task/Command-line-arguments/Klong/command-line-arguments.klong @@ -0,0 +1 @@ +.p'.a diff --git a/Task/Comments/ARM-Assembly/comments.arm b/Task/Comments/ARM-Assembly/comments.arm new file mode 100644 index 0000000000..f644b3131a --- /dev/null +++ b/Task/Comments/ARM-Assembly/comments.arm @@ -0,0 +1,8 @@ +/* ARM assembly Raspberry PI comment one line */ +/* comment line 1 + comment line 2 +*/ + + mov r0,#0 @ this comment on end of line + mov r1,#0 // authorized comment +} diff --git a/Task/Comments/Nim/comments.nim b/Task/Comments/Nim/comments.nim index 7d2baad18f..69cf2e3938 100644 --- a/Task/Comments/Nim/comments.nim +++ b/Task/Comments/Nim/comments.nim @@ -1,14 +1,15 @@ -# Nim supports only single-line comments +# Nim supports single-line comments var x = 0 ## Documentation comments start with double hash characters. -var y = 0 ## Comments are a proper part of the syntax and are indentation sensitive. - ## If the next line only consists of a comment piece, it must be aligned - ## either to the preceding one (documentation generator would merge these lines) -## or to the code block (starting a new comment piece). +var y = 0 ## Documentation comments are a proper part of the syntax (they're not discarded by parser, and a real part of AST). - # any misaligned comment line (like this one) would trigger an "invalid indentation" error +#[ +There are also multi-line comments +Everything inside of #[]# is commented. +]# -var z = 0 ## Alternatively you can end the preceding comment piece with a backslash \ - ## to reset alignment to any column you like. - ## See also http://nim-code.org/tut1.html#comments +# You can also discard multiline statements: + +discard """This can be considered as a "comment" too +This is multi-line""" diff --git a/Task/Comments/Simula/comments-3.simula b/Task/Comments/Simula/comments-3.simula new file mode 100644 index 0000000000..0894f4ef33 --- /dev/null +++ b/Task/Comments/Simula/comments-3.simula @@ -0,0 +1 @@ +!OutText("Dying."); !Outimage; !terminate_program; diff --git a/Task/Compare-sorting-algorithms-performance/Kotlin/compare-sorting-algorithms-performance.kotlin b/Task/Compare-sorting-algorithms-performance/Kotlin/compare-sorting-algorithms-performance.kotlin new file mode 100644 index 0000000000..2f39ac1001 --- /dev/null +++ b/Task/Compare-sorting-algorithms-performance/Kotlin/compare-sorting-algorithms-performance.kotlin @@ -0,0 +1,142 @@ +// Version 1.2.31 + +import java.util.Random +import kotlin.system.measureNanoTime + +typealias Sorter = (IntArray) -> Unit + +val rand = Random() + +fun onesSeq(n: Int) = IntArray(n) { 1 } + +fun ascendingSeq(n: Int) = shuffledSeq(n).sorted().toIntArray() + +fun shuffledSeq(n: Int) = IntArray(n) { 1 + rand.nextInt(10 * n) } + +fun bubbleSort(a: IntArray) { + var n = a.size + do { + var n2 = 0 + for (i in 1 until n) { + if (a[i - 1] > a[i]) { + val tmp = a[i] + a[i] = a[i - 1] + a[i - 1] = tmp + n2 = i + } + } + n = n2 + } while (n != 0) +} + +fun insertionSort(a: IntArray) { + for (index in 1 until a.size) { + val value = a[index] + var subIndex = index - 1 + while (subIndex >= 0 && a[subIndex] > value) { + a[subIndex + 1] = a[subIndex] + subIndex-- + } + a[subIndex + 1] = value + } +} + +fun quickSort(a: IntArray) { + fun sorter(first: Int, last: Int) { + if (last - first < 1) return + val pivot = a[first + (last - first) / 2] + var left = first + var right = last + while (left <= right) { + while (a[left] < pivot) left++ + while (a[right] > pivot) right-- + if (left <= right) { + val tmp = a[left] + a[left] = a[right] + a[right] = tmp + left++ + right-- + } + } + if (first < right) sorter(first, right) + if (left < last) sorter(left, last) + } + sorter(0, a.lastIndex) +} + +fun radixSort(a: IntArray) { + val tmp = IntArray(a.size) + for (shift in 31 downTo 0) { + tmp.fill(0) + var j = 0 + for (i in 0 until a.size) { + val move = (a[i] shl shift) >= 0 + val toBeMoved = if (shift == 0) !move else move + if (toBeMoved) + tmp[j++] = a[i] + else { + a[i - j] = a[i] + } + } + for (i in j until tmp.size) tmp[i] = a[i - j] + for (i in 0 until a.size) a[i] = tmp[i] + } +} + +val gaps = listOf(701, 301, 132, 57, 23, 10, 4, 1) // Marcin Ciura's gap sequence + +fun shellSort(a: IntArray) { + for (gap in gaps) { + for (i in gap until a.size) { + val temp = a[i] + var j = i + while (j >= gap && a[j - gap] > temp) { + a[j] = a[j - gap] + j -= gap + } + a[j] = temp + } + } +} + +fun main(args: Array) { + val runs = 10 + val lengths = listOf(1, 10, 100, 1_000, 10_000, 100_000) + val sorts = listOf( + ::bubbleSort, ::insertionSort, ::quickSort, ::radixSort, ::shellSort + ) + + /* allow JVM to compile sort functions before timings start */ + for (sort in sorts) sort(intArrayOf(1)) + + val sortTitles = listOf("Bubble", "Insert", "Quick ", "Radix ", "Shell ") + val seqTitles = listOf("All Ones", "Ascending", "Shuffled") + val totals = List(seqTitles.size) { List(sorts.size) { LongArray(lengths.size) } } + for ((k, n) in lengths.withIndex()) { + val seqs = listOf(onesSeq(n), ascendingSeq(n), shuffledSeq(n)) + repeat(runs) { + for (i in 0 until seqs.size) { + for (j in 0 until sorts.size) { + val seq = seqs[i].copyOf() + totals[i][j][k] += measureNanoTime { sorts[j](seq) } + } + } + } + } + println("All timings in micro-seconds\n") + print("Sequence length") + for (len in lengths) print("%8d ".format(len)) + println("\n") + for (i in 0 until seqTitles.size) { + println(" ${seqTitles[i]}:") + for (j in 0 until sorts.size) { + print(" ${sortTitles[j]} ") + for (k in 0 until lengths.size) { + val time = totals[i][j][k] / runs / 1_000 + print("%8d ".format(time)) + } + println() + } + println("\n") + } +} diff --git a/Task/Compile-time-calculation/Scala/compile-time-calculation.scala b/Task/Compile-time-calculation/Scala/compile-time-calculation.scala new file mode 100644 index 0000000000..22d0e7ecdc --- /dev/null +++ b/Task/Compile-time-calculation/Scala/compile-time-calculation.scala @@ -0,0 +1,7 @@ +object Main extends { + val tenFactorial = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 + + def tenFac = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 + + println(s"10! = $tenFactorial", tenFac) +} diff --git a/Task/Compound-data-type/Elena/compound-data-type.elena b/Task/Compound-data-type/Elena/compound-data-type.elena new file mode 100644 index 0000000000..3677cec90f --- /dev/null +++ b/Task/Compound-data-type/Elena/compound-data-type.elena @@ -0,0 +1,12 @@ +struct Point +{ + int prop x :: _x. + + int prop y :: _y. + + constructor new(IntNumber x, IntNumber y) + [ + _x := x. + _y := y. + ] +} diff --git a/Task/Compound-data-type/Julia/compound-data-type-1.julia b/Task/Compound-data-type/Julia/compound-data-type-1.julia index 6234a7c31c..50d981ab72 100644 --- a/Task/Compound-data-type/Julia/compound-data-type-1.julia +++ b/Task/Compound-data-type/Julia/compound-data-type-1.julia @@ -1,4 +1,4 @@ -type Point{T<:Real} +struct Point{T<:Real} x::T y::T end diff --git a/Task/Compound-data-type/Julia/compound-data-type-2.julia b/Task/Compound-data-type/Julia/compound-data-type-2.julia index 596735b274..44737cca2d 100644 --- a/Task/Compound-data-type/Julia/compound-data-type-2.julia +++ b/Task/Compound-data-type/Julia/compound-data-type-2.julia @@ -1,4 +1,4 @@ -==(u::Point, v::Point) = (u.x == v.x) & (u.y == v.y) --(u::Point) = Point(-u.x, -u.y) -+(u::Point, v::Point) = Point(u.x + v.x, u.y + v.y) --(u::Point, v::Point) = Point(u.x - v.x, u.y - v.y) +Base.:(==)(u::Point, v::Point) = u.x == v.x && u.y == v.y +Base.:-(u::Point) = Point(-u.x, -u.y) +Base.:+(u::Point, v::Point) = Point(u.x + v.x, u.y + v.y) +Base.:-(u::Point, v::Point) = u + (-v) diff --git a/Task/Compound-data-type/Julia/compound-data-type-3.julia b/Task/Compound-data-type/Julia/compound-data-type-3.julia index 29b702b609..e804886c4b 100644 --- a/Task/Compound-data-type/Julia/compound-data-type-3.julia +++ b/Task/Compound-data-type/Julia/compound-data-type-3.julia @@ -1,14 +1,8 @@ -a = Point(1, 2) -b = Point(3, 7) -c = Point(2, 4) - -println("a = ", a) -println("b = ", b) -println("c = ", c) - -println("a + b = ", a+b) -println("-a + b = ", -a+b) -println("a - b = ", a-b) -println("a + b + c = ", a+b+c) -println("a == c ", a == c) -println("a + a == c ", a + a == c) +a, b, c = Point(1, 2), Point(3, 7), Point(2, 4) +@show a b c +@show a + b +@show -a + b +@show a - b +@show a + b + c +@show a == b +@show a + a == c diff --git a/Task/Compound-data-type/Scala/compound-data-type.scala b/Task/Compound-data-type/Scala/compound-data-type.scala index 7642545827..aa01cc8bde 100644 --- a/Task/Compound-data-type/Scala/compound-data-type.scala +++ b/Task/Compound-data-type/Scala/compound-data-type.scala @@ -1,4 +1,4 @@ -case class Point(x:Int=0, y:Int=0) +case class Point(x: Int = 0, y: Int = 0) -val p=Point(1,2) +val p = Point(1, 2) println(p.y) //=> 2 diff --git a/Task/Concurrent-computing/Astro/concurrent-computing.astro b/Task/Concurrent-computing/Astro/concurrent-computing.astro index d050c0423b..0f97524a41 100644 --- a/Task/Concurrent-computing/Astro/concurrent-computing.astro +++ b/Task/Concurrent-computing/Astro/concurrent-computing.astro @@ -1,12 +1,5 @@ -fun main(): - let words = ['Enjoy', 'Rosetta', 'Code'] - random.seed(time.now()) - let q = Chan[Str]() - - for w in words: - run (w:) -> - time.sleep(random()) - q << w - - for i in [:words.size]: - print q +let words = ["Enjoy", "Rosetta", "Code"] +for word in words: + async (word) => + sleep(random()) + print(word) diff --git a/Task/Concurrent-computing/Go/concurrent-computing-1.go b/Task/Concurrent-computing/Go/concurrent-computing-1.go index ee69c491a5..897690ddf5 100644 --- a/Task/Concurrent-computing/Go/concurrent-computing-1.go +++ b/Task/Concurrent-computing/Go/concurrent-computing-1.go @@ -2,19 +2,20 @@ package main import ( "fmt" - "math/rand" + "golang.org/x/exp/rand" "time" ) func main() { words := []string{"Enjoy", "Rosetta", "Code"} - rand.Seed(time.Now().UnixNano()) + seed := uint64(time.Now().UnixNano()) q := make(chan string) - for _, w := range words { - go func(w string) { - time.Sleep(time.Duration(rand.Int63n(1e9))) + for i, w := range words { + go func(w string, seed uint64) { + r := rand.New(rand.NewSource(seed)) + time.Sleep(time.Duration(r.Int63n(1e9))) q <- w - }(w) + }(w, seed+uint64(i)) } for i := 0; i < len(words); i++ { fmt.Println(<-q) diff --git a/Task/Concurrent-computing/Julia/concurrent-computing.julia b/Task/Concurrent-computing/Julia/concurrent-computing.julia new file mode 100644 index 0000000000..12853a0557 --- /dev/null +++ b/Task/Concurrent-computing/Julia/concurrent-computing.julia @@ -0,0 +1,10 @@ +words = ["Enjoy", "Rosetta", "Code"] + +function sleepprint(s) + sleep(rand()) + println(s) +end + +@sync for word in words + @async sleepprint(word) +end diff --git a/Task/Conditional-structures/Astro/conditional-structures.astro b/Task/Conditional-structures/Astro/conditional-structures.astro index d2548d02a9..2d4173ccb0 100644 --- a/Task/Conditional-structures/Astro/conditional-structures.astro +++ b/Task/Conditional-structures/Astro/conditional-structures.astro @@ -1,14 +1,12 @@ -if x == 0: - foo() -elif x == 1: - bar() -elif x == 2: - baz() -else: - qux() +if x == 0: foo() +elif x == 1: bar() +elif x == 2: baz() +else: qux() x -| 0 -> foo() -| 1 -> bar() -| 2 -> baz() -| _ -> qux() +| 0 => foo() +| 1 => bar() +| 2 => baz() +| _ => qux() + +(a) ? b : c diff --git a/Task/Conditional-structures/BASIC256/conditional-structures.basic256 b/Task/Conditional-structures/BASIC256/conditional-structures.basic256 new file mode 100644 index 0000000000..aa907d6931 --- /dev/null +++ b/Task/Conditional-structures/BASIC256/conditional-structures.basic256 @@ -0,0 +1,19 @@ +for i = 0 to 1 + for j = 0 to 1 + print i + print j + if (i) then + if (j) then + print "i is true j is true" + else + print "i is true j is false" + end if + else + if (j) then + print "i is false j is true" + else + print "i is false j is false" + end if + end if + next j +next i diff --git a/Task/Conditional-structures/JCL/conditional-structures-1.jcl b/Task/Conditional-structures/JCL/conditional-structures-1.jcl new file mode 100644 index 0000000000..65847dad8a --- /dev/null +++ b/Task/Conditional-structures/JCL/conditional-structures-1.jcl @@ -0,0 +1,2 @@ + COND=(rcval,relop,step) + relop is a relational opeator : EQ NE GT LT GE LE (= ¬= < > <= >=) diff --git a/Task/Conditional-structures/JCL/conditional-structures-2.jcl b/Task/Conditional-structures/JCL/conditional-structures-2.jcl new file mode 100644 index 0000000000..68c063bd34 --- /dev/null +++ b/Task/Conditional-structures/JCL/conditional-structures-2.jcl @@ -0,0 +1 @@ + if rcval relop step.rc then not execute the current step diff --git a/Task/Conditional-structures/JCL/conditional-structures-3.jcl b/Task/Conditional-structures/JCL/conditional-structures-3.jcl new file mode 100644 index 0000000000..f49b65d73b --- /dev/null +++ b/Task/Conditional-structures/JCL/conditional-structures-3.jcl @@ -0,0 +1 @@ +//STEP6 EXEC PGM=MYPROG,COND=(0,NE,STEP3) diff --git a/Task/Conditional-structures/JCL/conditional-structures-4.jcl b/Task/Conditional-structures/JCL/conditional-structures-4.jcl new file mode 100644 index 0000000000..d90dfc2bb1 --- /dev/null +++ b/Task/Conditional-structures/JCL/conditional-structures-4.jcl @@ -0,0 +1 @@ + COND=((rcval1,relop1,step1),(rcval2,relop2,step2),...) diff --git a/Task/Conditional-structures/JCL/conditional-structures-5.jcl b/Task/Conditional-structures/JCL/conditional-structures-5.jcl new file mode 100644 index 0000000000..c8e97bf6d8 --- /dev/null +++ b/Task/Conditional-structures/JCL/conditional-structures-5.jcl @@ -0,0 +1 @@ + if rcval1 relop1 step1.rc or rcval2 relop2 step2.rc or ... then not execute the current step diff --git a/Task/Conditional-structures/JCL/conditional-structures-6.jcl b/Task/Conditional-structures/JCL/conditional-structures-6.jcl new file mode 100644 index 0000000000..d4dd90c748 --- /dev/null +++ b/Task/Conditional-structures/JCL/conditional-structures-6.jcl @@ -0,0 +1 @@ +//STEP6 EXEC PGM=MYPROG,COND=((4,LE,STEP1),(8,LE,STEP3)) diff --git a/Task/Conditional-structures/Julia/conditional-structures-1.julia b/Task/Conditional-structures/Julia/conditional-structures-1.julia new file mode 100644 index 0000000000..198282e758 --- /dev/null +++ b/Task/Conditional-structures/Julia/conditional-structures-1.julia @@ -0,0 +1,18 @@ +function test(x, y) + if x < y + println("x is less than y") + elseif x > y + println("x is greater than y") + else + println("x is equal to y") + end +end + +julia> test(1, 2) +x is less than y + +julia> test(2, 1) +x is greater than y + +julia> test(1, 1) +x is equal to y diff --git a/Task/Conditional-structures/Julia/conditional-structures-2.julia b/Task/Conditional-structures/Julia/conditional-structures-2.julia new file mode 100644 index 0000000000..88b7073409 --- /dev/null +++ b/Task/Conditional-structures/Julia/conditional-structures-2.julia @@ -0,0 +1 @@ +a ? b : c diff --git a/Task/Conditional-structures/Perl-6/conditional-structures-2.pl6 b/Task/Conditional-structures/Perl-6/conditional-structures-2.pl6 index 9989e8556b..51c2ef6abf 100644 --- a/Task/Conditional-structures/Perl-6/conditional-structures-2.pl6 +++ b/Task/Conditional-structures/Perl-6/conditional-structures-2.pl6 @@ -1,5 +1,5 @@ given lc prompt("Done? ") { when 'yes' { return } when 'no' { next } - default { say "Please answer either yes or not." } + default { say "Please answer either yes or no." } } diff --git a/Task/Conditional-structures/Red/conditional-structures-1.red b/Task/Conditional-structures/Red/conditional-structures-1.red new file mode 100644 index 0000000000..ed577c9e0e --- /dev/null +++ b/Task/Conditional-structures/Red/conditional-structures-1.red @@ -0,0 +1,2 @@ +>> if 10 > 2 [print "ten is bigger"] +ten is bigger diff --git a/Task/Conditional-structures/Red/conditional-structures-2.red b/Task/Conditional-structures/Red/conditional-structures-2.red new file mode 100644 index 0000000000..77605f8b8b --- /dev/null +++ b/Task/Conditional-structures/Red/conditional-structures-2.red @@ -0,0 +1,2 @@ +>> either 3 > 2 [print "Three larger"][print "Nope!"] +Three larger diff --git a/Task/Conditional-structures/Red/conditional-structures-3.red b/Task/Conditional-structures/Red/conditional-structures-3.red new file mode 100644 index 0000000000..938b0290d2 --- /dev/null +++ b/Task/Conditional-structures/Red/conditional-structures-3.red @@ -0,0 +1,22 @@ +n: 50 +case [ + n < 10 [print "small number"] + n < 100 [print "medium number"] + n < 1000 [print "large number"] + true [print "none of these"] +] + +medium number + +;CASE/ALL Prints all that are true +n: 50 +case/all [ + n < 10 [print "small number"] + n < 100 [print "medium number"] + n < 1000 [print "large number"] + true [print "none of these"] +] + +medium number +large number +none of these diff --git a/Task/Conditional-structures/Red/conditional-structures-4.red b/Task/Conditional-structures/Red/conditional-structures-4.red new file mode 100644 index 0000000000..a016eb8281 --- /dev/null +++ b/Task/Conditional-structures/Red/conditional-structures-4.red @@ -0,0 +1,17 @@ +switch "india" [ + "a" [print "string"] + 23 [print "integer"] + "India" [print "The country India"] +] + +The country India + +switch/default "U.S." [ + "a" [print "string"] + 23 [print "integer"] + "India" [print "The country India"] +][ +print "no match" +] + +no match diff --git a/Task/Conditional-structures/Rust/conditional-structures-3.rust b/Task/Conditional-structures/Rust/conditional-structures-3.rust index 3abd45f6cf..22fe0f5a20 100644 --- a/Task/Conditional-structures/Rust/conditional-structures-3.rust +++ b/Task/Conditional-structures/Rust/conditional-structures-3.rust @@ -1,21 +1,21 @@ trait PrintType { - fn print_type(); + fn print_type(&self); } impl PrintType for char { - fn print_type() { + fn print_type(&self) { println!("char"); } } impl PrintType for f64 { - fn print_type() { + fn print_type(&self) { println!("64-bit float"); } } -fn prints_type_of_args(arg1: T, arg2: U) - where T: PrintType +fn prints_type_of_args(arg1: &T, arg2: &U) + where T: PrintType, U: PrintType { arg1.print_type(); @@ -23,6 +23,6 @@ fn prints_type_of_args(arg1: T, arg2: U) } fn main() { - prints_type_of_args('a', 2.0); - prints_type_of_args('a', 'b'); + prints_type_of_args(&'a', &2.0); + prints_type_of_args(&'a', &'b'); } diff --git a/Task/Conditional-structures/Rust/conditional-structures-4.rust b/Task/Conditional-structures/Rust/conditional-structures-4.rust index 62e81ffc75..c5c39e166e 100644 --- a/Task/Conditional-structures/Rust/conditional-structures-4.rust +++ b/Task/Conditional-structures/Rust/conditional-structures-4.rust @@ -1,6 +1,6 @@ if some_conditional { do_stuff(); -} else if some_other_conditional +} else if some_other_conditional { do_other_stuff(); } else { destroy_humanity(); diff --git a/Task/Conditional-structures/Rust/conditional-structures-5.rust b/Task/Conditional-structures/Rust/conditional-structures-5.rust index 94af31436c..3cf9191baa 100644 --- a/Task/Conditional-structures/Rust/conditional-structures-5.rust +++ b/Task/Conditional-structures/Rust/conditional-structures-5.rust @@ -2,8 +2,8 @@ fn some_other_function(p: Option) { match p { Some(Point { x: 0, y: 0 }) => println!("Point is on origin"), Some(Point { x: 0, y: _ }) | Some(Point { x: _, y: 0 }) => println!("Point is on an axis"), - Some(Point {x: a, y: b}) if a == b println!("x and y are the same value"), - Some(Point {x: ref mut a, y: ref b}) if x > 4 && y < 2 => println!("we got a mutable reference to x-value and an immutable reference to y-value."), + Some(Point {x: a, y: b}) if a == b => println!("x and y are the same value"), + Some(Point {x: ref mut a, y: ref b}) if *a > 4 && *b < 2 => println!("we got a mutable reference to x-value and an immutable reference to y-value."), op @ Some(p) => println!("op is the Option while p is the contained Point"), None => println!("We didn't get a point"), } diff --git a/Task/Conditional-structures/Stata/conditional-structures-1.stata b/Task/Conditional-structures/Stata/conditional-structures-1.stata new file mode 100644 index 0000000000..18cd2c2ab2 --- /dev/null +++ b/Task/Conditional-structures/Stata/conditional-structures-1.stata @@ -0,0 +1,11 @@ +clear +set obs 4 +gen a = cond(mod(_n, 2)==1, "A", "B") +list, noobs noheader + + +---+ + | A | + | B | + | A | + | B | + +---+ diff --git a/Task/Conditional-structures/Stata/conditional-structures-2.stata b/Task/Conditional-structures/Stata/conditional-structures-2.stata new file mode 100644 index 0000000000..154f9816cf --- /dev/null +++ b/Task/Conditional-structures/Stata/conditional-structures-2.stata @@ -0,0 +1,34 @@ +program isprime + sca n = `0' + sca p = 1 + if n<5 { + if n!=2 & n!=3 { + sca p = 0 + } + } + else { + if mod(n, 2)==0 { + sca p = 0 + } + else { + sca k=3 + while k*k<=n { + if mod(n, k)==0 { + sca p = 0 + continue, break + } + sca k = k+2 + } + } + } + + if p { + di "`n' is prime." + } + else { + di "`n' is not prime." + } +end + +isprime `=10^12-11' +999999999989 is prime. diff --git a/Task/Conditional-structures/Stata/conditional-structures-3.stata b/Task/Conditional-structures/Stata/conditional-structures-3.stata new file mode 100644 index 0000000000..c2801b8e40 --- /dev/null +++ b/Task/Conditional-structures/Stata/conditional-structures-3.stata @@ -0,0 +1,6 @@ +clear +set obs 100 +count + 100 +count if mod(_n, 3)==0 + 33 diff --git a/Task/Conditional-structures/Stata/conditional-structures-4.stata b/Task/Conditional-structures/Stata/conditional-structures-4.stata new file mode 100644 index 0000000000..81f5068923 --- /dev/null +++ b/Task/Conditional-structures/Stata/conditional-structures-4.stata @@ -0,0 +1,13 @@ +function isprime(n) { + if (n<5) return(n==2 | n==3) + else if (mod(n, 2)==0) return(0) + else { + for (k=3; k*k<=n; k=k+2) { + if (mod(n, k)==0) return(0) + } + return(1) + } +} + +isprime(10^12-11) + 1 diff --git a/Task/Conditional-structures/Stata/conditional-structures-5.stata b/Task/Conditional-structures/Stata/conditional-structures-5.stata new file mode 100644 index 0000000000..2b9d65206a --- /dev/null +++ b/Task/Conditional-structures/Stata/conditional-structures-5.stata @@ -0,0 +1,6 @@ +function fib(n) { + return(n<2 ? n : fib(n-1)+fib(n-2)) +} + +fib(10) + 55 diff --git a/Task/Conditional-structures/VBA/conditional-structures-1.vba b/Task/Conditional-structures/VBA/conditional-structures-1.vba new file mode 100644 index 0000000000..c0d693fa84 --- /dev/null +++ b/Task/Conditional-structures/VBA/conditional-structures-1.vba @@ -0,0 +1,25 @@ +Sub C_S_If() +Dim A$, B$ + + A = "Hello" + B = "World" + 'test + If A = B Then Debug.Print A & " = " & B + 'other syntax + If A = B Then + Debug.Print A & " = " & B + Else + Debug.Print A & " and " & B & " are differents." + End If + 'other syntax + If A = B Then + Debug.Print A & " = " & B + Else: Debug.Print A & " and " & B & " are differents." + End If + 'other syntax + If A = B Then Debug.Print A & " = " & B _ + Else Debug.Print A & " and " & B & " are differents." + 'other syntax + If A = B Then Debug.Print A & " = " & B Else Debug.Print A & " and " & B & " are differents." + If A = B Then Debug.Print A & " = " & B Else: Debug.Print A & " and " & B & " are differents." +End Sub diff --git a/Task/Conditional-structures/VBA/conditional-structures-2.vba b/Task/Conditional-structures/VBA/conditional-structures-2.vba new file mode 100644 index 0000000000..a80ece797c --- /dev/null +++ b/Task/Conditional-structures/VBA/conditional-structures-2.vba @@ -0,0 +1,16 @@ +Sub C_S_ElseIf() +Dim A$, B$ + + A = "Hello" + B = "World" + 'test + If A = B Then Debug.Print A & " = " & B + 'other syntax + If A = B Then + Debug.Print A & " = " & B + ElseIf A > B Then + Debug.Print A & " > " & B + Else + Debug.Print A & " < " & B + End If +End Sub diff --git a/Task/Conditional-structures/VBA/conditional-structures-3.vba b/Task/Conditional-structures/VBA/conditional-structures-3.vba new file mode 100644 index 0000000000..50ddbc38bd --- /dev/null +++ b/Task/Conditional-structures/VBA/conditional-structures-3.vba @@ -0,0 +1,52 @@ +Sub C_S_Select_Case() +'With Strings +Dim A$, C& + + A = "Hello" + Select Case A + Case "World" + Debug.Print "A = World" + Case "Hello" + Debug.Print "A = Hello" + Case Else + Debug.Print "You make a mistake" + End Select +'With numerics + C = 11 + Select Case C + Case Is <= 10 + Debug.Print "C <= 10" + Case Is < 20, Is > 10 + Debug.Print "10 < C < 20" + Case Is >= 20 + Debug.Print "C >= 20" + End Select +'Select Case Boolean + 'With Strings + Select Case False + Case A <> "Hello" + Debug.Print "A = Hello" + Case A Like "*orl*" + Debug.Print "A Not Like *orl*" + Case Else + Debug.Print "You make a mistake" + End Select 'return : "A = Hello" + 'Other conditions's order + Select Case False + Case A Like "*orl*" + Debug.Print "A Not Like *orl*" + Case A <> "Hello" + Debug.Print "A = Hello" + Case Else + Debug.Print "You make a mistake" + End Select 'return : "A Not Like *orl*" + 'With numerics + Select Case True + Case C <= 10 + Debug.Print "C <= 10" + Case C < 20, C > 10 + Debug.Print "10 < C < 20" + Case C >= 20 + Debug.Print "C >= 20" + End Select +End Sub diff --git a/Task/Conditional-structures/VBA/conditional-structures-4.vba b/Task/Conditional-structures/VBA/conditional-structures-4.vba new file mode 100644 index 0000000000..86e9cefc8d --- /dev/null +++ b/Task/Conditional-structures/VBA/conditional-structures-4.vba @@ -0,0 +1,6 @@ +Sub C_S_IIF() + Dim myName + myName = 2 + Debug.Print IIf(myName = 1, "Bryan", "Justin") + 'return : Justin +End Sub diff --git a/Task/Conditional-structures/VBA/conditional-structures-5.vba b/Task/Conditional-structures/VBA/conditional-structures-5.vba new file mode 100644 index 0000000000..6ad4d98ed7 --- /dev/null +++ b/Task/Conditional-structures/VBA/conditional-structures-5.vba @@ -0,0 +1,6 @@ +Sub C_S_Switch() + Dim myName + myName = 2 + Debug.Print Switch(myName = 1, "Bryan", myName = 2, "Justin", myName = 3, "John") + 'return : Justin +End Sub diff --git a/Task/Conditional-structures/Visual-Basic/conditional-structures-1.vb b/Task/Conditional-structures/Visual-Basic/conditional-structures-1.vb new file mode 100644 index 0000000000..068255a406 --- /dev/null +++ b/Task/Conditional-structures/Visual-Basic/conditional-structures-1.vb @@ -0,0 +1,20 @@ +If condition Then + statement +End If + +If condition Then + statement +Else + statement +End If + +If condition1 Then + statement +ElseIf condition2 Then + statement +... +ElseIf conditionN Then + statement +Else + statement +End If diff --git a/Task/Conditional-structures/Visual-Basic/conditional-structures-2.vb b/Task/Conditional-structures/Visual-Basic/conditional-structures-2.vb new file mode 100644 index 0000000000..c7bec70a71 --- /dev/null +++ b/Task/Conditional-structures/Visual-Basic/conditional-structures-2.vb @@ -0,0 +1,3 @@ +If condition Then statement + +If condition Then statement Else statement diff --git a/Task/Conditional-structures/Visual-Basic/conditional-structures-3.vb b/Task/Conditional-structures/Visual-Basic/conditional-structures-3.vb new file mode 100644 index 0000000000..2460e4f1a5 --- /dev/null +++ b/Task/Conditional-structures/Visual-Basic/conditional-structures-3.vb @@ -0,0 +1,19 @@ +Select Case Expression + Case Value1: statement + Case Value2: statement + ... + Case ValueN: statement + Case Else: statement +End Select + +Select Case Expression + Case Value1 + statements + Case Value2 + statements + ... + Case ValueN + statements + Case Else + statements +End Select diff --git a/Task/Conditional-structures/Visual-Basic/conditional-structures-4.vb b/Task/Conditional-structures/Visual-Basic/conditional-structures-4.vb new file mode 100644 index 0000000000..b54fbf6fd2 --- /dev/null +++ b/Task/Conditional-structures/Visual-Basic/conditional-structures-4.vb @@ -0,0 +1 @@ +IIf(expr, then-value, else-value) diff --git a/Task/Conditional-structures/Visual-Basic/conditional-structures-5.vb b/Task/Conditional-structures/Visual-Basic/conditional-structures-5.vb new file mode 100644 index 0000000000..fe3b2db8b7 --- /dev/null +++ b/Task/Conditional-structures/Visual-Basic/conditional-structures-5.vb @@ -0,0 +1,3 @@ + myName = 2 + Debug.Print IIf(myName = 1, "John", "Jack") + 'return : "Jack") diff --git a/Task/Conditional-structures/Visual-Basic/conditional-structures-6.vb b/Task/Conditional-structures/Visual-Basic/conditional-structures-6.vb new file mode 100644 index 0000000000..eceb71119e --- /dev/null +++ b/Task/Conditional-structures/Visual-Basic/conditional-structures-6.vb @@ -0,0 +1 @@ +Switch(expr-1, value-1[, expr-2, value-2 … [, expr-n,value-n]]) diff --git a/Task/Conditional-structures/Visual-Basic/conditional-structures-7.vb b/Task/Conditional-structures/Visual-Basic/conditional-structures-7.vb new file mode 100644 index 0000000000..f081386707 --- /dev/null +++ b/Task/Conditional-structures/Visual-Basic/conditional-structures-7.vb @@ -0,0 +1,3 @@ + myName = 2 + Debug.Print Switch(myName = 1, "James", myName = 2, "Jacob", myName = 3, "Jeremy") + 'return : "Jacob" diff --git a/Task/Constrained-genericity/Julia/constrained-genericity.julia b/Task/Constrained-genericity/Julia/constrained-genericity.julia new file mode 100644 index 0000000000..df10c69396 --- /dev/null +++ b/Task/Constrained-genericity/Julia/constrained-genericity.julia @@ -0,0 +1,19 @@ +abstract type Edible end +eat(::Edible) = "Yum!" + +mutable struct FoodBox{T<:Edible} + food::Vector{T} +end + +struct Carrot <: Edible + variety::AbstractString +end + +struct Brick + volume::Float64 +end + +c = Carrot("Baby") +b = Brick(125.0) +eat(c) +eat(b) diff --git a/Task/Constrained-genericity/Nim/constrained-genericity.nim b/Task/Constrained-genericity/Nim/constrained-genericity.nim index ae6dc252b6..e5065f74f9 100644 --- a/Task/Constrained-genericity/Nim/constrained-genericity.nim +++ b/Task/Constrained-genericity/Nim/constrained-genericity.nim @@ -1,5 +1,5 @@ type - Eatable = generic e + Eatable = concept e eat(e) FoodBox[e: Eatable] = seq[e] diff --git a/Task/Constrained-random-points-on-a-circle/COBOL/constrained-random-points-on-a-circle.cobol b/Task/Constrained-random-points-on-a-circle/COBOL/constrained-random-points-on-a-circle.cobol new file mode 100644 index 0000000000..7af82678f8 --- /dev/null +++ b/Task/Constrained-random-points-on-a-circle/COBOL/constrained-random-points-on-a-circle.cobol @@ -0,0 +1,113 @@ + identification division. + program-id. circle. + environment division. + input-output section. + file-control. + select plot-file assign "circle.txt". + data division. + file section. + fd plot-file report plot. + working-storage section. + 1 binary. + 2 seed pic 9(18). + 2 x pic s9(4). + 2 y pic s9(4). + 2 i pic 9(4). + 2 dot-count pic 9(4) value 0. + 2 dot-count-save pic 9(4) value 0. + 2 temp-points. + 3 pic s9(4) occurs 2. + 2 xy-table. + 3 point-pair occurs 0 to 404 depending dot-count. + 4 x-point pic s9(4). + 4 y-point pic s9(4). + 1 plot-table value all "0". + 2 occurs 31. + 3 dot pic 9 occurs 31. + 1 cur-date-time. + 2 yyyymmdd pic 9(8). + 2 hh pic 9(2). + 2 mm pic 9(2). + 2 ss pic 9(2). + 1 plot-work. + 2 plot-item pic xb occurs 31. + report section. + rd plot. + 1 plot-line type de. + 2 line plus 1. + 3 column is 1 source is plot-work pic x(62). + procedure division. + begin. + perform compute-seed + perform find-all-valid-points + perform shuffle-point-pairs + perform select-100-dots + perform print-dots + stop run + . + + find-all-valid-points. + perform varying x from -15 by 1 until x > +15 + perform varying y from -15 by 1 until y > +15 + if (function sqrt (x ** 2 + y ** 2)) + >= 10 and <= 15 + then + move 1 to dot (x + 16 y + 16) + add 1 to dot-count + compute x-point (dot-count) = x + 16 + compute y-point (dot-count) = y + 16 + end-if + end-perform + end-perform + display "Total points: " dot-count + . + + shuffle-point-pairs. + move dot-count to dot-count-save + compute i = function random (seed) * dot-count + 1 + perform varying dot-count from dot-count by -1 + until dot-count < 2 + move point-pair (i) to temp-points + move point-pair (dot-count) to point-pair (i) + move temp-points to point-pair (dot-count) + compute i = function random * dot-count + 1 + end-perform + move dot-count-save to dot-count + . + + select-100-dots. + perform varying i from 1 by 1 + until i > 100 + compute x = x-point (i) + compute y = y-point (i) + move 2 to dot (x y) + end-perform + . + + print-dots. + open output plot-file + initiate plot + perform varying y from 1 by 1 until y > 31 + move spaces to plot-work + perform varying x from 1 by 1 until x > 31 + if dot (x y) = 2 + move "o" to plot-item (x) + end-if + end-perform + generate plot-line + end-perform + terminate plot + close plot-file + . + + compute-seed. + unstring function current-date into + yyyymmdd hh mm ss + compute seed = + (function integer-of-date (yyyymmdd) * 86400) + compute seed = seed + + (hh * 3600) + (mm * 60) + ss + compute seed = function mod (seed 32768) + . + + end program circle. diff --git a/Task/Constrained-random-points-on-a-circle/Julia/constrained-random-points-on-a-circle.julia b/Task/Constrained-random-points-on-a-circle/Julia/constrained-random-points-on-a-circle.julia index 263e9c2ac0..c784314949 100644 --- a/Task/Constrained-random-points-on-a-circle/Julia/constrained-random-points-on-a-circle.julia +++ b/Task/Constrained-random-points-on-a-circle/Julia/constrained-random-points-on-a-circle.julia @@ -1,18 +1,19 @@ -const LO = 10 -const HI = 15 -const GOAL = 100 - -canvas = falses(2HI+1, 2HI+1) -i = 0 - -while i < GOAL - x = rand(-HI:HI) - y = rand(-HI:HI) - LO^2-1 < x^2 + y^2 < HI^2+1 || continue - i += 1 - canvas[x+HI+1, y+HI+1] = true +function printcircle(lo::Integer, hi::Integer, ndots::Integer; pad::Integer = 2) + canvas = falses(2hi + 1, 2hi + 1) + i = 0 + while i < ndots + x, y = rand(-hi:hi, 2) + if lo ^ 2 - 1 < x ^ 2 + y ^ 2 < hi ^ 2 + 1 + canvas[x + hi + 1, y + hi + 1] = true + i += 1 + end + end + # print + for i in 1:(2hi + 1) + row = map(j -> j ? "\u25cf " : " ", canvas[i, :]) + println(" " ^ pad, join(row)) + end + return canvas end -for i in 1:(2HI+1) - println(" ", join(map(j -> j ? "\u25cf " : " ", canvas[i,:]))) -end +printcircle(10, 15, 100) diff --git a/Task/Constrained-random-points-on-a-circle/Rust/constrained-random-points-on-a-circle.rust b/Task/Constrained-random-points-on-a-circle/Rust/constrained-random-points-on-a-circle.rust new file mode 100644 index 0000000000..a1bca182fd --- /dev/null +++ b/Task/Constrained-random-points-on-a-circle/Rust/constrained-random-points-on-a-circle.rust @@ -0,0 +1,73 @@ +#![feature(inclusive_range_syntax)] + +extern crate rand; + +use rand::Rng; + +const POINTS_N: usize = 100; + +fn generate_point(rng: &mut R) -> (i32, i32) { + loop { + let x = rng.gen_range(-15, 16); // exclusive + let y = rng.gen_range(-15, 16); + + let r2 = x * x + y * y; + if r2 >= 100 && r2 <= 225 { + return (x, y); + } + } +} + +fn filtering_method(rng: &mut R) { + let mut rows = [[" "; 62]; 31]; + + // Generate points + for _ in 0..POINTS_N { + let (x, y) = generate_point(rng); + rows[(y + 15) as usize][(x + 15) as usize * 2] = "*"; + } + + // draw the points + for row in &rows { + println!("{}", row.concat()); + } +} + +fn precalculating_method(rng: &mut R) { + // Generate all possible points + let mut possible_points = Vec::with_capacity(404); + for y in -15..=15 { + for x in -15..=15 { + let r2 = x * x + y * y; + if r2 >= 100 && r2 <= 225 { + possible_points.push((x, y)); + } + } + } + + // A truncated Fisher-Yates shuffle + let len = possible_points.len(); + for i in (len - POINTS_N..len).rev() { + let j = rng.gen_range(0, i + 1); + possible_points.swap(i, j); + } + + // turn the selected points into "pixels" + let mut rows = [[" "; 62]; 31]; + for &(x, y) in &possible_points[len - POINTS_N..] { + rows[(y + 15) as usize][(x + 15) as usize * 2] = "*"; + } + + // draw the "pixels" + for row in &rows { + println!("{}", row.concat()); + } +} + +fn main() { + let mut rng = rand::weak_rng(); + + filtering_method(&mut rng); + + precalculating_method(&mut rng); +} diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/D/continued-fraction-arithmetic-construct-from-rational-number.d b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/D/continued-fraction-arithmetic-construct-from-rational-number.d new file mode 100644 index 0000000000..4d8a79c79e --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/D/continued-fraction-arithmetic-construct-from-rational-number.d @@ -0,0 +1,72 @@ +import std.concurrency; +import std.stdio; + +struct Pair { + int first, second; +} + +auto r2cf(Pair frac) { + return new Generator!int({ + auto num = frac.first; + auto den = frac.second; + while (den != 0) { + auto div = num / den; + auto rem = num % den; + num = den; + den = rem; + div.yield(); + } + }); +} + +void iterate(Generator!int seq) { + foreach(i; seq) { + write(i, " "); + } + writeln(); +} + +void main() { + auto fracs = [ + Pair( 1, 2), + Pair( 3, 1), + Pair( 23, 8), + Pair( 13, 11), + Pair( 22, 7), + Pair(-151, 77), + ]; + foreach(frac; fracs) { + writef("%4d / %-2d = ", frac.first, frac.second); + frac.r2cf.iterate; + } + writeln; + + auto root2 = [ + Pair( 14_142, 10_000), + Pair( 141_421, 100_000), + Pair( 1_414_214, 1_000_000), + Pair(14_142_136, 10_000_000), + ]; + writeln("Sqrt(2) ->"); + foreach(frac; root2) { + writef("%8d / %-8d = ", frac.first, frac.second); + frac.r2cf.iterate; + } + writeln; + + auto pi = [ + Pair( 31, 10), + Pair( 314, 100), + Pair( 3_142, 1_000), + Pair( 31_428, 10_000), + Pair( 314_285, 100_000), + Pair( 3_142_857, 1_000_000), + Pair( 31_428_571, 10_000_000), + Pair(314_285_714, 100_000_000), + ]; + writeln("Pi ->"); + foreach(frac; pi) { + writef("%9d / %-9d = ", frac.first, frac.second); + frac.r2cf.iterate; + } +} diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Java/continued-fraction-arithmetic-construct-from-rational-number.java b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Java/continued-fraction-arithmetic-construct-from-rational-number.java new file mode 100644 index 0000000000..07d40cdd20 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Java/continued-fraction-arithmetic-construct-from-rational-number.java @@ -0,0 +1,77 @@ +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +public class ConstructFromRationalNumber { + private static class R2cf implements Iterator { + private int num; + private int den; + + R2cf(int num, int den) { + this.num = num; + this.den = den; + } + + @Override + public boolean hasNext() { + return den != 0; + } + + @Override + public Integer next() { + int div = num / den; + int rem = num % den; + num = den; + den = rem; + return div; + } + } + + private static void iterate(R2cf generator) { + generator.forEachRemaining(n -> System.out.printf("%d ", n)); + System.out.println(); + } + + public static void main(String[] args) { + List> fracs = List.of( + Map.entry(1, 2), + Map.entry(3, 1), + Map.entry(23, 8), + Map.entry(13, 11), + Map.entry(22, 7), + Map.entry(-151, 77) + ); + for (Map.Entry frac : fracs) { + System.out.printf("%4d / %-2d = ", frac.getKey(), frac.getValue()); + iterate(new R2cf(frac.getKey(), frac.getValue())); + } + + System.out.println("\nSqrt(2) ->"); + List> root2 = List.of( + Map.entry( 14_142, 10_000), + Map.entry( 141_421, 100_000), + Map.entry( 1_414_214, 1_000_000), + Map.entry(14_142_136, 10_000_000) + ); + for (Map.Entry frac : root2) { + System.out.printf("%8d / %-8d = ", frac.getKey(), frac.getValue()); + iterate(new R2cf(frac.getKey(), frac.getValue())); + } + + System.out.println("\nPi ->"); + List> pi = List.of( + Map.entry( 31, 10), + Map.entry( 314, 100), + Map.entry( 3_142, 1_000), + Map.entry( 31_428, 10_000), + Map.entry( 314_285, 100_000), + Map.entry( 3_142_857, 1_000_000), + Map.entry( 31_428_571, 10_000_000), + Map.entry(314_285_714, 100_000_000) + ); + for (Map.Entry frac : pi) { + System.out.printf("%9d / %-9d = ", frac.getKey(), frac.getValue()); + iterate(new R2cf(frac.getKey(), frac.getValue())); + } + } +} diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Julia/continued-fraction-arithmetic-construct-from-rational-number.julia b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Julia/continued-fraction-arithmetic-construct-from-rational-number.julia index cd04626312..b027154c10 100644 --- a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Julia/continued-fraction-arithmetic-construct-from-rational-number.julia +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Julia/continued-fraction-arithmetic-construct-from-rational-number.julia @@ -1,69 +1,55 @@ -# It's most appropriate to define a Julia iterable object for this task -# Julia doesn't have Python's yield, the closest to it is produce/consume calls with Julia tasks +# It'st most appropriate to define a Julia iterable object for this task +# Julia doesn't have Python'st yield, the closest to it is produce/consume calls with Julia tasks # but for various reasons they don't work out for this task # This solution works with two integers, a Julia rational or a real -type R2cf -n1::Union{Int,Float64} # numerator or real -n2::Int # denominator or 1 if real -t1::Int # generated coefficient -f::Float64 # aux. field for working with real inputs +mutable struct ContinuedFraction{T<:Integer} + n1::T # numerator or real + n2::T # denominator or 1 if real + t1::T # generated coefficient end -# constructors for all possible input types -R2cf(n::Union{Int,Float64})=R2cf(n,1,0,0.1) -R2cf(n1::Int,n2::Int)=R2cf(n1,n2,0,0.1) -R2cf(r::Rational{Int})=R2cf(num(r),den(r),0,0.1) +# Constructors for all possible input types +ContinuedFraction{T<:Integer}(n1::T, n2::T) = ContinuedFraction(n1, n2, 0) +ContinuedFraction(n::Rational) = ContinuedFraction(numerator(n), denominator(n)) +ContinuedFraction(n::AbstractFloat) = ContinuedFraction(Rational(n)) -# methods to make our object iterable -Base.start(::R2cf)=nothing - -# generates the next coefficient -function Base.next(cf::R2cf,s) -if typeof(cf.n1)==Int -cf.n1, (cf.t1, cf.n2) = cf.n2, divrem(cf.n1, cf.n2) -else -cf.t1,cf.f=divrem(cf.n1,1) -if cf.f!=0.0 cf.n1=1/cf.f end -end -return (cf.t1,nothing) +# Methods to make our object iterable +Base.start(::ContinuedFraction) = nothing +# Returns true if we've prepared the continued fraction +Base.done(cf::ContinuedFraction, st) = cf.n2 == 0 +# Generates the next coefficient +function Base.next(cf::ContinuedFraction, st) + cf.n1, (cf.t1, cf.n2) = cf.n2, divrem(cf.n1, cf.n2) + return cf.t1, nothing end -# returns true if we've prepared the continued fraction -function Base.done(cf::R2cf,s) -if typeof(cf.n1)==Int -return cf.n2==0 -else -return cf.f==0.0 -end -end +# Tell Julia that this object always returns ints (all coeffs are integers) +Base.eltype{T}(::Type{ContinuedFraction{T}}) = T -# tell Julia that this object always returns ints (all coeffs are integers) -Base.eltype(::Type{R2cf})=Int - -# overload the default collect function so that we can collect the first maxiter coeffs of infinite continued fractions +# Overload the default collect function so that we can collect the first maxiter coeffs of infinite continued fractions # array slicing doesn't work as Julia crashes before the slicing due to our infinitely long array -function Base.collect(itr::R2cf,maxiter::Int) -r=Array{Int,1}() # all results are ints -i=1 -for v=itr -push!(r,v) -i+=1 -if i==maxiter break end -end -return r +function Base.collect(itr::ContinuedFraction, maxiter::Integer = 100) + r = Array{eltype(itr)}(maxiter) + i = 1 + for v in itr + r[i] = v + i += 1 + if i > maxiter break end + end + return r[1:i-1] end -# test cases according to task description with outputs in comments -println(collect(R2cf(1,2))) # => [0, 2] -println(collect(R2cf(3,1))) # => [3] -println(collect(R2cf(23,8))) # => [2, 1, 7] -println(collect(R2cf(13,11))) # => [1, 5, 2] -println(collect(R2cf(22,7))) # => [3, 7] -println(collect(R2cf(14142,10000))) # => [1, 2, 2, 2, 2, 2, 1, 1, 29] -println(collect(R2cf(141421,100000))) # => [1, 2, 2, 2, 2, 2, 2, 3, 1, 1, 3, 1, 7, 2] -println(collect(R2cf(1414214,1000000))) # => [1, 2, 2, 2, 2, 2, 2, 2, 3, 6, 1, 2, 1, 12] -println(collect(R2cf(14142136,10000000))) # => [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 6, 1, 2, 4, 1, 1, 2] +# Test cases according to task description with outputs in comments +println(collect(ContinuedFraction(1, 2))) # => [0, 2] +println(collect(ContinuedFraction(3, 1))) # => [3] +println(collect(ContinuedFraction(23, 8))) # => [2, 1, 7] +println(collect(ContinuedFraction(13, 11))) # => [1, 5, 2] +println(collect(ContinuedFraction(22, 7))) # => [3, 7] +println(collect(ContinuedFraction(14142, 10000))) # => [1, 2, 2, 2, 2, 2, 1, 1, 29] +println(collect(ContinuedFraction(141421, 100000))) # => [1, 2, 2, 2, 2, 2, 2, 3, 1, 1, 3, 1, 7, 2] +println(collect(ContinuedFraction(1414214, 1000000))) # => [1, 2, 2, 2, 2, 2, 2, 2, 3, 6, 1, 2, 1, 12] +println(collect(ContinuedFraction(14142136, 10000000))) # => [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 6, 1, 2, 4, 1, 1, 2] -println(collect(R2cf(13//11))) # => [1, 5, 2] -println(collect(R2cf(2 ^ 0.5), 20)) # => [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] +println(collect(ContinuedFraction(13 // 11))) # => [1, 5, 2] +println(collect(ContinuedFraction(√2), 20)) # => [1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2] diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Modula-2/continued-fraction-arithmetic-construct-from-rational-number.mod2 b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Modula-2/continued-fraction-arithmetic-construct-from-rational-number.mod2 new file mode 100644 index 0000000000..c38668640f --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Modula-2/continued-fraction-arithmetic-construct-from-rational-number.mod2 @@ -0,0 +1,76 @@ +MODULE ConstructFromrationalNumber; +FROM FormatString IMPORT FormatString; +FROM Terminal IMPORT WriteString,WriteLn,ReadChar; + +TYPE R2cf = RECORD + num,den : INTEGER; +END; + +PROCEDURE HasNext(self : R2cf) : BOOLEAN; +BEGIN + RETURN self.den # 0; +END HasNext; + +PROCEDURE Next(VAR self : R2cf) : INTEGER; +VAR div,rem : INTEGER; +BEGIN + div := self.num / self.den; + rem := self.num REM self.den; + self.num := self.den; + self.den := rem; + RETURN div; +END Next; + +PROCEDURE Iterate(self : R2cf); +VAR buf : ARRAY[0..64] OF CHAR; +BEGIN + WHILE HasNext(self) DO + FormatString("%i ", buf, Next(self)); + WriteString(buf); + END; + WriteLn; +END Iterate; + +PROCEDURE Print(num,den : INTEGER); +VAR frac : R2cf; +VAR buf : ARRAY[0..64] OF CHAR; +BEGIN + FormatString("%9i / %-9i = ", buf, num, den); + WriteString(buf); + + frac.num := num; + frac.den := den; + Iterate(frac); +END Print; + +VAR frac : R2cf; +BEGIN + Print(1,2); + Print(3,1); + Print(23,8); + Print(13,11); + Print(22,7); + Print(-151,77); + + WriteLn; + WriteString("Sqrt(2) ->"); + WriteLn; + Print(14142,10000); + Print(141421,100000); + Print(1414214,1000000); + Print(14142136,10000000); + + WriteLn; + WriteString("Pi ->"); + WriteLn; + Print(31,10); + Print(314,100); + Print(3142,1000); + Print(31428,10000); + Print(314285,100000); + Print(3142857,1000000); + Print(31428571,10000000); + Print(314285714,100000000); + + ReadChar; +END ConstructFromrationalNumber. diff --git a/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Perl-6/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n-.pl6 b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Perl-6/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n-.pl6 new file mode 100644 index 0000000000..9407120887 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N-/Perl-6/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n-.pl6 @@ -0,0 +1,75 @@ +class NG { + has ( $!a1, $!a, $!b1, $!b ); + submethod BUILD ( :$!a1, :$!a, :$!b1, :$!b ) { } + + # Public methods + method new( $a1, $a, $b1, $b ) { self.bless( :$a1, :$a, :$b1, :$b ) } + method apply(@cf, :$limit = Inf) { + (gather { + map { take self!extract unless self!needterm; self!inject($_) }, @cf; + take self!drain until self!done; + })[ ^ $limit ] + } + + # Private methods + method !inject ($n) { + sub xform($n, $x, $y) { $x, $n * $x + $y } + ( $!a, $!a1 ) = xform( $n, $!a1, $!a ); + ( $!b, $!b1 ) = xform( $n, $!b1, $!b ); + } + method !extract { + sub xform($n, $x, $y) { $y, $x - $y * $n } + my $n = $!a div $!b; + ($!a, $!b ) = xform( $n, $!a, $!b ); + ($!a1, $!b1) = xform( $n, $!a1, $!b1 ); + $n + } + method !drain { $!a = $!a1, $!b = $!b1 if self!needterm; self!extract } + method !needterm { so [||] !$!b, !$!b1, $!a/$!b != $!a1/$!b1 } + method !done { not [||] $!b, $!b1 } +} + +sub r2cf(Rat $x is copy) { # Rational to continued fraction + gather loop { + $x -= take $x.floor; + last if !$x; + $x = 1 / $x; + } +} + +sub cf2r(@a) { # continued fraction to Rational + my $x = @a[* - 1]; # Use FatRats for arbitrary precision + $x = ( @a[$_- 1] + 1 / $x ).FatRat for reverse 1 ..^ @a; + $x +} + +sub ppcf(@cf) { # format continued fraction for pretty printing + "[{ @cf.join(',').subst(',',';') }]" +} + +sub pprat($a) { # format Rational for pretty printing + # Use FatRats for arbitrary precision + $a.FatRat.denominator == 1 ?? $a !! $a.FatRat.nude.join('/') +} + +sub test_NG ($rat, @ng, $op) { + my @cf = $rat.Rat(1e-18).&r2cf; + my @op = NG.new( |@ng ).apply( @cf ); + say $rat.perl, ' as a cf: ', @cf.&ppcf, " $op = ", + @op.&ppcf, "\tor ", @op.&cf2r.&pprat, "\n"; +} + +# Testing +test_NG(|$_) for ( + [ 13/11, [<2 1 0 2>], '+ 1/2 ' ], + [ 22/7, [<2 1 0 2>], '+ 1/2 ' ], + [ 22/7, [<1 0 0 4>], '/ 4 ' ], + [ 22/7, [<7 0 0 22>], '* 7/22 ' ], + [ 2**.5, [<1 1 0 2>], "\n(1+√2)/2 (approximately)" ] +); + +say '100 terms of (1+√2)/2 as a continued fraction and as a rational value:'; + +my @continued-fraction = NG.new( 1,1,0,2 ).apply( (lazy flat 1, 2 xx * ), limit => 100 ); +say @continued-fraction.&ppcf.comb(/ . ** 1..80/).join("\n"); +say @continued-fraction.&cf2r.&pprat; diff --git a/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2-/Kotlin/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n1,-contined-fraction-n2-.kotlin b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2-/Kotlin/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n1,-contined-fraction-n2-.kotlin new file mode 100644 index 0000000000..3ab990abec --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2-/Kotlin/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n1,-contined-fraction-n2-.kotlin @@ -0,0 +1,216 @@ +// version 1.2.10 + +import kotlin.math.abs + +abstract class MatrixNG { + var cfn = 0 + var thisTerm = 0 + var haveTerm = false + + abstract fun consumeTerm() + abstract fun consumeTerm(n: Int) + abstract fun needTerm(): Boolean +} + +class NG4( + var a1: Int, var a: Int, var b1: Int, var b: Int +) : MatrixNG() { + + private var t = 0 + + override fun needTerm(): Boolean { + if (b1 == 0 && b == 0) return false + if (b1 == 0 || b == 0) return true + thisTerm = a / b + if (thisTerm == a1 / b1) { + t = a; a = b; b = t - b * thisTerm + t = a1; a1 = b1; b1 = t - b1 * thisTerm + haveTerm = true + return false + } + return true + } + + override fun consumeTerm() { + a = a1 + b = b1 + } + + override fun consumeTerm(n: Int) { + t = a; a = a1; a1 = t + a1 * n + t = b; b = b1; b1 = t + b1 * n + } +} + +class NG8( + var a12: Int, var a1: Int, var a2: Int, var a: Int, + var b12: Int, var b1: Int, var b2: Int, var b: Int +) : MatrixNG() { + + private var t = 0 + private var ab = 0.0 + private var a1b1 = 0.0 + private var a2b2 = 0.0 + private var a12b12 = 0.0 + + fun chooseCFN() = if (abs(a1b1 - ab) > abs(a2b2-ab)) 0 else 1 + + override fun needTerm(): Boolean { + if (b1 == 0 && b == 0 && b2 == 0 && b12 == 0) return false + if (b == 0) { + cfn = if (b2 == 0) 0 else 1 + return true + } + else ab = a.toDouble() / b + + if (b2 == 0) { + cfn = 1 + return true + } + else a2b2 = a2.toDouble() / b2 + + if (b1 == 0) { + cfn = 0 + return true + } + else a1b1 = a1.toDouble() / b1 + + if (b12 == 0) { + cfn = chooseCFN() + return true + } + else a12b12 = a12.toDouble() / b12 + + thisTerm = ab.toInt() + if (thisTerm == a1b1.toInt() && thisTerm == a2b2.toInt() && + thisTerm == a12b12.toInt()) { + t = a; a = b; b = t - b * thisTerm + t = a1; a1 = b1; b1 = t - b1 * thisTerm + t = a2; a2 = b2; b2 = t - b2 * thisTerm + t = a12; a12 = b12; b12 = t - b12 * thisTerm + haveTerm = true + return false + } + cfn = chooseCFN() + return true + } + + override fun consumeTerm() { + if (cfn == 0) { + a = a1; a2 = a12 + b = b1; b2 = b12 + } + else { + a = a2; a1 = a12 + b = b2; b1 = b12 + } + } + + override fun consumeTerm(n: Int) { + if (cfn == 0) { + t = a; a = a1; a1 = t + a1 * n + t = a2; a2 = a12; a12 = t + a12 * n + t = b; b = b1; b1 = t + b1 * n + t = b2; b2 = b12; b12 = t + b12 * n + } + else { + t = a; a = a2; a2 = t + a2 * n + t = a1; a1 = a12; a12 = t + a12 * n + t = b; b = b2; b2 = t + b2 * n + t = b1; b1 = b12; b12 = t + b12 * n + } + } +} + +interface ContinuedFraction { + fun nextTerm(): Int + fun moreTerms(): Boolean +} + +class R2cf(var n1: Int, var n2: Int) : ContinuedFraction { + + override fun nextTerm(): Int { + val thisTerm = n1 /n2 + val t2 = n2 + n2 = n1 - thisTerm * n2 + n1 = t2 + return thisTerm + } + + override fun moreTerms() = abs(n2) > 0 +} + +class NG : ContinuedFraction { + val ng: MatrixNG + val n: List + + constructor(ng: NG4, n1: ContinuedFraction) { + this.ng = ng + n = listOf(n1) + } + + constructor(ng: NG8, n1: ContinuedFraction, n2: ContinuedFraction) { + this.ng = ng + n = listOf(n1, n2) + } + + override fun nextTerm(): Int { + ng.haveTerm = false + return ng.thisTerm + } + + override fun moreTerms(): Boolean { + while (ng.needTerm()) { + if (n[ng.cfn].moreTerms()) + ng.consumeTerm(n[ng.cfn].nextTerm()) + else + ng.consumeTerm() + } + return ng.haveTerm + } +} + +fun test(desc: String, vararg cfs: ContinuedFraction) { + println("TESTING -> $desc") + for (cf in cfs) { + while (cf.moreTerms()) print ("${cf.nextTerm()} ") + println() + } + println() +} + +fun main(args: Array) { + val a = NG8(0, 1, 1, 0, 0, 0, 0, 1) + val n2 = R2cf(22, 7) + val n1 = R2cf(1, 2) + val a3 = NG4(2, 1, 0, 2) + val n3 = R2cf(22, 7) + test("[3;7] + [0;2]", NG(a, n1, n2), NG(a3, n3)) + + val b = NG8(1, 0, 0, 0, 0, 0, 0, 1) + val b1 = R2cf(13, 11) + val b2 = R2cf(22, 7) + test("[1;5,2] * [3;7]", NG(b, b1, b2), R2cf(286, 77)) + + val c = NG8(0, 1, -1, 0, 0, 0, 0, 1) + val c1 = R2cf(13, 11) + val c2 = R2cf(22, 7) + test("[1;5,2] - [3;7]", NG(c, c1, c2), R2cf(-151, 77)) + + val d = NG8(0, 1, 0, 0, 0, 0, 1, 0) + val d1 = R2cf(22 * 22, 7 * 7) + val d2 = R2cf(22,7) + test("Divide [] by [3;7]", NG(d, d1, d2)) + + val na = NG8(0, 1, 1, 0, 0, 0, 0, 1) + val a1 = R2cf(2, 7) + val a2 = R2cf(13, 11) + val aa = NG(na, a1, a2) + val nb = NG8(0, 1, -1, 0, 0, 0, 0, 1) + val b3 = R2cf(2, 7) + val b4 = R2cf(13, 11) + val bb = NG(nb, b3, b4) + val nc = NG8(1, 0, 0, 0, 0, 0, 0, 1) + val desc = "([0;3,2] + [1;5,2]) * ([0;3,2] - [1;5,2])" + test(desc, NG(nc, aa, bb), R2cf(-7797, 5929)) +} diff --git a/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2-/Perl-6/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n1,-contined-fraction-n2-.pl6 b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2-/Perl-6/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n1,-contined-fraction-n2-.pl6 new file mode 100644 index 0000000000..aae2ae50b4 --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-G-matrix-NG,-Contined-Fraction-N1,-Contined-Fraction-N2-/Perl-6/continued-fraction-arithmetic-g-matrix-ng,-contined-fraction-n1,-contined-fraction-n2-.pl6 @@ -0,0 +1,114 @@ +class NG2 { + has ( $!a12, $!a1, $!a2, $!a, $!b12, $!b1, $!b2, $!b ); + + # Public methods + method operator($!a12, $!a1, $!a2, $!a, $!b12, $!b1, $!b2, $!b ) { self } + + method apply(@cf1, @cf2, :$limit = 30) { + my @cfs = [@cf1], [@cf2]; + gather { + while @cfs[0] or @cfs[1] { + my $term; + (take $term if $term = self!extract) unless self!needterm; + my $from = self!from; + $from = @cfs[$from] ?? $from !! $from +^ 1; + self!inject($from, @cfs[$from].shift); + } + take self!drain while $!b; + }[ ^$limit ].grep: *.defined; + } + + # Private methods + method !inject ($n, $t) { + multi sub xform(0, $t, $x12, $x1, $x2, $x) { $x2 + $x12 * $t, $x + $x1 * $t, $x12, $x1 } + multi sub xform(1, $t, $x12, $x1, $x2, $x) { $x1 + $x12 * $t, $x12, $x + $x2 * $t, $x2 } + ( $!a12, $!a1, $!a2, $!a ) = xform($n, $t, $!a12, $!a1, $!a2, $!a ); + ( $!b12, $!b1, $!b2, $!b ) = xform($n, $t, $!b12, $!b1, $!b2, $!b ); + } + method !extract { + my $t = $!a div $!b; + ( $!a12, $!a1, $!a2, $!a, $!b12, $!b1, $!b2, $!b ) = + $!b12, $!b1, $!b2, $!b, + $!a12 - $!b12 * $t, + $!a1 - $!b1 * $t, + $!a2 - $!b2 * $t, + $!a - $!b * $t; + $t; + } + method !from { + return $!b == $!b2 == 0 ?? 0 !! + $!b == 0 || $!b2 == 0 ?? 1 !! + abs($!a1*$!b*$!b2 - $!a*$!b1*$!b2) > abs($!a2*$!b*$!b1 - $!a*$!b1*$!b2) ?? 0 !! 1; + } + method !needterm { + so !([&&] $!b12, $!b1, $!b2, $!b) or $!a/$!b != $!a1/$!b1 != $!a2/$!b2 != $!a12/$!b1; + } + method !noterms($which) { + $which ?? (($!a1, $!a, $!b1, $!b ) = $!a12, $!a2, $!b12, $!b2) + !! (($!a2, $!a, $!b2, $!b ) = $!a12, $!a1, $!b12, $!b1); + } + method !drain { + self!noterms(self!from) if self!needterm; + self!extract; + } +} + +sub r2cf(Rat $x is copy) { # Rational to continued fraction + gather loop { + $x -= take $x.floor; + last unless $x; + $x = 1 / $x; + } +} + +sub cf2r(@a) { # continued fraction to Rational + my $x = @a[* - 1].FatRat; # Use FatRats for arbitrary precision + $x = @a[$_- 1] + 1 / $x for reverse 1 ..^ @a; + $x +} + +# format continued fraction for pretty printing +sub ppcf(@cf) { "[{ @cf.join(',').subst(',',';') }]" } + +# format Rational for pretty printing. Use FatRats for arbitrary precision +sub pprat($a) { $a.FatRat.denominator == 1 ?? $a !! $a.FatRat.nude.join('/') } + +my %ops = ( # convenience hash of NG matrix operators + '+' => (0,1,1,0,0,0,0,1), + '-' => (0,1,-1,0,0,0,0,1), + '*' => (1,0,0,0,0,0,0,1), + '/' => (0,1,0,0,0,0,1,0) +); + +sub test_NG2 ($rat1, $op, $rat2) { + my @cf1 = $rat1.&r2cf; + my @cf2 = $rat2.&r2cf; + my @result = NG2.new.operator(|%ops{$op}).apply( @cf1, @cf2 ); + say "{$rat1.&pprat} $op {$rat2.&pprat} => {@cf1.&ppcf} $op ", + "{@cf2.&ppcf} = {@result.&ppcf} => {@result.&cf2r.&pprat}\n"; +} + +# Testing +test_NG2(|$_) for + [ 22/7, '+', 1/2 ], + [ 23/11, '*', 22/7 ], + [ 13/11, '-', 22/7 ], + [ 484/49, '/', 22/7 ]; + + +# Sometimes you may want to limit the terms in the continued fraction to something other than default. +# Here a lazy infinite continued fraction for √2, then multiply it by itself. We'll limit the result +# to 6 terms for brevity’s' sake. We'll then convert that continued fraction back to an arbitrary precision +# FatRat Rational number. (Perl 6 stores FatRats internally as a ratio of two arbitrarily long integers. +# We need to exercise a little caution because they can eat up all of your memory if allowed to grow unchecked, +# hence the limit of 6 terms in continued fraction.) We'll then convert that number to a normal precision +# Rat, which is accurate to the nearest 1 / 2^64, + +say "√2 expressed as a continued fraction, then squared: "; +my @root2 = lazy flat 1, 2 xx *; +my @result = NG2.new.operator(|%ops{'*'}).apply( @root2, @root2, limit => 6 ); +say @root2.&ppcf, "² = \n"; +say @result.&ppcf; +say "\nConverted back to an arbitrary (ludicrous) precision Rational: "; +say @result.&cf2r.nude.join(" /\n"); +say "\nCoerced to a standard precision Rational: ", @result.&cf2r.Num.Rat; diff --git a/Task/Continued-fraction/Julia/continued-fraction.julia b/Task/Continued-fraction/Julia/continued-fraction.julia new file mode 100644 index 0000000000..b79ea56a77 --- /dev/null +++ b/Task/Continued-fraction/Julia/continued-fraction.julia @@ -0,0 +1,36 @@ +function _sqrt(a::Bool, n) + if a + return n > 0 ? 2.0 : 1.0 + else + return 1.0 + end +end + +function _napier(a::Bool, n) + if a + return n > 0 ? Float64(n) : 2.0 + else + return n > 1 ? n - 1.0 : 1.0 + end +end + +function _pi(a::Bool, n) + if a + return n > 0 ? 6.0 : 3.0 + else + return (2.0 * n - 1.0) ^ 2.0 # exponentiation operator + end +end + +function calc(f::Function, expansions::Integer) + a, b = true, false + r = 0.0 + for i in expansions:-1:1 + r = f(b, i) / (f(a, i) + r) + end + return f(a, 0) + r +end + +for (v, f) in (("√2", _sqrt), ("e", _napier), ("π", _pi)) + @printf("%3s = %f\n", v, calc(f, 1000)) +end diff --git a/Task/Continued-fraction/Ring/continued-fraction.ring b/Task/Continued-fraction/Ring/continued-fraction.ring new file mode 100644 index 0000000000..f858c00f85 --- /dev/null +++ b/Task/Continued-fraction/Ring/continued-fraction.ring @@ -0,0 +1,21 @@ +# Project : Continued fraction +# Date : 2018/03/17 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : + +see "SQR(2) = " + contfrac(1, 1, "2", "1") + nl +see " e = " + contfrac(2, 1, "n", "n") + nl +see " PI = " + contfrac(3, 1, "6", "(2*n+1)^2") + nl + +func contfrac(a0, b1, a, b) + expr = "" + n = 0 + while len(expr) < (700 - n) + n = n + 1 + eval("temp1=" + a) + eval("temp2=" + b) + expr = expr + string(temp1) + char(43) + string(temp2) + "/(" + end + str = copy(")",n) + eval("temp3=" + expr + "1" + str) + return a0 + b1 / temp3 diff --git a/Task/Continued-fraction/Scheme/continued-fraction-1.ss b/Task/Continued-fraction/Scheme/continued-fraction-1.ss new file mode 100644 index 0000000000..e952565fc1 --- /dev/null +++ b/Task/Continued-fraction/Scheme/continued-fraction-1.ss @@ -0,0 +1,50 @@ +#!r6rs +(import (rnrs base (6)) + (srfi :41 streams)) + +(define nats (stream-cons 0 (stream-map (lambda (x) (+ x 1)) nats))) + +(define (build-stream fn) (stream-map fn nats)) + +(define (stream-cycle s . S) + (cond + ((stream-null? (car S)) stream-null) + (else (stream-cons (stream-car s) + (apply stream-cycle (append S (list (stream-cdr s)))))))) + +(define (cf-floor cf) (stream-car cf)) +(define (cf-num cf) (stream-car (stream-cdr cf))) +(define (cf-denom cf) (stream-cdr (stream-cdr cf))) + +(define (cf-integer? x) (stream-null? (stream-cdr x))) + +(define (cf->real x) + (let refine ((x x) (n 65536)) + (cond + ((= n 0) +inf.0) + ((cf-integer? x) (cf-floor x)) + (else (+ (cf-floor x) + (/ (cf-num x) + (refine (cf-denom x) (- n 1)))))))) + +(define (real->cf x) + (let-values (((integer-part fractional-part) (div-and-mod x 1))) + (if (= fractional-part 0.0) + (stream (exact integer-part)) + (stream-cons + (exact integer-part) + (stream-cons + 1 + (real->cf (/ fractional-part))))))) + + +(define sqrt2 (stream-cons 1 (stream-constant 1 2))) + +(define napier + (stream-append (stream 2 1) + (stream-cycle (stream-cdr nats) (stream-cdr nats)))) + +(define pi + (stream-cons 3 + (stream-cycle (build-stream (lambda (n) (expt (- (* 2 (+ n 1)) 1) 2))) + (stream-constant 6)))) diff --git a/Task/Continued-fraction/Scheme/continued-fraction-2.ss b/Task/Continued-fraction/Scheme/continued-fraction-2.ss new file mode 100644 index 0000000000..847418c441 --- /dev/null +++ b/Task/Continued-fraction/Scheme/continued-fraction-2.ss @@ -0,0 +1,6 @@ +> (cf->real sqrt2) +1.4142135623730951 +> (cf->real napier) +2.7182818284590455 +> (cf->real pi) +3.141592653589794 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 new file mode 100644 index 0000000000..7b4f44c35e --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Factor/convert-decimal-number-to-rational.factor @@ -0,0 +1,2 @@ +USE: math.floating-point +{ 0.9054054 0.518518 0.75 } [ double>ratio ] map [ . ] each diff --git a/Task/Convert-decimal-number-to-rational/Rust/convert-decimal-number-to-rational.rust b/Task/Convert-decimal-number-to-rational/Rust/convert-decimal-number-to-rational.rust new file mode 100644 index 0000000000..cb211717d0 --- /dev/null +++ b/Task/Convert-decimal-number-to-rational/Rust/convert-decimal-number-to-rational.rust @@ -0,0 +1,58 @@ +extern crate rand; +extern crate num; + +use num::Integer; +use rand::Rng; + +fn decimal_to_rational (mut n : f64) -> [isize;2] { + //Based on Farey sequences + assert!(n.is_finite()); + let flag_neg = n < 0.0; + if flag_neg { n = n*(-1.0) } + if n < std::f64::MIN_POSITIVE { return [0,1] } + if (n - n.round()).abs() < std::f64::EPSILON { return [n.round() as isize, 1] } + let mut a : isize = 0; + let mut b : isize = 1; + let mut c : isize = n.ceil() as isize; + let mut d : isize = 1; + let aux1 = isize::max_value()/2; + while c < aux1 && d < aux1 { + let aux2 : f64 = (a as f64 + c as f64)/(b as f64 + d as f64); + if (n - aux2).abs() < std::f64::EPSILON { break } + if n > aux2 { + a = a + c; + b = b + d; + } else { + c = a + c; + d = b + d; + } + } + // Make sure that the fraction is irreducible + let gcd = (a+c).gcd(&(b+d)); + if flag_neg { [-(a + c)/gcd, (b + d)/gcd] } else { [(a + c)/gcd, (b + d)/gcd] } +} + +#[test] +fn test1 () { + // Test the function with 1_000_000 random decimal numbers + let mut rng = rand::thread_rng(); + for _i in 1..1_000_000 { + let number = rng.gen::(); + let result = decimal_to_rational(number); + assert!((number - (result[0] as f64)/(result[1] as f64)).abs() < std::f64::EPSILON); + assert!(result[0].gcd(&result[1]) == 1); + } +} + +fn main () { + let mut rng = rand::thread_rng(); + for _i in 1..10 { + let number = rng.gen::(); + let result = decimal_to_rational(number); + if result[1] == 1 { println!("{} -> {}", number, result[0]) } else { println!("{} -> {}/{}", number, result[0], result[1]) } + } + for i in [-0.9054054, 0.518518, -0.75, 0.5185185185185185, -0.9054054054054054, 0.0, 1.0, 2.0].iter() { + let result = decimal_to_rational(*i as f64); + if result[1] == 1 { println!("{} = {}",*i, result[0]) } else { println!("{} = {}/{}", *i, result[0], result[1]) } + } +} diff --git a/Task/Conways-Game-of-Life/Elena/conways-game-of-life.elena b/Task/Conways-Game-of-Life/Elena/conways-game-of-life.elena index 293195b1f9..939678506b 100644 --- a/Task/Conways-Game-of-Life/Elena/conways-game-of-life.elena +++ b/Task/Conways-Game-of-Life/Elena/conways-game-of-life.elena @@ -9,9 +9,9 @@ const int maxY = 28. type listener_func = ListenerFunc. -limited class ListenerFunc :: dispatchable +limited closure class ListenerFunc { - action eval space:space [] + closure space:space [] } sealed class Model @@ -43,7 +43,7 @@ sealed class Model $onUpdate [ if ($nil != theListener) - [ theListener eval space:theSpace ]. + [ theListener(theSpace) ]. ] init @@ -69,18 +69,22 @@ symbol testSet = ((0,1,0), class gameOfLifeRuleSet = BaseRuleSet:: { - validate space:s int:x int:y + proceed space:s int:x int:y vint:retVal [ int cell := s getAt int:x int:y. - int number := s getLiveCell int:x int:y. // NOTE : number of living cells around the self includes the cell itself + int number := s getLiveCell int:x int:y int:1. // NOTE : number of living cells around the self includes the cell itself if ((cell == 0) && (number == 3)) - [ ^ true. ]. - + [ + retVal int := 1 + ]; if ((cell == 1) && ((number == 4) || (number == 3))) - [ ^ true. ]. - - ^ false. + [ + retVal int := 1 + ]; + [ + retVal int := 0 + ] ] }. @@ -120,7 +124,7 @@ program = var model := Model newRandomset ruleset:gameOfLifeRuleSet. - model onUpdate listener_func(&space:sp)[ sp print ]. + model onUpdate listener_func(:sp)[ sp print ]. until (console isKeyAvailable) [ diff --git a/Task/Conways-Game-of-Life/Fortran/conways-game-of-life.f b/Task/Conways-Game-of-Life/Fortran/conways-game-of-life.f index 7880dcaace..b535d1ab89 100644 --- a/Task/Conways-Game-of-Life/Fortran/conways-game-of-life.f +++ b/Task/Conways-Game-of-Life/Fortran/conways-game-of-life.f @@ -18,7 +18,7 @@ CALL Drawgen(cells(1:gridsize, 1:gridsize), generation) DO generation = 1, 8 - CALL Nextgen(cells) + CALL NextgenV2(cells) CALL Drawgen(cells(1:gridsize, 1:gridsize), generation) END DO @@ -48,8 +48,8 @@ INTEGER :: neighbours, i, j buffer = cells ! Store current status - DO i = 1, SIZE(cells, 1)-2 - DO j = 1, SIZE(cells, 2)-2 + DO j = 1, SIZE(cells, 2)-2 + DO i = 1, SIZE(cells, 1)-2 if(buffer(i, j)) then neighbours = sum(count(buffer(i-1:i+1, j-1:j+1), 1)) - 1 else @@ -71,4 +71,30 @@ END DO END SUBROUTINE Nextgen +!########################################################################### +! In this version instead of cycling through all points an integer array +! is used the sum the live neighbors of all points. The sum is done with +! the entire array cycling through the eight positions of the neighbors. +! Executing a grid size of 10000 in 500 generations this version gave a +! speedup of almost 4 times. +!########################################################################### + PURE SUBROUTINE NextgenV2(cells) + LOGICAL, INTENT(IN OUT) :: cells(:,:) + INTEGER(KIND=1) :: buffer(1:SIZE(cells, 1)-2,1:SIZE(cells, 2)-2) + INTEGER :: gridsize, i, j + + gridsize=SIZE(cells, 1) + buffer=0 + + DO j=-1, 1 + DO i=-1,1 + IF(i==0 .AND. j==0) CYCLE + WHERE(cells(i+2:gridsize-i-1,j+2:gridsize-j-1)) buffer=buffer+1 + END DO + END DO + + WHERE(buffer<2 .or. buffer>3) cells(2:gridsize-1,2:gridsize-1) = .FALSE. + WHERE(buffer==3) cells(2:gridsize-1,2:gridsize-1) = .TRUE. + END SUBROUTINE NextgenV2 +!########################################################################### END PROGRAM LIFE_2D diff --git a/Task/Conways-Game-of-Life/Kotlin/conways-game-of-life.kotlin b/Task/Conways-Game-of-Life/Kotlin/conways-game-of-life.kotlin new file mode 100644 index 0000000000..2e5f88f42d --- /dev/null +++ b/Task/Conways-Game-of-Life/Kotlin/conways-game-of-life.kotlin @@ -0,0 +1,111 @@ +// version 1.2.0 + +import java.util.Random + +val rand = Random(0) // using a seed to produce same output on each run + +enum class Pattern { BLINKER, GLIDER, RANDOM } + +class Field(val w: Int, val h: Int) { + val s = List(h) { BooleanArray(w) } + + operator fun set(x: Int, y: Int, b: Boolean) { + s[y][x] = b + } + + fun next(x: Int, y: Int): Boolean { + var on = 0 + for (i in -1..1) { + for (j in -1..1) { + if (state(x + i, y + j) && !(j == 0 && i == 0)) on++ + } + } + return on == 3 || (on == 2 && state(x, y)) + } + + fun state(x: Int, y: Int): Boolean { + if ((x !in 0 until w) || (y !in 0 until h)) return false + return s[y][x] + } +} + +class Life(val pattern: Pattern) { + val w: Int + val h: Int + var a: Field + var b: Field + + init { + when (pattern) { + Pattern.BLINKER -> { + w = 3 + h = 3 + a = Field(w, h) + b = Field(w, h) + a[0, 1] = true + a[1, 1] = true + a[2, 1] = true + } + + Pattern.GLIDER -> { + w = 4 + h = 4 + a = Field(w, h) + b = Field(w, h) + a[1, 0] = true + a[2, 1] = true + for (i in 0..2) a[i, 2] = true + } + + Pattern.RANDOM -> { + w = 80 + h = 15 + a = Field(w, h) + b = Field(w, h) + for (i in 0 until w * h / 2) { + a[rand.nextInt(w), rand.nextInt(h)] = true + } + } + } + } + + fun step() { + for (y in 0 until h) { + for (x in 0 until w) { + b[x, y] = a.next(x, y) + } + } + val t = a + a = b + b = t + } + + override fun toString(): String { + val sb = StringBuilder() + for (y in 0 until h) { + for (x in 0 until w) { + val c = if (a.state(x, y)) '#' else '.' + sb.append(c) + } + sb.append('\n') + } + return sb.toString() + } +} + +fun main(args: Array) { + val lives = listOf( + Triple(Life(Pattern.BLINKER), 3, "BLINKER"), + Triple(Life(Pattern.GLIDER), 4, "GLIDER"), + Triple(Life(Pattern.RANDOM), 100, "RANDOM") + ) + for ((game, gens, title) in lives) { + println("$title:\n") + repeat(gens + 1) { + println("Generation: $it\n$game") + Thread.sleep(30) + game.step() + } + println() + } +} diff --git a/Task/Conways-Game-of-Life/Nim/conways-game-of-life.nim b/Task/Conways-Game-of-Life/Nim/conways-game-of-life.nim index 2cf2170538..f687650a0f 100644 --- a/Task/Conways-Game-of-Life/Nim/conways-game-of-life.nim +++ b/Task/Conways-Game-of-Life/Nim/conways-game-of-life.nim @@ -1,4 +1,4 @@ -import os, strutils, math +import os, strutils, random randomize() var w, h: int @@ -9,8 +9,8 @@ if w <= 0: w = 30 if h <= 0: h = 30 # Initialize -var univ, utmp = newSeq[seq[bool]] h -for y in 0 .. (setq a "abcd") +"abcd" +> (setq b a) +"abcd" +> b +"abcd" +> (= a b) +true diff --git a/Task/Copy-a-string/Nim/copy-a-string.nim b/Task/Copy-a-string/Nim/copy-a-string.nim index cb0994c38b..49f8ae785e 100644 --- a/Task/Copy-a-string/Nim/copy-a-string.nim +++ b/Task/Copy-a-string/Nim/copy-a-string.nim @@ -1,3 +1,3 @@ var c = "This is a string" - d = c # Copy of content into new string + d = c # Copy c into a new string diff --git a/Task/Copy-a-string/Perl-6/copy-a-string-3.pl6 b/Task/Copy-a-string/Perl-6/copy-a-string-3.pl6 index 2583cf6b79..ac1394a3c5 100644 --- a/Task/Copy-a-string/Perl-6/copy-a-string-3.pl6 +++ b/Task/Copy-a-string/Perl-6/copy-a-string-3.pl6 @@ -1,12 +1,12 @@ -my $original = 'Hello.'; -my $bound-ro ::= $original; -say $bound-ro; # prints "Hello." -try { - $bound-ro = 'Runtime error!'; - CATCH { - say "$!"; # prints "Cannot modify readonly value" - }; -}; +# y $original = 'Hello.'; +#my $bound-ro ::= $original; +#say $bound-ro; # prints "Hello." +#try { +# $bound-ro = 'Runtime error!'; +# CATCH { +# say "$!"; # prints "Cannot modify readonly value" +# }; +#}; say $bound-ro; # prints "Hello." $original = 'Goodbye.'; say $bound-ro; # prints "Goodbye." diff --git a/Task/Count-in-factors/Factor/count-in-factors.factor b/Task/Count-in-factors/Factor/count-in-factors.factor new file mode 100644 index 0000000000..8fffbb7131 --- /dev/null +++ b/Task/Count-in-factors/Factor/count-in-factors.factor @@ -0,0 +1,2 @@ +USING: math.parser math.primes.factors math.ranges ; +IN: scratchpad "1: 1" print 2 20 [a,b] [ dup pprint ": " write factors [ number>string ] map " x " join print ] each diff --git a/Task/Count-in-factors/Julia/count-in-factors.julia b/Task/Count-in-factors/Julia/count-in-factors.julia index 1a169172fa..e5c2e4ebcd 100644 --- a/Task/Count-in-factors/Julia/count-in-factors.julia +++ b/Task/Count-in-factors/Julia/count-in-factors.julia @@ -1,20 +1,13 @@ -function factor_print{T<:Integer}(n::T) - const SEP = " \u00d7 " - -2 < n || return "-1"*SEP*factor_print(-n) - if isprime(n) || n < 2 - return string(n) - end - a = T[] - for (k, v) in factor(n) - append!(a, k*ones(T, v)) - end - sort!(a) - join(a, SEP) +using Primes +function strfactor(n::Integer) + n > -2 || return "-1 × " * strfactor(-n) + isprime(n) || n < 2 && return dec(n) + f = factor(Vector{typeof(n)}, n) + return join(f, " × ") end -lo = -4 -hi = 40 -println("Factor print ", lo, " to ", hi) -for i in lo:hi - println(@sprintf("%5d = ", i), factor_print(i)) +lo, hi = -4, 40 +println("Factor print $lo to $hi:") +for n in lo:hi + @printf("%5d = %s\n", n, strfactor(n)) end diff --git a/Task/Count-in-octal/Factor/count-in-octal.factor b/Task/Count-in-octal/Factor/count-in-octal.factor new file mode 100644 index 0000000000..37b94ff23b --- /dev/null +++ b/Task/Count-in-octal/Factor/count-in-octal.factor @@ -0,0 +1,2 @@ +USING: kernel math prettyprint ; +0 [ dup .o 1 + t ] loop diff --git a/Task/Count-occurrences-of-a-substring/Perl-6/count-occurrences-of-a-substring.pl6 b/Task/Count-occurrences-of-a-substring/Perl-6/count-occurrences-of-a-substring.pl6 index 49bbb4817f..935e348b10 100644 --- a/Task/Count-occurrences-of-a-substring/Perl-6/count-occurrences-of-a-substring.pl6 +++ b/Task/Count-occurrences-of-a-substring/Perl-6/count-occurrences-of-a-substring.pl6 @@ -1,4 +1,6 @@ -sub count-substring($big,$little) { +$big.comb: /$little/ } +sub count-substring($big,$little) { +$big.comb: ~$little } -say count-substring("the three truths","th"); -say count-substring("ababababab","abab"); +say count-substring("the three truths","th"); # 3 +say count-substring("ababababab","abab"); # 4 + +say count-substring(123123123,12); # 3 diff --git a/Task/Count-occurrences-of-a-substring/Red/count-occurrences-of-a-substring.red b/Task/Count-occurrences-of-a-substring/Red/count-occurrences-of-a-substring.red new file mode 100644 index 0000000000..8fd3c74b5e --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Red/count-occurrences-of-a-substring.red @@ -0,0 +1,25 @@ +Red [] +;;----------------------------------- +count-sub1: func [hay needle][ +;;----------------------------------- + prin rejoin ["hay: " pad copy hay 20 ",needle: " pad copy needle 6 ",count: " ] + i: 0 + parse hay [ some [thru needle (i: i + 1)] ] + print i +] +;;----------------------------------- +count-sub2: func [hay needle][ +;;----------------------------------- + prin rejoin ["hay: " pad copy hay 20 ",needle: " pad copy needle 6 ",count: " ] + i: 0 + while [hay: find hay needle][ + i: i + 1 + hay: skip hay length? needle + ] + print i +] +count-sub1 "the three truths" "th" +count-sub1 "ababababab" "abab" +print "^/version 2" +count-sub2 "the three truths" "th" +count-sub2 "ababababab" "abab" diff --git a/Task/Count-occurrences-of-a-substring/Stata/count-occurrences-of-a-substring.stata b/Task/Count-occurrences-of-a-substring/Stata/count-occurrences-of-a-substring.stata new file mode 100644 index 0000000000..456d686396 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Stata/count-occurrences-of-a-substring.stata @@ -0,0 +1,14 @@ +function strcount(s, x) { + n = 0 + k = 1-(i=strlen(x)) + do { + if (k = ustrpos(s, x, k+i)) n++ + } while(k) + return(n) +} + +strcount("peter piper picked a peck of pickled peppers", "pe") + 5 + +strcount("ababababab","abab") + 2 diff --git a/Task/Count-the-coins/Perl-6/count-the-coins.pl6 b/Task/Count-the-coins/Perl-6/count-the-coins.pl6 new file mode 100644 index 0000000000..e128cae0f4 --- /dev/null +++ b/Task/Count-the-coins/Perl-6/count-the-coins.pl6 @@ -0,0 +1,30 @@ +# Recursive (cached) +sub change-r($amount, @coins) { + my @cache = $[1 xx @coins]; + + multi ways($n where $n >= 0, @now [$coin,*@later]) { + @cache[$n][+@later] //= ways($n - $coin, @now) + ways($n, @later); + } + multi ways($,@) { 0 } + + # more efficient to start with coins sorted in descending order + ways($amount, @coins.sort(-*).list); +} + +change-r 1_00, [1,5,10,25]; +change-r 1000_00, [1,5,10,25,50,100]; + +# Iterative +sub change-i(\n, @coins) { + my @table = [1 xx @coins], [0 xx @coins] xx n; + for 1..n X ^@coins -> (\i, \j) { + my \c = @coins[j]; + @table[i][j] = [+] + @table[i - c][j ] // 0, + @table[i ][j - 1] // 0; + } + @table[*-1][*-1]; +} + +say change-i 1_00, [1,5,10,25]; +say change-i 1000_00, [1,5,10,25,50,100]; diff --git a/Task/Count-the-coins/Rust/count-the-coins.rust b/Task/Count-the-coins/Rust/count-the-coins.rust index 37edafe493..54cd032ece 100644 --- a/Task/Count-the-coins/Rust/count-the-coins.rust +++ b/Task/Count-the-coins/Rust/count-the-coins.rust @@ -12,5 +12,5 @@ fn make_change(coins: &[usize], cents: usize) -> usize { fn main() { println!("{}", make_change(&[1,5,10,25], 100)); - println!("{}", make_change(&[1,5,10,25,50,100], 100000)); + println!("{}", make_change(&[1,5,10,25,50,100], 100_000)); } diff --git a/Task/Create-a-file-on-magnetic-tape/00DESCRIPTION b/Task/Create-a-file-on-magnetic-tape/00DESCRIPTION index 1cb379e3d7..725a16cd4f 100644 --- a/Task/Create-a-file-on-magnetic-tape/00DESCRIPTION +++ b/Task/Create-a-file-on-magnetic-tape/00DESCRIPTION @@ -1,7 +1,6 @@ {{omit from|Axe}} {{omit from|AWK|not OO}} {{omit from|BASIC|not OO}} -{{omit from|C|not OO}} {{omit from|Fortran|not OO}} {{omit from|GUISS}} {{omit from|Locomotive Basic}} diff --git a/Task/Create-a-file-on-magnetic-tape/C/create-a-file-on-magnetic-tape.c b/Task/Create-a-file-on-magnetic-tape/C/create-a-file-on-magnetic-tape.c new file mode 100644 index 0000000000..b069d3db50 --- /dev/null +++ b/Task/Create-a-file-on-magnetic-tape/C/create-a-file-on-magnetic-tape.c @@ -0,0 +1,21 @@ +/*Abhishek Ghosh, 24th September 2017*/ + +#include + +int main() +{ + FILE* fp = fopen("TAPE.FILE","w"); + + fprintf(fp,"This code should be able to write a file to magnetic tape.\n"); + fprintf(fp,"The Wikipedia page on Magnetic tape data storage shows that magnetic tapes are still in use.\n"); + fprintf(fp,"In fact, the latest format, at the time of writing this code is TS1155 released in 2017.\n"); + fprintf(fp,"And since C is already 44, maybe 45, years old in 2017, I am sure someone somewhere did use a C compiler on magnetic tapes.\n"); + fprintf(fp,"If you happen to have one, please try to compile and execute me on that system.\n"); + fprintf(fp,"My creator tested me on an i5 machine with SSD and RAM that couldn't have even been dreamt of by Denis Ritchie.\n"); + fprintf(fp,"Who knows ? Maybe he did foresee today, after all he created something which is still young after 44-45 years and counting...\n"); + fprintf(fp,"EOF"); + + fclose(fp); + + return 0; +} diff --git a/Task/Create-a-file-on-magnetic-tape/D/create-a-file-on-magnetic-tape.d b/Task/Create-a-file-on-magnetic-tape/D/create-a-file-on-magnetic-tape.d new file mode 100644 index 0000000000..4d1f720140 --- /dev/null +++ b/Task/Create-a-file-on-magnetic-tape/D/create-a-file-on-magnetic-tape.d @@ -0,0 +1,10 @@ +import std.stdio; + +void main() { + version(Windows) { + File f = File("TAPE.FILE", "w"); + } else { + File f = File("/dev/tape", "w"); + } + f.writeln("Hello World!"); +} diff --git a/Task/Create-a-file-on-magnetic-tape/Haskell/create-a-file-on-magnetic-tape.hs b/Task/Create-a-file-on-magnetic-tape/Haskell/create-a-file-on-magnetic-tape.hs new file mode 100644 index 0000000000..669b00c2f9 --- /dev/null +++ b/Task/Create-a-file-on-magnetic-tape/Haskell/create-a-file-on-magnetic-tape.hs @@ -0,0 +1,4 @@ +module Main (main) where + +main :: IO () +main = writeFile "/dev/tape" "Hello from Rosetta Code!" diff --git a/Task/Create-a-file-on-magnetic-tape/Ring/create-a-file-on-magnetic-tape.ring b/Task/Create-a-file-on-magnetic-tape/Ring/create-a-file-on-magnetic-tape.ring new file mode 100644 index 0000000000..db5dd6a3c6 --- /dev/null +++ b/Task/Create-a-file-on-magnetic-tape/Ring/create-a-file-on-magnetic-tape.ring @@ -0,0 +1,10 @@ +# Project : Create a file on magnetic tape +# Date : 2017/12/09 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +fn = "Tape.file" +fp = fopen(fn,"w") +str = "I am a tape file now, or hope to be soon." +fwrite(fp, str) +fclose(fp) diff --git a/Task/Create-a-file/Gambas/create-a-file.gambas b/Task/Create-a-file/Gambas/create-a-file.gambas index ce44976c48..990fbb7aa7 100644 --- a/Task/Create-a-file/Gambas/create-a-file.gambas +++ b/Task/Create-a-file/Gambas/create-a-file.gambas @@ -1 +1,12 @@ -File.Save(User.home &/ "FileToSave", "Put this text in a file") +Public Sub Main() +Dim byCount As Byte +Dim sToSave As String + +For byCount = 0 To 50 + sToSave &= Format(Str(byCount), "00") & " - Charlie was here!" & gb.NewLine +Next + +File.Save(User.Home &/ "TestFile", sToSave) +Print File.Load(User.Home &/ "TestFile") + +End diff --git a/Task/Create-a-two-dimensional-array-at-runtime/C++/create-a-two-dimensional-array-at-runtime-1.cpp b/Task/Create-a-two-dimensional-array-at-runtime/C++/create-a-two-dimensional-array-at-runtime-1.cpp index 12133cc5d6..6064436579 100644 --- a/Task/Create-a-two-dimensional-array-at-runtime/C++/create-a-two-dimensional-array-at-runtime-1.cpp +++ b/Task/Create-a-two-dimensional-array-at-runtime/C++/create-a-two-dimensional-array-at-runtime-1.cpp @@ -1,6 +1,4 @@ #include -#include -#include int main() { diff --git a/Task/Create-a-two-dimensional-array-at-runtime/C++/create-a-two-dimensional-array-at-runtime-2.cpp b/Task/Create-a-two-dimensional-array-at-runtime/C++/create-a-two-dimensional-array-at-runtime-2.cpp index 864e748373..308ec4869e 100644 --- a/Task/Create-a-two-dimensional-array-at-runtime/C++/create-a-two-dimensional-array-at-runtime-2.cpp +++ b/Task/Create-a-two-dimensional-array-at-runtime/C++/create-a-two-dimensional-array-at-runtime-2.cpp @@ -1,6 +1,4 @@ #include -#include -#include #include int main() diff --git a/Task/Create-a-two-dimensional-array-at-runtime/C++/create-a-two-dimensional-array-at-runtime-3.cpp b/Task/Create-a-two-dimensional-array-at-runtime/C++/create-a-two-dimensional-array-at-runtime-3.cpp index 5fc8a564e6..9b526f2212 100644 --- a/Task/Create-a-two-dimensional-array-at-runtime/C++/create-a-two-dimensional-array-at-runtime-3.cpp +++ b/Task/Create-a-two-dimensional-array-at-runtime/C++/create-a-two-dimensional-array-at-runtime-3.cpp @@ -1,5 +1,5 @@ #include -#include "boost/multi_array.hpp" +#include typedef boost::multi_array two_d_array_type; diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Julia/create-a-two-dimensional-array-at-runtime.julia b/Task/Create-a-two-dimensional-array-at-runtime/Julia/create-a-two-dimensional-array-at-runtime.julia index 9a12897b97..bfdf4549da 100644 --- a/Task/Create-a-two-dimensional-array-at-runtime/Julia/create-a-two-dimensional-array-at-runtime.julia +++ b/Task/Create-a-two-dimensional-array-at-runtime/Julia/create-a-two-dimensional-array-at-runtime.julia @@ -1,38 +1,16 @@ -julia> "Inspired by Python's `input` function." - function input(prompt::AbstractString="") - print(prompt) - chomp(readline()) - end -input (generic function with 2 methods) +function input(prompt::AbstractString) + print(prompt) + return readline() +end -julia> n = parse(Int, input("Upper bound for dimension 1: ")) # parse as `Int` -Upper bound for dimension 1: 5 -5 +n = input("Upper bound for dimension 1: ") |> + x -> parse(Int, x) +m = input("Upper bound for dimension 2: ") |> + x -> parse(Int, x) -julia> m = parse(Int, input("Upper bound for dimension 2: ")) -Upper bound for dimension 2: 5 -5 - -julia> x = rand(n, m) # create an n·m random matrix -5x5 Array{Float64,2}: - 0.80217 0.422318 0.594049 0.45547 0.208822 - 0.0533981 0.304858 0.0276755 0.797732 0.828796 - 0.522506 0.563856 0.216759 0.865961 0.034306 - 0.792363 0.815744 0.868697 0.42509 0.588946 - 0.112034 0.539611 0.674581 0.508299 0.939373 - -julia> x[3, 3] # overloads `getindex` generic function -0.21675944652281487 - -julia> x[3, 3] = 5 # overloads `setindex!` generic function -5 - -julia> x::Matirx # `Matrix{T}` is an alias for `Array{T, 2}` -5x5 Array{Float64,2}: - 0.80217 0.422318 0.594049 0.45547 0.208822 - 0.0533981 0.304858 0.0276755 0.797732 0.828796 - 0.522506 0.563856 5.0 0.865961 0.034306 - 0.792363 0.815744 0.868697 0.42509 0.588946 - 0.112034 0.539611 0.674581 0.508299 0.939373 - -julia> x = 0; gc() # Julia has no `del` command, rebind `x` and call the garbage collector +x = rand(n, m) +display(x) +x[3, 3] # overloads `getindex` generic function +x[3, 3] = 5.0 # overloads `setindex!` generic function +x::Matrix # `Matrix{T}` is an alias for `Array{T, 2}` +x = 0; gc() # Julia has no `del` command, rebind `x` and call the garbage collector diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Rust/create-a-two-dimensional-array-at-runtime.rust b/Task/Create-a-two-dimensional-array-at-runtime/Rust/create-a-two-dimensional-array-at-runtime.rust index e609400e0c..86eaf4f633 100644 --- a/Task/Create-a-two-dimensional-array-at-runtime/Rust/create-a-two-dimensional-array-at-runtime.rust +++ b/Task/Create-a-two-dimensional-array-at-runtime/Rust/create-a-two-dimensional-array-at-runtime.rust @@ -1,28 +1,15 @@ use std::env; + fn main() { let mut args = env::args().skip(1).flat_map(|num| num.parse()); let rows = args.next().expect("Expected number of rows as first argument"); let cols = args.next().expect("Expected number of columns as second argument"); - assert!(rows != 0 && cols != 0); + assert_ne!(rows, 0, "rows were zero"); + assert_ne!(cols, 0, "cols were zero"); // Creates a vector of vectors with all elements initialized to 0. - let mut v = init_vec(rows, || init_vec(cols, || 0)); + let mut v = vec![vec![0; cols]; rows]; v[0][0] = 1; println!("{}", v[0][0]); - - -} - -// Returns a dynamically-allocated array of size `n`, -// initialized with the values computed by `f` - -fn init_vec(n: usize, f: F) -> Vec - where F: Fn() -> T -{ - let mut vec = Vec::with_capacity(n); - for _ in 0..n { - vec.push(f()); - } - vec } diff --git a/Task/Create-a-two-dimensional-array-at-runtime/Sinclair-ZX81-BASIC/create-a-two-dimensional-array-at-runtime.sinclair b/Task/Create-a-two-dimensional-array-at-runtime/Sinclair-ZX81-BASIC/create-a-two-dimensional-array-at-runtime.sinclair new file mode 100644 index 0000000000..efd5e989db --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/Sinclair-ZX81-BASIC/create-a-two-dimensional-array-at-runtime.sinclair @@ -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/Stata/create-a-two-dimensional-array-at-runtime-2.stata b/Task/Create-a-two-dimensional-array-at-runtime/Stata/create-a-two-dimensional-array-at-runtime-2.stata index 81d2ea9492..6918b9f336 100644 --- a/Task/Create-a-two-dimensional-array-at-runtime/Stata/create-a-two-dimensional-array-at-runtime-2.stata +++ b/Task/Create-a-two-dimensional-array-at-runtime/Stata/create-a-two-dimensional-array-at-runtime-2.stata @@ -1,8 +1,10 @@ mata mata stata display "Number of rows?" _request(nr) mata stata display "Number of columns?" _request(nc) -a=J($nr,$nc,0) -a[1,2]=1.5 +nr = strtoreal(st_global("nr")) +nc = strtoreal(st_global("nc")) +a = J(nr,nc,0) +a[1,2] = 1.5 a mata drop a end diff --git a/Task/Create-a-two-dimensional-array-at-runtime/VBA/create-a-two-dimensional-array-at-runtime.vba b/Task/Create-a-two-dimensional-array-at-runtime/VBA/create-a-two-dimensional-array-at-runtime.vba new file mode 100644 index 0000000000..f1ab460ff4 --- /dev/null +++ b/Task/Create-a-two-dimensional-array-at-runtime/VBA/create-a-two-dimensional-array-at-runtime.vba @@ -0,0 +1,19 @@ +Option Explicit + +Sub Main_Create_Array() +Dim NbColumns As Integer, NbRows As Integer + + 'Get two integers from the user, + Do + NbColumns = Application.InputBox("Enter number of columns : ", "Numeric only", 3, Type:=1) + NbRows = Application.InputBox("Enter number of rows : ", "Numeric only", 5, Type:=1) + Loop While NbColumns = 0 Or NbRows = 0 + 'Create a two-dimensional array at runtime + ReDim myArray(1 To NbRows, 1 To NbColumns) + 'Write some element of that array, + myArray(LBound(myArray, 1), UBound(myArray, 2)) = "Toto" + 'and then output that element. + MsgBox myArray(LBound(myArray, 1), UBound(myArray, 2)) + 'destroy the array + Erase myArray +End Sub diff --git a/Task/Create-an-HTML-table/Julia/create-an-html-table-1.julia b/Task/Create-an-HTML-table/Julia/create-an-html-table-1.julia new file mode 100644 index 0000000000..68962fa9f9 --- /dev/null +++ b/Task/Create-an-HTML-table/Julia/create-an-html-table-1.julia @@ -0,0 +1,13 @@ +function tag(x::Pair, attr::Pair...) + t, b = x + attrstr = join(" $n=\"$p\"" for (n, p) in attr) + return "<$t$attrstr>$b" +end + +colnames = split(",X,Y,Z", ',') + +header = join(tag(:th => txt) for txt in colnames) * "\n" +rows = collect(tag(:tr => join(tag(:td => i, :style => "font-weight: bold;") * join(tag(:td => rand(1000:9999)) for j in 1:3))) for i in 1:6) +body = "\n" * join(rows, '\n') * "\n" +table = tag(:table => string('\n', header, body, '\n'), :style => "width: 60%") +println(table) diff --git a/Task/Create-an-HTML-table/Julia/create-an-html-table-2.julia b/Task/Create-an-HTML-table/Julia/create-an-html-table-2.julia new file mode 100644 index 0000000000..eb3c211f60 --- /dev/null +++ b/Task/Create-an-HTML-table/Julia/create-an-html-table-2.julia @@ -0,0 +1,11 @@ + + + + + + + + + + +
XYZ
1539957703362
2456415775428
3625772906138
4391251632451
5142618743944
6389698277006
diff --git a/Task/Create-an-HTML-table/Rust/create-an-html-table-1.rust b/Task/Create-an-HTML-table/Rust/create-an-html-table-1.rust index 47b8b33532..d27ec2806f 100644 --- a/Task/Create-an-HTML-table/Rust/create-an-html-table-1.rust +++ b/Task/Create-an-HTML-table/Rust/create-an-html-table-1.rust @@ -2,18 +2,23 @@ extern crate rand; use rand::Rng; -fn random_cell() -> usize { - // Anything between 0 and 10000 has 4 digits or less - return rand::thread_rng().gen_range(0, 10000); +fn random_cell(rng: &mut R) -> u32 { + // Anything between 0 and 10_000 (exclusive) has 4 digits or fewer. Using `gen_range::` + // is faster for smaller RNGs. Because the parameters are constant, the compiler can do all + // the range construction at compile time, removing the need for + // `rand::distributions::range::Range` + rng.gen_range(0, 10_000) } fn main() { + let mut rng = rand::thread_rng(); // Cache the RNG for reuse + println!(""); for row in 0..3 { - let x = random_cell(); - let y = random_cell(); - let z = random_cell(); + let x = random_cell(&mut rng); + let y = random_cell(&mut rng); + let z = random_cell(&mut rng); println!("", row, x, y, z); } diff --git a/Task/Create-an-object-at-a-given-address/Julia/create-an-object-at-a-given-address.julia b/Task/Create-an-object-at-a-given-address/Julia/create-an-object-at-a-given-address.julia new file mode 100644 index 0000000000..0918a10f05 --- /dev/null +++ b/Task/Create-an-object-at-a-given-address/Julia/create-an-object-at-a-given-address.julia @@ -0,0 +1,13 @@ +function unsafepointers() + intspace = [42] + address = pointer_from_objref(intspace) + println("The address of intspace is $address") + anotherint = unsafe_pointer_to_objref(address) + println("intspace is $(intspace[1]), memory at $address, reference value $(anotherint[1])") + intspace[1] = 123456 + println("Now, intspace is $(intspace[1]), memory at $address, reference value $(anotherint[1])") + anotherint[1] = 7890 + println("Now, intspace is $(intspace[1]), memory at $(pointer_from_objref(anotherint)), reference value $(anotherint[1])") +end + +unsafepointers() diff --git a/Task/Currying/00DESCRIPTION b/Task/Currying/00DESCRIPTION index 77c39cb16d..a8fb8eed09 100644 --- a/Task/Currying/00DESCRIPTION +++ b/Task/Currying/00DESCRIPTION @@ -1,6 +1,10 @@ {{Wikipedia|Currying}} -Create a simple demonstrative example of [[wp:Currying|Currying]] in the specific language. + + +;Task: +Create a simple demonstrative example of [[wp:Currying|Currying]] in a specific language. Add any historic details as to how the feature made its way into the language. [[Category:Functions and subroutines]] +

diff --git a/Task/Currying/C/currying.c b/Task/Currying/C/currying.c new file mode 100644 index 0000000000..b710662d3d --- /dev/null +++ b/Task/Currying/C/currying.c @@ -0,0 +1,32 @@ +/*Abhishek Ghosh, 24th October 2017*/ +#include +#include + +long int factorial(int n){ + if(n>1) + return n*factorial(n-1); + return 1; +} + +long int sumOfFactorials(int num,...){ + va_list vaList; + long int sum = 0; + + va_start(vaList,num); + + while(num--) + sum += factorial(va_arg(vaList,int)); + + va_end(vaList); + + return sum; +} + +int main() +{ + printf("\nSum of factorials of [1,5] : %ld",sumOfFactorials(5,1,2,3,4,5)); + printf("\nSum of factorials of [3,5] : %ld",sumOfFactorials(3,3,4,5)); + printf("\nSum of factorials of [1,3] : %ld",sumOfFactorials(3,1,2,3)); + + return 0; +} diff --git a/Task/Currying/Ceylon/currying.ceylon b/Task/Currying/Ceylon/currying.ceylon new file mode 100644 index 0000000000..7018a5adf1 --- /dev/null +++ b/Task/Currying/Ceylon/currying.ceylon @@ -0,0 +1,10 @@ +shared void run() { + + function divide(Integer x, Integer y) => x / y; + + value partsOf120 = curry(divide)(120); + + print("half of 120 is ``partsOf120(2)`` + a third is ``partsOf120(3)`` + and a quarter is ``partsOf120(4)``"); +} diff --git a/Task/Currying/Factor/currying-1.factor b/Task/Currying/Factor/currying-1.factor new file mode 100644 index 0000000000..f9d7be4550 --- /dev/null +++ b/Task/Currying/Factor/currying-1.factor @@ -0,0 +1,8 @@ +IN: scratchpad 2 [ 3 + ] curry + +--- Data stack: +[ 2 3 + ] +IN: scratchpad call + +--- Data stack: +5 diff --git a/Task/Currying/Factor/currying-2.factor b/Task/Currying/Factor/currying-2.factor new file mode 100644 index 0000000000..baacf490b1 --- /dev/null +++ b/Task/Currying/Factor/currying-2.factor @@ -0,0 +1,9 @@ +IN: scratchpad [ 3 4 ] [ 5 + ] compose + +--- Data stack: +[ 3 4 5 + ] +IN: scratchpad call + +--- Data stack: +3 +9 diff --git a/Task/Currying/Factor/currying-3.factor b/Task/Currying/Factor/currying-3.factor new file mode 100644 index 0000000000..da1b0e4100 --- /dev/null +++ b/Task/Currying/Factor/currying-3.factor @@ -0,0 +1,4 @@ +IN: scratchpad { 1 2 3 4 5 } [ 1 + ] { 2 / } append map + +--- Data stack: +{ 1 1+1/2 2 2+1/2 3 } diff --git a/Task/Currying/Factor/currying-4.factor b/Task/Currying/Factor/currying-4.factor new file mode 100644 index 0000000000..e25a6f3458 --- /dev/null +++ b/Task/Currying/Factor/currying-4.factor @@ -0,0 +1,5 @@ +USE: fry +IN: scratchpad 2 3 '[ _ _ + ] + +--- Data stack: +[ 2 3 + ] diff --git a/Task/Currying/Factor/currying-5.factor b/Task/Currying/Factor/currying-5.factor new file mode 100644 index 0000000000..dc50e93f96 --- /dev/null +++ b/Task/Currying/Factor/currying-5.factor @@ -0,0 +1,4 @@ +IN: scratchpad { 1 2 3 4 5 } [ 1 + ] '[ 2 + @ ] map + +--- Data stack: +{ 4 5 6 7 8 } diff --git a/Task/Currying/Python/currying-3.py b/Task/Currying/Python/currying-3.py new file mode 100644 index 0000000000..447fb32c0a --- /dev/null +++ b/Task/Currying/Python/currying-3.py @@ -0,0 +1,10 @@ +>>> from functools import partial +>>> from operator import add +>>> add2 = partial(add, 2) +>>> add2 +functools.partial(, 2) +>>> add2(7) +9 +>>> double = partial(map, lambda x: x*2) +>>> print(*double(range(5))) +0 2 4 6 8 diff --git a/Task/Currying/Python/currying-4.py b/Task/Currying/Python/currying-4.py new file mode 100644 index 0000000000..8d4147054b --- /dev/null +++ b/Task/Currying/Python/currying-4.py @@ -0,0 +1,13 @@ +>>> from toolz import curry +>>> import operator +>>> add = curry(operator.add) +>>> add2 = add(2) +>>> add2 + +>>> add2(7) +9 +>>> # Toolz also has pre-curried versions of most HOFs from builtins, stdlib, and toolz +>>>from toolz.curried import map +>>> double = map(lambda x: x*2) +>>> print(*double(range(5))) +0 2 4 6 8 diff --git a/Task/Currying/Rust/currying.rust b/Task/Currying/Rust/currying.rust index b303ddea95..c5b0458fff 100644 --- a/Task/Currying/Rust/currying.rust +++ b/Task/Currying/Rust/currying.rust @@ -1,4 +1,3 @@ -#![feature(conservative_impl_trait)] fn add_n(n : i32) -> impl Fn(i32) -> i32 { move |x| n + x } diff --git a/Task/Cut-a-rectangle/Perl-6/cut-a-rectangle.pl6 b/Task/Cut-a-rectangle/Perl-6/cut-a-rectangle.pl6 index db7d849a72..429f41f805 100644 --- a/Task/Cut-a-rectangle/Perl-6/cut-a-rectangle.pl6 +++ b/Task/Cut-a-rectangle/Perl-6/cut-a-rectangle.pl6 @@ -64,7 +64,7 @@ sub solve(Int $hh, Int $ww, Int $recur) returns Int { } my ($y, $x); -loop ($y = 1; $y <= 10; $y++) { +loop ($y = 1; $y <= 9; $y++) { loop ($x = 1; $x <= $y; $x++) { if (!($x +& 1) || !($y +& 1)) { printf("%d x %d: %d\n", $y, $x, solve($y, $x, 1)); diff --git a/Task/DNS-query/Crystal/dns-query.crystal b/Task/DNS-query/Crystal/dns-query.crystal new file mode 100644 index 0000000000..b6d7adf2d5 --- /dev/null +++ b/Task/DNS-query/Crystal/dns-query.crystal @@ -0,0 +1,9 @@ +require "socket" + +Socket::Addrinfo.resolve( + "www.kame.net", + 80, + type: Socket::Type::STREAM +).each { |a| + puts a.ip_address.address +} diff --git a/Task/DNS-query/Objeck/dns-query.objeck b/Task/DNS-query/Objeck/dns-query.objeck new file mode 100644 index 0000000000..7e15e13672 --- /dev/null +++ b/Task/DNS-query/Objeck/dns-query.objeck @@ -0,0 +1,10 @@ +use System.IO.Net; + +class Rosetta { + function : Main(args : String[]) ~ Nil { + resoloved := TCPSocket->Resolve("www.kame.net"); + each(i : resoloved) { + resoloved[i]->PrintLine(); + }; + } +} diff --git a/Task/Date-format/Julia/date-format.julia b/Task/Date-format/Julia/date-format.julia index f15fd6125b..c6c2775789 100644 --- a/Task/Date-format/Julia/date-format.julia +++ b/Task/Date-format/Julia/date-format.julia @@ -1,5 +1,5 @@ -ts = time() +ts = Dates.today() println("Today's date is:") -println(" ", strftime("%F", ts)) -println(" ", strftime("%A, %B %d, %Y", ts)) +println("\t$ts") +println("\t", Dates.format(ts, "E, U dd, yyyy")) diff --git a/Task/Date-manipulation/D/date-manipulation.d b/Task/Date-manipulation/D/date-manipulation.d new file mode 100644 index 0000000000..1a7332b89c --- /dev/null +++ b/Task/Date-manipulation/D/date-manipulation.d @@ -0,0 +1,30 @@ +import std.stdio; +import std.format; +import std.datetime; +import std.algorithm; + +enum months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; + +void main() +{ + // input + string date = "March 7 2009 7:30pm EST"; + + // parsing date string to integer values + string month, md, tz; + int day, year, hour, minute; + date.formattedRead("%s %d %d %d:%d%s %s", &month, &day, &year, &hour, &minute, &md, &tz); + int mon = cast (int) months.countUntil(month) + 1; + + // convert to 24-hour + if (md == "pm") + hour += 12; + + // create date from integer + DateTime dt = DateTime(year, mon, day, hour, minute); + + // output + writeln(dt); + writeln(dt + 12.hours); + +} diff --git a/Task/Date-manipulation/Julia/date-manipulation.julia b/Task/Date-manipulation/Julia/date-manipulation.julia new file mode 100644 index 0000000000..aa8bfd93ab --- /dev/null +++ b/Task/Date-manipulation/Julia/date-manipulation.julia @@ -0,0 +1,12 @@ +using Base.Dates + +function main() + dtstr = "March 7 2009 7:30pm" # Base.Dates doesn't handle "EST" + cleandtstr = replace(dtstr, r"(am|pm)"i, "") + dtformat = dateformat"U dd yyyy HH:MM" + dtime = parse(DateTime, cleandtstr, dtformat) + + Hour(12 * contains(dtstr, r"pm"i)) # add 12h for the pm + println(Dates.format(dtime + Hour(12), dtformat)) +end + +main() diff --git a/Task/Date-manipulation/Maple/date-manipulation-1.maple b/Task/Date-manipulation/Maple/date-manipulation-1.maple new file mode 100644 index 0000000000..fbda4cdcde --- /dev/null +++ b/Task/Date-manipulation/Maple/date-manipulation-1.maple @@ -0,0 +1,15 @@ +twelve_hours := proc(str) + local dt, zone; + local months := ["January","February","March","April","May","June","July","August","September","October","November","December"]; + dt := StringTools:-ParseTime("%B %d %Y %l:%M%p", str); + zone := StringTools:-RegSplit(" ", str)[-1]; + dt := Date(dt:-year, dt:-month, dt:-monthDay, dt:-hour, dt:-minute, timezone = zone); + dt := dt + 12 * Unit(hours); + printf("%s %d %d ", months[Month(dt)], DayOfMonth(dt), Year(dt)); + if (HourOfDay(dt) >= 12) then + printf("%d:%dpm ", HourOfDay(dt)-12, Minute(dt)); + else + printf("%d:%dam ", HourOfDay(dt), Minute(dt)); + end if; + printf(TimeZone(dt)); +end proc; diff --git a/Task/Date-manipulation/Maple/date-manipulation-2.maple b/Task/Date-manipulation/Maple/date-manipulation-2.maple new file mode 100644 index 0000000000..0c842e2727 --- /dev/null +++ b/Task/Date-manipulation/Maple/date-manipulation-2.maple @@ -0,0 +1,3 @@ +twelve_hours("March 7 2009 7:30pm EST"); +twelve_hours("March 2 2009 0:10am WET"); +twelve_hours("March 2 2009 6:30am AST"); diff --git a/Task/Date-manipulation/Red/date-manipulation.red b/Task/Date-manipulation/Red/date-manipulation.red new file mode 100644 index 0000000000..9ea0fa80ff --- /dev/null +++ b/Task/Date-manipulation/Red/date-manipulation.red @@ -0,0 +1,6 @@ +d: 07-Mar-2009/19:30 + 12:00 +print d +8-Mar-2009/7:30:00 +d/timezone: 1 +print d +8-Mar-2009/8:30:00+01:00 diff --git a/Task/Date-manipulation/Ring/date-manipulation.ring b/Task/Date-manipulation/Ring/date-manipulation.ring new file mode 100644 index 0000000000..d5a2667e7b --- /dev/null +++ b/Task/Date-manipulation/Ring/date-manipulation.ring @@ -0,0 +1,29 @@ +# Project : Date manipulation +# Date : 2018/02/14 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +load "stdlib.ring" +dateorigin = "March 7 2009 7:30pm EST" +monthname = "January February March April May June July August September October November December" +for i = 1 to 12 + if dateorigin[1] = monthname[i] + monthnum = i + ok +next +thedate = str2list(substr(dateorigin, " ", nl)) +t = thedate[4] +t1 = substr(t,"pm", "") +t2 = substr(t1,":",".") +t3 = number(t2) +if right(t,2) = "pm" + t3 = t3+ 12 +ok +ap = "pm" +d = "07/03/2009" +if t3 + 12 > 24 + d = adddays("07/03/2009",1) + ap = "am" +ok +see "Original - " + dateorigin + nl +see "Manipulated - " + d + " " + t1 + ap + nl diff --git a/Task/Day-of-the-week/00DESCRIPTION b/Task/Day-of-the-week/00DESCRIPTION index 07eb00a9f2..91a8ebf482 100644 --- a/Task/Day-of-the-week/00DESCRIPTION +++ b/Task/Day-of-the-week/00DESCRIPTION @@ -4,6 +4,8 @@ A company decides that whenever Xmas falls on a Sunday they will give their workers all extra paid holidays so that, together with any public holidays, workers will not have to work the following week (between the 25th of December and the first of January). + +;Task: '''In what years between 2008 and 2121 will the 25th of December be a Sunday?''' Using any standard date handling libraries of your programming language; 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 298658aba8..d6b6ab012c 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,15 +1,10 @@ -isdefined(:Date) || using Dates +using Base.Dates -lo = 2008 -hi = 2121 -xmas = Date(lo, 12, 25):Year(1):Date(hi, 12, 25) - -smas = recur(xmas) do y - Dates.dayofweek(y) == Dates.Sun +lo, hi = 2008, 2121 +xmas = collect(Date(lo, 12, 25):Year(1):Date(hi, 12, 25)) +filter!(xmas) do dt + dayofweek(dt) == Dates.Sunday end -println("Years (from ", lo, " to ", hi, ") having Christmas on a Sunday:") - -for y in smas - println(" ", Dates.year(y)) -end +println("Years from $lo to $hi having Christmas on Sunday: ") +foreach(println, year.(xmas)) diff --git a/Task/Day-of-the-week/Maple/day-of-the-week.maple b/Task/Day-of-the-week/Maple/day-of-the-week.maple new file mode 100644 index 0000000000..1db6536ea8 --- /dev/null +++ b/Task/Day-of-the-week/Maple/day-of-the-week.maple @@ -0,0 +1,11 @@ +xmas:= proc() + local i, dt; + for i from 2008 to 2121 by 1 do + dt := Date(i, 12, 25); + if (Calendar:-DayOfWeek(dt) = 1) then + print(i); + end if; + end do; +end proc; + +xmas(); diff --git a/Task/Day-of-the-week/Red/day-of-the-week.red b/Task/Day-of-the-week/Red/day-of-the-week.red new file mode 100644 index 0000000000..5217f9bf25 --- /dev/null +++ b/Task/Day-of-the-week/Red/day-of-the-week.red @@ -0,0 +1,15 @@ +Red [] +repeat yy 114 [ + d: to-date reduce [25 12 (2007 + yy )] + if 7 = d/weekday [ print d ] ;; 7 = sunday +] +;; or +print "version 2" + +d: to-date [25 12 2008] +while [d <= 25/12/2121 ] [ + if 7 = d/weekday [ + print rejoin [d/day '. d/month '. d/year ] + ] + d/year: d/year + 1 +] diff --git a/Task/Day-of-the-week/Rust/day-of-the-week.rust b/Task/Day-of-the-week/Rust/day-of-the-week.rust new file mode 100644 index 0000000000..2af8ccae87 --- /dev/null +++ b/Task/Day-of-the-week/Rust/day-of-the-week.rust @@ -0,0 +1,8 @@ +extern crate chrono; + +use chrono::prelude::*; + +fn main() { + let years = (2008..2121).filter(|&y| Local.ymd(y, 12, 25).weekday() == Weekday::Sun).collect::>(); + println!("Years = {:?}", years); +} diff --git a/Task/Day-of-the-week/Stata/day-of-the-week.stata b/Task/Day-of-the-week/Stata/day-of-the-week.stata index 1f650bc1e4..f3aa0a8498 100644 --- a/Task/Day-of-the-week/Stata/day-of-the-week.stata +++ b/Task/Day-of-the-week/Stata/day-of-the-week.stata @@ -1,28 +1,25 @@ -clear all +clear range year 2008 2121 `=2121-2008+1' -list if dow(mdy(12,25,year))==0 +list if dow(mdy(12,25,year))==0, noobs sep(50) - +------+ - | year | - |------| - 4. | 2011 | - 9. | 2016 | - 15. | 2022 | - 26. | 2033 | - 32. | 2039 | - |------| - 37. | 2044 | - 43. | 2050 | - 54. | 2061 | - 60. | 2067 | - 65. | 2072 | - |------| - 71. | 2078 | - 82. | 2089 | - 88. | 2095 | - 94. | 2101 | -100. | 2107 | - |------| -105. | 2112 | -111. | 2118 | - +------+ + +------+ + | year | + |------| + | 2011 | + | 2016 | + | 2022 | + | 2033 | + | 2039 | + | 2044 | + | 2050 | + | 2061 | + | 2067 | + | 2072 | + | 2078 | + | 2089 | + | 2095 | + | 2101 | + | 2107 | + | 2112 | + | 2118 | + +------+ diff --git a/Task/Day-of-the-week/VBA/day-of-the-week.vba b/Task/Day-of-the-week/VBA/day-of-the-week.vba new file mode 100644 index 0000000000..b3f91a312a --- /dev/null +++ b/Task/Day-of-the-week/VBA/day-of-the-week.vba @@ -0,0 +1,13 @@ +Option Explicit + +Sub MainDayOfTheWeek() + Debug.Print "Xmas will be a Sunday in : " & XmasSunday(2008, 2121) +End Sub + +Private Function XmasSunday(firstYear As Integer, lastYear As Integer) As String +Dim i As Integer, temp$ + For i = firstYear To lastYear + If Weekday(CDate("25/12/" & i)) = vbSunday Then temp = temp & ", " & i + Next + XmasSunday = Mid(temp, 2) +End Function diff --git a/Task/Deal-cards-for-FreeCell/Groovy/deal-cards-for-freecell.groovy b/Task/Deal-cards-for-FreeCell/Groovy/deal-cards-for-freecell.groovy new file mode 100644 index 0000000000..24b2c1da59 --- /dev/null +++ b/Task/Deal-cards-for-FreeCell/Groovy/deal-cards-for-freecell.groovy @@ -0,0 +1,41 @@ +class FreeCell{ + int seed + + List createDeck(){ + List suits = ['♣','♦','♥','♠'] + List values = ['A','2','3','4','5','6','7','8','9','10','J','Q','K'] + return [suits,values].combinations{suit,value -> "$suit$value"} + } + + int random() { + seed = (214013 * seed + 2531011) & Integer.MAX_VALUE + return seed >> 16 + } + + List shuffledDeck(List cards) { + List deck = cards.clone() + + (deck.size() - 1..1).each{index -> + int r = random() % (index + 1) + deck.swap(r, index) + } + + return deck + } + + List dealGame(int seed = 1){ + this.seed= seed + List cards = shuffledDeck(createDeck()) + + (1..cards.size()).each{ number-> + print "${cards.pop()}\t" + if(number % 8 == 0) println('') + } + + println('\n') + } +} + +def freecell = new FreeCell() +freecell.dealGame() +freecell.dealGame(617) diff --git a/Task/Deal-cards-for-FreeCell/Objeck/deal-cards-for-freecell.objeck b/Task/Deal-cards-for-FreeCell/Objeck/deal-cards-for-freecell.objeck new file mode 100644 index 0000000000..ddb7b187a8 --- /dev/null +++ b/Task/Deal-cards-for-FreeCell/Objeck/deal-cards-for-freecell.objeck @@ -0,0 +1,70 @@ +class FreeCell { + function : Main(args : String[]) ~ Nil { + Deal(1)->PrintLine(); + Deal(617)->PrintLine(); + } + + function : Deal(seed : Int) ~ String { + deck := Deck->New(seed)->ToString(); + return "Game #{$seed}:\n{$deck}\n"; + } +} + +class Deck { + @cards : Card[]; + + New(seed : Int) { + r := Random->New(seed); + + @cards := Card->New[52]; + for(i := 0; i < 52; i+= 1;) { + @cards[i] := Card->New(51 - i); + }; + + for(i := 0; i < 51; i += 1;) { + j := 51 - r->Next() % (52 - i); + tmp := @cards[i]; @cards[i] := @cards[j]; @cards[j] := tmp; + }; + } + + method : public : ToString() ~ String { + buffer := ""; + + each(i : @cards) { + buffer += @cards[i]->ToString(); + buffer += (i % 8 = 7 ? "\n" : " "); + }; + + return buffer; + } + + +} + +class Random { + @seed : Int; + + New(seed : Int) { + @seed := seed; + } + + method : public : Next() ~ Int { + @seed := (@seed * 214013 + 2531011) and Int->MaxSize(); + return @seed >> 16; + } +} + +class Card { + @value : Int; + @suit : Int; + + New(value : Int) { + @value := value / 4; @suit := value % 4; + } + + method : public : ToString() ~ String { + suits := "♣♦♥♠"; values := "A23456789TJQK"; + value := values->Get(@value); suit := suits->Get(@suit); + return "{$value}{$suit}"; + } +} diff --git a/Task/Deal-cards-for-FreeCell/REXX/deal-cards-for-freecell.rexx b/Task/Deal-cards-for-FreeCell/REXX/deal-cards-for-freecell.rexx index 72fcef3367..a20c3d82c9 100644 --- a/Task/Deal-cards-for-FreeCell/REXX/deal-cards-for-freecell.rexx +++ b/Task/Deal-cards-for-FreeCell/REXX/deal-cards-for-freecell.rexx @@ -1,25 +1,26 @@ /*REXX program deals cards for a specific FreeCell solitaire card game (0 ──► 32767).*/ numeric digits 15 /*ensure enough digits for the random #*/ -parse arg g c . /*obtain optional arguments from the CL*/ -if g=='' | g=="," then g=1 /*No game specified? Then use default.*/ -if c=='' | c=="," then c=8 /* " cols " " " " */ -state=g /*seed random # generator with game num*/ +parse arg game cols . /*obtain optional arguments from the CL*/ +if game=='' | game=="," then game=1 /*No game specified? Then use default.*/ +if cols=='' | cols=="," then cols=8 /* " cols " " " " */ +state=game /*seed random # generator with game num*/ if 8=='f8'x then suit= "cdhs" /*EBCDIC? Then use letters for suits.*/ else suit= "♣♦♥♠" /* ASCII? " " symbols " " */ rank= 'A23456789tJQK' /*t in the rank represents a ten (10).*/ -__=left('', 13) /*used for indentation for the tableau.*/ -say center('tableau for FreeCell game' g,50,"─") /*show a title for the FreeCell game #.*/ +pad=left('', 13) /*used for indentation for the tableau.*/ +say center('tableau for FreeCell game' game, 50, "─") /*show title for FreeCell game #*/ say /* [↓] @ is an array of all 52 cards.*/ #=-1; do r=1 for length(rank) /*build the deck first by the rank. */ do s=1 for length(suit); #=#+1 /* " " " secondly " " suit. */ - @.#=substr(rank,r,1)substr(suit,s,1) /*build the $ array one card at at time*/ + @.#=substr(rank, r,1)substr(suit, s,1) /*build the $ array one card at at time*/ end /*s*/ /* [↑] first card is number 0 (zero).*/ end /*r*/ /* [↑] build deck per FreeCell rules. */ -$=__ /*@: cards to be dealt, eight at a time*/ +$=pad /*@: cards to be dealt, eight at a time*/ do cards=51 by -1 for 52 /* [↓] deal the cards for the tableau.*/ ?=rand() // (cards+1) /*get next rand#; card # is remainder.*/ $=$ @.?; @.?=@.cards /*swap two cards: use random and last.*/ - if words($)==c then do; say $; $=__; end /*deal FreeCell cards for the tableau. */ + if words($)==cols then do; say $; $=pad /*deal FreeCell cards for the tableau. */ + end end /*cards*/ /*normally, 8 cards are dealt to a row.*/ /* [↓] residual cards may exist. */ if $\='' then say $ /*Any residual cards in the tableau ? */ diff --git a/Task/Deal-cards-for-FreeCell/Rust/deal-cards-for-freecell.rust b/Task/Deal-cards-for-FreeCell/Rust/deal-cards-for-freecell.rust index 71003a7eac..3eb91ab697 100644 --- a/Task/Deal-cards-for-FreeCell/Rust/deal-cards-for-freecell.rust +++ b/Task/Deal-cards-for-FreeCell/Rust/deal-cards-for-freecell.rust @@ -1,59 +1,48 @@ -struct MSVCRandGen { - seed: u32 -} +// Code available at https://rosettacode.org/wiki/Linear_congruential_generator#Rust +extern crate linear_congruential_generator; -impl MSVCRandGen { - fn rand(&mut self) -> u32 { - self.seed = (self.seed.wrapping_mul(214013).wrapping_add(2531011)) % 0x80000000; - assert!(self.seed >> 16 < 32768); - (self.seed >> 16) & 0x7FFF - } - fn max_rand(&mut self, mymax: u32) -> u32 { - self.rand() % mymax - } - fn shuffle(&mut self, deck: &mut [T]) { - if deck.len() > 0 { - let mut i = (deck.len() as u32) - 1; - while i > 0 { - let j = self.max_rand(i+1); - deck.swap(i as usize, j as usize); - i = i-1; - } - } +use linear_congruential_generator::{MsLcg, Rng, SeedableRng}; + +// We can't use `rand::Rng::shuffle` because it uses the more uniform `rand::Rng::gen_range` +// (`% range` is subject to modulo bias). If an exact match of the old dealer is not needed, +// `rand::Rng::shuffle` should be used. +fn shuffle(rng: &mut MsLcg, deck: &mut [T]) { + let len = deck.len() as u32; + for i in (1..len).rev() { + let j = rng.next_u32() % (i + 1); + deck.swap(i as usize, j as usize); } } -fn deal_ms_fc_board(seed: u32) -> String { - let mut randomizer = MSVCRandGen { seed: seed, }; - let num_cols = 8; +fn gen_deck() -> Vec { + const RANKS: [char; 13] = ['A','2','3','4','5','6','7','8','9','T','J','Q','K']; + const SUITS: [char; 4] = ['C', 'D', 'H', 'S']; - let mut columns = vec![Vec::new(); num_cols]; - let mut deck: Vec<_> = (0..4*13).collect(); + let render_card = |card: usize| { + let (suit, rank) = (card % 4, card / 4); + format!("{}{}", RANKS[rank], SUITS[suit]) + }; - let rank_strings: Vec = "A23456789TJQK".chars().collect(); - let suit_strings: Vec = "CDHS".chars().collect(); + (0..52).map(render_card).collect() +} - randomizer.shuffle(&mut deck); +fn deal_ms_fc_board(seed: u32) -> Vec { + let mut rng = MsLcg::from_seed(seed); + let mut deck = gen_deck(); + shuffle(&mut rng, &mut deck); deck.reverse(); - for i in 0..52 { - columns[i % num_cols].push(deck[i]); - } - - let render_card = |card: usize| -> String { - let (suit, rank) = (card % 4, card / 4); - format!("{}{}", rank_strings[rank], suit_strings[suit]) - }; - - let render_column = |col: Vec| -> String { - format!(": {}\n", col.into_iter().map(&render_card).collect::>().join(" ")) - }; - - columns.into_iter().map(render_column).collect::>().join("") + deck.chunks(8).map(|row| row.join(" ")).collect::>() } fn main() { - let arg: u32 = std::env::args().nth(1).and_then(|n| n.parse().ok()).expect("I need a number."); - print!("{}", deal_ms_fc_board(arg)); + let seed = std::env::args() + .nth(1) + .and_then(|n| n.parse().ok()) + .expect("A 32-bit seed is required"); + + for row in deal_ms_fc_board(seed) { + println!(": {}", row); + } } diff --git a/Task/Death-Star/00DESCRIPTION b/Task/Death-Star/00DESCRIPTION index 3fed6b9b0c..a9c755c485 100644 --- a/Task/Death-Star/00DESCRIPTION +++ b/Task/Death-Star/00DESCRIPTION @@ -1,7 +1,9 @@ {{omit from|AWK|Does not have this functionality in the language}} {{omit from|Lotus 123 Macro Scripting}} {{omit from|ML/I}} +{{omit from|Modula-2}} {{omit from|Retro}} +{{omit from|SQL PL|It does not handle GUI}} [[File:Deathstar-tcl.gif|400px|thumb]] diff --git a/Task/Death-Star/Perl-6/death-star.pl6 b/Task/Death-Star/Perl-6/death-star.pl6 index 8e330bc977..b8a2f3f32c 100644 --- a/Task/Death-Star/Perl-6/death-star.pl6 +++ b/Task/Death-Star/Perl-6/death-star.pl6 @@ -30,7 +30,7 @@ my $neg = sphere.new( ); sub MAIN ($outfile = 'deathstar-perl6.pgm') { - spurt $outfile, ("P5\n$x $y\n$depth"); # .pgm header + spurt $outfile, ("P5\n$x $y\n$depth\n"); # .pgm header my $out = open( $outfile, :a, :bin ) or die "$!\n"; say 'Calculating row:'; $out.write( Blob.new( draw_ds(3, .15) ) ); diff --git a/Task/Deconvolution-1D/Go/deconvolution-1d-3.go b/Task/Deconvolution-1D/Go/deconvolution-1d-3.go new file mode 100644 index 0000000000..0510139bfc --- /dev/null +++ b/Task/Deconvolution-1D/Go/deconvolution-1d-3.go @@ -0,0 +1,36 @@ +package main + +import ( + "fmt" + + "gonum.org/v1/gonum/mat" +) + +var ( + h = []float64{-8, -9, -3, -1, -6, 7} + f = []float64{-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1} + g = []float64{24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96, + 96, 31, 55, 36, 29, -43, -7} +) + +func band(g, f []float64) *mat.Dense { + nh := len(g) - len(f) + 1 + b := mat.NewDense(len(g), nh, nil) + for j := 0; j < nh; j++ { + for i, fi := range f { + b.Set(i+j, j, fi) + } + } + return b +} + +func deconv(g, f []float64) mat.Matrix { + z := mat.NewDense(len(g)-len(f)+1, 1, nil) + z.Solve(band(g, f), mat.NewVecDense(len(g), g)) + return z +} + +func main() { + fmt.Printf("deconv(g, f) =\n%.1f\n\n", mat.Formatted(deconv(g, f))) + fmt.Printf("deconv(g, h) =\n%.1f\n", mat.Formatted(deconv(g, h))) +} diff --git a/Task/Deconvolution-1D/Haskell/deconvolution-1d.hs b/Task/Deconvolution-1D/Haskell/deconvolution-1d.hs new file mode 100644 index 0000000000..8e0d1b9415 --- /dev/null +++ b/Task/Deconvolution-1D/Haskell/deconvolution-1d.hs @@ -0,0 +1,43 @@ +deconv1d :: [Double] -> [Double] -> [Double] +deconv1d xs ys = takeWhile (/= 0) $ deconv xs ys + where + [] `deconv` _ = [] + (0:xs) `deconv` (0:ys) = xs `deconv` ys + (x:xs) `deconv` (y:ys) = + let q = x / y + in q : zipWith (-) xs (scale q ys ++ repeat 0) `deconv` (y : ys) + +scale :: Double -> [Double] -> [Double] +scale = map . (*) + +h, f, g :: [Double] +h = [-8, -9, -3, -1, -6, 7] + +f = [-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1] + +g = + [ 24 + , 75 + , 71 + , -34 + , 3 + , 22 + , -45 + , 23 + , 245 + , 25 + , 52 + , 25 + , -67 + , -96 + , 96 + , 31 + , 55 + , 36 + , 29 + , -43 + , -7 + ] + +main :: IO () +main = print $ (h == deconv1d g f) && (f == deconv1d g h) diff --git a/Task/Deconvolution-1D/Julia/deconvolution-1d.julia b/Task/Deconvolution-1D/Julia/deconvolution-1d.julia new file mode 100644 index 0000000000..536125a87a --- /dev/null +++ b/Task/Deconvolution-1D/Julia/deconvolution-1d.julia @@ -0,0 +1,9 @@ +h = [-8, -9, -3, -1, -6, 7] +g = [24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96, 96, 31, 55, 36, 29, -43, -7] +f = [-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1] + +hanswer = deconv(float.(g), float.(f)) +println("The deconvolution deconv(g, f) is $hanswer, which is the same as h = $h\n") + +fanswer = deconv(float.(g), float.(h)) +println("The deconvolution deconv(g, h) is $fanswer, which is the same as f = $f\n") diff --git a/Task/Deconvolution-1D/Perl-6/deconvolution-1d.pl6 b/Task/Deconvolution-1D/Perl-6/deconvolution-1d.pl6 index 0d6e3c030c..3d954c104c 100644 --- a/Task/Deconvolution-1D/Perl-6/deconvolution-1d.pl6 +++ b/Task/Deconvolution-1D/Perl-6/deconvolution-1d.pl6 @@ -20,13 +20,11 @@ sub rref ($m is copy) { return unless $m; my ($lead, $rows, $cols) = 0, +$m, +$m[0]; - # Trim off over specified rows if they exist. - # Not strictly necessary, but can save a lot of - # redundant calculations. [remove until debugged] -# if $rows >= $cols { -# $m = trim_system($m); -# $rows = +$m; -# } + # Trim off over specified rows if they exist, for efficiency + if $rows >= $cols { + $m = trim_system($m); + $rows = +$m; + } for ^$rows -> $r { $lead < $cols or return $m; @@ -58,10 +56,10 @@ sub rref ($m is copy) { my ($vars, @t) = +$m[0]-1, (); for ^$vars -> $lead { for ^$m -> $row { - @t.push( $m.splice( $row, 1 ) ) and last if $m[$row][$lead]; + @t.push: | $m.splice( $row, 1 ) and last if $m[$row][$lead]; } } - while (+@t < $vars) and +$m { @t.push( $m.splice( 0, 1 ) ) }; + while (+@t < $vars) and +$m { @t.push: $m.splice( 0, 1 ) }; return @t; } } diff --git a/Task/Deconvolution-1D/REXX/deconvolution-1d.rexx b/Task/Deconvolution-1D/REXX/deconvolution-1d.rexx new file mode 100644 index 0000000000..8cf2708085 --- /dev/null +++ b/Task/Deconvolution-1D/REXX/deconvolution-1d.rexx @@ -0,0 +1,37 @@ +/*REXX pgm performs deconvolution of two arrays: deconv(g,f)=h and deconv(g,h)=f */ +call make@ 'H', "-8 -9 -3 -1 -6 7" +call make@ 'F', "-3 -6 -1 8 -6 3 -1 -9 -9 3 -2 5 2 -2 -7 -1" +call make@ 'G', "24 75 71 -34 3 22 -45 23 245 25 52 25 -67 -96 96 31 55 36 29 -43 -7" +call show@ 'H' /*display the elements of array H. */ +call show@ 'F' /* " " " " " F. */ +call show@ 'G' /* " " " " " G. */ +call deco@ 'G', "F", 'X' /*deconvolution of G and F ───► X */ +call test@ 'X', "H" /*test: is array H equal to array X?*/ +call deco@ 'G', "H", 'Y' /*deconvolution of G and H ───► Y */ +call test@ 'F', "Y" /*test: is array F equal to array Y?*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +deco@: parse arg $1,$2,$r; b=@.$2.# + 1; a=@.$1.# + 1 /*get sizes of array 1&2*/ + @.$r.#=a - b /*size of return array. */ + do n=0 to a-b /*define return array. */ + @.$r.n=@.$1.n /*define RETURN element.*/ + if n0 then do j=L to n-1; _=n-j /*define elements > 0. */ + @.$r.n=@.$r.n - @.$r.j * @.$2._ /*compute " " " */ + end /*j*/ /* [↑] subtract product.*/ + @.$r.n=@.$r.n / @.$2.0 /*divide array element. */ + end /*n*/; return +/*──────────────────────────────────────────────────────────────────────────────────────*/ +make@: parse arg $,z; @.$.#=words(z) - 1 /*obtain args; set size.*/ + do k=0 to @.$.#; @.$.k=word(z,k+1) /*define array element. */ + end /*k*/; return /*array starts at unity.*/ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +show@: parse arg $,z,_; do s=0 to @.$.#; _=strip(_ @.$.s) /*obtain the arguments. */ + end /*s*/ /* [↑] build the list. */ + say 'array' $": "_; return /*show the list; return*/ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +test@: parse arg $1,$2; do t=0 to max(@.$1.#, @.$2.#) /*obtain the arguments. */ + if @.$1.t=@.$2.t then iterate /*create array list. */ + say "***error*** arrays" $1 ' and ' $2 "aren't equal." + end /*t*/; return /* [↑] build the list. */ diff --git a/Task/Deconvolution-2D+/Perl-6/deconvolution-2d+.pl6 b/Task/Deconvolution-2D+/Perl-6/deconvolution-2d+.pl6 new file mode 100644 index 0000000000..510f30ae94 --- /dev/null +++ b/Task/Deconvolution-2D+/Perl-6/deconvolution-2d+.pl6 @@ -0,0 +1,141 @@ +# Deconvolution of N dimensional matrices. +sub deconvolve-N ( @g, @f ) { + my @hsize = @g.shape »-« @f.shape »+» 1; + + my @toSolve = coords(@g.shape).map: + { [row(@g, @f, $^coords, @hsize)] }; + + my @solved = rref( @toSolve ); + + my @h; + for flat coords(@hsize) Z @solved[*;*-1] -> $_, $v { + @h.AT-POS(|$_) = $v; + } + return @h; +} + +# Construct a row for each value in @g to be sent to the simultaneous equation solver +sub row ( @g, @f, @gcoord, $hsize ) { + my @row; + @gcoord = @gcoord[(^@f.shape)]; # clip extraneous values + for coords( $hsize ) -> @hc { + my @fcoord; + for ^@hc -> $i { + my $window = @gcoord[$i] - @hc[$i]; + @fcoord.push($window) and next if 0 <= $window < @f.shape[$i]; + last; + } + @row.push: @fcoord == @hc ?? @f.AT-POS(|@fcoord) !! 0; + } + @row.push: @g.AT-POS(|@gcoord); + return @row; +} + +# Constructs an AoA of coordinates to all elements of N dimensional array +sub coords ( @dim ) { + @[reverse $_ for [X] ([^$_] for reverse @dim)]; +} + +# Reduced Row Echelon Form simultaneous equation solver +# Can handle over-specified systems (N unknowns in N + M equations) +sub rref (@m) { + return unless @m; + my ($lead, $rows, $cols) = 0, +@m, +@m[0]; + + # Trim off over specified rows if they exist, for efficiency + if $rows >= $cols { + @m = trim_system(@m); + $rows = +@m; + } + + for ^$rows -> $r { + $lead < $cols or return @m; + my $i = $r; + until @m[$i;$lead] { + ++$i == $rows or next; + $i = $r; + ++$lead == $cols and return @m; + } + @m[$i, $r] = @m[$r, $i] if $r != $i; + my $lv = @m[$r;$lead]; + @m[$r] »/=» $lv; + for ^$rows -> $n { + next if $n == $r; + @m[$n] »-=» @m[$r] »*» (@m[$n;$lead] // 0); + } + ++$lead; + } + return @m; + + # Reduce a system of equations to N equations with N unknowns + sub trim_system ($m) { + my ($vars, @t) = +$m[0]-1; + for ^$vars -> $lead { + for ^$m -> $row { + @t.push: | $m.splice( $row, 1 ) and last if $m[$row;$lead]; + } + } + while (+@t < $vars) and +$m { @t.push: $m.splice(0, 1) }; + return @t; + } +} + +# Pretty printer for N dimensional arrays +# Assumes if first element in level is an array, then all are +sub pretty_print ( @array, $indent = 0 ) { + if @array[0] ~~ Array { + say ' ' x $indent,"["; + pretty_print( $_, $indent + 2 ) for @array; + say ' ' x $indent, "]{$indent??','!!''}"; + } else { + say ' ' x $indent, "[{say_it(@array)} ]{$indent??','!!''}"; + } + + sub say_it ( @array ) { return join ",", @array».fmt("%4s"); } +} + +my @f[3;2;3] = ( + [ + [ -9, 5, -8 ], + [ 3, 5, 1 ], + ], + [ + [ -1, -7, 2 ], + [ -5, -6, 6 ], + ], + [ + [ 8, 5, 8 ], + [ -2, -6, -4 ], + ] +); + +my @g[4;4;6] = ( + [ + [ 54, 42, 53, -42, 85, -72 ], + [ 45,-170, 94, -36, 48, 73 ], + [ -39, 65,-112, -16, -78, -72 ], + [ 6, -11, -6, 62, 49, 8 ], + ], + [ + [ -57, 49, -23, 52,-135, 66 ], + [ -23, 127, -58, -5,-118, 64 ], + [ 87, -16, 121, 23, -41, -12 ], + [ -19, 29, 35,-148, -11, 45 ], + ], + [ + [ -55,-147,-146, -31, 55, 60 ], + [ -88, -45, -28, 46, -26,-144 ], + [ -12,-107, -34, 150, 249, 66 ], + [ 11, -15, -34, 27, -78, -50 ], + ], + [ + [ 56, 67, 108, 4, 2, -48 ], + [ 58, 67, 89, 32, 32, -8 ], + [ -42, -31,-103, -30, -23, -8 ], + [ 6, 4, -26, -10, 26, 12 ], + ] +); + +say "# {+@f.shape}D array:"; +say "h ="; +pretty_print( deconvolve-N( @g, @f ) ); diff --git a/Task/Deepcopy/C/deepcopy-1.c b/Task/Deepcopy/C/deepcopy-1.c new file mode 100644 index 0000000000..fa8f26e416 --- /dev/null +++ b/Task/Deepcopy/C/deepcopy-1.c @@ -0,0 +1,49 @@ +/*Abhishek Ghosh, 15th November 2017*/ + +#include + +typedef struct{ + int a; +}layer1; + +typedef struct{ + layer1 l1; + float b,c; +}layer2; + +typedef struct{ + layer2 l2; + layer1 l1; + int d,e; +}layer3; + +void showCake(layer3 cake){ + printf("\ncake.d = %d",cake.d); + printf("\ncake.e = %d",cake.e); + printf("\ncake.l1.a = %d",cake.l1.a); + printf("\ncake.l2.b = %f",cake.l2.b); + printf("\ncake.l2.l1.a = %d",cake.l2.l1.a); +} + +int main() +{ + layer3 cake1,cake2; + + cake1.d = 1; + cake1.e = 2; + cake1.l1.a = 3; + cake1.l2.b = 4; + cake1.l2.l1.a = 5; + + printf("Cake 1 is : "); + showCake(cake1); + + cake2 = cake1; + + cake2.l2.b += cake2.l2.l1.a; + + printf("\nCake 2 is : "); + showCake(cake2); + + return 0; +} diff --git a/Task/Deepcopy/C/deepcopy-2.c b/Task/Deepcopy/C/deepcopy-2.c new file mode 100644 index 0000000000..9854f0d30a --- /dev/null +++ b/Task/Deepcopy/C/deepcopy-2.c @@ -0,0 +1,92 @@ +/*Abhishek Ghosh, 15th November 2017*/ + +#include +#include + +typedef struct elem{ + int data; + struct elem* next; +}cell; + +typedef cell* list; + +void addToList(list *a,int num){ + list temp, holder; + + if(*a==NULL){ + *a = (list)malloc(sizeof(cell)); + (*a)->data = num; + (*a)->next = NULL; + } + else{ + temp = *a; + + while(temp->next!=NULL) + temp = temp->next; + + holder = (list)malloc(sizeof(cell)); + holder->data = num; + holder->next = NULL; + + temp->next = holder; + } +} + +list copyList(list a){ + list b, tempA, tempB, temp; + + if(a!=NULL){ + b = (list)malloc(sizeof(cell)); + b->data = a->data; + b->next = NULL; + + tempA = a->next; + tempB = b; + + while(tempA!=NULL){ + temp = (list)malloc(sizeof(cell)); + temp->data = tempA->data; + temp->next = NULL; + + tempB->next = temp; + tempB = temp; + + tempA = tempA->next; + } + } + + return b; +} + +void printList(list a){ + list temp = a; + + while(temp!=NULL){ + printf("%d,",temp->data); + temp = temp->next; + } + printf("\b"); +} + +int main() +{ + list a,b; + int i; + + for(i=1;i<=5;i++) + addToList(&a,i); + + printf("List a is : "); + + printList(a); + + b = copyList(a); + + free(a); + + printf("\nList a destroyed, List b is : "); + + printList(b); + + return 0; +} diff --git a/Task/Deepcopy/Kotlin/deepcopy.kotlin b/Task/Deepcopy/Kotlin/deepcopy.kotlin new file mode 100644 index 0000000000..dd756f026e --- /dev/null +++ b/Task/Deepcopy/Kotlin/deepcopy.kotlin @@ -0,0 +1,71 @@ +// Version 1.2.31 + +import java.io.Serializable +import java.io.ByteArrayOutputStream +import java.io.ByteArrayInputStream +import java.io.ObjectOutputStream +import java.io.ObjectInputStream + +fun deepCopy(obj: T?): T? { + if (obj == null) return null + val baos = ByteArrayOutputStream() + val oos = ObjectOutputStream(baos) + oos.writeObject(obj) + oos.close() + val bais = ByteArrayInputStream(baos.toByteArray()) + val ois = ObjectInputStream(bais) + @Suppress("unchecked_cast") + return ois.readObject() as T +} + +class Person( + val name: String, + var age: Int, + val sex: Char, + var income: Double, + var partner: Person? +) : Serializable + +fun printDetails(p1: Person, p2: Person?, p3: Person, p4: Person?) { + with (p3) { + println("Name : $name") + println("Age : $age") + println("Sex : $sex") + println("Income : $income") + if (p4 == null) { + println("Partner : None") + } + else { + println("Partner :-") + with (p4) { + println(" Name : $name") + println(" Age : $age") + println(" Sex : $sex") + println(" Income : $income") + } + } + println("\nSame person as original '$name' == ${p1 === p3}") + if (p4 != null) { + println("Same person as original '${p2!!.name}' == ${p2 === p4}") + } + } + println() +} + +fun main(args: Array) { + var p1 = Person("John", 35, 'M', 50000.0, null) + val p2 = Person("Jane", 32, 'F', 25000.0, p1) + p1.partner = p2 + var p3 = deepCopy(p1) + val p4 = p3!!.partner + printDetails(p1, p2, p3, p4) + + println("..or, say, after 2 years have elapsed:-\n") + with (p1) { + age = 37 + income = 55000.0 + partner = null + } + p3 = deepCopy(p1) + printDetails(p1, null, p3!!, null) +} diff --git a/Task/Deepcopy/Rust/deepcopy.rust b/Task/Deepcopy/Rust/deepcopy.rust index da3b1d49a4..02fba8b4e7 100644 --- a/Task/Deepcopy/Rust/deepcopy.rust +++ b/Task/Deepcopy/Rust/deepcopy.rust @@ -1,4 +1,4 @@ - // The compiler can automatically implement Clone on structs (assuming all members have implemented Clone). +// The compiler can automatically implement Clone on structs (assuming all members have implemented Clone). #[derive(Clone)] struct Tree { left: Leaf, @@ -9,18 +9,19 @@ struct Tree { type Leaf = Option>>; impl Tree { - fn root(d: T) -> Self { - Tree { left: None, data: d, right: None } + fn root(data: T) -> Self { + Self { left: None, data, right: None } } + fn leaf(d: T) -> Leaf { - Some(Box::new(Tree::root(d))) + Some(Box::new(Self::root(d))) } } - fn main() { - let mut tree = Tree::root(vec![4,5,6]); - tree.right = Tree::leaf(vec![1,2,3]); - tree.left = Tree::leaf(vec![7,8,9]); + let mut tree = Tree::root([4, 5, 6]); + tree.right = Tree::leaf([1, 2, 3]); + tree.left = Tree::leaf([7, 8, 9]); + let newtree = tree.clone(); } diff --git a/Task/Define-a-primitive-data-type/Elena/define-a-primitive-data-type.elena b/Task/Define-a-primitive-data-type/Elena/define-a-primitive-data-type.elena index 3b3bae5a76..b4c17cb767 100644 --- a/Task/Define-a-primitive-data-type/Elena/define-a-primitive-data-type.elena +++ b/Task/Define-a-primitive-data-type/Elena/define-a-primitive-data-type.elena @@ -1,3 +1,5 @@ +import extensions. + type tiny = TinyInt. sealed struct TinyInt :: BaseNumber @@ -27,16 +29,16 @@ sealed struct TinyInt :: BaseNumber int = theValue. tiny add(TinyInt t) - = theValue + t. + = theValue + t int. tiny subtract(TinyInt t) - = theValue + t. + = theValue + t int. tiny multiply(TinyInt t) - = theValue + t. + = theValue + t int. tiny divide(TinyInt t) - = theValue + t. + = theValue + t int. bool equal(TinyInt t) = theValue == t int. @@ -48,6 +50,7 @@ sealed struct TinyInt :: BaseNumber program = [ tiny i := 4t. + tiny j := i + i. try(control do: diff --git a/Task/Define-a-primitive-data-type/Go/define-a-primitive-data-type.go b/Task/Define-a-primitive-data-type/Go/define-a-primitive-data-type.go new file mode 100644 index 0000000000..2700873640 --- /dev/null +++ b/Task/Define-a-primitive-data-type/Go/define-a-primitive-data-type.go @@ -0,0 +1,56 @@ +package main + +import "fmt" + +type TinyInt int + +func NewTinyInt(i int) TinyInt { + if i < 1 { + i = 1 + } else if i > 10 { + i = 10 + } + return TinyInt(i) +} + +func (t1 TinyInt) Add(t2 TinyInt) TinyInt { + return NewTinyInt(int(t1) + int(t2)) +} + +func (t1 TinyInt) Sub(t2 TinyInt) TinyInt { + return NewTinyInt(int(t1) - int(t2)) +} + +func (t1 TinyInt) Mul(t2 TinyInt) TinyInt { + return NewTinyInt(int(t1) * int(t2)) +} + +func (t1 TinyInt) Div(t2 TinyInt) TinyInt { + return NewTinyInt(int(t1) / int(t2)) +} + +func (t1 TinyInt) Rem(t2 TinyInt) TinyInt { + return NewTinyInt(int(t1) % int(t2)) +} + +func (t TinyInt) Inc() TinyInt { + return t.Add(TinyInt(1)) +} + +func (t TinyInt) Dec() TinyInt { + return t.Sub(TinyInt(1)) +} + +func main() { + t1 := NewTinyInt(6) + t2 := NewTinyInt(3) + fmt.Println("t1 =", t1) + fmt.Println("t2 =", t2) + fmt.Println("t1 + t2 =", t1.Add(t2)) + fmt.Println("t1 - t2 =", t1.Sub(t2)) + fmt.Println("t1 * t2 =", t1.Mul(t2)) + fmt.Println("t1 / t2 =", t1.Div(t2)) + fmt.Println("t1 % t2 =", t1.Rem(t2)) + fmt.Println("t1 + 1 =", t1.Inc()) + fmt.Println("t1 - 1 =", t1.Dec()) +} diff --git a/Task/Define-a-primitive-data-type/Julia/define-a-primitive-data-type.julia b/Task/Define-a-primitive-data-type/Julia/define-a-primitive-data-type.julia new file mode 100644 index 0000000000..91141f0971 --- /dev/null +++ b/Task/Define-a-primitive-data-type/Julia/define-a-primitive-data-type.julia @@ -0,0 +1,24 @@ +struct LittleInt <: Integer + val::Int8 + function LittleInt(n::Real) + 1 ≤ n ≤ 10 || throw(ArgumentError("LittleInt number must be in [1, 10]")) + return new(Int8(n)) + end +end +Base.show(io::IO, x::LittleInt) = print(io, x.val) +Base.convert(::Type{T}, x::LittleInt) where T<:Number = convert(T, x.val) +Base.promote_rule(::Type{LittleInt}, ::Type{T}) where T<:Number = T + +for op in (:+, :*, :÷, :-, :&, :|, :$, :<, :>, :(==)) + @eval (Base.$op)(a::LittleInt, b::LittleInt) = LittleInt(($op)(a.val, b.val)) +end + +# Test +a = LittleInt(3) +b = LittleInt(4.0) +@show a b +@show a + b +@show b - a +@show a * LittleInt(2) +@show b ÷ LittleInt(2) +@show a * b diff --git a/Task/Define-a-primitive-data-type/Nim/define-a-primitive-data-type.nim b/Task/Define-a-primitive-data-type/Nim/define-a-primitive-data-type.nim index 61d65cbcd2..d289645551 100644 --- a/Task/Define-a-primitive-data-type/Nim/define-a-primitive-data-type.nim +++ b/Task/Define-a-primitive-data-type/Nim/define-a-primitive-data-type.nim @@ -1,7 +1,8 @@ -var x: range[1..10] = 10 +type + MyInt = range[0..10] -x = 5 +var x: MyInt = 5 -x = x + 6 # Runtime error: Value out of range +x = x + 6 # Runtime error: value out of range: 11 -x = 12 # Compile error: Invalid conversion +x = 12 # Compile-time error: conversion from int literal(12) to MyInt is invalid diff --git a/Task/Delegates/Clojure/delegates.clj b/Task/Delegates/Clojure/delegates.clj new file mode 100644 index 0000000000..7d6cc49768 --- /dev/null +++ b/Task/Delegates/Clojure/delegates.clj @@ -0,0 +1,13 @@ +(defprotocol Thing + (thing [_])) + +(defprotocol Operation + (operation [_])) + +(defrecord Delegator [delegate] + Operation + (operation [_] (try (thing delegate) (catch IllegalArgumentException e "default implementation")))) + +(defrecord Delegate [] + Thing + (thing [_] "delegate implementation")) diff --git a/Task/Delegates/Julia/delegates-1.julia b/Task/Delegates/Julia/delegates-1.julia new file mode 100644 index 0000000000..622c89675d --- /dev/null +++ b/Task/Delegates/Julia/delegates-1.julia @@ -0,0 +1,15 @@ +module Delegates + +export Delegator, Delegate + +struct Delegator{T} + delegate::T +end + +struct Delegate end + +operation(x::Delegator) = thing(x.delegate) +thing(::Any) = "default implementation" +thing(::Delegate) = "delegate implementation" + +end # module Delegates diff --git a/Task/Delegates/Julia/delegates-2.julia b/Task/Delegates/Julia/delegates-2.julia new file mode 100644 index 0000000000..2bf187dec6 --- /dev/null +++ b/Task/Delegates/Julia/delegates-2.julia @@ -0,0 +1,11 @@ +using .Delegates + +a = Delegator(nothing) +b = Delegator("string") + +d = Delegate() +c = Delegator(d) + +@show Delegates.operation(a) +@show Delegates.operation(b) +@show Delegates.operation(c) diff --git a/Task/Delegates/Kotlin/delegates.kotlin b/Task/Delegates/Kotlin/delegates.kotlin new file mode 100644 index 0000000000..0ce055c8eb --- /dev/null +++ b/Task/Delegates/Kotlin/delegates.kotlin @@ -0,0 +1,25 @@ +// version 1.1.51 + +interface Thingable { + fun thing(): String? +} + +class Delegate(val responds: Boolean) : Thingable { + override fun thing() = if (responds) "delegate implementation" else null +} + +class Delegator(d: Delegate) : Thingable by d { + fun operation() = thing() ?: "default implementation" +} + +fun main(args: Array) { + // delegate doesn't respond to 'thing' + val d = Delegate(false) + val dd = Delegator(d) + println(dd.operation()) + + // delegate responds to 'thing' + val d2 = Delegate(true) + val dd2 = Delegator(d2) + println(dd2.operation()) +} diff --git a/Task/Delegates/Sidef/delegates.sidef b/Task/Delegates/Sidef/delegates.sidef new file mode 100644 index 0000000000..6f56376a77 --- /dev/null +++ b/Task/Delegates/Sidef/delegates.sidef @@ -0,0 +1,25 @@ +class NonDelegate { } + +class Delegate { + method thing { + return "delegate implementation" + } +} + +class Delegator (delegate = null) { + method operation { + + if (delegate.respond_to(:thing)) { + return delegate.thing + } + + return "default implementation" + } +} + +var d = Delegator() +say "empty: #{d.operation}" +d.delegate = NonDelegate() +say "NonDelegate: #{d.operation}" +d.delegate = Delegate() +say "Delegate: #{d.operation}" diff --git a/Task/Delete-a-file/VBA/delete-a-file.vba b/Task/Delete-a-file/VBA/delete-a-file.vba new file mode 100644 index 0000000000..ebc0b35229 --- /dev/null +++ b/Task/Delete-a-file/VBA/delete-a-file.vba @@ -0,0 +1,10 @@ +Option Explicit + +Sub DeleteFileOrDirectory() +Dim myPath As String + myPath = "C:\Users\surname.name\Desktop\Docs" +'delete file + Kill myPath & "\input.txt" +'delete Directory + RmDir myPath +End Sub diff --git a/Task/Detect-division-by-zero/HolyC/detect-division-by-zero.holyc b/Task/Detect-division-by-zero/HolyC/detect-division-by-zero.holyc new file mode 100644 index 0000000000..77889bf22c --- /dev/null +++ b/Task/Detect-division-by-zero/HolyC/detect-division-by-zero.holyc @@ -0,0 +1,5 @@ +try { + Print("%d\n", 10 / 0); +} catch { + Print("Divide by zero"); +} diff --git a/Task/Detect-division-by-zero/Julia/detect-division-by-zero.julia b/Task/Detect-division-by-zero/Julia/detect-division-by-zero.julia index 9f378300aa..723d38b289 100644 --- a/Task/Detect-division-by-zero/Julia/detect-division-by-zero.julia +++ b/Task/Detect-division-by-zero/Julia/detect-division-by-zero.julia @@ -1,13 +1,6 @@ -function isdefinite{T<:Number}(n::T) - !isequal(n, NaN) && abs(n) != Inf -end +isdefinite(n::Number) = !isnan(n) && !isinf(n) -for n in {1, 1//1, 1.0, 1im, 0} - d = n/0 - print("Divding ", n, " by 0 ") - if isdefinite(d) - println("results in ", d, ".") - else - println("yields an indefinite value (", d, ").") - end +for n in (1, 1//1, 1.0, 1im, 0) + d = n / 0 + println("Dividing $n by 0 ", isdefinite(d) ? "results in $d." : "yields an indefinite value ($d).") end diff --git a/Task/Detect-division-by-zero/Rust/detect-division-by-zero.rust b/Task/Detect-division-by-zero/Rust/detect-division-by-zero.rust new file mode 100644 index 0000000000..5cba3b083b --- /dev/null +++ b/Task/Detect-division-by-zero/Rust/detect-division-by-zero.rust @@ -0,0 +1,11 @@ +fn test_division(numerator: u32, denominator: u32) { + match numerator.checked_div(denominator) { + Some(result) => println!("{} / {} = {}", numerator, denominator, result), + None => println!("{} / {} results in a division by zero", numerator, denominator) + } +} + +fn main() { + test_division(5, 4); + test_division(4, 0); +} diff --git a/Task/Detect-division-by-zero/VBA/detect-division-by-zero.vba b/Task/Detect-division-by-zero/VBA/detect-division-by-zero.vba new file mode 100644 index 0000000000..8687d6cd48 --- /dev/null +++ b/Task/Detect-division-by-zero/VBA/detect-division-by-zero.vba @@ -0,0 +1,14 @@ +Option Explicit + +Sub Main() +Dim Div + If CatchDivideByZero(152, 0, Div) Then Debug.Print Div Else Debug.Print "Error" + If CatchDivideByZero(152, 10, Div) Then Debug.Print Div Else Debug.Print "Error" +End Sub + +Function CatchDivideByZero(Num, Den, Div) As Boolean + On Error Resume Next + Div = Num / Den + If Err = 0 Then CatchDivideByZero = True + On Error GoTo 0 +End Function diff --git a/Task/Determine-if-a-string-is-numeric/Befunge/determine-if-a-string-is-numeric.bf b/Task/Determine-if-a-string-is-numeric/Befunge/determine-if-a-string-is-numeric.bf new file mode 100644 index 0000000000..22d6a13a05 --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/Befunge/determine-if-a-string-is-numeric.bf @@ -0,0 +1,10 @@ + ~:0\`#v_:"+"-!#v_:"-"-!#v_::"E"-\"e"-*#v_ v +v _v# < < 0< +>~:0\`#v_>::"0"-0\`\"9"-0`+!#v_:"."-!#v_::"E"-\"e"-*!#v_ v +^ $< > > $ v +>~:0\`#v_>::"0"-0\`\"9"-0`+!#v_:"."-!#v_::"E"-\"e"-*!#v_> v> +^ $< >$~:0\`#v_:"+"-#v_v +v $_v# < < :#< +>~:0\`#v_>::"0"-0\`\"9"-0`+!#v_:"."-!#v_::"E"-\"e"-*!v 0 > v +^ $< v < << ^_^#-"-"< + > "ciremuN">:#,_@ >>#$_"ciremun toN">:#,_@^ < 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 71cc34b1a8..d34c2d7e69 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,23 +1,9 @@ -function isnumeric{T<:String}(s::T) - isa(parse(s), Number) -end +isnumeric(s::AbstractString) = parse(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"] +tests = ["1", "-121", "one", "pi", "1 + 1", "NaN", "1234567890123456789", "1234567890123456789123456789", + "1234567890123456789123456789.0", "1.3", "1.4e10", "Inf", "1//2", "1.0 + 1.0im"] for t in tests fl = isnumeric(t) ? "is" : "is not" - println(@sprintf(" %35s %s a direct numeric literal.", t, fl)) + @printf("%35s %s a direct numeric literal.\n", t, fl) end 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 29a402ec11..8dc44c19f8 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 @@ -1,7 +1,14 @@ -sub is-number( $term --> Bool ) { - ?($term ~~ /\d/) and $term ~~ Numeric; +sub is-number-w-ws( Str $term --> Bool ) { # treat Falsey strings as numeric + $term.Numeric !~~ Failure; } -printf "%10s %s\n", "<$_>", is-number( $_ ) for flat -<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', '', ' '; +sub is-number-wo-ws( Str $term --> Bool ) { # treat Falsey strings as non-numeric + ?($term ~~ / \S /) && $term.Numeric !~~ Failure; +} + +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; diff --git a/Task/Determine-if-a-string-is-numeric/VBA/determine-if-a-string-is-numeric.vba b/Task/Determine-if-a-string-is-numeric/VBA/determine-if-a-string-is-numeric.vba new file mode 100644 index 0000000000..288ecee8de --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/VBA/determine-if-a-string-is-numeric.vba @@ -0,0 +1,16 @@ +Sub Main() + Debug.Print Is_Numeric("") + Debug.Print Is_Numeric("-5.32") + Debug.Print Is_Numeric("-51,321 32") + Debug.Print Is_Numeric("123.4") + Debug.Print Is_Numeric("123,4") + Debug.Print Is_Numeric("123;4") + Debug.Print Is_Numeric("123.4x") +End Sub + +Private Function Is_Numeric(s As String) As Boolean +Dim Separat As String, Other As String + Separat = Application.DecimalSeparator + Other = IIf(Separat = ",", ".", ",") + Is_Numeric = IsNumeric(Replace(s, Other, Separat)) +End Function diff --git a/Task/Determine-if-only-one-instance-is-running/Perl-6/determine-if-only-one-instance-is-running.pl6 b/Task/Determine-if-only-one-instance-is-running/Perl-6/determine-if-only-one-instance-is-running.pl6 index 3305f877fb..23aeb40456 100644 --- a/Task/Determine-if-only-one-instance-is-running/Perl-6/determine-if-only-one-instance-is-running.pl6 +++ b/Task/Determine-if-only-one-instance-is-running/Perl-6/determine-if-only-one-instance-is-running.pl6 @@ -15,7 +15,7 @@ my $pidfile = open "$lockpid", :w or die "Can't create $lockpid: $!"; $pidfile.say($pid); $pidfile.close; -if try link($lockfile, $lockpid) { +if try link($lockpid, $lockfile) { $havelock = True; } else { diff --git a/Task/Digital-root-Multiplicative-digital-root/Factor/digital-root-multiplicative-digital-root.factor b/Task/Digital-root-Multiplicative-digital-root/Factor/digital-root-multiplicative-digital-root.factor new file mode 100644 index 0000000000..205ccde4cb --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/Factor/digital-root-multiplicative-digital-root.factor @@ -0,0 +1,31 @@ +USING: arrays formatting fry io kernel lists lists.lazy math +math.text.utils prettyprint sequences ; +IN: rosetta-code.multiplicative-digital-root + +: mdr ( n -- {persistence,root} ) + 0 swap + [ 1 digit-groups dup length 1 > ] [ product [ 1 + ] dip ] while + dup empty? [ drop { 0 } ] when first 2array ; + +: print-mdr ( n -- ) + dup [ 1array ] dip mdr append + "%-12d has multiplicative persistence %d and MDR %d.\n" + vprintf ; + +: first5 ( n -- seq ) ! first 5 numbers with MDR of n + 0 lfrom swap '[ mdr second _ = ] lfilter 5 swap ltake list>array ; + +: print-first5 ( i n -- ) + "%-5d" printf bl first5 [ "%-5d " printf ] each nl ; + +: header ( -- ) + "MDR | First five numbers with that MDR" print + "--------------------------------------" print ; + +: first5-table ( -- ) + header 10 iota [ print-first5 ] each-index ; + +: main ( -- ) + { 123321 7739 893 899998 } [ print-mdr ] each nl first5-table ; + +MAIN: main diff --git a/Task/Digital-root-Multiplicative-digital-root/Ring/digital-root-multiplicative-digital-root.ring b/Task/Digital-root-Multiplicative-digital-root/Ring/digital-root-multiplicative-digital-root.ring new file mode 100644 index 0000000000..328477f6f1 --- /dev/null +++ b/Task/Digital-root-Multiplicative-digital-root/Ring/digital-root-multiplicative-digital-root.ring @@ -0,0 +1,63 @@ +# Project : Digital root/Multiplicative digital root +# Date : 2017/11/21 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +load "stdlib.ring" +root = newlist(10, 5) +for r = 1 to 10 + for x = 1 to 5 + root[r][x] = 0 + next +next +root2 = list(10) +for y = 1 to 10 + root2[y] = 0 +next +see "Number MDR MP" + nl +num = [123321, 7739, 893, 899998] +digroot(num) +see nl +num = 0:12000 +digroot(num) +see "First five numbers with MDR in first column:" + nl +for n1 = 1 to 10 + see "" + (n1-1) + " => " + for n2 = 1 to 5 + see "" + root[n1][n2] + " " + next + see nl +next + +func digroot(num) + for n = 1 to len(num) + sum = 0 + numold = num[n] + while true + pro = 1 + strnum = string(numold) + for nr = 1 to len(strnum) + pro = pro * number(strnum[nr]) + next + sum = sum + 1 + numold = pro + numn = string(num[n]) + sp = 6 - len(string(num[n])) + if sp > 0 + for p = 1 to sp + 2 + numn = " " + numn + next + ok + if len(string(numold)) = 1 and len(num) < 5 + see "" + numn + " " + numold + " " + sum + nl + exit + ok + if len(string(numold)) = 1 and len(num) > 4 + root2[numold+1] = root2[numold+1] + 1 + if root2[numold+1] < 6 + root[numold+1][root2[numold+1]] = num[n] + ok + exit + ok + end + next diff --git a/Task/Digital-root/Elena/digital-root.elena b/Task/Digital-root/Elena/digital-root.elena new file mode 100644 index 0000000000..51eb42ca33 --- /dev/null +++ b/Task/Digital-root/Elena/digital-root.elena @@ -0,0 +1,30 @@ +import extensions. +import system'routines. + +extension $op +{ + digitalRoot + [ + int additivepersistence := 0. + long num := self. + + while (num > 9) + [ + num := num literal; toArray; selectBy(:ch)(ch toInt - 48); summarize(LongInteger new). + + additivepersistence += 1. + ]. + + ^ { item1 = additivepersistence. item2 = num toInt. }. + ] +} + +program = +[ + (627615l, 39390l, 588225l, 393900588225l) forEach(:num) + [ + var t := num digitalRoot. + + console printLineFormatted("{0} has additive persistence {1} and digital root {2}", num, t item1, t item2). + ] +]. diff --git a/Task/Digital-root/Factor/digital-root.factor b/Task/Digital-root/Factor/digital-root.factor new file mode 100644 index 0000000000..aedd9f68f9 --- /dev/null +++ b/Task/Digital-root/Factor/digital-root.factor @@ -0,0 +1,13 @@ +USING: arrays formatting kernel math math.text.utils sequences ; +IN: rosetta-code.digital-root + +: digital-root ( n -- persistence root ) + 0 swap [ 1 digit-groups dup length 1 > ] [ sum [ 1 + ] dip ] + while first ; + +: print-root ( n -- ) + dup digital-root + "%-12d has additive persistence %d and digital root %d.\n" + printf ; + +{ 627615 39390 588225 393900588225 } [ print-root ] each diff --git a/Task/Digital-root/Julia/digital-root.julia b/Task/Digital-root/Julia/digital-root.julia index fcb5e22b15..04b0707f67 100644 --- a/Task/Digital-root/Julia/digital-root.julia +++ b/Task/Digital-root/Julia/digital-root.julia @@ -1,15 +1,14 @@ -function digitalroot{S<:Integer,T<:Integer}(n::S, bs::T=10) - -1 < n && 1 < bs || throw(DomainError()) - ds = n - pers = 0 - while bs <= ds +function digitalroot(n::Integer, bs::Integer=10) + if n < 0 || bs < 2 throw(DomainError()) end + ds, pers = n, 0 + while bs ≤ ds ds = sum(digits(ds, bs)) pers += 1 end - return (pers, ds) + return pers, ds end -for i in {627615, 39390, 588225, 393900588225, big(2)^100} - (pers, ds) = digitalroot(i) +for i in [627615, 39390, 588225, 393900588225, big(2) ^ 100] + pers, ds = digitalroot(i) println(i, " has persistence ", pers, " and digital root ", ds) end diff --git a/Task/Digital-root/Modula-2/digital-root.mod2 b/Task/Digital-root/Modula-2/digital-root.mod2 new file mode 100644 index 0000000000..78fc690771 --- /dev/null +++ b/Task/Digital-root/Modula-2/digital-root.mod2 @@ -0,0 +1,51 @@ +MODULE DigitalRoot; +FROM FormatString IMPORT FormatString; +FROM Terminal IMPORT WriteString,WriteLn,ReadChar; + +TYPE Root = + RECORD + persistence,root : LONGINT; + END; + +PROCEDURE digitalRoot(inRoot,base : LONGINT) : Root; +VAR root,persistence,num : LONGINT; +BEGIN + root := ABS(inRoot); + persistence := 0; + WHILE root>=base DO + num := root; + root := 0; + WHILE num#0 DO + root := root + (num MOD base); + num := num DIV base; + END; + INC(persistence) + END; + RETURN Root{persistence, root} +END digitalRoot; + +PROCEDURE Print(n,b : LONGINT); +VAR + buf : ARRAY[0..63] OF CHAR; + r : Root; +BEGIN + r := digitalRoot(n,b); + FormatString("%u (base %u): persistence=%u, digital root=%u\n", buf, n, b, r.persistence, r.root); + WriteString(buf) +END Print; + +VAR + buf : ARRAY[0..63] OF CHAR; + b,n : LONGINT; + r : Root; +BEGIN + Print(1,10); + Print(14,10); + Print(267,10); + Print(8128,10); + Print(39390,10); + Print(627615,10); + Print(588225,10); + + ReadChar +END DigitalRoot. diff --git a/Task/Digital-root/UNIX-Shell/digital-root.sh b/Task/Digital-root/UNIX-Shell/digital-root.sh new file mode 100644 index 0000000000..6dda4433e0 --- /dev/null +++ b/Task/Digital-root/UNIX-Shell/digital-root.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash + +numbers=(627615 39390 588225 393900588225 55) +declare root + +for number in "${numbers[@]}"; do + declare -i iterations + root="${number}" + while [[ "${#root}" -ne 1 ]]; do + root="$(( $(fold -w1 <<<"${root}" | xargs | sed 's/ /+/g') ))" + iterations+=1 + done + echo -e "${number} has additive persistence ${iterations} and digital root ${root}" + unset iterations +done | column -t diff --git a/Task/Dinesmans-multiple-dwelling-problem/Bracmat/dinesmans-multiple-dwelling-problem.bracmat b/Task/Dinesmans-multiple-dwelling-problem/Bracmat/dinesmans-multiple-dwelling-problem.bracmat index 140d8b67aa..fcebd885eb 100644 --- a/Task/Dinesmans-multiple-dwelling-problem/Bracmat/dinesmans-multiple-dwelling-problem.bracmat +++ b/Task/Dinesmans-multiple-dwelling-problem/Bracmat/dinesmans-multiple-dwelling-problem.bracmat @@ -23,5 +23,5 @@ ) ) & solution$(.!people) -| { After outputting all solutions, the lhs of the | operator fails. The rhs of the | operator, here an empty string, is the final result. } +| { After outputting all solutions, the lhs of the | operator fails. The rhs of the | operator, here an empty string, is the final result. } ); diff --git a/Task/Dinesmans-multiple-dwelling-problem/C-sharp/dinesmans-multiple-dwelling-problem.cs b/Task/Dinesmans-multiple-dwelling-problem/C-sharp/dinesmans-multiple-dwelling-problem-1.cs similarity index 100% rename from Task/Dinesmans-multiple-dwelling-problem/C-sharp/dinesmans-multiple-dwelling-problem.cs rename to Task/Dinesmans-multiple-dwelling-problem/C-sharp/dinesmans-multiple-dwelling-problem-1.cs diff --git a/Task/Dinesmans-multiple-dwelling-problem/C-sharp/dinesmans-multiple-dwelling-problem-2.cs b/Task/Dinesmans-multiple-dwelling-problem/C-sharp/dinesmans-multiple-dwelling-problem-2.cs new file mode 100644 index 0000000000..a52907337c --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/C-sharp/dinesmans-multiple-dwelling-problem-2.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using static System.Linq.Enumerable; + +static class Program +{ + enum Tenants { Baker = 0, Cooper = 1, Fletcher = 2, Miller = 3, Smith = 4 }; + + static void Main() + { + var count = Enum.GetNames(typeof(Tenants)).Length; + var top = count - 1; + + var solve = + from f in Range(0, count).Permutations() + let floors = f.ToArray() + where floors[(int)Tenants.Baker] != top //r1 + where floors[(int)Tenants.Cooper] != 0 //r2 + where floors[(int)Tenants.Fletcher] != top && floors[(int)Tenants.Fletcher] != 0 //r3 + where floors[(int)Tenants.Miller] > floors[(int)Tenants.Cooper] //r4 + where Math.Abs(floors[(int)Tenants.Smith] - floors[(int)Tenants.Fletcher]) !=1 //r5 + where Math.Abs(floors[(int)Tenants.Fletcher] - floors[(int)Tenants.Cooper]) !=1 //r6 + select floors; + var solved = solve.First(); + var output = Range(0,count).OrderBy(i=>solved[i]).Select(f => ((Tenants)f).ToString()); + Console.WriteLine(String.Join(" ", output)); + Console.Read(); + } + + public static IEnumerable> Permutations(this IEnumerable values) + { + if (values.Count() == 1) + return values.ToSingleton(); + + return values.SelectMany(v => Permutations(values.Except(v.ToSingleton())), (v, p) => p.Prepend(v)); + } + + public static IEnumerable ToSingleton(this T item) { yield return item; } +} diff --git a/Task/Dinesmans-multiple-dwelling-problem/Julia/dinesmans-multiple-dwelling-problem.julia b/Task/Dinesmans-multiple-dwelling-problem/Julia/dinesmans-multiple-dwelling-problem.julia new file mode 100644 index 0000000000..66ecd927f6 --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/Julia/dinesmans-multiple-dwelling-problem.julia @@ -0,0 +1,23 @@ +using Combinatorics + +function solve(n::Vector{<:AbstractString}, pred::Vector{<:Function}) + rst = Vector{typeof(n)}(0) + for candidate in permutations(n) + if all(p(candidate) for p in predicates) + push!(rst, candidate) + end + end + return rst +end + +Names = ["Baker", "Cooper", "Fletcher", "Miller", "Smith"] +predicates = [ + (s) -> last(s) != "Baker", + (s) -> first(s) != "Cooper", + (s) -> first(s) != "Fletcher" && last(s) != "Fletcher", + (s) -> findfirst(s, "Miller") > findfirst(s, "Cooper"), + (s) -> abs(findfirst(s, "Smith") - findfirst(s, "Fletcher")) != 1, + (s) -> abs(findfirst(s, "Cooper") - findfirst(s, "Fletcher")) != 1] + +solutions = solve(Names, predicates) +foreach(x -> println(join(x, ", ")), solutions) diff --git a/Task/Dinesmans-multiple-dwelling-problem/K/dinesmans-multiple-dwelling-problem.k b/Task/Dinesmans-multiple-dwelling-problem/K/dinesmans-multiple-dwelling-problem.k new file mode 100644 index 0000000000..c63ac15cc1 --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/K/dinesmans-multiple-dwelling-problem.k @@ -0,0 +1,12 @@ +perm: {x@m@&n=(#?:)'m:!n#n:#x} +filter: {y[& x'y]} +reject: {y[& ~x'y]} +adjacent: {1 = _abs (z?x) - (z?y)} + +p: perm[`Baker `Cooper `Fletcher `Miller `Smith] +p: reject[{`Cooper=x[0]}; p] +p: reject[{`Baker=x[4]}; p] +p: filter[{(x ? `Miller) > (x ? `Cooper)}; p] +p: reject[{adjacent[`Smith; `Fletcher; x]}; p] +p: reject[{adjacent[`Cooper; `Fletcher; x]}; p] +p: reject[{(x ? `Fletcher)_in (0 4)}; p] diff --git a/Task/Dinesmans-multiple-dwelling-problem/Lua/dinesmans-multiple-dwelling-problem.lua b/Task/Dinesmans-multiple-dwelling-problem/Lua/dinesmans-multiple-dwelling-problem.lua new file mode 100644 index 0000000000..2d09144f43 --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/Lua/dinesmans-multiple-dwelling-problem.lua @@ -0,0 +1,63 @@ +local wrap, yield = coroutine.wrap, coroutine.yield +local function perm(n) + local r = {} + for i=1,n do r[i]=i end + return wrap(function() + local function swap(m) + if m==0 then + yield(r) + else + for i=m,1,-1 do + r[i],r[m]=r[m],r[i] + swap(m-1) + r[i],r[m]=r[m],r[i] + end + end + end + swap(n) + end) +end + +local function iden(...)return ... end +local function imap(t,f) + local r,fn = {m=imap, c=table.concat, u=table.unpack}, f or iden + for i=1,#t do r[i]=fn(t[i])end + return r +end + +local tenants = {'Baker', 'Cooper', 'Fletcher', 'Miller', 'Smith'} + +local conds = { + 'Baker ~= TOP', + 'Cooper ~= BOTTOM', + 'Fletcher ~= TOP and Fletcher~= BOTTOM', + 'Miller > Cooper', + 'Smith + 1 ~= Fletcher and Smith - 1 ~= Fletcher', + 'Cooper + 1 ~= Fletcher and Cooper - 1 ~= Fletcher', +} + +local function makePredicate(conds, tenants) + return load('return function('..imap(tenants):c','.. + ') return ' .. + imap(conds,function(c) + return string.format("(%s)",c) + end):c"and ".. + " end ",'-',nil,{TOP=5, BOTTOM=1})() +end + +local function solve (conds, tenants) + local try, pred, upk = perm(#tenants), makePredicate(conds, tenants), table.unpack + local answer = try() + while answer and not pred(upk(answer)) do answer = try()end + if answer then + local floor = 0 + return imap(answer, function(person) + floor=floor+1; + return string.format(" %s lives on floor %d",tenants[floor],person) + end):c"\n" + else + return nil, 'no solution' + end +end + +print(solve (conds, tenants)) diff --git a/Task/Dinesmans-multiple-dwelling-problem/R/dinesmans-multiple-dwelling-problem-1.r b/Task/Dinesmans-multiple-dwelling-problem/R/dinesmans-multiple-dwelling-problem-1.r new file mode 100644 index 0000000000..2ab2b68886 --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/R/dinesmans-multiple-dwelling-problem-1.r @@ -0,0 +1,16 @@ +names = unlist(strsplit("baker cooper fletcher miller smith", " ")) + +test <- function(floors) { + f <- function(name) which(name == floors) + if ((f('baker') != 5) && + (f('cooper') != 1) && + (any(f('fletcher') == 2:4)) && + (f('miller') > f('cooper')) && + (abs(f('fletcher') - f('cooper')) > 1) && + (abs(f('smith') - f('fletcher')) > 1)) + cat("\nFrom bottom to top: --> ", floors, "\n") +} + +do.perms <- function(seq, func, built = c()){ + if (0 == length(seq)) func(built) + else for (x in seq) do.perms( seq[!seq==x], func, c(x, built)) } diff --git a/Task/Dinesmans-multiple-dwelling-problem/R/dinesmans-multiple-dwelling-problem-2.r b/Task/Dinesmans-multiple-dwelling-problem/R/dinesmans-multiple-dwelling-problem-2.r new file mode 100644 index 0000000000..d3d2d5c1da --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/R/dinesmans-multiple-dwelling-problem-2.r @@ -0,0 +1,7 @@ +> do.perms(names, test) +From bottom to top: --> smith cooper baker fletcher miller + +> system.time(do.perms(names, test)) +From bottom to top: --> smith cooper baker fletcher miller + user system elapsed + 0 0 0 diff --git a/Task/Dinesmans-multiple-dwelling-problem/Ruby/dinesmans-multiple-dwelling-problem-4.rb b/Task/Dinesmans-multiple-dwelling-problem/Ruby/dinesmans-multiple-dwelling-problem-4.rb new file mode 100644 index 0000000000..b4192c4e6a --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/Ruby/dinesmans-multiple-dwelling-problem-4.rb @@ -0,0 +1,11 @@ +N = %w(Baker Cooper Fletcher Miller Smith) +b,c,f,m,s = N + +N.permutation.map{|a| a.join " "}. +grep(/(?=.*#{b}.) + (?=.+#{c}) + (?=.+#{f}.) + (?=.*#{c}.*#{m}) + (?=.*(#{f}..+#{s}|#{s}..+#{f})) + (?=.*(#{f}..+#{c}|#{c}..+#{f}))/x). +first diff --git a/Task/Dining-philosophers/Common-Lisp/dining-philosophers.lisp b/Task/Dining-philosophers/Common-Lisp/dining-philosophers-1.lisp similarity index 100% rename from Task/Dining-philosophers/Common-Lisp/dining-philosophers.lisp rename to Task/Dining-philosophers/Common-Lisp/dining-philosophers-1.lisp diff --git a/Task/Dining-philosophers/Common-Lisp/dining-philosophers-2.lisp b/Task/Dining-philosophers/Common-Lisp/dining-philosophers-2.lisp new file mode 100644 index 0000000000..80a5176d7e --- /dev/null +++ b/Task/Dining-philosophers/Common-Lisp/dining-philosophers-2.lisp @@ -0,0 +1,49 @@ +(ql:quickload '(:stmx :bordeaux-threads)) + +(defpackage :dining-philosophers + (:use :cl)) + +(in-package :dining-philosophers) + +(defstruct philosopher + name + left-fork + right-fork) + +(defparameter *philosophers* '("Aristotle" "Kant" "Spinoza" "Marx" "Russell")) +(defparameter *eating-max* 5.0) +(defparameter *thinking-max* 5.0) +(defvar *log-lock* (bt:make-lock)) +(defvar *running* nil) + +(defun print-log (name status) + (bt:with-lock-held (*log-lock*) + (format t "~a is ~a~%" name status))) + +(defun philosopher-cycle (philosopher) + "Continously atomically grab and return the left and right forks of the given PHILOSOPHER." + (with-slots (name left-fork right-fork) philosopher + (loop while *running* + do + (print-log name "hungry") + (stmx:atomic + (stmx.util:take left-fork) + (stmx.util:take right-fork)) + (print-log name "eating") + (sleep (random *eating-max*)) + (stmx:atomic + (stmx.util:put left-fork t) + (stmx.util:put right-fork t)) + (print-log name "thinking") + (sleep (random *thinking-max*))))) + +(defun scenario () + (let ((forks (loop repeat (length *philosophers*) collect (stmx.util:tcell t)))) + (setf *running* t) + (loop for name in *philosophers* + for left-fork in forks + for right-fork in (append (cdr forks) (list (car forks))) + do (let ((philosopher (make-philosopher :name name :left-fork left-fork :right-fork right-fork))) + (bt:make-thread (lambda () (philosopher-cycle philosopher)) + :initial-bindings (cons (cons '*standard-output* *standard-output*) + bt:*default-special-bindings*)))))) diff --git a/Task/Dining-philosophers/Common-Lisp/dining-philosophers-3.lisp b/Task/Dining-philosophers/Common-Lisp/dining-philosophers-3.lisp new file mode 100644 index 0000000000..45fccd7f73 --- /dev/null +++ b/Task/Dining-philosophers/Common-Lisp/dining-philosophers-3.lisp @@ -0,0 +1,44 @@ +DINING-PHILOSOPHERS> (scenario) +Aristotle is hungry +Aristotle is eating +Kant is hungry +Spinoza is hungry +Spinoza is eating +Marx is hungry +NIL +Russell is hungry +Aristotle is thinking +Russell is eating +Spinoza is thinking +Kant is eating +Spinoza is hungry +Russell is thinking +Marx is eating +Kant is thinking +Aristotle is hungry +Aristotle is eating +Marx is thinking +Spinoza is eating +Spinoza is thinking +Marx is hungry +Marx is eating +Russell is hungry +Marx is thinking +Kant is hungry +Aristotle is thinking +Russell is eating +Kant is eating +Marx is hungry +Spinoza is hungry +Kant is thinking +Spinoza is eating +Kant is hungry +Aristotle is hungry +Russell is thinking +Aristotle is eating +Aristotle is thinking +Aristotle is hungry +Aristotle is eating +Spinoza is thinking +Marx is eating +... diff --git a/Task/Dining-philosophers/Julia/dining-philosophers.julia b/Task/Dining-philosophers/Julia/dining-philosophers.julia new file mode 100644 index 0000000000..112b7814cc --- /dev/null +++ b/Task/Dining-philosophers/Julia/dining-philosophers.julia @@ -0,0 +1,83 @@ +mutable struct Philosopher + name::String + hungry::Bool + righthanded::Bool + rightforkheld::Channel + leftforkheld::Channel + function Philosopher(name, leftfork, rightfork) + this = new() + this.name = name + this.hungry = rand([false, true]) # not specified so start as either + this.righthanded = (name == "Aristotle") ? false : true + this.leftforkheld = leftfork + this.rightforkheld = rightfork + this + end +end + +mutable struct FiveForkTable + fork51::Channel + fork12::Channel + fork23::Channel + fork34::Channel + fork45::Channel + function FiveForkTable() + this = new() + this.fork51 = Channel(1); put!(this.fork51, "fork") # start with one fork per channel + this.fork12 = Channel(1); put!(this.fork12, "fork") + this.fork23 = Channel(1); put!(this.fork23, "fork") + this.fork34 = Channel(1); put!(this.fork34, "fork") + this.fork45 = Channel(1); put!(this.fork45, "fork") + this + end +end + + +table = FiveForkTable(); +tasks = [Philosopher("Aristotle", table.fork12, table.fork51), + Philosopher("Kant", table.fork23, table.fork12), + Philosopher("Spinoza", table.fork34, table.fork23), + Philosopher("Marx", table.fork45, table.fork34), + Philosopher("Russell", table.fork51, table.fork45)] + +function dine(t,p) + if p.righthanded + take!(p.rightforkheld); println("$(p.name) takes right fork") + take!(p.leftforkheld); println("$(p.name) takes left fork") + else + take!(p.leftforkheld); println("$(p.name) takes left fork") + take!(p.rightforkheld); println("$(p.name) takes right fork") + end +end + +function leavetothink(t, p) + put!(p.rightforkheld, "fork"); println("$(p.name) puts down right fork") + put!(p.leftforkheld, "fork"); println("$(p.name) puts down left fork") +end + +contemplate(t) = sleep(t) + +function dophil(p, t, fullaftersecs=2.0, hungryaftersecs=10.0) + while true + if p.hungry + println("$(p.name) is hungry") + dine(table, p) + sleep(fullaftersecs) + p.hungry = false + leavetothink(t, p) + else + println("$(p.name) is out of the dining room for now.") + contemplate(hungryaftersecs) + p.hungry = true + end + end +end + +function runall(tasklist) + for p in tasklist + @async dophil(p, table) + end + while true begin sleep(5) end end +end + +runall(tasks) diff --git a/Task/Dining-philosophers/Kotlin/dining-philosophers.kotlin b/Task/Dining-philosophers/Kotlin/dining-philosophers.kotlin new file mode 100644 index 0000000000..4e74a37ba6 --- /dev/null +++ b/Task/Dining-philosophers/Kotlin/dining-philosophers.kotlin @@ -0,0 +1,58 @@ +// Version 1.2.31 + +import java.util.Random +import java.util.concurrent.locks.Lock +import java.util.concurrent.locks.ReentrantLock + +val rand = Random() + +class Fork(val name: String) { + val lock = ReentrantLock() + + fun pickUp(philosopher: String) { + lock.lock() + println(" $philosopher picked up $name") + } + + fun putDown(philosopher: String) { + lock.unlock() + println(" $philosopher put down $name") + } +} + +class Philosopher(val pname: String, val f1: Fork, val f2: Fork) : Thread() { + override fun run() { + (1..20).forEach { + println("$pname is hungry") + f1.pickUp(pname) + f2.pickUp(pname) + println("$pname is eating bite $it") + Thread.sleep(rand.nextInt(300) + 100L) + f2.putDown(pname) + f1.putDown(pname) + } + } +} + +fun diningPhilosophers(names: List) { + val size = names.size + val forks = List(size) { Fork("Fork ${it + 1}") } + val philosophers = mutableListOf() + names.forEachIndexed { i, n -> + var i1 = i + var i2 = (i + 1) % size + if (i2 < i1) { + i1 = i2 + i2 = i + } + val p = Philosopher(n, forks[i1], forks[i2]) + p.start() + philosophers.add(p) + } + philosophers.forEach { it.join() } +} + +fun main(args: Array) { + val names = listOf("Aristotle", "Kant", "Spinoza", "Marx", "Russell") + diningPhilosophers(names) +} diff --git a/Task/Dining-philosophers/REXX/dining-philosophers.rexx b/Task/Dining-philosophers/REXX/dining-philosophers.rexx index 95e5bee11f..f172f63ca7 100644 --- a/Task/Dining-philosophers/REXX/dining-philosophers.rexx +++ b/Task/Dining-philosophers/REXX/dining-philosophers.rexx @@ -1,48 +1,48 @@ -/*REXX pgm demonstrates a solution in solving the dining philosophers problem.*/ -signal on halt /*branches to HALT: (on Ctrl─break).*/ -parse arg seed diners /*obtain optional arguments from the CL*/ -if datatype(seed,'W') then call random ,, seed /*for random repeatability.*/ -if diners='' then diners = 'Aristotle, Kant, Spinoza, Marx, Russell' - tell=(left(seed,1)\=='+') /*Leading + in SEED? Then no statistics*/ -diners=space(translate(diners,,',')) /*change to an uncommatized diners list*/ - #=words(diners); @.= 0 /*#: the number of dining philosophers.*/ - eatL=15; eatH= 60 /*minimum & maximum minutes for eating.*/ -thinkL=30; thinkH=180 /* " " " " " thinking*/ -forks.=1 /*indicate that all forks are on table.*/ - do tic=1 /*'til halted.*/ /*use "minutes" for time advancement.*/ - call grabForks /*determine if anybody can grab 2 forks*/ - call passTime /*handle philosophers eating|thinking. */ - end /*tic*/ /* ··· and time marches on ··· */ - /* [↓] this REXX program was halted,*/ -halt: say ' ··· REXX program halted!' /*probably by Ctrl─Break or equivalent.*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────FORK subroutine───────────────────────────*/ -fork: parse arg x 1 ox; x=abs(x); L=x-1; if L==0 then L=# /*on a boundary? */ -if ox<0 then do; forks.L=1; forks.x=1; return; end /*drop the forks.*/ -got2=forks.L & forks.x /*get 2 forks │ ¬*/ -if got2 then do; forks.L=0; forks.x=0; end /*got two forks. */ -return got2 /*return with success ··· or failure. */ -/*──────────────────────────────────GRABFORKS subroutine──────────────────────*/ -grabForks: do person=1 for # /*see if any person can grab two forks.*/ - if @.person.state\==0 then iterate /*the diner ain't waiting. */ - if \fork(person) then iterate /*the diner didn't grab 2. */ - @.person.state= 'eating' /*diner spaghetti slurping.*/ - @.person.dur=random(eatL,eatH) /*how long will diner eat? */ - end /*person*/ /* [↑] handle all diners. */ -return -/*──────────────────────────────────PASSTIME subroutine───────────────────────*/ -passTime: if tell then say /*display a handy blank line separator.*/ - do p=1 for # /*handle each of the diner's activity. */ - if tell then say right(tic,9,.) right(word(diners,p),20), - right(word(@.p.state 'waiting', 1+(@.p.state==0)),9) right(@.p.dur,5) - if @.p.dur==0 then iterate /*this diner is waiting for two forks. */ - @.p.dur=@.p.dur - 1 /*indicate single time unit has passed.*/ - if @.p.dur\==0 then iterate /*Activity done? No, then keep it up.*/ - if @.p.state=='eating' then do /*now, leave the table.*/ - call fork -p /*drop the darn forks. */ - @.p.state='thinking' /*status.*/ - @.p.dur=random(thinkL,thinkH) /*length.*/ - end /* [↓] diner ──► the table.*/ - else if @.p.state=='thinking' then @.p.state=0 - end /*p*/ /*[↑] P (person) ≡dining philosophers.*/ -return +/*REXX program demonstrates a solution in solving the dining philosophers problem. */ +signal on halt /*branches to HALT: (on Ctrl─break).*/ +parse arg seed diners /*obtain optional arguments from the CL*/ +if datatype(seed, 'W') then call random ,, seed /*this allows for random repeatability.*/ +if diners= '' then diners = 'Aristotle, Kant, Spinoza, Marx, Russell' + tell=(left(seed, 1) \== '+') /*Leading + in SEED? Then no statistics*/ +diners=space( translate(diners, , ',') ) /*change to an uncommatized diners list*/ + #=words(diners); @.= 0 /*#: the number of dining philosophers.*/ + eatL=15; eatH= 60 /*minimum & maximum minutes for eating.*/ +thinkL=30; thinkH=180 /* " " " " " thinking*/ +forks.=1 /*indicate that all forks are on table.*/ + do tic=1 /*'til halted.*/ /*use "minutes" for time advancement.*/ + call grabForks /*determine if anybody can grab 2 forks*/ + call passTime /*handle philosophers eating|thinking. */ + end /*tic*/ /* ··· and time marches on ··· */ + /* [↓] this REXX program was halted,*/ +halt: say ' ··· REXX program halted!' /*probably by Ctrl─Break or equivalent.*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +fork: parse arg x 1 ox; x=abs(x); L=x - 1; if L==0 then L=# /*use "round Robin".*/ + if ox<0 then do; forks.L=1; forks.x=1; return; end /*drop the forks. */ + got2= forks.L & forks.x /*get 2 forks or not*/ + if got2 then do; forks.L=0; forks.x=0; end /*obtained 2 forks. */ + return got2 /*return with success ··· or failure. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +grabForks: do person=1 for # /*see if any person can grab two forks.*/ + if @.person.state\==0 then iterate /*this diner ain't in a waiting state. */ + if \fork(person) then iterate /*this diner didn't grab two forks. */ + @.person.state= 'eating' /*this diner is slurping spaghetti. */ + @.person.dur=random(eatL, eatH) /*how long will this diner eat pasta ? */ + end /*person*/ /* [↑] process the dining philosophers*/ + return /*all the diners have been examined. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +passTime: if tell then say /*display a handy blank line separator.*/ + do p=1 for # /*handle each of the diner's activity. */ + if tell then say right(tic, 9, .) right( word( diners, p), 20), + right(word(@.p.state 'waiting',1+(@.p.state==0)),9) right(@.p.dur,5) + if @.p.dur==0 then iterate /*this diner is waiting for two forks. */ + @.p.dur= @.p.dur - 1 /*indicate single time unit has passed.*/ + if @.p.dur\==0 then iterate /*Activity done? No, then keep it up.*/ + if @.p.state=='eating' then do /*now, leave the table.*/ + call fork -p /*drop the darn forks. */ + @.p.state= 'thinking' /*status.*/ + @.p.dur=random(thinkL, thinkH) /*length.*/ + end /* [↓] a diner goes ──► the table. */ + else if @.p.state=='thinking' then @.p.state=0 + end /*p*/ /*[↑] P (person)≡ dining philosophers.*/ + return diff --git a/Task/Discordian-date/Julia/discordian-date.julia b/Task/Discordian-date/Julia/discordian-date.julia index 2f9e89039c..0426508033 100644 --- a/Task/Discordian-date/Julia/discordian-date.julia +++ b/Task/Discordian-date/Julia/discordian-date.julia @@ -1,20 +1,18 @@ -# v0.6.0 -using Dates +using Base.Dates function discordiandate(year::Integer, month::Integer, day::Integer) - const DISCORDIANSEASONS = ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"] - const HOLIDAYS = Dict( - "Chaos 5" => "Mungday", - "Chaos 50" => "Chaoflux", - "Discord 5" => "Mojoday", - "Discord 50" => "Discoflux", - "Confusion 5" => "Syaday", - "Confusion 50" => "Confuflux", - "Bureaucracy 5" => "Zaraday", - "Bureaucracy 50" => "Bureflux", - "The Aftermath 5" => "Maladay", - "The Aftermath 50" => "Afflux", - ) + discordianseasons = ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"] + holidays = Dict( + "Chaos 5" => "Mungday", + "Chaos 50" => "Chaoflux", + "Discord 5" => "Mojoday", + "Discord 50" => "Discoflux", + "Confusion 5" => "Syaday", + "Confusion 50" => "Confuflux", + "Bureaucracy 5" => "Zaraday", + "Bureaucracy 50" => "Bureflux", + "The Aftermath 5" => "Maladay", + "The Aftermath 50" => "Afflux") today = Date(year, month, day) isleap = isleapyear(year) if isleap && month == 2 && day == 29 @@ -24,12 +22,11 @@ function discordiandate(year::Integer, month::Integer, day::Integer) if isleap && dy >= 60 dy -= 1 end - dday = string(DISCORDIANSEASONS[div(dy, 73) + 1], " ", rem(dy, 73)) - if haskey(HOLIDAYS, dday) - rst = dday * " ($(HOLIDAYS[dday])), YOLD $(year + 1166)" - else - rst = dday * ", YOLD $(year + 1166)" + rst = string(discordianseasons[div(dy, 73) + 1], " ", rem(dy, 73)) # day + if haskey(holidays, rst) + rst *= " ($(holidays[rst]))" # if holiday end + rst *= ", YOLD $(year + 1166)" # year end return rst end diff --git a/Task/Discordian-date/Rust/discordian-date.rust b/Task/Discordian-date/Rust/discordian-date.rust new file mode 100644 index 0000000000..8a71142360 --- /dev/null +++ b/Task/Discordian-date/Rust/discordian-date.rust @@ -0,0 +1,71 @@ +extern crate chrono; + +use chrono::NaiveDate; +use std::str::FromStr; + +fn main() { + let date = std::env::args().nth(1).expect("Please provide a YYYY-MM-DD date."); + println!("{} is {}", date, NaiveDate::from_str(&date).unwrap().to_poee()); +} + +// The necessary constants for the seasons, weekdays, and holydays. +const APOSTLES: [&str; 5] = ["Mungday", "Mojoday", "Syaday", "Zaraday", "Maladay"]; +const HOLYDAYS: [&str; 5] = ["Chaoflux", "Discoflux", "Confuflux", "Bureflux", "Afflux"]; +const SEASONS: [&str; 5] = ["Chaos", "Discord", "Confusion", "Bureaucracy", "The Aftermath"]; +const WEEKDAYS: [&str; 5] = ["Sweetmorn", "Boomtime", "Pungenday", "Prickle-Prickle", "Setting Orange"]; + +// The necessary constants for the conversion. +const APOSTLE_HOLYDAY: usize = 5; +const CURSE_OF_GREYFACE: i32 = 1166; +const SEASON_DAYS: usize = 73; +const SEASON_HOLYDAY: usize = 50; +const ST_TIBS_DAY: usize = 59; +const WEEK_DAYS: usize = 5; + +// This extends the `Datelike` trait of Rust's Chrono crate with a method that +// prints any Datelike type as a String. +impl DiscordianDate for T {} +pub trait DiscordianDate: Datelike { + fn to_poee(&self) -> String { + let day = self.ordinal0() as usize; + let leap = self.year() % 4 == 0 && self.year() % 100 != 0 || self.year() % 400 == 0; + let year = self.year() + CURSE_OF_GREYFACE; + + if leap && day == ST_TIBS_DAY { return format!("St. Tib's Day, in the YOLD {}", year); } + + let day_offset = if leap && day > ST_TIBS_DAY { day - 1 } else { day }; + + let day_of_season = day_offset % SEASON_DAYS + 1; + + let season = SEASONS[day_offset / SEASON_DAYS]; + let weekday = WEEKDAYS[day_offset % WEEK_DAYS]; + + let holiday = if day_of_season == APOSTLE_HOLYDAY { + format!("\nCelebrate {}", APOSTLES[day_offset / SEASON_DAYS]) + } else if day_of_season == SEASON_HOLYDAY { + format!("\nCelebrate {}", HOLYDAYS[day_offset / SEASON_DAYS]) + } else { + String::with_capacity(0) + }; + + format!("{}, the {} day of {} in the YOLD {}{}", + weekday, ordinalize(day_of_season), season, year, holiday) + } +} + +/// A helper function to ordinalize a numeral. +fn ordinalize(num: usize) -> String { + let s = format!("{}", num); + + let suffix = if s.ends_with('1') && !s.ends_with("11") { + "st" + } else if s.ends_with('2') && !s.ends_with("12") { + "nd" + } else if s.ends_with('3') && !s.ends_with("13") { + "rd" + } else { + "th" + }; + + format!("{}{}", s, suffix) +} diff --git a/Task/Distributed-programming/Perl-6/distributed-programming-1.pl6 b/Task/Distributed-programming/Perl-6/distributed-programming-1.pl6 new file mode 100644 index 0000000000..0aaee7a563 --- /dev/null +++ b/Task/Distributed-programming/Perl-6/distributed-programming-1.pl6 @@ -0,0 +1,36 @@ +#!/usr/bin/env perl6 +use JSON::Fast ; +sub MAIN( :$server='0.0.0.0' , :$port=3333 ) { + my %db ; + react { + whenever IO::Socket::Async.listen( $server , $port ) -> $conn { + whenever $conn.Supply.lines -> $line { + my %response = 'status' => '' ; + my $msg = from-json $line ; + say $msg.perl ; + given $msg{"function"} { + when 'set' { + %db{ $msg } = $msg ; + %response = 'ok' ; + } + when 'get' { + %response = $msg ; + %response = %db{ $msg } ; + %response = 'ok' ; + } + when 'dump' { + %response = %db ; + } + when 'delete' { + %db{ $msg }:delete; + %response = 'ok' ; + } + } + $conn.print( to-json(%response, :!pretty) ~ "\n" ) ; + LAST { $conn.close ; } + QUIT { default { $conn.close ; say "oh no, $_";}} + CATCH { default { say .^name, ': ', .Str , " handled in $?LINE";}} + } + } + } +} diff --git a/Task/Distributed-programming/Perl-6/distributed-programming-2.pl6 b/Task/Distributed-programming/Perl-6/distributed-programming-2.pl6 new file mode 100644 index 0000000000..3b4a7bb544 --- /dev/null +++ b/Task/Distributed-programming/Perl-6/distributed-programming-2.pl6 @@ -0,0 +1,29 @@ +#!/usr/bin/env perl6 +use JSON::Fast ; +multi MAIN('set', $topic, $message='', :$server='localhost', :$port='3333', :$json='') { + my %msg = function => 'set' , topic=> $topic , message=> $message ; + %msg{"message"} = from-json( $json ) if $json ; + sendmsg( %msg , $server, $port) ; +} +multi MAIN('get', $topic, :$server='localhost', :$port='3333') { + my %msg = function => 'get' , topic=> $topic ; + sendmsg( %msg , $server, $port) ; +} +multi MAIN('delete', $topic, :$server='localhost', :$port='3333') { + my %msg = function => 'delete' , topic=> $topic ; + sendmsg( %msg , $server, $port) ; +} +multi MAIN('dump', :$server='localhost', :$port='3333') { + my %msg = function => 'dump' ; + sendmsg( %msg , $server, $port) ; +} +sub sendmsg( %msg , $server, $port){ + my $conn = await IO::Socket::Async.connect( $server , $port ); + $conn.print: to-json( %msg,:!pretty)~"\n"; + react { + whenever $conn.Supply -> $data { + print $data; + $conn.close; + } + } +} diff --git a/Task/Documentation/Forth/documentation-1.fth b/Task/Documentation/Forth/documentation-1.fth new file mode 100644 index 0000000000..6479f6de37 --- /dev/null +++ b/Task/Documentation/Forth/documentation-1.fth @@ -0,0 +1 @@ +\ this is a comment diff --git a/Task/Documentation/Forth/documentation-2.fth b/Task/Documentation/Forth/documentation-2.fth new file mode 100644 index 0000000000..6a05dc16b1 --- /dev/null +++ b/Task/Documentation/Forth/documentation-2.fth @@ -0,0 +1 @@ +: cubed ( n -- n^3 ) dup dup * * ; diff --git a/Task/Documentation/Kotlin/documentation.kotlin b/Task/Documentation/Kotlin/documentation.kotlin new file mode 100644 index 0000000000..6dfb678e3a --- /dev/null +++ b/Task/Documentation/Kotlin/documentation.kotlin @@ -0,0 +1,19 @@ +/** + * A group of *members*. + * @author A Programmer. + * @since version 1.1.51. + * + * This class has no useful logic; it's just a documentation example. + * + * @param T the type of a member in this group. + * @property name the name of this group. + * @constructor Creates an empty group. + */ +class Group(val name: String) { + /** + * Adds a [member] to this group. + * @throws AddException if the member can't be added. + * @return the new size of the group. + */ + fun add(member: T): Int { ... } +} diff --git a/Task/Documentation/Stata/documentation.stata b/Task/Documentation/Stata/documentation.stata new file mode 100644 index 0000000000..654293ab98 --- /dev/null +++ b/Task/Documentation/Stata/documentation.stata @@ -0,0 +1,3 @@ +prog def hello + di "Hello, World!" +end diff --git a/Task/Dot-product/Aime/dot-product.aime b/Task/Dot-product/Aime/dot-product.aime index d5f173efcd..52f71210d6 100644 --- a/Task/Dot-product/Aime/dot-product.aime +++ b/Task/Dot-product/Aime/dot-product.aime @@ -6,16 +6,16 @@ dp(list a, list b) p = 0; for (i, v in a) { - p += v * __real(b[i]); + p += v * b[i]; } - return p; + p; } integer main(void) { - o_(dp(l_effect(1r, 3r, -5r), l_effect(4r, -2r, -1r)), "\n"); + o_(dp(list(1r, 3r, -5r), list(4r, -2r, -1r)), "\n"); - return 0; + 0; } diff --git a/Task/Dot-product/BASIC/dot-product-1.basic b/Task/Dot-product/BASIC/dot-product-1.basic new file mode 100644 index 0000000000..48c23ec1d7 --- /dev/null +++ b/Task/Dot-product/BASIC/dot-product-1.basic @@ -0,0 +1,20 @@ + 100 : + 110 REM DOT PRODUCT + 120 : + 130 REM INITIALIZE VECTORS OF LENGTH N + 140 N = 3 + 150 DIM V1(N): DIM V2(N) + 160 FOR I = 1 TO N + 170 V1(I) = INT ( RND (1) * 20 - 9.5) + 180 V2(I) = INT ( RND (1) * 20 - 9.5) + 190 NEXT I + 300 : + 310 REM CALCULATE THE DOT PRODUCT + 320 : + 330 FOR I = 1 TO N:DP = DP + V1(I) * V2(I): NEXT I + 400 : + 410 REM DISPLAY RESULT + 420 : + 430 PRINT "[";: FOR I = 1 TO N: PRINT " ";V1(I);: NEXT I + 440 PRINT "] . [";: FOR I = 1 TO N: PRINT " ";V2(I);: NEXT I + 450 PRINT "] = ";DP diff --git a/Task/Dot-product/BASIC/dot-product-2.basic b/Task/Dot-product/BASIC/dot-product-2.basic new file mode 100644 index 0000000000..8d71daf079 --- /dev/null +++ b/Task/Dot-product/BASIC/dot-product-2.basic @@ -0,0 +1,7 @@ + DIM vec1(2), vec2(2), dot(0) + + vec1() = 1, 3, -5 + vec2() = 4, -2, -1 + + dot() = vec1() . vec2() + PRINT "Result is "; dot(0) diff --git a/Task/Dot-product/Elena/dot-product.elena b/Task/Dot-product/Elena/dot-product.elena new file mode 100644 index 0000000000..48f679a491 --- /dev/null +++ b/Task/Dot-product/Elena/dot-product.elena @@ -0,0 +1,13 @@ +import extensions. +import system'routines. + +extension $op +{ + method dotProduct array:array + = self zip(array) by(:x:y)(x * y); summarize. +} + +program = +[ + console printLine((1, 3, -5) dotProduct:(4, -2, -1)). +]. diff --git a/Task/Dot-product/Fortran/dot-product.f b/Task/Dot-product/Fortran/dot-product.f index 09d9c4fcea..1e2ad41dde 100644 --- a/Task/Dot-product/Fortran/dot-product.f +++ b/Task/Dot-product/Fortran/dot-product.f @@ -1,5 +1,5 @@ program test_dot_product - write (*, '(i0)') dot_product ((/1, 3, -5/), (/4, -2, -1/)) + write (*, '(i0)') dot_product ([1, 3, -5], [4, -2, -1]) end program test_dot_product diff --git a/Task/Dot-product/Modula-2/dot-product.mod2 b/Task/Dot-product/Modula-2/dot-product.mod2 new file mode 100644 index 0000000000..40f29e9569 --- /dev/null +++ b/Task/Dot-product/Modula-2/dot-product.mod2 @@ -0,0 +1,25 @@ +MODULE DotProduct; +FROM RealStr IMPORT RealToStr; +FROM Terminal IMPORT WriteString,WriteLn,ReadChar; + +TYPE Vector = + RECORD + x,y,z : REAL + END; + +PROCEDURE DotProduct(u,v : Vector) : REAL; +BEGIN + RETURN u.x*v.x + u.y*v.y + u.z*v.z +END DotProduct; + +VAR + buf : ARRAY[0..63] OF CHAR; + dp : REAL; +BEGIN + dp := DotProduct(Vector{1.0,3.0,-5.0},Vector{4.0,-2.0,-1.0}); + RealToStr(dp, buf); + WriteString(buf); + WriteLn; + + ReadChar +END DotProduct. diff --git a/Task/Doubly-linked-list-Definition/Ring/doubly-linked-list-definition.ring b/Task/Doubly-linked-list-Definition/Ring/doubly-linked-list-definition.ring new file mode 100644 index 0000000000..f631c2e6e9 --- /dev/null +++ b/Task/Doubly-linked-list-Definition/Ring/doubly-linked-list-definition.ring @@ -0,0 +1,19 @@ +# Project : Doubly-linked list/Definition +# Date : 2018/01/08 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +test = [1, 5, 7, 0, 3, 2] +insert(test, 0, 9) +insert(test, len(test), 4) +item = len(test)/2 +insert(test, item, 6) +showarray(test) + +func showarray(vect) + svect = "" + for n = 1 to len(vect) + svect = svect + vect[n] + " " + next + svect = left(svect, len(svect) - 1) + see svect diff --git a/Task/Doubly-linked-list-Element-definition/Julia/doubly-linked-list-element-definition.julia b/Task/Doubly-linked-list-Element-definition/Julia/doubly-linked-list-element-definition.julia new file mode 100644 index 0000000000..54e90fae8b --- /dev/null +++ b/Task/Doubly-linked-list-Element-definition/Julia/doubly-linked-list-element-definition.julia @@ -0,0 +1,8 @@ +abstract type AbstractNode{T} end + +struct EmptyNode{T} <: AbstractNode{T} end +mutable struct Node{T} <: AbstractNode{T} + value::T + pred::AbstractNode{T} + succ::AbstractNode{T} +end diff --git a/Task/Doubly-linked-list-Element-definition/PicoLisp/doubly-linked-list-element-definition.l b/Task/Doubly-linked-list-Element-definition/PicoLisp/doubly-linked-list-element-definition.l index 71d0888da3..4f2de7a833 100644 --- a/Task/Doubly-linked-list-Element-definition/PicoLisp/doubly-linked-list-element-definition.l +++ b/Task/Doubly-linked-list-Element-definition/PicoLisp/doubly-linked-list-element-definition.l @@ -1,5 +1,11 @@ -# 'cons' an element to a doubly-linked list -(de 2cons (X DLst) +(de 2tail (X DLst) + (let L (cdr DLst) + (con DLst (cons X L NIL)) + (if L + (con (cdr L) (cdr DLst)) + (set DLst (cdr DLst)) ) ) ) + +(de 2head (X DLst) (let L (car DLst) # Get current data list (set DLst (cons X NIL L)) # Prepend two new cons pairs (if L # Unless DLst was empty @@ -7,4 +13,4 @@ (con DLst (car DLst)) ) ) ) # otherwise set 'end' link # We prepend 'not' to the list in the previous example -(2cons 'not *DLst) +(2head 'not *DLst) diff --git a/Task/Doubly-linked-list-Element-insertion/Perl-6/doubly-linked-list-element-insertion.pl6 b/Task/Doubly-linked-list-Element-insertion/Perl-6/doubly-linked-list-element-insertion.pl6 index 68489a2808..3cce67e783 100644 --- a/Task/Doubly-linked-list-Element-insertion/Perl-6/doubly-linked-list-element-insertion.pl6 +++ b/Task/Doubly-linked-list-Element-insertion/Perl-6/doubly-linked-list-element-insertion.pl6 @@ -1,3 +1,50 @@ +role DLElem[::T] { + has DLElem[T] $.prev is rw; + has DLElem[T] $.next is rw; + has T $.payload = T; + + method pre-insert(T $payload) { + die "Can't insert before beginning" unless $!prev; + my $elem = ::?CLASS.new(:$payload); + $!prev.next = $elem; + $elem.prev = $!prev; + $elem.next = self; + $!prev = $elem; + $elem; + } + + method post-insert(T $payload) { + die "Can't insert after end" unless $!next; + my $elem = ::?CLASS.new(:$payload); + $!next.prev = $elem; + $elem.next = $!next; + $elem.prev = self; + $!next = $elem; + $elem; + } + + method delete { + die "Can't delete a sentinel" unless $!prev and $!next; + $!next.prev = $!prev; + $!prev.next = $!next; # conveniently returns next element + } +} + +role DLList[::DLE] { + has DLE $.first; + has DLE $.last; + + submethod BUILD { + $!first = DLE.new; + $!last = DLE.new; + $!first.next = $!last; + $!last.prev = $!first; + } + + method list { ($!first.next, *.next ...^ !*.next).map: *.payload } + method reverse { ($!last.prev, *.prev ...^ !*.prev).map: *.payload } +} + class DLElem_Str does DLElem[Str] {} class DLList_Str does DLList[DLElem_Str] {} diff --git a/Task/Doubly-linked-list-Traversal/Ring/doubly-linked-list-traversal.ring b/Task/Doubly-linked-list-Traversal/Ring/doubly-linked-list-traversal.ring new file mode 100644 index 0000000000..399f265a52 --- /dev/null +++ b/Task/Doubly-linked-list-Traversal/Ring/doubly-linked-list-traversal.ring @@ -0,0 +1,14 @@ +# Project : Doubly-linked list/Traversal +# Date : 2018/03/13 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : + +trav = [123, 789, 456] +travfor = sort(trav) +see "Traverse forwards:" + nl +see travfor +see nl +travback = reverse(travfor) +see "Traverse backwards:" + nl +see travback +see nl diff --git a/Task/Dragon-curve/Julia/dragon-curve.julia b/Task/Dragon-curve/Julia/dragon-curve.julia new file mode 100644 index 0000000000..999912c877 --- /dev/null +++ b/Task/Dragon-curve/Julia/dragon-curve.julia @@ -0,0 +1,18 @@ +using Luxor +function dragon(turtle::Turtle, level=4, size=200, direction=45) + if level != 0 + Turn(turtle, -direction) + dragon(turtle, level-1, size/sqrt(2), 45) + Turn(turtle, direction*2) + dragon(turtle, level-1, size/sqrt(2), -45) + Turn(turtle, -direction) + else + Forward(turtle, size) + end +end + +Drawing(900, 500, "./Dragon.png") +t = Turtle(300, 300, true, 0, (0., 0.0, 0.0)); +dragon(t, 10,400) +finish() +preview() diff --git a/Task/Dragon-curve/Perl-6/dragon-curve.pl6 b/Task/Dragon-curve/Perl-6/dragon-curve.pl6 index a4a3fd3b8c..70f561a21b 100644 --- a/Task/Dragon-curve/Perl-6/dragon-curve.pl6 +++ b/Task/Dragon-curve/Perl-6/dragon-curve.pl6 @@ -11,20 +11,23 @@ my $dragon = "FX" but Lindenmayer( { X => 'X+YF+', Y => '-FX-Y' } ); -$dragon++ for ^10; +$dragon++ for ^15; say " -"; +"; +say ''; for $dragon.comb { state ($x, $y) = 100, 100; state $d = 2 + 0i; if /F/ { - say ""; + say ""; } elsif /< + - >/ { $d *= "{$_}1i" } } diff --git a/Task/Dragon-curve/REXX/dragon-curve.rexx b/Task/Dragon-curve/REXX/dragon-curve.rexx index 9d06304650..c30368f00d 100644 --- a/Task/Dragon-curve/REXX/dragon-curve.rexx +++ b/Task/Dragon-curve/REXX/dragon-curve.rexx @@ -27,5 +27,5 @@ p=translate(left(p,1), 0123, 'NESW'); $= /*get the orientation for drago do r=minX to maxX; a= /*nullify the line that will be drawn. */ do c=minY to maxY; a=a || @.r.c /*create a line (row) of curve points. */ end /*c*/ /* [↑] append a single column of a row.*/ - if a\='' then say strip(a, 'T') /*display a line (row) of curve points.*/ + if a\='' then say strip(a, "T") /*display a line (row) of curve points.*/ end /*r*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Draw-a-clock/BASIC/draw-a-clock.basic b/Task/Draw-a-clock/BASIC/draw-a-clock.basic new file mode 100644 index 0000000000..95d1c2a14d --- /dev/null +++ b/Task/Draw-a-clock/BASIC/draw-a-clock.basic @@ -0,0 +1,32 @@ +10 gosub 1500: rem setup clock digit strings +20 ti$ = "123456" +25 rem do some other stuff after this line +30 print x: x=x+1 +40 for i=0 to 500: next +50 gosub 1000: rem display the time +60 goto 30 +70 end +1000 t$ = ti$ +1010 for i=1 to 6 +1020 t(i) = val(mid$(t$,i,1)) +1030 next +1040 print chr$(19); +1050 for j=1 to 5 +1055 print tab(19); +1060 for i=1 to 6 +1070 k=t(i)*3+1 +1080 print mid$(z$(j),k,3); +1090 rem if j<5 then print" ";: goto 1130 +1100 if i=2 then print" "; +1110 if i=4 then print" "; +1130 next +1140 print +1150 next +1160 return +1500 dim z$(5) +1510 z$(1) = "UCI I UCICCIB BCCCUCIUCIUCI" +1520 z$(2) = "B B B B BB BB B B BB B" +1530 z$(3) = "B B B UCK CBJCBJCIBCIBCIJCB" +1540 z$(4) = "B B B B B B BB BB B B" +1550 z$(5) = "JCKCCCJCCCCK BCCKJCKJCK CK" +1560 return diff --git a/Task/Draw-a-clock/JavaScript/draw-a-clock-2.js b/Task/Draw-a-clock/JavaScript/draw-a-clock-2.js index 859baf2f05..fa7af8952f 100644 --- a/Task/Draw-a-clock/JavaScript/draw-a-clock-2.js +++ b/Task/Draw-a-clock/JavaScript/draw-a-clock-2.js @@ -1,69 +1,69 @@ - - - - - - diff --git a/Task/Draw-a-clock/Rust/draw-a-clock.rust b/Task/Draw-a-clock/Rust/draw-a-clock.rust index 280ce8e144..cd8d9b4631 100644 --- a/Task/Draw-a-clock/Rust/draw-a-clock.rust +++ b/Task/Draw-a-clock/Rust/draw-a-clock.rust @@ -1,9 +1,11 @@ // cargo-deps: time="0.1" extern crate time; -use std::thread; -static TOP: &'static str = " ⡎⢉⢵ ⠀⢺⠀ ⠊⠉⡱ ⠊⣉⡱ ⢀⠔⡇ ⣏⣉⡉ ⣎⣉⡁ ⠊⢉⠝ ⢎⣉⡱ ⡎⠉⢱ ⠀⠶⠀"; -static BOT: &'static str = " ⢗⣁⡸ ⢀⣸⣀ ⣔⣉⣀ ⢄⣀⡸ ⠉⠉⡏ ⢄⣀⡸ ⢇⣀⡸ ⢰⠁⠀ ⢇⣀⡸ ⢈⣉⡹ ⠀⠶⠀"; +use std::thread; +use std::time::Duration; + +const TOP: &str = " ⡎⢉⢵ ⠀⢺⠀ ⠊⠉⡱ ⠊⣉⡱ ⢀⠔⡇ ⣏⣉⡉ ⣎⣉⡁ ⠊⢉⠝ ⢎⣉⡱ ⡎⠉⢱ ⠀⠶⠀"; +const BOT: &str = " ⢗⣁⡸ ⢀⣸⣀ ⣔⣉⣀ ⢄⣀⡸ ⠉⠉⡏ ⢄⣀⡸ ⢇⣀⡸ ⢰⠁⠀ ⢇⣀⡸ ⢈⣉⡹ ⠀⠶⠀"; fn main() { let top: Vec<&str> = TOP.split_whitespace().collect(); @@ -18,7 +20,7 @@ fn main() { println!("{}", top_str); println!("{}", bot_str); - thread::sleep(std::time::Duration::from_secs(1)); + thread::sleep(Duration::from_secs(1)); } } diff --git a/Task/Draw-a-cuboid/C/draw-a-cuboid.c b/Task/Draw-a-cuboid/C/draw-a-cuboid.c index dee16bab57..cbfc44eb32 100644 --- a/Task/Draw-a-cuboid/C/draw-a-cuboid.c +++ b/Task/Draw-a-cuboid/C/draw-a-cuboid.c @@ -1,3 +1,4 @@ +/*Code verified and output corrected by Abhishek Ghosh, 23rd September 2017*/ #include #include #include diff --git a/Task/Draw-a-cuboid/JavaScript/draw-a-cuboid.js b/Task/Draw-a-cuboid/JavaScript/draw-a-cuboid.js index 779aeab8d5..7e27d6f577 100644 --- a/Task/Draw-a-cuboid/JavaScript/draw-a-cuboid.js +++ b/Task/Draw-a-cuboid/JavaScript/draw-a-cuboid.js @@ -3,17 +3,13 @@ - - - - - diff --git a/Task/Draw-a-cuboid/Julia/draw-a-cuboid.julia b/Task/Draw-a-cuboid/Julia/draw-a-cuboid.julia new file mode 100644 index 0000000000..2e9f820dfe --- /dev/null +++ b/Task/Draw-a-cuboid/Julia/draw-a-cuboid.julia @@ -0,0 +1,18 @@ +_pr(t::Dict, x::Int, y::Int, z::Int) = join((rstrip(join(t[(n, m)] for n in range(0, 3+x+z))) for m in reverse(range(0, 3+y+z))), "\n") + +function cuboid(x::Int, y::Int, z::Int) + t = Dict((n, m) => " " for n in range(0, 3 + x + z), m in range(0, 3 + y + z)) + xrow = vcat("+", collect("$(i % 10)" for i in range(0, x)), "+") + for (i, ch) in enumerate(xrow) t[(i, 0)] = t[(i, 1+y)] = t[(1+z+i, 2+y+z)] = ch end + yrow = vcat("+", collect("$(j % 10)" for j in range(0, y)), "+") + for (j, ch) in enumerate(yrow) t[(0, j)] = t[(x+1, j)] = t[(2+x+z, 1+z+j)] = ch end + zdep = vcat("+", collect("$(k % 10)" for k in range(0, y)), "+") + for (k, ch) in enumerate(xrow) t[(k, 1+y+k)] = t[(1+x+k, 1+y+k)] = t[(1+x+k, k)] = ch end + + return _pr(t, x, y, z) +end + +for (x, y, z) in [(2, 3, 4), (3, 4, 2), (4, 2, 3), (5, 5, 6)] + println("\nCUBOID($x, $y, $z)\n") + println(cuboid(x, y, z)) +end diff --git a/Task/Draw-a-cuboid/Ring/draw-a-cuboid.ring b/Task/Draw-a-cuboid/Ring/draw-a-cuboid.ring new file mode 100644 index 0000000000..7c55edf5e1 --- /dev/null +++ b/Task/Draw-a-cuboid/Ring/draw-a-cuboid.ring @@ -0,0 +1,61 @@ +# Project : Draw a cuboid +# Date : 2018/01/18 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : + +load "guilib.ring" + +paint = null + +new qapp + { + win1 = new qwidget() { + setwindowtitle("Draw a cuboid") + setgeometry(100,100,500,600) + label1 = new qlabel(win1) { + setgeometry(10,10,400,400) + settext("") + } + new qpushbutton(win1) { + setgeometry(150,500,100,30) + settext("draw") + setclickevent("draw()") + } + show() + } + exec() + } + +func draw + p1 = new qpicture() + color = new qcolor() { + setrgb(0,0,255,255) + } + pen = new qpen() { + setcolor(color) + setwidth(1) + } + paint = new qpainter() { + begin(p1) + setpen(pen) + + color = new qcolor() + color.setrgb(255,0,0,255) + mybrush = new qbrush() {setstyle(1) setcolor(color)} + setbrush(mybrush) + paint.drawPolygon([[200,200],[300,200],[300,100],[200,100]], 0) + color = new qcolor() + color.setrgb(0,255,0,255) + mybrush = new qbrush() {setstyle(1) setcolor(color)} + setbrush(mybrush) + paint.drawPolygon([[200,100],[250,50],[350,50],[300,100]], 0) + color = new qcolor() + color.setrgb(0, 0, 255,255) + mybrush = new qbrush() {setstyle(1) setcolor(color)} + setbrush(mybrush) + paint.drawPolygon([[350,50],[350,150],[300,200],[300,100]], 0) + + endpaint() + } + label1 { setpicture(p1) show() } + return diff --git a/Task/Draw-a-sphere/MATLAB/draw-a-sphere.m b/Task/Draw-a-sphere/MATLAB/draw-a-sphere.m new file mode 100644 index 0000000000..439bc3c1ad --- /dev/null +++ b/Task/Draw-a-sphere/MATLAB/draw-a-sphere.m @@ -0,0 +1 @@ +figure; sphere diff --git a/Task/Draw-a-sphere/REXX/draw-a-sphere.rexx b/Task/Draw-a-sphere/REXX/draw-a-sphere.rexx index 671d65d0aa..846e277e0f 100644 --- a/Task/Draw-a-sphere/REXX/draw-a-sphere.rexx +++ b/Task/Draw-a-sphere/REXX/draw-a-sphere.rexx @@ -20,7 +20,6 @@ drawSphere: procedure; parse arg r, k, ambient /*get the arguments parse value norm(x y sqrt(rr-xx-yy) ) with v1 v2 v3 dot=s1*v1 + s2*v2 + s3*v3 /*the dot product of the Vs*/ if dot>0 then dot=0 /*if positive, make it zero*/ /*◄■■■■ same as: dot=max(0, dot) */ - if dot>0 then dot=0 /*if positive, make it zero*/ b=-dot**k + ambient /*calculate the brightness.*/ if b<=0 then brite=shadeLen else brite=max( (1-b) * shadeLen, 0) % 1 diff --git a/Task/Draw-a-sphere/Scala/draw-a-sphere.scala b/Task/Draw-a-sphere/Scala/draw-a-sphere.scala new file mode 100644 index 0000000000..90c3410036 --- /dev/null +++ b/Task/Draw-a-sphere/Scala/draw-a-sphere.scala @@ -0,0 +1,34 @@ +object Sphere extends App { + private val (shades, light) = (Seq('.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'), Array(30d, 30d, -50d)) + + private def drawSphere(r: Double, k: Double, ambient: Double): Unit = { + def dot(x: Array[Double], y: Array[Double]) = { + val d = x.head * y.head + x(1) * y(1) + x.last * y.last + if (d < 0) -d else 0D + } + + for (i <- math.floor(-r).toInt to math.ceil(r).toInt; x = i + .5) + println( + (for (j <- math.floor(-2 * r).toInt to math.ceil(2 * r).toInt; y = j / 2.0 + .5) + yield if (x * x + y * y <= r * r) { + + def intensity(vec: Array[Double]) = { + val b = math.pow(dot(light, vec), k) + ambient + if (b <= 0) shades.length - 2 + else math.max((1 - b) * (shades.length - 1), 0).toInt + } + + shades(intensity(normalize(Array(x, y, scala.math.sqrt(r * r - x * x - y * y))))) + } else ' ').mkString) + } + + private def normalize(v: Array[Double]): Array[Double] = { + val len = math.sqrt(v.head * v.head + v(1) * v(1) + v.last * v.last) + v.map(_ / len) + } + + normalize(light).copyToArray(light) + drawSphere(20, 4, .1) + drawSphere(10, 2, .4) + +} diff --git a/Task/Dutch-national-flag-problem/00DESCRIPTION b/Task/Dutch-national-flag-problem/00DESCRIPTION index 13d06b235e..b17cbf119e 100644 --- a/Task/Dutch-national-flag-problem/00DESCRIPTION +++ b/Task/Dutch-national-flag-problem/00DESCRIPTION @@ -1,4 +1,4 @@ -[[File:Dutch_flag_3.jpg|200px||right]] +[[File:Dutch_flag_3.jpg|350px||right]] The Dutch national flag is composed of three coloured bands in the order red then white and lastly blue. The problem posed by [[wp:Edsger Dijkstra|Edsger Dijkstra]] is: :Given a number of red, blue and white balls in random order, arrange them in the order of the colours Dutch national flag. diff --git a/Task/Dutch-national-flag-problem/AWK/dutch-national-flag-problem-1.awk b/Task/Dutch-national-flag-problem/AWK/dutch-national-flag-problem-1.awk new file mode 100644 index 0000000000..e99dbc6eaa --- /dev/null +++ b/Task/Dutch-national-flag-problem/AWK/dutch-national-flag-problem-1.awk @@ -0,0 +1,47 @@ +BEGIN { + weight[1] = "red"; weight[2] = "white"; weight[3] = "blue"; + # ballnr must be >= 3. Using very high numbers here may make your computer + # run out of RAM. (10 millions balls ~= 2.5GiB RAM on x86_64) + ballnr = 10 + + srand() + # Generating a random pool of balls. This python-like loop is actually + # a prettyfied one-liner + do + for (i = 1; i <= ballnr; i++) + do + balls[i] = int(3 * rand() + 1) + # These conditions ensure the 3 first balls contains + # a white, blue and red ball. Removing 'i < 4' would + # hit performance a lot. + while ( (i < 4 && i > 1 && balls[i] == balls[i - 1]) || + (i < 4 && i > 2 && balls[i] == balls[i - 2]) ) + while (is_dnf(balls, ballnr)) + + printf("BEFORE: ") + print_balls(balls, ballnr, weight) + + # Using gawk default quicksort. Using variants of PROCINFO["sorted_in"] + # wasn't faster than a simple call to asort(). + asort(balls) + + printf("\n\nAFTER : ") + print_balls(balls, ballnr, weight) + + sorting = is_dnf(balls, ballnr) ? "valid" : "invalid" + print("\n\nSorting is " sorting ".") +} + +function print_balls(balls, ballnr, weight ,i) { + for (i = 1; i <= ballnr; i++) + printf("%-7s", weight[balls[i]]) +} + +function is_dnf(balls, ballnr) { + # Checking if the balls are sorted in the Dutch national flag order, + # using a simple scan with weight comparison + for (i = 2; i <= ballnr; i++) + if (balls[i - 1] > balls[i]) + return 0 + return 1 +} diff --git a/Task/Dutch-national-flag-problem/AWK/dutch-national-flag-problem-2.awk b/Task/Dutch-national-flag-problem/AWK/dutch-national-flag-problem-2.awk new file mode 100644 index 0000000000..9c47fd2bf4 --- /dev/null +++ b/Task/Dutch-national-flag-problem/AWK/dutch-national-flag-problem-2.awk @@ -0,0 +1,5 @@ +BEFORE: blue red white red white blue red white blue white + +AFTER : red red red white white white white blue blue blue + +Sorting is valid. diff --git a/Task/Dutch-national-flag-problem/Java/dutch-national-flag-problem.java b/Task/Dutch-national-flag-problem/Java/dutch-national-flag-problem.java index 88b88fde61..70f33402a0 100644 --- a/Task/Dutch-national-flag-problem/Java/dutch-national-flag-problem.java +++ b/Task/Dutch-national-flag-problem/Java/dutch-national-flag-problem.java @@ -6,41 +6,25 @@ public class DutchNationalFlag { RED, WHITE, BLUE } - public static void main(String[] args) { + public static void main(String[] args){ DutchColors[] balls = new DutchColors[12]; - DutchColors[] values = DutchColors.values(); Random rand = new Random(); - for (int i = 0; i < balls.length; i++) - balls[i] = values[rand.nextInt(values.length)]; + for (int i = 0; i < balls.length; i++) + balls[i]=values[rand.nextInt(values.length)]; System.out.println("Before: " + Arrays.toString(balls)); - dutchNationalFlagSort(balls); + Arrays.sort(balls); + System.out.println("After: " + Arrays.toString(balls)); - System.out.println("After : " + Arrays.toString(balls)); - } - - private static void dutchNationalFlagSort(DutchColors[] items) { - int lo = 0, mid = 0, hi = items.length - 1; - - while (mid <= hi) - switch (items[mid]) { - case RED: - swap(items, lo++, mid++); - break; - case WHITE: - mid++; - break; - case BLUE: - swap(items, mid, hi--); - break; + boolean sorted = true; + for (int i = 1; i < balls.length; i++ ){ + if (balls[i-1].compareTo(balls[i]) > 0){ + sorted=false; + break; } - } - - private static void swap(DutchColors[] arr, int a, int b) { - DutchColors tmp = arr[a]; - arr[a] = arr[b]; - arr[b] = tmp; + } + System.out.println("Correctly sorted: " + sorted); } } diff --git a/Task/Dutch-national-flag-problem/Ring/dutch-national-flag-problem.ring b/Task/Dutch-national-flag-problem/Ring/dutch-national-flag-problem.ring new file mode 100644 index 0000000000..3adcf56985 --- /dev/null +++ b/Task/Dutch-national-flag-problem/Ring/dutch-national-flag-problem.ring @@ -0,0 +1,25 @@ +# Project : Dutch national flag problem +# Date : 2017/11/23 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +flag = ["Red","White","Blue"] +balls = list(10) + +see "Random: |" +for i = 1 to 10 + color = random(2) + 1 + balls[i] = flag[color] + see balls[i] + " |" +next +see nl + +see "Sorted: |" +for i = 1 to 3 + color = flag[i] + for j = 1 to 10 + if balls[j] = color + see balls[j] + " |" + ok + next +next diff --git a/Task/Dutch-national-flag-problem/Ruby/dutch-national-flag-problem.rb b/Task/Dutch-national-flag-problem/Ruby/dutch-national-flag-problem.rb new file mode 100644 index 0000000000..b406e69557 --- /dev/null +++ b/Task/Dutch-national-flag-problem/Ruby/dutch-national-flag-problem.rb @@ -0,0 +1,25 @@ +class Ball + FLAG = {red: 1, white: 2, blue: 3} + + def initialize + @color = FLAG.keys.sample + end + + def color + @color + end + + def <=>(other) # needed for sort, results in -1 for <, 0 for == and 1 for >. + FLAG[self.color] <=> FLAG[other.color] + end + + def inspect + @color + end +end + +balls = [] +balls = Array.new(8){Ball.new} while balls == balls.sort + +puts "Random: #{balls}" +puts "Sorted: #{balls.sort}" diff --git a/Task/Dynamic-variable-names/C-sharp/dynamic-variable-names.cs b/Task/Dynamic-variable-names/C-sharp/dynamic-variable-names.cs new file mode 100644 index 0000000000..083cf5a3ea --- /dev/null +++ b/Task/Dynamic-variable-names/C-sharp/dynamic-variable-names.cs @@ -0,0 +1,17 @@ +using System; +using System.Dynamic; +using System.Collections.Generic; + +public class Program +{ + public static void Main() + { + string varname = Console.ReadLine(); + //Let's pretend the user has entered "foo" + dynamic expando = new ExpandoObject(); + var map = expando as IDictionary; + map.Add(varname, "Hello world!"); + + Console.WriteLine(expando.foo); + } +} diff --git a/Task/Dynamic-variable-names/Factor/dynamic-variable-names.factor b/Task/Dynamic-variable-names/Factor/dynamic-variable-names.factor new file mode 100644 index 0000000000..6616d60601 --- /dev/null +++ b/Task/Dynamic-variable-names/Factor/dynamic-variable-names.factor @@ -0,0 +1 @@ +42 readln set diff --git a/Task/Dynamic-variable-names/Julia/dynamic-variable-names.julia b/Task/Dynamic-variable-names/Julia/dynamic-variable-names.julia new file mode 100644 index 0000000000..362fc1894b --- /dev/null +++ b/Task/Dynamic-variable-names/Julia/dynamic-variable-names.julia @@ -0,0 +1,15 @@ +print("Insert the variable name: ") + +variable = Symbol(readline(STDIN)) +expression = quote + $variable = 42 + println("Inside quote:") + @show $variable +end + +eval(expression) + +println("Outside quote:") +@show variable +println("If I named the variable x:") +@show x diff --git a/Task/Dynamic-variable-names/Perl-6/dynamic-variable-names.pl6 b/Task/Dynamic-variable-names/Perl-6/dynamic-variable-names.pl6 index c0b38b46b8..64e9a8e24f 100644 --- a/Task/Dynamic-variable-names/Perl-6/dynamic-variable-names.pl6 +++ b/Task/Dynamic-variable-names/Perl-6/dynamic-variable-names.pl6 @@ -2,10 +2,10 @@ our $our-var = 'The our var'; my $my-var = 'The my var'; my $name = prompt 'Variable name: '; -my $value = $::($name); # use the right sigil, etc +my $value = $::('name'); # use the right sigil, etc put qq/Var ($name) starts with value 「$value」/; -$::($name) = 137; +$::('name') = 137; -put qq/Var ($name) ends with value 「{$::($name)}」/; +put qq/Var ($name) ends with value 「{$::('name')}」/; diff --git a/Task/Dynamic-variable-names/UNIX-Shell/dynamic-variable-names.sh b/Task/Dynamic-variable-names/UNIX-Shell/dynamic-variable-names.sh new file mode 100644 index 0000000000..28c37be8d5 --- /dev/null +++ b/Task/Dynamic-variable-names/UNIX-Shell/dynamic-variable-names.sh @@ -0,0 +1,3 @@ +read name +declare $name=42 +echo "${name}=${!name}" diff --git a/Task/Echo-server/Aime/echo-server.aime b/Task/Echo-server/Aime/echo-server.aime index 543faac86e..7f88a87ba8 100644 --- a/Task/Echo-server/Aime/echo-server.aime +++ b/Task/Echo-server/Aime/echo-server.aime @@ -19,7 +19,7 @@ readc(dispatch w, file i, file o, data b) b_rule(b, -1, t, 0, e); f_data(o, b); w_register(w, o); - b_bill(b, t, e, ~t - e); + b_ecopy(b, t, e, ~t - e); } else { b_add(b, t); } @@ -34,7 +34,7 @@ serve(dispatch w, file s) data b; accept(i, o, s, NONBLOCKING_INPUT | NONBLOCKING_OUTPUT); - w_watch(w, i, readc, w, i, o, b); + w.watch(i, readc, w, i, o, b); } integer @@ -44,8 +44,8 @@ main(void) file s; tcpip_listen(s, 12321, 0); - w_watch(w, s, serve, w, s); - w_press(w); + w.watch(s, serve, w, s); + w.press; - return 0; + 0; } diff --git a/Task/Echo-server/Perl-6/echo-server.pl6 b/Task/Echo-server/Perl-6/echo-server-1.pl6 similarity index 77% rename from Task/Echo-server/Perl-6/echo-server.pl6 rename to Task/Echo-server/Perl-6/echo-server-1.pl6 index 90b8ea9acc..9815d96fef 100644 --- a/Task/Echo-server/Perl-6/echo-server.pl6 +++ b/Task/Echo-server/Perl-6/echo-server-1.pl6 @@ -1,7 +1,7 @@ my $socket = IO::Socket::INET.new: - localhost => 'localhost', - localport => 12321, - listen => 1; + :localhost, + :localport<12321>, + :listen; while $socket.accept -> $conn { say "Accepted connection"; diff --git a/Task/Echo-server/Perl-6/echo-server-2.pl6 b/Task/Echo-server/Perl-6/echo-server-2.pl6 new file mode 100644 index 0000000000..afdaf44242 --- /dev/null +++ b/Task/Echo-server/Perl-6/echo-server-2.pl6 @@ -0,0 +1,7 @@ +react { + whenever IO::Socket::Async.listen('0.0.0.0', 12321) -> $conn { + whenever $conn.Supply.lines -> $line { + $conn.print( "$line\n" ) ; + } + } +} diff --git a/Task/Echo-server/Scala/echo-server.scala b/Task/Echo-server/Scala/echo-server.scala new file mode 100644 index 0000000000..761a5bdcb9 --- /dev/null +++ b/Task/Echo-server/Scala/echo-server.scala @@ -0,0 +1,30 @@ +import java.io.PrintWriter +import java.net.{ServerSocket, Socket} + +import scala.io.Source + +object EchoServer extends App { + private val serverSocket = new ServerSocket(23) + private var numConnections = 0 + + class ClientHandler(clientSocket: Socket) extends Runnable { + private val (connectionId, closeCmd) = ({numConnections += 1; numConnections}, ":exit") + + override def run(): Unit = + new PrintWriter(clientSocket.getOutputStream, true) { + println(s"Connection opened, close with entering '$closeCmd'.") + Source.fromInputStream(clientSocket.getInputStream).getLines + .takeWhile(!_.toLowerCase.startsWith(closeCmd)) + .foreach { line => + Console.println(s"Received on #$connectionId: $line") + println(line) // Echo + } + Console.println(s"Gracefully closing connection, #$connectionId") + clientSocket.close() + } + + println(s"Handling connection, $connectionId") + } + + while (true) new Thread(new ClientHandler(serverSocket.accept())).start() +} diff --git a/Task/Echo-server/X86-Assembly/echo-server.x86 b/Task/Echo-server/X86-Assembly/echo-server.x86 new file mode 100644 index 0000000000..c1a19acf98 --- /dev/null +++ b/Task/Echo-server/X86-Assembly/echo-server.x86 @@ -0,0 +1,178 @@ +; x86_64 Linux NASM + +global _start + +%define af_inet 2 +%define sock_stream 1 +%define default_proto 0 +%define sol_sock 1 +%define reuse_addr 2 +%define reuse_port 15 +%define server_port 9001 +%define addr_any 0 +%define family_offset 0 +%define port_offset 2 +%define addr_offset 4 +%define unused_offset 8 +%define addr_len 16 +%define buffer_len 64 +%define max_connections 3 + + +section .text + +; rdi - 16 bit value to be byte swapped +; return - byte swapped value +htn_swap16: + + xor rax, rax + mov rdx, 0x000000ff + + mov rsi, rdi + and rsi, rdx + shl rsi, 8 + or rax, rsi + shl rdx, 8 + + mov rsi, rdi + and rsi, rdx + shr rsi, 8 + or rax, rsi + ret + +; return - server socket +create_server_socket: + + mov rax, 41 + mov rdi, af_inet + mov rsi, sock_stream + mov rdx, default_proto + syscall + push rax + + mov rax, 54 + mov rdi, qword [rsp] + mov rsi, sol_sock + mov rdx, reuse_addr + mov qword [rsp - 16], 1 + lea r10, [rsp - 16] + mov r8, 4 + syscall + + mov rax, 54 + mov rdi, qword [rsp] + mov rsi, sol_sock + mov rdx, reuse_port + mov qword [rsp - 16], 1 + lea r10, [rsp - 16] + mov r8, 4 + syscall + + + pop rax + ret + +; rdi - socket +; rsi - port +; rdx - connections +; return - void +bind_and_listen: + + push rdi + push rdx + + mov rdi, rsi + call htn_swap16 + + lea rsi, [rsp - 16] + mov word [rsi + family_offset], af_inet + mov word [rsi + port_offset], ax + mov dword [rsi + addr_offset], addr_any + mov qword [rsi + unused_offset], 0 + + mov rax, 49 + mov rdi, qword [rsp + 8] + mov rdx, addr_len + syscall + + mov rax, 50 + pop rsi + pop rdi + syscall + ret + +; rdi - server socket +; return - client socket +accept: + + mov rax, 43 + lea rsi, [rsp - 16] + lea rdx, [rsp - 24] + syscall + ret + +; rdi - client socket +; return - void +echo: + + push rdi + mov rax, 0 + lea rsi, [rsp - 104] + mov rdx, buffer_len + syscall + + pop rdi + mov rdx, rax + lea rsi, [rsp - 112] + mov rax, 1 + syscall + ret + + +_start: + + call create_server_socket + mov r14, rax + + mov rdi, rax + mov rsi, server_port + mov rdx, max_connections + call bind_and_listen + +accept_connection: + + mov rdi, r14 + call accept + + mov r15, rax + mov rax, 57 + syscall + + test rax, rax + jz handle_connection + + ; close client socket + mov rax, 3 + mov rdi, r15 + syscall + jmp accept_connection + +handle_connection: + + mov rdi, r15 + call echo + + close_client: + mov rax, 3 + mov rdi, r15 + syscall + + close_server: + mov rax, 3 + mov rdi, r14 + syscall + + exit: + mov rax, 60 + xor rdi, rdi + syscall diff --git a/Task/Element-wise-operations/C-sharp/element-wise-operations.cs b/Task/Element-wise-operations/C-sharp/element-wise-operations.cs new file mode 100644 index 0000000000..2aef21a2dd --- /dev/null +++ b/Task/Element-wise-operations/C-sharp/element-wise-operations.cs @@ -0,0 +1,85 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +public static class ElementWiseOperations +{ + private static readonly Dictionary> operations = + new Dictionary> { + { "add", (a, b) => a + b }, + { "sub", (a, b) => a - b }, + { "mul", (a, b) => a * b }, + { "div", (a, b) => a / b }, + { "pow", (a, b) => Math.Pow(a, b) } + }; + + private static readonly Func nothing = (a, b) => a; + + public static double[,] DoOperation(this double[,] m, string name, double[,] other) => + DoOperation(m, operations.TryGetValue(name, out var operation) ? operation : nothing, other); + + public static double[,] DoOperation(this double[,] m, Func operation, double[,] other) { + if (m == null || other == null) throw new ArgumentNullException(); + int rows = m.GetLength(0), columns = m.GetLength(1); + if (rows != other.GetLength(0) || columns != other.GetLength(1)) { + throw new ArgumentException("Matrices have different dimensions."); + } + + double[,] result = new double[rows, columns]; + for (int r = 0; r < rows; r++) { + for (int c = 0; c < columns; c++) { + result[r, c] = operation(m[r, c], other[r, c]); + } + } + return result; + } + + public static double[,] DoOperation(this double[,] m, string name, double number) => + DoOperation(m, operations.TryGetValue(name, out var operation) ? operation : nothing, number); + + public static double[,] DoOperation(this double[,] m, Func operation, double number) { + if (m == null) throw new ArgumentNullException(); + int rows = m.GetLength(0), columns = m.GetLength(1); + double[,] result = new double[rows, columns]; + for (int r = 0; r < rows; r++) { + for (int c = 0; c < columns; c++) { + result[r, c] = operation(m[r, c], number); + } + } + return result; + } + + public static void Print(this double[,] m) { + if (m == null) throw new ArgumentNullException(); + int rows = m.GetLength(0), columns = m.GetLength(1); + for (int r = 0; r < rows; r++) { + Console.WriteLine("[ " + string.Join(", ", Enumerable.Range(0, columns).Select(c => m[r, c])) + " ]"); + } + } + +} + +public class Program +{ + public static void Main() { + double[,] matrix = { + { 1, 2, 3, 4 }, + { 5, 6, 7, 8 }, + { 9, 10, 11, 12 } + }; + + double[,] tens = { + { 10, 10, 10, 10 }, + { 20, 20, 20, 20 }, + { 30, 30, 30, 30 } + }; + + matrix.Print(); + WriteLine(); + + (matrix = matrix.DoOperation("add", tens)).Print(); + WriteLine(); + + matrix.DoOperation((a, b) => b - a, 100).Print(); + } +} diff --git a/Task/Element-wise-operations/Fortran/element-wise-operations.f b/Task/Element-wise-operations/Fortran/element-wise-operations.f new file mode 100644 index 0000000000..6a99a08f5f --- /dev/null +++ b/Task/Element-wise-operations/Fortran/element-wise-operations.f @@ -0,0 +1,61 @@ +program element_operations + implicit none + + real(kind=4), dimension(3,3) :: a,b + integer :: i + + a=reshape([(i,i=1,9)],shape(a)) + + print*,'addition' + b=a+a + call print_arr(b) + + print*,'multiplication' + b=a*a + call print_arr(b) + + print*,'division' + b=a/b + call print_arr(b) + + print*,'exponentiation' + b=a**a + call print_arr(b) + + print*,'trignometric' + b=cos(a) + call print_arr(b) + + print*,'mod' + b=mod(int(a),3) + call print_arr(b) + + print*,'element selection' + b=0 + where(a>3) b=1 + call print_arr(b) + + print*,'elemental functions can be applied to single values:' + print*,square(3.0) + print*,'or element wise to arrays:' + b=square(a) + call print_arr(b) + + +contains + + elemental real function square(a) + real, intent(in) :: a + square=a*a + end function square + + subroutine print_arr(arr) + real, intent(in) :: arr(:,:) + integer :: i + do i=1,size(arr,dim=2) + print*,arr(:,i) + end do + end subroutine print_arr + + +end program element_operations diff --git a/Task/Element-wise-operations/Kotlin/element-wise-operations.kotlin b/Task/Element-wise-operations/Kotlin/element-wise-operations.kotlin new file mode 100644 index 0000000000..5c62d8c723 --- /dev/null +++ b/Task/Element-wise-operations/Kotlin/element-wise-operations.kotlin @@ -0,0 +1,48 @@ +// version 1.1.51 + +typealias Matrix = Array +typealias Op = Double.(Double) -> Double + +fun Double.dPow(exp: Double) = Math.pow(this, exp) + +fun Matrix.elementwiseOp(other: Matrix, op: Op): Matrix { + require(this.size == other.size && this[0].size == other[0].size) + val result = Array(this.size) { DoubleArray(this[0].size) } + for (i in 0 until this.size) { + for (j in 0 until this[0].size) result[i][j] = this[i][j].op(other[i][j]) + } + return result +} + +fun Matrix.elementwiseOp(d: Double, op: Op): Matrix { + val result = Array(this.size) { DoubleArray(this[0].size) } + for (i in 0 until this.size) { + for (j in 0 until this[0].size) result[i][j] = this[i][j].op(d) + } + return result +} + +fun Matrix.print(name: Char?, scalar: Boolean? = false) { + println(when (scalar) { + true -> "m $name s" + false -> "m $name m" + else -> "m" + } + ":") + for (i in 0 until this.size) println(this[i].asList()) + println() +} + +fun main(args: Array) { + val ops = listOf(Double::plus, Double::minus, Double::times, Double::div, Double::dPow) + val names = "+-*/^" + val m = arrayOf( + doubleArrayOf(3.0, 5.0, 7.0), + doubleArrayOf(1.0, 2.0, 3.0), + doubleArrayOf(2.0, 4.0, 6.0) + ) + m.print(null, null) + for ((i, op) in ops.withIndex()) m.elementwiseOp(m, op).print(names[i]) + val s = 2.0 + println("s = $s:\n") + for ((i, op) in ops.withIndex()) m.elementwiseOp(s, op).print(names[i], true) +} diff --git a/Task/Element-wise-operations/Maple/element-wise-operations.maple b/Task/Element-wise-operations/Maple/element-wise-operations.maple new file mode 100644 index 0000000000..14010c0584 --- /dev/null +++ b/Task/Element-wise-operations/Maple/element-wise-operations.maple @@ -0,0 +1,16 @@ +# Built-in element-wise operator ~ + +#addition +<1,2,3;4,5,6> +~ 2; + +#subtraction +<2,3,1,4;0,-2,-2,1> -~ 4; + +#multiplication +<2,3,1,4;0,-2,-2,1> *~ 4; + +#division +<2,3,7,9;6,8,4,5;7,0,10,11> /~ 2; + +#exponentiation +<1,2,0; 7,2,7; 6,11,3>^~5; diff --git a/Task/Element-wise-operations/Perl-6/element-wise-operations.pl6 b/Task/Element-wise-operations/Perl-6/element-wise-operations.pl6 new file mode 100644 index 0000000000..92e968faa1 --- /dev/null +++ b/Task/Element-wise-operations/Perl-6/element-wise-operations.pl6 @@ -0,0 +1,33 @@ +my @a = + [1,2,3], + [4,5,6], + [7,8,9]; + +sub msay(@x) { + for @x -> @row { + print ' ', $_%1 ?? $_.nude.join('/') !! $_ for @row; + say ''; + } + say ''; +} + +msay @a «+» @a; +msay @a «-» @a; +msay @a «*» @a; +msay @a «/» @a; +msay @a «+» [1,2,3]; +msay @a «-» [1,2,3]; +msay @a «*» [1,2,3]; +msay @a «/» [1,2,3]; +msay @a «+» 2; +msay @a «-» 2; +msay @a «*» 2; +msay @a «/» 2; + +# In addition to calling the underlying higher-order functions directly, it's possible to name a function. + +sub infix: (\l,\r) { l <<+>> r } + +msay @a M+ @a; +msay @a M+ [1,2,3]; +msay @a M+ 2; diff --git a/Task/Element-wise-operations/Sidef/element-wise-operations.sidef b/Task/Element-wise-operations/Sidef/element-wise-operations.sidef new file mode 100644 index 0000000000..fcee4781dc --- /dev/null +++ b/Task/Element-wise-operations/Sidef/element-wise-operations.sidef @@ -0,0 +1,25 @@ +var m1 = [[3,1,4],[1,5,9]] +var m2 = [[2,7,1],[8,2,2]] + +say ":: Matrix-matrix operations" +say (m1 ~W+ m2) +say (m1 ~W- m2) +say (m1 ~W* m2) +say (m1 ~W/ m2) +say (m1 ~W// m2) +say (m1 ~W** m2) +say (m1 ~W% m2) + +say "\n:: Matrix-scalar operations" +say (m1 ~S+ 42) +say (m1 ~S- 42) +say (m1 ~S/ 42) +say (m1 ~S** 10) +# ... + +say "\n:: Scalar-matrix operations" +say (m1 ~RS+ 42) +say (m1 ~RS- 42) +say (m1 ~RS/ 42) +say (m1 ~RS** 10) +# ... diff --git a/Task/Element-wise-operations/Stata/element-wise-operations.stata b/Task/Element-wise-operations/Stata/element-wise-operations.stata new file mode 100644 index 0000000000..c361fa3474 --- /dev/null +++ b/Task/Element-wise-operations/Stata/element-wise-operations.stata @@ -0,0 +1,17 @@ +mata +a = rnormal(5,5,0,1) +b = 2 +a:+b +a:-b +a:*b +a:/b +a:^b + +a = rnormal(5,5,0,1) +b = rnormal(5,1,0,1) +a:+b +a:-b +a:*b +a:/b +a:^b +end diff --git a/Task/Empty-directory/Factor/empty-directory.factor b/Task/Empty-directory/Factor/empty-directory.factor new file mode 100644 index 0000000000..31d2ff7e66 --- /dev/null +++ b/Task/Empty-directory/Factor/empty-directory.factor @@ -0,0 +1,2 @@ +USE: io.directories +: empty-directory? ( path -- ? ) directory-entries empty? ; diff --git a/Task/Empty-directory/Rust/empty-directory.rust b/Task/Empty-directory/Rust/empty-directory.rust new file mode 100644 index 0000000000..08f39ee637 --- /dev/null +++ b/Task/Empty-directory/Rust/empty-directory.rust @@ -0,0 +1,20 @@ +use std::fs::read_dir; +use std::error::Error; + +fn main() { + for path in std::env::args().skip(1) { // iterate over the arguments, skipping the first (which is the executable) + match read_dir(path.as_str()) { // try to read the directory specified + Ok(contents) => { + let len = contents.collect::>().len(); // calculate the amount of items in the directory + if len == 0 { + println!("{} is empty", path); + } else { + println!("{} is not empty", path); + } + }, + Err(e) => { // If the attempt failed, print the corresponding error msg + println!("Failed to read directory \"{}\": {}", path, e.description()); + } + } + } +} diff --git a/Task/Empty-directory/VBA/empty-directory.vba b/Task/Empty-directory/VBA/empty-directory.vba new file mode 100644 index 0000000000..5bb6a39c89 --- /dev/null +++ b/Task/Empty-directory/VBA/empty-directory.vba @@ -0,0 +1,11 @@ +Sub Main() + Debug.Print IsEmptyDirectory("C:\Temp") + Debug.Print IsEmptyDirectory("C:\Temp\") +End Sub + +Private Function IsEmptyDirectory(D As String) As Boolean +Dim Sep As String + Sep = Application.PathSeparator + D = IIf(Right(D, 1) <> Sep, D & Sep, D) + IsEmptyDirectory = (Dir(D & "*.*") = "") +End Function diff --git a/Task/Empty-program/ALGOL-W/empty-program.alg b/Task/Empty-program/ALGOL-W/empty-program.alg index e27f1f2ec2..1ff688ebec 100644 --- a/Task/Empty-program/ALGOL-W/empty-program.alg +++ b/Task/Empty-program/ALGOL-W/empty-program.alg @@ -1 +1,2 @@ -begin end. +. +comment using the ; diff --git a/Task/Empty-program/N-t-roff/empty-program-1.n b/Task/Empty-program/N-t-roff/empty-program-1.n new file mode 100644 index 0000000000..e69de29bb2 diff --git a/Task/Empty-program/N-t-roff/empty-program-2.n b/Task/Empty-program/N-t-roff/empty-program-2.n new file mode 100644 index 0000000000..ff34b544fa --- /dev/null +++ b/Task/Empty-program/N-t-roff/empty-program-2.n @@ -0,0 +1 @@ +.mso me.tmac diff --git a/Task/Empty-program/Stata/empty-program-2.stata b/Task/Empty-program/Stata/empty-program-2.stata index 4a59335a47..decf1a2831 100644 --- a/Task/Empty-program/Stata/empty-program-2.stata +++ b/Task/Empty-program/Stata/empty-program-2.stata @@ -1,2 +1 @@ -function nop() { -} +function nop() {} diff --git a/Task/Empty-program/VBA/empty-program.vba b/Task/Empty-program/VBA/empty-program.vba new file mode 100644 index 0000000000..a1b1c1e8e3 --- /dev/null +++ b/Task/Empty-program/VBA/empty-program.vba @@ -0,0 +1,2 @@ +Sub Demo() +End Sub diff --git a/Task/Empty-string/Factor/empty-string-1.factor b/Task/Empty-string/Factor/empty-string-1.factor new file mode 100644 index 0000000000..076145c11b --- /dev/null +++ b/Task/Empty-string/Factor/empty-string-1.factor @@ -0,0 +1 @@ +"" empty? . diff --git a/Task/Empty-string/Factor/empty-string-2.factor b/Task/Empty-string/Factor/empty-string-2.factor new file mode 100644 index 0000000000..c19763c207 --- /dev/null +++ b/Task/Empty-string/Factor/empty-string-2.factor @@ -0,0 +1,6 @@ +USE: locals +[let + "" :> empty-string + empty-string empty? . + empty-string empty? not . +] diff --git a/Task/Empty-string/HolyC/empty-string.holyc b/Task/Empty-string/HolyC/empty-string.holyc new file mode 100644 index 0000000000..491a68502e --- /dev/null +++ b/Task/Empty-string/HolyC/empty-string.holyc @@ -0,0 +1,12 @@ +/* assign an empty string */ +U8 *str = StrNew(""); +/* or */ +U8 *str = ""; + +/* to test if string is empty */ +if (StrLen(str) == 0) { ... } +/* or compare to a known empty string. "== 0" means strings are equal */ +if (StrCmp(str, "") == 0) { ... } + +/* to test if string is not empty */ +if (StrLen(str)) { ... } diff --git a/Task/Empty-string/Red/empty-string.red b/Task/Empty-string/Red/empty-string.red new file mode 100644 index 0000000000..9e04bfddd5 --- /dev/null +++ b/Task/Empty-string/Red/empty-string.red @@ -0,0 +1,6 @@ +Red [] +s: copy "" ;; assign empty string +?? s +if empty? s [print "string is empty "] ;; check if string is empty +s: "abc" +prin s unless empty? s [print " not empty"] diff --git a/Task/Enforced-immutability/Factor/enforced-immutability.factor b/Task/Enforced-immutability/Factor/enforced-immutability.factor new file mode 100644 index 0000000000..944126e7c9 --- /dev/null +++ b/Task/Enforced-immutability/Factor/enforced-immutability.factor @@ -0,0 +1,2 @@ +TUPLE: range + { from read-only } { length read-only } { step read-only } ; diff --git a/Task/Enforced-immutability/Julia/enforced-immutability.julia b/Task/Enforced-immutability/Julia/enforced-immutability.julia new file mode 100644 index 0000000000..aa1b4a84da --- /dev/null +++ b/Task/Enforced-immutability/Julia/enforced-immutability.julia @@ -0,0 +1,2 @@ +const x = 1 +x = π # ERROR: invalid ridefinition of constant x diff --git a/Task/Enforced-immutability/Ring/enforced-immutability.ring b/Task/Enforced-immutability/Ring/enforced-immutability.ring new file mode 100644 index 0000000000..85ef635ecb --- /dev/null +++ b/Task/Enforced-immutability/Ring/enforced-immutability.ring @@ -0,0 +1,8 @@ +# Project : Enforced immutability +# Date : 2017/11/29 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +x = 10 +assert( x = 10) +assert( x = 100 ) diff --git a/Task/Enforced-immutability/UNIX-Shell/enforced-immutability.sh b/Task/Enforced-immutability/UNIX-Shell/enforced-immutability-1.sh similarity index 100% rename from Task/Enforced-immutability/UNIX-Shell/enforced-immutability.sh rename to Task/Enforced-immutability/UNIX-Shell/enforced-immutability-1.sh diff --git a/Task/Enforced-immutability/UNIX-Shell/enforced-immutability-2.sh b/Task/Enforced-immutability/UNIX-Shell/enforced-immutability-2.sh new file mode 100644 index 0000000000..dabe5e390e --- /dev/null +++ b/Task/Enforced-immutability/UNIX-Shell/enforced-immutability-2.sh @@ -0,0 +1 @@ +set -r PIE = APPLE diff --git a/Task/Entropy/ALGOL-68/entropy.alg b/Task/Entropy/ALGOL-68/entropy.alg index 15cacf08d4..3b404fcf1e 100644 --- a/Task/Entropy/ALGOL-68/entropy.alg +++ b/Task/Entropy/ALGOL-68/entropy.alg @@ -1,27 +1,19 @@ -# calculate the shannon entropy of a string # - -PROC shannon entropy = ( STRING s )REAL: +BEGIN + # calculate the shannon entropy of a string # + PROC shannon entropy = ( STRING s )REAL: BEGIN - INT string length = ( UPB s - LWB s ) + 1; - - # count the occurances of each character # - + # count the occurences of each character # [ 0 : max abs char ]INT char count; - FOR char pos FROM LWB char count TO UPB char count DO char count[ char pos ] := 0 OD; - FOR char pos FROM LWB s TO UPB s DO char count[ ABS s[ char pos ] ] +:= 1 OD; - # calculate the entropy, we use log base 10 and then convert # # to log base 2 after calculating the sum # - REAL entropy := 0; - FOR char pos FROM LWB char count TO UPB char count DO IF char count[ char pos ] /= 0 THEN @@ -30,14 +22,10 @@ PROC shannon entropy = ( STRING s )REAL: entropy -:= probability * log( probability ) FI OD; - entropy / log( 2 ) END; # shannon entropy # - - -main: -( # test the shannon entropy routine # print( ( shannon entropy( "1223334444" ), newline ) ) -) + +END diff --git a/Task/Entropy/Aime/entropy.aime b/Task/Entropy/Aime/entropy.aime index 99a9af7144..e107f15c44 100644 --- a/Task/Entropy/Aime/entropy.aime +++ b/Task/Entropy/Aime/entropy.aime @@ -1,25 +1,16 @@ -integer i, l; -record r; -real h, x; -text s; +integer c; +real h, v; +index x; +data s; -s = argv(1); -l = length(s); - -i = l; -while (i) { - i -= 1; - rn_a_integer(r, cut(s, i, 1), 1); +for (, c in (s = argv(1))) { + x[c] += 1r; } h = 0; -if (r_first(r, s)) { - do { - x = r_q_integer(r, s); - x /= l; - h -= x * log2(x); - } while (r_greater(r, s, s)); +for (, v in x) { + v /= ~s; + h -= v * log2(v); } -o_real(6, h); -o_newline(); +o_form("/d6/\n", h); diff --git a/Task/Entropy/BASIC/entropy-1.basic b/Task/Entropy/BASIC/entropy-1.basic new file mode 100644 index 0000000000..58d100dc7b --- /dev/null +++ b/Task/Entropy/BASIC/entropy-1.basic @@ -0,0 +1,23 @@ +10 DEF FN L(X)=LOG(X)/LOG(2) +20 S$="1223334444" +30 U$="" +40 FOR I=1 TO LEN(S$) +50 K=0 +60 FOR J=1 TO LEN(U$) +70 IF MID$(U$,J,1)=MID$(S$,I,1) THEN K=1 +80 NEXT J +90 IF K=0 THEN U$=U$+MID$(S$,I,1) +100 NEXT I +110 DIM R(LEN(U$)-1) +120 FOR I=1 TO LEN(U$) +130 C=0 +140 FOR J=1 TO LEN(S$) +150 IF MID$(U$,I,1)=MID$(S$,J,1) THEN C=C+1 +160 NEXT J +170 R(I-1)=(C/LEN(S$))*FN L(C/LEN(S$)) +180 NEXT I +190 E=0 +200 FOR I=0 TO LEN(U$)-1 +210 E=E-R(I) +220 NEXT I +230 PRINT E diff --git a/Task/Entropy/BASIC/entropy-2.basic b/Task/Entropy/BASIC/entropy-2.basic new file mode 100644 index 0000000000..bbe65e6a85 --- /dev/null +++ b/Task/Entropy/BASIC/entropy-2.basic @@ -0,0 +1,22 @@ + 10 LET X$="1223334444" + 20 LET U$="" + 30 FOR I=1 TO LEN X$ + 40 LET K=0 + 50 FOR J=1 TO LEN U$ + 60 IF U$(J)=X$(I) THEN LET K=K+1 + 70 NEXT J + 80 IF K=0 THEN LET U$=U$+X$(I) + 90 NEXT I +100 DIM R(LEN U$) +110 FOR I=1 TO LEN U$ +120 LET C=0 +130 FOR J=1 TO LEN X$ +140 IF U$(I)=X$(J) THEN LET C=C+1 +150 NEXT J +160 LET R(I)=C/LEN X$*LN (C/LEN X$)/LN 2 +170 NEXT I +180 LET E=0 +190 FOR I=1 TO LEN U$ +200 LET E=E-R(I) +210 NEXT I +220 PRINT E diff --git a/Task/Entropy/BBC-BASIC/entropy.bbc b/Task/Entropy/BBC-BASIC/entropy.bbc new file mode 100644 index 0000000000..a5a82823a3 --- /dev/null +++ b/Task/Entropy/BBC-BASIC/entropy.bbc @@ -0,0 +1,24 @@ +REM >entropy +PRINT FNentropy("1223334444") +END +: +DEF FNentropy(x$) +LOCAL unique$, count%, n%, ratio(), u%, i%, j% +unique$ = "" +n% = LEN x$ +FOR i% = 1 TO n% + IF INSTR(unique$, MID$(x$, i%, 1)) = 0 THEN unique$ += MID$(x$, i%, 1) +NEXT +u% = LEN unique$ +DIM ratio(u% - 1) +FOR i% = 1 TO u% + count% = 0 + FOR j% = 1 TO n% + IF MID$(unique$, i%, 1) = MID$(x$, j%, 1) THEN count% += 1 + NEXT + ratio(i% - 1) = (count% / n%) * FNlogtwo(count% / n%) +NEXT += -SUM(ratio()) +: +DEF FNlogtwo(n) += LN n / LN 2 diff --git a/Task/Entropy/C++/entropy.cpp b/Task/Entropy/C++/entropy.cpp index aca6a29f13..bff5cceb94 100644 --- a/Task/Entropy/C++/entropy.cpp +++ b/Task/Entropy/C++/entropy.cpp @@ -17,10 +17,10 @@ int main( int argc , char *argv[ ] ) { double infocontent = 0 ; for ( std::pair p : frequencies ) { double freq = static_cast( p.second ) / numlen ; - infocontent += freq * log2( freq ) ; + infocontent -= freq * log2( freq ) ; } - infocontent *= -1 ; + std::cout << "The information content of " << teststring - << " is " << infocontent << " !\n" ; + << " is " << infocontent << std::endl ; return 0 ; } diff --git a/Task/Entropy/Common-Lisp/entropy.lisp b/Task/Entropy/Common-Lisp/entropy-1.lisp similarity index 59% rename from Task/Entropy/Common-Lisp/entropy.lisp rename to Task/Entropy/Common-Lisp/entropy-1.lisp index 8107f2e8a2..56bab18072 100644 --- a/Task/Entropy/Common-Lisp/entropy.lisp +++ b/Task/Entropy/Common-Lisp/entropy-1.lisp @@ -3,6 +3,8 @@ (entropy 0)) (mapc (lambda (c) (setf (gethash c table) (+ (gethash c table 0) 1))) (coerce string 'list)) - (maphash (lambda (k v) (decf entropy (* (/ v (length input-string)) (log (/ v (length input-string)) 2)))) + (maphash (lambda (k v) + (decf entropy (* (/ v (length input-string)) + (log (/ v (length input-string)) 2)))) table) entropy)) diff --git a/Task/Entropy/Common-Lisp/entropy-2.lisp b/Task/Entropy/Common-Lisp/entropy-2.lisp new file mode 100644 index 0000000000..e8dfb72d92 --- /dev/null +++ b/Task/Entropy/Common-Lisp/entropy-2.lisp @@ -0,0 +1,8 @@ +(defun entropy (string &aux (length (length string))) + (declare (type string string)) + (let ((table (make-hash-table))) + (loop for char across string + do (incf (gethash char table 0))) + (- (loop for freq being each hash-value in table + for freq/length = (/ freq length) + sum (* freq/length (log freq/length 2)))))) diff --git a/Task/Entropy/Factor/entropy.factor b/Task/Entropy/Factor/entropy.factor new file mode 100644 index 0000000000..8e471dcb6a --- /dev/null +++ b/Task/Entropy/Factor/entropy.factor @@ -0,0 +1,11 @@ +USING: assocs kernel math math.functions math.statistics +prettyprint sequences ; +IN: rosetta-code.entropy + +: shannon-entropy ( str -- entropy ) + [ length ] [ histogram >alist [ second ] map ] bi + [ swap / ] with map + [ dup log 2 log / * ] map-sum neg ; + +"1223334444" shannon-entropy . +"Factor is my favorite programming language." shannon-entropy . diff --git a/Task/Entropy/Julia/entropy.julia b/Task/Entropy/Julia/entropy.julia index 24fbd05391..8d76e01ecb 100644 --- a/Task/Entropy/Julia/entropy.julia +++ b/Task/Entropy/Julia/entropy.julia @@ -1 +1,3 @@ -entropy(s)=-sum(x->x*log(2,x), [count(x->x==c,s)/length(s) for c in unique(s)]) +entropy(s) = -sum(x -> x * log(2, x), count(x -> x == c, s) / length(s) for c in unique(s)) +@show entropy("1223334444") +@show entropy([1, 2, 3, 1, 2, 1, 2, 3, 1, 2, 3, 4, 5] diff --git a/Task/Entropy/Objeck/entropy.objeck b/Task/Entropy/Objeck/entropy.objeck new file mode 100644 index 0000000000..83a57c4337 --- /dev/null +++ b/Task/Entropy/Objeck/entropy.objeck @@ -0,0 +1,48 @@ +use Collection; + +class Entropy { + function : native : GetShannonEntropy(result : String) ~ Float { + frequencies := IntMap->New(); + + each(i : result) { + c := result->Get(i); + + if(frequencies->Has(c)) { + count := frequencies->Find(c)->As(IntHolder); + count->Set(count->Get() + 1); + } + else { + frequencies->Insert(c, IntHolder->New(1)); + }; + }; + + length := result->Size(); + entropy := 0.0; + + counts := frequencies->GetValues(); + each(i : counts) { + count := counts->Get(i)->As(IntHolder)->Get(); + freq := count->As(Float) / length; + entropy += freq * (freq->Log() / 2.0->Log()); + }; + + return -1 * entropy; + } + + function : Main(args : String[]) ~ Nil { + inputs := [ + "1223334444", + "1223334444555555555", + "122333", + "1227774444", + "aaBBcccDDDD", + "1234567890abcdefghijklmnopqrstuvwxyz", + "Rosetta Code"]; + + each(i : inputs) { + input := inputs[i]; + "Shannon entropy of '{$input}': "->Print(); + GetShannonEntropy(inputs[i])->PrintLine(); + }; + } +} diff --git a/Task/Enumerations/Factor/enumerations-1.factor b/Task/Enumerations/Factor/enumerations-1.factor new file mode 100644 index 0000000000..b4f176a06b --- /dev/null +++ b/Task/Enumerations/Factor/enumerations-1.factor @@ -0,0 +1,9 @@ +IN: scratchpad { "sun" "mon" "tue" "wed" "thur" "fri" "sat" } + +--- Data stack: +T{ enum f ~array~ } +IN: scratchpad [ 1 swap at ] [ keys ] bi + +--- Data stack: +"mon" +{ 0 1 2 3 4 5 6 } diff --git a/Task/Enumerations/Factor/enumerations-2.factor b/Task/Enumerations/Factor/enumerations-2.factor new file mode 100644 index 0000000000..598d9c19cd --- /dev/null +++ b/Task/Enumerations/Factor/enumerations-2.factor @@ -0,0 +1,11 @@ +IN: scratchpad USE: alien.syntax +IN: scratchpad ENUM: day sun mon { tue 42 } wed thur fri sat ; +IN: scratchpad 1 + +--- Data stack: +mon +IN: scratchpad 42 + +--- Data stack: +mon +tue diff --git a/Task/Enumerations/Shen/enumerations.shen b/Task/Enumerations/Shen/enumerations.shen new file mode 100644 index 0000000000..41034b49ab --- /dev/null +++ b/Task/Enumerations/Shen/enumerations.shen @@ -0,0 +1,7 @@ +(tc +) + +(datatype fruit + + if (element? Fruit [apple banana cherry]) + _____________ + Fruit : fruit;) diff --git a/Task/Environment-variables/Julia/environment-variables.julia b/Task/Environment-variables/Julia/environment-variables.julia index 0c912e901f..94b52a0f7b 100644 --- a/Task/Environment-variables/Julia/environment-variables.julia +++ b/Task/Environment-variables/Julia/environment-variables.julia @@ -1 +1,3 @@ -ENV["HOME"] +@show ENV["PATH"] +@show ENV["HOME"] +@show ENV["USER"] diff --git a/Task/Environment-variables/Stata/environment-variables.stata b/Task/Environment-variables/Stata/environment-variables.stata index 6b40d34e17..0526f9efb9 100644 --- a/Task/Environment-variables/Stata/environment-variables.stata +++ b/Task/Environment-variables/Stata/environment-variables.stata @@ -1,3 +1,3 @@ -display "`: env PATH'" -display "`: env USERNAME'" -display "`: env USERPROFILE'" +display "`:env PATH'" +display "`:env USERNAME'" +display "`:env USERPROFILE'" diff --git a/Task/Equilibrium-index/ABAP/equilibrium-index.abap b/Task/Equilibrium-index/ABAP/equilibrium-index.abap new file mode 100644 index 0000000000..2042644e0f --- /dev/null +++ b/Task/Equilibrium-index/ABAP/equilibrium-index.abap @@ -0,0 +1,14 @@ +REPORT equilibrium_index. + +TYPES: y_i TYPE STANDARD TABLE OF i WITH EMPTY KEY. + +cl_demo_output=>display( REDUCE y_i( LET sequences = VALUE y_i( ( -7 ) ( 1 ) ( 5 ) ( 2 ) ( -4 ) ( 3 ) ( 0 ) ) + total_sum = REDUCE #( INIT sum = 0 + FOR sequence IN sequences + NEXT sum = sum + ( sequence ) ) IN + INIT x = VALUE y_i( ) + y = 0 + FOR i = 1 UNTIL i > lines( sequences ) + LET z = sequences[ i ] IN + NEXT x = COND #( WHEN y = ( total_sum - y - z ) THEN VALUE y_i( BASE x ( i - 1 ) ) ELSE x ) + y = y + z ) ). diff --git a/Task/Equilibrium-index/Aime/equilibrium-index.aime b/Task/Equilibrium-index/Aime/equilibrium-index.aime new file mode 100644 index 0000000000..4ffac2e914 --- /dev/null +++ b/Task/Equilibrium-index/Aime/equilibrium-index.aime @@ -0,0 +1,25 @@ +list +eqindex(list l) +{ + integer e, i, s, sum; + list x; + + s = sum = 0; + l.ucall(add_i, 1, sum); + for (i, e in l) { + if (s * 2 + e == sum) { + x.append(i); + } + s += e; + } + + x; +} + +integer +main(void) +{ + list(-7, 1, 5, 2, -4, 3, 0).eqindex.ucall(o_, 0, "\n"); + + 0; +} diff --git a/Task/Equilibrium-index/Elena/equilibrium-index.elena b/Task/Equilibrium-index/Elena/equilibrium-index.elena new file mode 100644 index 0000000000..3f7c5bf6b6 --- /dev/null +++ b/Task/Equilibrium-index/Elena/equilibrium-index.elena @@ -0,0 +1,66 @@ +import extensions. +import system'routines. +import system'collections. +import extensions'routines. + +class EquilibriumEnumerator :: Enumerator +{ + int left. + int right. + int index. + enumerator en. + + multi constructor new : object + <= new enumerator:object. + + constructor new(Enumerator en) + [ + @en := en. + + $self reset. + ] + + constructor new(BaseEnumerable list) + <= new(list enumerator). + + bool next + [ + index += 1. + + while(en next) + [ + var element := en get. + right -= element. + bool found := (left == right). + left += element. + + if (found) + [ + ^ true + ]. + + index += 1. + ]. + + ^ false + ] + + reset + [ + en reset. + + left := 0. + right := en summarize. + index := -1. + + en reset. + ] + + get = index. +} + +program = +[ + EquilibriumEnumerator new:(-7, 1, 5, 2, -4, 3, 0); + forEach:printingLn. +]. diff --git a/Task/Equilibrium-index/JavaScript/equilibrium-index-2.js b/Task/Equilibrium-index/JavaScript/equilibrium-index-2.js index 617450f7f1..8c60265a6c 100644 --- a/Task/Equilibrium-index/JavaScript/equilibrium-index-2.js +++ b/Task/Equilibrium-index/JavaScript/equilibrium-index-2.js @@ -1,93 +1 @@ -(() => { - // EQUILIBRIUM INDICES ---------------------------------------------------- - - // equilibriumIndices :: [Int] -> [Int] - const equilibriumIndices = xs => - foldr((a, [x, y], i) => - x === y ? cons(i, a) : a, - [], - zip( - scanl1(plus, xs), // Sums from the left - scanr1(plus, xs) // Sums from the right - ) - ); - - // GENERIC FUNCTIONS ------------------------------------------------------ - - // cons :: a -> [a] -> [a] - const cons = (x, xs) => [x].concat(xs); - - // foldr (a -> b -> a) -> a -> [b] -> a - const foldr = (f, a, xs) => xs.reduceRight(f, a); - - // map :: (a -> b) -> [a] -> [b] - const map = (f, xs) => xs.map(f); - - // plus :: Num a => a -> a -> a - const plus = (a, b) => a + b; - - // scanl :: (b -> a -> b) -> b -> [a] -> [b] - const scanl = (f, startValue, xs) => - xs.reduce((a, x) => { - const v = f(a.acc, x); - return { - acc: v, - scan: a.scan.concat(v) - }; - }, { - acc: startValue, - scan: [startValue] - }) - .scan; - - // scanl1 :: (a -> a -> a) -> [a] -> [a] - const scanl1 = (f, xs) => - xs.length > 0 ? scanl(f, xs[0], xs.slice(1)) : []; - - // scanr :: (b -> a -> b) -> b -> [a] -> [b] - const scanr = (f, startValue, xs) => - xs.reduceRight((a, x) => { - const v = f(a.acc, x); - return { - acc: v, - scan: [v].concat(a.scan) - }; - }, { - acc: startValue, - scan: [startValue] - }) - .scan; - - // scanr1 :: (a -> a -> a) -> [a] -> [a] - const scanr1 = (f, xs) => - xs.length > 0 ? scanr(f, xs.slice(-1)[0], xs.slice(0, -1)) : []; - - // Any value -> optional number of indents -> String - // show :: a -> String - // show :: a -> Int -> String - const show = (...x) => - JSON.stringify.apply( - null, x.length > 1 ? [x[0], null, x[1]] : x - ); - - // tail :: [a] -> [a] - const tail = xs => xs.length ? xs.slice(1) : undefined; - - // zip :: [a] -> [b] -> [(a,b)] - const zip = (xs, ys) => - xs.slice(0, Math.min(xs.length, ys.length)) - .map((x, i) => [x, ys[i]]); - - // TEST ------------------------------------------------------------------- - return show( - map(equilibriumIndices, [ - [-7, 1, 5, 2, -4, 3, 0], - [2, 4, 6], - [2, 9, 2], - [1, -1, 1, -1, 1, -1, 1], - [1], - [] - ]) - ); - // -> [[3, 6], [], [1], [0, 1, 2, 3, 4, 5, 6], [0], []] -})(); +[[3,6],[],[1],[0,1,2,3,4,5,6],[0],[]] diff --git a/Task/Equilibrium-index/JavaScript/equilibrium-index-3.js b/Task/Equilibrium-index/JavaScript/equilibrium-index-3.js index 8c60265a6c..9faa515ff6 100644 --- a/Task/Equilibrium-index/JavaScript/equilibrium-index-3.js +++ b/Task/Equilibrium-index/JavaScript/equilibrium-index-3.js @@ -1 +1,16 @@ -[[3,6],[],[1],[0,1,2,3,4,5,6],[0],[]] +function equilibrium(arr) { + let sum = arr.reduce((a, b) => a + b); + let leftSum = 0; + + for (let i = 0; i < arr.length; ++i) { + sum -= arr[i]; + + if (leftSum === sum) { + return i; + } + + leftSum += arr[i]; + } + + return -1; +} diff --git a/Task/Equilibrium-index/JavaScript/equilibrium-index-4.js b/Task/Equilibrium-index/JavaScript/equilibrium-index-4.js new file mode 100644 index 0000000000..aabe38bbef --- /dev/null +++ b/Task/Equilibrium-index/JavaScript/equilibrium-index-4.js @@ -0,0 +1 @@ +3, -1, 1, 0, 0 diff --git a/Task/Equilibrium-index/Julia/equilibrium-index.julia b/Task/Equilibrium-index/Julia/equilibrium-index.julia index be510dc429..aeb11cadc0 100644 --- a/Task/Equilibrium-index/Julia/equilibrium-index.julia +++ b/Task/Equilibrium-index/Julia/equilibrium-index.julia @@ -1,7 +1,5 @@ -# v0.6.0 - function equindex2pass(data::Array) - rst = Array{Int}([]) + rst = Vector{Int}(0) suml, sumr, ddelayed = 0, sum(data), 0 for (i, d) in enumerate(data) suml += ddelayed @@ -11,7 +9,7 @@ function equindex2pass(data::Array) push!(rst, i) end end - return length(rst) > 0 ? rst : nothing + return rst end @show equindex2pass([1, -1, 1, -1, 1, -1, 1]) diff --git a/Task/Equilibrium-index/Objeck/equilibrium-index.objeck b/Task/Equilibrium-index/Objeck/equilibrium-index.objeck new file mode 100644 index 0000000000..f3564f050e --- /dev/null +++ b/Task/Equilibrium-index/Objeck/equilibrium-index.objeck @@ -0,0 +1,24 @@ +class Rosetta { + function : Main(args : String[]) ~ Nil { + sequence := [-7, 1, 5, 2, -4, 3, 0]; + EqulibriumIndices(sequence); + } + + function : EqulibriumIndices(sequence : Int[]) ~ Nil { + # find total sum + totalSum := 0; + each(i : sequence) { + totalSum += sequence[i]; + }; + + # compare running sum to remaining sum to find equlibrium indices + runningSum := 0; + each(i : sequence) { + n := sequence[i]; + if (totalSum - runningSum - n = runningSum) { + i->PrintLine(); + }; + runningSum += n; + }; + } +} diff --git a/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-10.basic b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-10.basic new file mode 100644 index 0000000000..2e096710f7 --- /dev/null +++ b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-10.basic @@ -0,0 +1,29 @@ +!RosettaCode: Ethiopian Multiplication +! True BASIC v6.007 +PROGRAM EthiopianMultiplication + DECLARE DEF FNdouble + DECLARE DEF FNhalve + DECLARE DEF FNeven + + LET x = 17 + LET y = 34 + + DO + IF FNeven(x) = 0 THEN + LET p = p + y + PRINT x,y + ELSE + PRINT x," ---" + END IF + + LET x = FNhalve(x) + LET y = FNdouble(y) + LOOP UNTIL x = 0 + PRINT " ", " ===" + PRINT " ", p + GET KEY done + + DEF FNdouble(A) = A * 2 + DEF FNhalve(A) = INT(A / 2) + DEF FNeven(A) = MOD(A+1,2) +END diff --git a/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-6.basic b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-6.basic index d7e6262e40..81238b337d 100644 --- a/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-6.basic +++ b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-6.basic @@ -1,33 +1,18 @@ -Procedure isEven(x) - ProcedureReturn (x & 1) ! 1 -EndProcedure - -Procedure halveValue(x) - ProcedureReturn x / 2 -EndProcedure - -Procedure doubleValue(x) - ProcedureReturn x << 1 -EndProcedure - -Procedure EthiopianMultiply(x, y) - Protected sum - Print("Ethiopian multiplication of " + Str(x) + " and " + Str(y) + " ... ") - Repeat - If Not isEven(x) - sum + y - EndIf - x = halveValue(x) - y = doubleValue(y) - Until x < 1 - PrintN(" equals " + Str(sum)) - ProcedureReturn sum -EndProcedure - -If OpenConsole() - EthiopianMultiply(17,34) - - Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") - Input() - CloseConsole() -EndIf +x = 17 +y = 34 +tot = 0 +While x >= 1 + TextWindow.Write(x) + TextWindow.CursorLeft = 10 + If Math.Remainder(x + 1, 2) = 0 Then + tot = tot + y + TextWindow.WriteLine(y) + Else + TextWindow.WriteLine("") + EndIf + x = Math.Floor(x / 2) + y = 2 * y +EndWhile +TextWindow.Write("=") +TextWindow.CursorLeft = 10 +TextWindow.WriteLine(tot) diff --git a/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-7.basic b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-7.basic index 91695fb6bf..d7e6262e40 100644 --- a/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-7.basic +++ b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-7.basic @@ -11,26 +11,21 @@ Procedure doubleValue(x) EndProcedure Procedure EthiopianMultiply(x, y) - Protected sum, sign = x - - Print("Ethiopian multiplication of " + Str(x) + " and " + Str(y) + " ...") + Protected sum + Print("Ethiopian multiplication of " + Str(x) + " and " + Str(y) + " ... ") Repeat If Not isEven(x) sum + y EndIf x = halveValue(x) y = doubleValue(y) - Until x = 0 - If sign < 0 : sum * -1: EndIf - + Until x < 1 PrintN(" equals " + Str(sum)) ProcedureReturn sum EndProcedure If OpenConsole() EthiopianMultiply(17,34) - EthiopianMultiply(-17,34) - EthiopianMultiply(-17,-34) Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") Input() diff --git a/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-8.basic b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-8.basic index 65f15f18a3..91695fb6bf 100644 --- a/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-8.basic +++ b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-8.basic @@ -1,38 +1,38 @@ - 10 LET HALVE=320 - 20 LET DOUBLE=340 - 30 LET EVEN=360 - 40 DIM L(20) - 50 DIM R(20) - 60 INPUT L(1) - 70 INPUT R(1) - 80 LET I=1 - 90 PRINT L(1),R(1) -100 IF L(I)=1 THEN GOTO 200 -110 LET I=I+1 -120 IF I>20 THEN STOP -130 LET X=L(I-1) -140 GOSUB HALVE -150 LET L(I)=Y -160 LET X=R(I-1) -170 GOSUB DOUBLE -180 LET R(I)=Y -190 GOTO 90 -200 FOR K=1 TO I -210 LET X=L(K) -220 GOSUB EVEN -230 IF NOT Y THEN GOTO 260 -240 LET R(K)=0 -250 PRINT AT K-1,16;" " -260 NEXT K -270 LET A=0 -280 FOR K=1 TO I -290 LET A=A+R(K) -300 NEXT K -310 GOTO 380 -320 LET Y=INT (X/2) -330 RETURN -340 LET Y=X*2 -350 RETURN -360 LET Y=X/2=INT (X/2) -370 RETURN -380 PRINT AT I+1,16;A +Procedure isEven(x) + ProcedureReturn (x & 1) ! 1 +EndProcedure + +Procedure halveValue(x) + ProcedureReturn x / 2 +EndProcedure + +Procedure doubleValue(x) + ProcedureReturn x << 1 +EndProcedure + +Procedure EthiopianMultiply(x, y) + Protected sum, sign = x + + Print("Ethiopian multiplication of " + Str(x) + " and " + Str(y) + " ...") + Repeat + If Not isEven(x) + sum + y + EndIf + x = halveValue(x) + y = doubleValue(y) + Until x = 0 + If sign < 0 : sum * -1: EndIf + + PrintN(" equals " + Str(sum)) + ProcedureReturn sum +EndProcedure + +If OpenConsole() + EthiopianMultiply(17,34) + EthiopianMultiply(-17,34) + EthiopianMultiply(-17,-34) + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit") + Input() + CloseConsole() +EndIf diff --git a/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-9.basic b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-9.basic index 2e096710f7..65f15f18a3 100644 --- a/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-9.basic +++ b/Task/Ethiopian-multiplication/BASIC/ethiopian-multiplication-9.basic @@ -1,29 +1,38 @@ -!RosettaCode: Ethiopian Multiplication -! True BASIC v6.007 -PROGRAM EthiopianMultiplication - DECLARE DEF FNdouble - DECLARE DEF FNhalve - DECLARE DEF FNeven - - LET x = 17 - LET y = 34 - - DO - IF FNeven(x) = 0 THEN - LET p = p + y - PRINT x,y - ELSE - PRINT x," ---" - END IF - - LET x = FNhalve(x) - LET y = FNdouble(y) - LOOP UNTIL x = 0 - PRINT " ", " ===" - PRINT " ", p - GET KEY done - - DEF FNdouble(A) = A * 2 - DEF FNhalve(A) = INT(A / 2) - DEF FNeven(A) = MOD(A+1,2) -END + 10 LET HALVE=320 + 20 LET DOUBLE=340 + 30 LET EVEN=360 + 40 DIM L(20) + 50 DIM R(20) + 60 INPUT L(1) + 70 INPUT R(1) + 80 LET I=1 + 90 PRINT L(1),R(1) +100 IF L(I)=1 THEN GOTO 200 +110 LET I=I+1 +120 IF I>20 THEN STOP +130 LET X=L(I-1) +140 GOSUB HALVE +150 LET L(I)=Y +160 LET X=R(I-1) +170 GOSUB DOUBLE +180 LET R(I)=Y +190 GOTO 90 +200 FOR K=1 TO I +210 LET X=L(K) +220 GOSUB EVEN +230 IF NOT Y THEN GOTO 260 +240 LET R(K)=0 +250 PRINT AT K-1,16;" " +260 NEXT K +270 LET A=0 +280 FOR K=1 TO I +290 LET A=A+R(K) +300 NEXT K +310 GOTO 380 +320 LET Y=INT (X/2) +330 RETURN +340 LET Y=X*2 +350 RETURN +360 LET Y=X/2=INT (X/2) +370 RETURN +380 PRINT AT I+1,16;A diff --git a/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-1.julia b/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-1.julia index a453d4287a..fdcfbca585 100644 --- a/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-1.julia +++ b/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-1.julia @@ -1,8 +1,3 @@ -# bit shifting, equivalent to div(x, 2) -halve(x::Int) = x >> 1 - -# preserves the type -double(x::Int) = 2*x - -# could just use iseven(x), but that feels like cheating -even(x::Int) = (mod(x, 2) == 0 ? true : false) +halve(x::Integer) = x >> one(x) +double(x::Integer) = Int8(2) * x +even(x::Integer) = x & 1 != 1 diff --git a/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-2.julia b/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-2.julia index 0d3bcc02e4..b645ca9f86 100644 --- a/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-2.julia +++ b/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-2.julia @@ -1,9 +1,11 @@ -function ethopian_multiplication(a::Int, b::Int) - res = 0 +function ethmult(a::Integer, b::Integer) + r = 0 while a > 0 - res += even(a) ? 0 : b + r += b * !even(a) a = halve(a) b = double(b) end - return res + return r end + +@show ethmult(17, 34) diff --git a/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-3.julia b/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-3.julia index 07c2b0bc43..a5144a2682 100644 --- a/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-3.julia +++ b/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-3.julia @@ -1,9 +1,11 @@ -function ethopian_multiplication_arr(a::Int, b::Int) +function ethmult2(a::Integer, b::Integer) A = [a] B = [b] while A[end] > 1 push!(A, halve(A[end])) push!(B, double(B[end])) end - return sum(B[!map(even, A)]) + return sum(B[map(!even, A)]) end + +@show ethmult2(17, 34) diff --git a/Task/Ethiopian-multiplication/Limbo/ethiopian-multiplication.limbo b/Task/Ethiopian-multiplication/Limbo/ethiopian-multiplication.limbo new file mode 100644 index 0000000000..e2d1729cb9 --- /dev/null +++ b/Task/Ethiopian-multiplication/Limbo/ethiopian-multiplication.limbo @@ -0,0 +1,54 @@ +implement Ethiopian; + +include "sys.m"; + sys: Sys; + print: import sys; +include "draw.m"; + draw: Draw; + +Ethiopian : module +{ + init : fn(ctxt : ref Draw->Context, args : list of string); +}; + +init (ctxt: ref Draw->Context, args: list of string) +{ + sys = load Sys Sys->PATH; + + print("\n%d\n", ethiopian(17, 34, 0)); + print("\n%d\n", ethiopian(99, 99, 1)); +} + +halve(n: int): int +{ + return (n /2); +} + +double(n: int): int +{ + return (n * 2); +} + +iseven(n: int): int +{ + return ((n%2) == 0); +} + +ethiopian(a: int, b: int, tutor: int): int +{ + product := 0; + if (tutor) + print("\nmultiplying %d x %d", a, b); + while (a >= 1) { + if (!(iseven(a))) { + if (tutor) + print("\n%3d %d", a, b); + product += b; + } else + if (tutor) + print("\n%3d ----", a); + a = halve(a); + b = double(b); + } + return product; +} diff --git a/Task/Ethiopian-multiplication/Modula-2/ethiopian-multiplication.mod2 b/Task/Ethiopian-multiplication/Modula-2/ethiopian-multiplication.mod2 new file mode 100644 index 0000000000..f5ec749519 --- /dev/null +++ b/Task/Ethiopian-multiplication/Modula-2/ethiopian-multiplication.mod2 @@ -0,0 +1,44 @@ +MODULE EthiopianMultiplication; + +FROM SWholeIO IMPORT + WriteCard; +FROM STextIO IMPORT + WriteString, WriteLn; + +PROCEDURE Halve(VAR A: CARDINAL); +BEGIN + A := A / 2; +END Halve; + +PROCEDURE Double(VAR A: CARDINAL); +BEGIN + A := 2 * A; +END Double; + +PROCEDURE IsEven(A: CARDINAL): BOOLEAN; +BEGIN + RETURN (X + 1) REM 2 = 0; +END IsEven; + +VAR + X, Y, Tot: CARDINAL; + +BEGIN + X := 17; + Y := 34; + Tot := 0; + WHILE X >= 1 DO + WriteCard(X, 9); + WriteString(" "); + IF IsEven(X) THEN + INC(Tot, Y); + WriteCard(Y, 9) + END; + WriteLn; + Halve(X); + Double(Y); + END; + WriteString("= "); + WriteCard(Tot, 9); + WriteLn; +END EthiopianMultiplication. diff --git a/Task/Ethiopian-multiplication/VBA/ethiopian-multiplication-1.vba b/Task/Ethiopian-multiplication/VBA/ethiopian-multiplication-1.vba new file mode 100644 index 0000000000..2a1e3ef54a --- /dev/null +++ b/Task/Ethiopian-multiplication/VBA/ethiopian-multiplication-1.vba @@ -0,0 +1,11 @@ +Private Function lngHalve(Nb As Long) As Long + lngHalve = Nb / 2 +End Function + +Private Function lngDouble(Nb As Long) As Long + lngDouble = Nb * 2 +End Function + +Private Function IsEven(Nb As Long) As Boolean + IsEven = (Nb Mod 2 = 0) +End Function diff --git a/Task/Ethiopian-multiplication/VBA/ethiopian-multiplication-2.vba b/Task/Ethiopian-multiplication/VBA/ethiopian-multiplication-2.vba new file mode 100644 index 0000000000..c15748babb --- /dev/null +++ b/Task/Ethiopian-multiplication/VBA/ethiopian-multiplication-2.vba @@ -0,0 +1,30 @@ +Private Function Ethiopian_Multiplication_Non_Optimized(First As Long, Second As Long) As Long +Dim Left_Hand_Column As New Collection, Right_Hand_Column As New Collection, i As Long, temp As Long + +'Take two numbers to be multiplied and write them down at the top of two columns. + Left_Hand_Column.Add First, CStr(First) + Right_Hand_Column.Add Second, CStr(Second) +'In the left-hand column repeatedly halve the last number, discarding any remainders, + 'and write the result below the last in the same column, until you write a value of 1. + Do + First = lngHalve(First) + Left_Hand_Column.Add First, CStr(First) + Loop While First > 1 +'In the right-hand column repeatedly double the last number and write the result below. + 'stop when you add a result in the same row as where the left hand column shows 1. + For i = 2 To Left_Hand_Column.Count + Second = lngDouble(Second) + Right_Hand_Column.Add Second, CStr(Second) + Next + +'Examine the table produced and discard any row where the value in the left column is even. + For i = Left_Hand_Column.Count To 1 Step -1 + If IsEven(Left_Hand_Column(i)) Then Right_Hand_Column.Remove CStr(Right_Hand_Column(i)) + Next +'Sum the values in the right-hand column that remain to produce the result of multiplying + 'the original two numbers together + For i = 1 To Right_Hand_Column.Count + temp = temp + Right_Hand_Column(i) + Next + Ethiopian_Multiplication_Non_Optimized = temp +End Function diff --git a/Task/Ethiopian-multiplication/VBA/ethiopian-multiplication-3.vba b/Task/Ethiopian-multiplication/VBA/ethiopian-multiplication-3.vba new file mode 100644 index 0000000000..08bf04a586 --- /dev/null +++ b/Task/Ethiopian-multiplication/VBA/ethiopian-multiplication-3.vba @@ -0,0 +1,7 @@ +Private Function Ethiopian_Multiplication(First As Long, Second As Long) As Long + Do + If Not IsEven(First) Then Mult_Eth = Mult_Eth + Second + First = lngHalve(First) + Second = lngDouble(Second) + Loop While First >= 1 +End Function diff --git a/Task/Ethiopian-multiplication/VBA/ethiopian-multiplication-4.vba b/Task/Ethiopian-multiplication/VBA/ethiopian-multiplication-4.vba new file mode 100644 index 0000000000..90cbe53a8d --- /dev/null +++ b/Task/Ethiopian-multiplication/VBA/ethiopian-multiplication-4.vba @@ -0,0 +1,7 @@ +Sub Main_Ethiopian() +Dim result As Long + result = Ethiopian_Multiplication(17, 34) + ' or : + 'result = Ethiopian_Multiplication_Non_Optimized(17, 34) + Debug.Print result +End Sub diff --git a/Task/Euler-method/Julia/euler-method.julia b/Task/Euler-method/Julia/euler-method.julia index d372468f2d..63ea39ec89 100644 --- a/Task/Euler-method/Julia/euler-method.julia +++ b/Task/Euler-method/Julia/euler-method.julia @@ -1,16 +1,16 @@ -euler(f,T,t0,t1,h)=[(T,T+=h*f(T))[1] for t=t0:h:t1] +euler(f::Function, T::Number, t0::Int, t1::Int, h::Int) = collect(begin T += h * f(T); T end for t in t0:h:t1) # Prints a series of arbitrary values in a tabular form, left aligned in cells with a given width -tabular(width,cells...)=println(join(map(s->rpad(s,width),cells),"")) +tabular(width, cells...) = println(join(map(s -> rpad(s, width), cells))) # prints the table according to the task description for h=5 and 10 sec -for h=(5,10) -print("Step $h:\n\n") -tabular(15,"Time","Euler","Analytic") -t=0 -for T=euler(y->-0.07*(y-20.0),100.0,0,100,h) -tabular(15,t,round(T,6),round(20.0+80.0*exp(-0.07*t),6)) -t+=h -end -println() +for h in (5, 10) + print("Step $h:\n\n") + tabular(15, "Time", "Euler", "Analytic") + t = 0 + for T in euler(y -> -0.07 * (y - 20.0), 100.0, 0, 100, h) + tabular(15, t, round(T,6), round(20.0 + 80.0 * exp(-0.07t), 6)) + t += h + end + println() end diff --git a/Task/Evaluate-binomial-coefficients/C++/evaluate-binomial-coefficients-1.cpp b/Task/Evaluate-binomial-coefficients/C++/evaluate-binomial-coefficients-1.cpp index 17ce2ba2d2..3b5e6f5096 100644 --- a/Task/Evaluate-binomial-coefficients/C++/evaluate-binomial-coefficients-1.cpp +++ b/Task/Evaluate-binomial-coefficients/C++/evaluate-binomial-coefficients-1.cpp @@ -13,11 +13,9 @@ double Factorial(double nValue) return nValue; } -double EvaluateBinomialCoefficient(double nValue, double nValue2) +double binomialCoefficient(double n, double k) { - double result; - if(nValue2 == 1)return nValue; - result = (Factorial(nValue))/(Factorial(nValue2)*Factorial((nValue - nValue2))); - nValue2 = result; - return nValue2; + if (abs(n - k) < 1e-7 || k < 1e-7) return 1.0; + if( abs(k-1.0) < 1e-7 || abs(k - (n-1)) < 1e-7)return n; + return Factorial(n) /(Factorial(k)*Factorial((n - k))); } diff --git a/Task/Evaluate-binomial-coefficients/C++/evaluate-binomial-coefficients-2.cpp b/Task/Evaluate-binomial-coefficients/C++/evaluate-binomial-coefficients-2.cpp index bd8910a815..f026655794 100644 --- a/Task/Evaluate-binomial-coefficients/C++/evaluate-binomial-coefficients-2.cpp +++ b/Task/Evaluate-binomial-coefficients/C++/evaluate-binomial-coefficients-2.cpp @@ -1,5 +1,5 @@ int main() { - cout<<"The Binomial Coefficient of 5, and 3, is equal to: "<< EvaluateBinomialCoefficient(5,3); + cout<<"The Binomial Coefficient of 5, and 3, is equal to: "<< binomialCoefficient(5,3); cin.get(); } diff --git a/Task/Evaluate-binomial-coefficients/Erlang/evaluate-binomial-coefficients.erl b/Task/Evaluate-binomial-coefficients/Erlang/evaluate-binomial-coefficients.erl index 28ee826aad..75575e4846 100644 --- a/Task/Evaluate-binomial-coefficients/Erlang/evaluate-binomial-coefficients.erl +++ b/Task/Evaluate-binomial-coefficients/Erlang/evaluate-binomial-coefficients.erl @@ -1,3 +1,4 @@ +choose(N, 0) -> 1; choose(N, K) when is_integer(N), is_integer(K), (N >= 0), (K >= 0), (N >= K) -> choose(N, K, 1, 1). diff --git a/Task/Evaluate-binomial-coefficients/Julia/evaluate-binomial-coefficients-1.julia b/Task/Evaluate-binomial-coefficients/Julia/evaluate-binomial-coefficients-1.julia new file mode 100644 index 0000000000..9e096aba2b --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Julia/evaluate-binomial-coefficients-1.julia @@ -0,0 +1 @@ +@show binomial(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 new file mode 100644 index 0000000000..f042ce7628 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Julia/evaluate-binomial-coefficients-2.julia @@ -0,0 +1,8 @@ +function binom(n::Integer, k::Integer) + n ≥ k || return 0 # short circuit base cases + n == 1 || k == 0 && return 1 + + return (n * binom(n - 1, k - 1)) ÷ k +end + +@show binom(5, 3) diff --git a/Task/Evaluate-binomial-coefficients/Julia/evaluate-binomial-coefficients.julia b/Task/Evaluate-binomial-coefficients/Julia/evaluate-binomial-coefficients.julia deleted file mode 100644 index fb0248ac28..0000000000 --- a/Task/Evaluate-binomial-coefficients/Julia/evaluate-binomial-coefficients.julia +++ /dev/null @@ -1,10 +0,0 @@ -function binom(n,k) - n >= k || return 0 #short circuit base cases - n == 1 && return 1 - k == 0 && return 1 - - (n * binom(n - 1, k - 1)) ÷ k #recursive call -end - -julia> binom(5,2) -10 diff --git a/Task/Even-or-odd/Common-Lisp/even-or-odd.lisp b/Task/Even-or-odd/Common-Lisp/even-or-odd-1.lisp similarity index 100% rename from Task/Even-or-odd/Common-Lisp/even-or-odd.lisp rename to Task/Even-or-odd/Common-Lisp/even-or-odd-1.lisp diff --git a/Task/Even-or-odd/Common-Lisp/even-or-odd-2.lisp b/Task/Even-or-odd/Common-Lisp/even-or-odd-2.lisp new file mode 100644 index 0000000000..b1370c37b9 --- /dev/null +++ b/Task/Even-or-odd/Common-Lisp/even-or-odd-2.lisp @@ -0,0 +1,13 @@ +;; Project : Even or odd +;; Date : 2018/03/05 +;; Author : Gal Zsolt [~ CalmoSoft ~] +;; Email : + +(defun evenodd (nr) + (cond ((evenp nr) "even") + ((oddp nr) "odd"))) +(dotimes (n 10) +(if (< n 1) (terpri)) +(if (< n 9) (format t "~a" " ")) +(write(+ n 1)) (format t "~a" ": ") +(format t "~a" (evenodd (+ n 1))) (terpri)) diff --git a/Task/Even-or-odd/Modula-2/even-or-odd.mod2 b/Task/Even-or-odd/Modula-2/even-or-odd.mod2 new file mode 100644 index 0000000000..32cce2f0e6 --- /dev/null +++ b/Task/Even-or-odd/Modula-2/even-or-odd.mod2 @@ -0,0 +1,15 @@ +MODULE EvenOrOdd; +FROM FormatString IMPORT FormatString; +FROM Terminal IMPORT WriteString,ReadChar; + +VAR + buf : ARRAY[0..63] OF CHAR; + i : INTEGER; +BEGIN + FOR i:=-5 TO 5 DO + FormatString("%i is even: %b\n", buf, i, i MOD 2 = 0); + WriteString(buf) + END; + + ReadChar +END EvenOrOdd. diff --git a/Task/Even-or-odd/Stata/even-or-odd.stata b/Task/Even-or-odd/Stata/even-or-odd.stata new file mode 100644 index 0000000000..6b9ab972d9 --- /dev/null +++ b/Task/Even-or-odd/Stata/even-or-odd.stata @@ -0,0 +1,9 @@ +mata +function iseven(n) { + return(mod(n,2)==0) +} + +function isodd(n) { + return(mod(n,2)==1) +} +end diff --git a/Task/Even-or-odd/UNIX-Shell/even-or-odd.sh b/Task/Even-or-odd/UNIX-Shell/even-or-odd.sh new file mode 100644 index 0000000000..23012701d3 --- /dev/null +++ b/Task/Even-or-odd/UNIX-Shell/even-or-odd.sh @@ -0,0 +1,4 @@ +iseven() { + [[ $(($1%2)) -eq 0 ]] && return 0 + return 1 +} diff --git a/Task/Even-or-odd/VBA/even-or-odd.vba b/Task/Even-or-odd/VBA/even-or-odd.vba new file mode 100644 index 0000000000..fefa8ccb95 --- /dev/null +++ b/Task/Even-or-odd/VBA/even-or-odd.vba @@ -0,0 +1,38 @@ +Option Explicit + +Sub Main_Even_Odd() +Dim i As Long + + For i = -50 To 48 Step 7 + Debug.Print i & " : IsEven ==> " & IIf(IsEven(i), "is even", "is odd") _ + & " " & Chr(124) & " IsEven2 ==> " & IIf(IsEven2(i), "is even", "is odd") _ + & " " & Chr(124) & " IsEven3 ==> " & IIf(IsEven3(i), "is even", "is odd") _ + & " " & Chr(124) & " IsEven4 ==> " & IIf(IsEven4(i), "is even", "is odd") + Next +End Sub + +Function IsEven(Number As Long) As Boolean +'Use the even and odd predicates + IsEven = (WorksheetFunction.Even(Number) = Number) +End Function + +Function IsEven2(Number As Long) As Boolean +'Check the least significant digit. +'With binary integers, i bitwise-and 1 equals 0 iff i is even, or equals 1 iff i is odd. +Dim lngTemp As Long + lngTemp = CLng(Right(CStr(Number), 1)) + If (lngTemp And 1) = 0 Then IsEven2 = True +End Function + +Function IsEven3(Number As Long) As Boolean +'Divide i by 2. +'The remainder equals 0 if i is even. +Dim sngTemp As Single + sngTemp = Number / 2 + IsEven3 = ((Int(sngTemp) - sngTemp) = 0) +End Function + +Function IsEven4(Number As Long) As Boolean +'Use modular congruences + IsEven4 = (Number Mod 2 = 0) +End Function diff --git a/Task/Events/Julia/events.julia b/Task/Events/Julia/events.julia new file mode 100644 index 0000000000..11a5fe4563 --- /dev/null +++ b/Task/Events/Julia/events.julia @@ -0,0 +1,20 @@ +function dolongcomputation(cond) + det(rand(4000, 4000)) + Base.notify(cond) +end + +function printnotice(cond) + Base.wait(cond) + println("They are finished.") +end + +function delegate() + println("Starting task, sleeping...") + condition = Base.Condition() + Base.@async(printnotice(condition)) + Base.@async(dolongcomputation(condition)) +end + +delegate() +sleep(5) +println("Done sleeping.") diff --git a/Task/Events/Python/events.py b/Task/Events/Python/events.py new file mode 100644 index 0000000000..40b5bb9183 --- /dev/null +++ b/Task/Events/Python/events.py @@ -0,0 +1,20 @@ +import threading +import time + + +def wait_for_event(event): + event.wait() + print("Thread: Got event") + +e = threading.Event() + +t = threading.Thread(target=wait_for_event, args=(e,)) +t.start() + +print("Main: Waiting one second") +time.sleep(1.0) +print("Main: Setting event") +e.set() +time.sleep(1.0) +print("Main: Done") +t.join() diff --git a/Task/Evolutionary-algorithm/00DESCRIPTION b/Task/Evolutionary-algorithm/00DESCRIPTION index 8553b6c95c..d46148a315 100644 --- a/Task/Evolutionary-algorithm/00DESCRIPTION +++ b/Task/Evolutionary-algorithm/00DESCRIPTION @@ -10,8 +10,8 @@ Starting with: ;See also: -*   [[wp:Weasel_program#Weasel_algorithm|Weasel algorithm]]. -*   [[wp:Evolutionary algorithm|Evolutionary algorithm]]. +*   Wikipedia entry:   [[wp:Weasel_program#Weasel_algorithm|Weasel algorithm]]. +*   Wikipedia entry:   [[wp:Evolutionary algorithm|Evolutionary algorithm]].
Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions diff --git a/Task/Evolutionary-algorithm/Aime/evolutionary-algorithm.aime b/Task/Evolutionary-algorithm/Aime/evolutionary-algorithm.aime index c88586454a..6ced51a515 100644 --- a/Task/Evolutionary-algorithm/Aime/evolutionary-algorithm.aime +++ b/Task/Evolutionary-algorithm/Aime/evolutionary-algorithm.aime @@ -1,33 +1,24 @@ integer fitness(data t, data b) { - integer f, i; + integer c, f, i; f = 0; - i = b_length(t); - while (i) { - i -= 1; - f += sign(t[i] ^ b[i]); + for (i, c in b) { + f += sign(t[i] ^ c); } - return f; + f; } void -mutate(data c, data b, data u) +mutate(data e, data b, data u) { - integer i, l; + integer c; - l = b_length(b); - i = 0; - while (i < l) { - if (drand(15)) { - b_append(c, b[i]); - } else { - b_append(c, u[drand(26)]); - } - i += 1; + for (, c in b) { + e.append(drand(15) ? c : u[drand(26)]); } } @@ -35,17 +26,15 @@ integer main(void) { data b, t, u; - integer f, i, l; + integer f, i; - b_cast(t, "METHINK IT IS LIKE A WEASEL"); - b_cast(u, "ABCDEFGHIJKLMNOPQRSTUVWXYZ "); + t = "METHINK IT IS LIKE A WEASEL"; + u = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "; - l = b_length(t); - - i = l; + i = ~t; while (i) { i -= 1; - b_append(b, u[drand(26)]); + b.append(u[drand(26)]); } f = fitness(t, b); @@ -53,7 +42,7 @@ main(void) data n; integer a; - o_form("/lw4/~\n", f, b_string(b)); + o_form("/lw4/~\n", f, b); n = b; @@ -73,7 +62,7 @@ main(void) b = n; } - o_form("/lw4/~\n", f, b_string(b)); + o_form("/lw4/~\n", f, b); return 0; } diff --git a/Task/Evolutionary-algorithm/Factor/evolutionary-algorithm.factor b/Task/Evolutionary-algorithm/Factor/evolutionary-algorithm.factor new file mode 100644 index 0000000000..140d3ad463 --- /dev/null +++ b/Task/Evolutionary-algorithm/Factor/evolutionary-algorithm.factor @@ -0,0 +1,37 @@ +USING: arrays formatting io kernel literals math prettyprint +random sequences strings ; +FROM: math.extras => ... ; +IN: rosetta-code.evolutionary-algorithm + +CONSTANT: target "METHINKS IT IS LIKE A WEASEL" +CONSTANT: mutation-rate 0.1 +CONSTANT: num-children 25 +CONSTANT: valid-chars + $[ CHAR: A ... CHAR: Z >array { 32 } append ] + +: rand-char ( -- n ) + valid-chars random ; + +: new-parent ( -- str ) + target length [ rand-char ] replicate >string ; + +: fitness ( str -- n ) + target [ = ] { } 2map-as sift length ; + +: mutate ( str rate -- str/str' ) + [ random-unit > [ drop rand-char ] when ] curry map ; + +: next-parent ( str -- str/str' ) + dup [ mutation-rate mutate ] curry num-children 1 - swap + replicate [ 1array ] dip append [ fitness ] supremum-by ; + +: print-parent ( str -- ) + [ fitness pprint bl ] [ print ] bi ; + +: main ( -- ) + 0 new-parent + [ dup target = ] + [ next-parent dup print-parent [ 1 + ] dip ] until drop + "Finished in %d generations." printf ; + +MAIN: main diff --git a/Task/Evolutionary-algorithm/Julia/evolutionary-algorithm.julia b/Task/Evolutionary-algorithm/Julia/evolutionary-algorithm.julia new file mode 100644 index 0000000000..71b134a0eb --- /dev/null +++ b/Task/Evolutionary-algorithm/Julia/evolutionary-algorithm.julia @@ -0,0 +1,24 @@ +fitness(a::AbstractString, b::AbstractString) = count(l == t for (l, t) in zip(a, b)) +function mutate(str::AbstractString, rate::Float64) + L = collect(Char, " ABCDEFGHIJKLMNOPQRSTUVWXYZ") + return map(str) do c + if rand() < rate rand(L) else c end + end +end + +function evolve(parent::String, target::String, mutrate::Float64, nchild::Int) + println("Initial parent is $parent, its fitness is $(fitness(parent, target))") + gens = 0 + while parent != target + children = collect(mutate(parent, mutrate) for i in 1:nchild) + bestfit, best = findmax(fitness.(children, target)) + parent = children[best] + gens += 1 + if gens % 10 == 0 + println("After $gens generations, the new parent is $parent and its fitness is $(fitness(parent, target))") + end + end + println("After $gens generations, the parent evolved into the target $target") +end + +evolve("IU RFSGJABGOLYWF XSMFXNIABKT", "METHINKS IT IS LIKE A WEASEL", 0.08998, 100) diff --git a/Task/Evolutionary-algorithm/Pony/evolutionary-algorithm-2.pony b/Task/Evolutionary-algorithm/Pony/evolutionary-algorithm-2.pony index 6b6f373b45..b961e7b3c5 100644 --- a/Task/Evolutionary-algorithm/Pony/evolutionary-algorithm-2.pony +++ b/Task/Evolutionary-algorithm/Pony/evolutionary-algorithm-2.pony @@ -14,7 +14,7 @@ class CreationFactory var f = USize(0) for i in Range(0, s.size()) do try - if s(i) == _desired(i) then + if s(i)? == _desired(i)? then f = f +1 end end @@ -57,7 +57,7 @@ class Mutator fun ref _random_letter(): U8 => let ln = _rand.int(_possibilities.size().u64()).usize() - try _possibilities(ln) else ' ' end + try _possibilities(ln)? else ' ' end class Generation let _size: USize diff --git a/Task/Evolutionary-algorithm/R/evolutionary-algorithm.r b/Task/Evolutionary-algorithm/R/evolutionary-algorithm-1.r similarity index 100% rename from Task/Evolutionary-algorithm/R/evolutionary-algorithm.r rename to Task/Evolutionary-algorithm/R/evolutionary-algorithm-1.r diff --git a/Task/Evolutionary-algorithm/R/evolutionary-algorithm-2.r b/Task/Evolutionary-algorithm/R/evolutionary-algorithm-2.r new file mode 100644 index 0000000000..da52147b9d --- /dev/null +++ b/Task/Evolutionary-algorithm/R/evolutionary-algorithm-2.r @@ -0,0 +1,34 @@ +# Setup +set.seed(42) +target= unlist(strsplit("METHINKS IT IS LIKE A WEASEL", "")) +chars= c(LETTERS, " ") +C= 100 + +# Fitness function; high value means higher fitness +fitness= function(x){ + sum(x == target) +} + +# Mutate function +mutate= function(x, rate= 0.01){ + idx= which(runif(length(target)) <= rate) + x[idx]= replicate(n= length(idx), expr= sample(x= chars, size= 1, replace= T)) + x +} + +# Evolve function +evolve= function(x){ + parents= rep(list(x), C+1) # Repliction + parents[1:C]= lapply(parents[1:C], function(x) mutate(x)) # Mutation + idx= which.max(lapply(parents, function(x) fitness(x))) # Selection + parents[[idx]] +} + +# Initialize first parent +parent= sample(x= chars, size= length(target), replace= T) + +# Main program +while (fitness(parent) < fitness(target)) { + parent= evolve(parent) + cat(paste0(parent, collapse=""), "\n") +} diff --git a/Task/Evolutionary-algorithm/Ring/evolutionary-algorithm.ring b/Task/Evolutionary-algorithm/Ring/evolutionary-algorithm.ring new file mode 100644 index 0000000000..25a27cb715 --- /dev/null +++ b/Task/Evolutionary-algorithm/Ring/evolutionary-algorithm.ring @@ -0,0 +1,60 @@ +# Project : Evolutionary algorithm +# Date : 2018/03/28 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : + +target = "METHINKS IT IS LIKE A WEASEL" +parent = "IU RFSGJABGOLYWF XSMFXNIABKT" +num = 0 +mutationrate = 0.5 +children = len(target) +child = list(children) +while parent != target + bestfitness = 0 + bestindex = 0 + for index = 1 to children + child[index] = mutate(parent, mutationrate) + fitness = fitness(target, child[index]) + if fitness > bestfitness + bestfitness = fitness + bestindex = index + ok + next + if bestindex > 0 + parent = child[bestindex] + num = num + 1 + see "" + num + ": " + parent + nl + ok +end + +func fitness(text, ref) + f = 0 + for i = 1 to len(text) + if substr(text, i, 1) = substr(ref, i, 1) + f = f + 1 + ok + next + return (f / len(text)) + +func mutate(text, rate) + rnd = randomf() + if rate > rnd + c = 63+random(27) + if c = 64 + c = 32 + ok + rnd2 = random(len(text)) + if rnd2 > 0 + text[rnd2] = char(c) + ok + ok + return text + +func randomf() + decimals(10) + str = "0." + for i = 1 to 10 + nr = random(9) + str = str + string(nr) + next + return number(str) diff --git a/Task/Evolutionary-algorithm/Rust/evolutionary-algorithm.rust b/Task/Evolutionary-algorithm/Rust/evolutionary-algorithm.rust new file mode 100644 index 0000000000..1bfaf8595e --- /dev/null +++ b/Task/Evolutionary-algorithm/Rust/evolutionary-algorithm.rust @@ -0,0 +1,101 @@ +//! Author : Thibault Barbie +//! +//! A simple evolutionary algorithm written in Rust. + +extern crate rand; + +use rand::Rng; + +fn main() { + let target = "METHINKS IT IS LIKE A WEASEL"; + let copies = 100; + let mutation_rate = 20; // 1/20 = 0.05 = 5% + + let mut rng = rand::weak_rng(); + + // Generate first sentence, mutating each character + let start = mutate(&mut rng, target, 1); // 1/1 = 1 = 100% + + println!("{}", target); + println!("{}", start); + + evolve(&mut rng, target, start, copies, mutation_rate); +} + +/// Evolution algorithm +/// +/// Evolves `parent` to match `target`. Returns the number of evolutions performed. +fn evolve( + rng: &mut R, + target: &str, + mut parent: String, + copies: usize, + mutation_rate: u32, +) -> usize { + let mut counter = 0; + let mut parent_fitness = target.len() + 1; + + loop { + counter += 1; + + let (best_fitness, best_sentence) = (0..copies) + .map(|_| { + // Copy and mutate a new sentence. + let sentence = mutate(rng, &parent, mutation_rate); + // Find the fitness of the new mutation + (fitness(target, &sentence), sentence) + }) + .min_by_key(|&(f, _)| f) // find the closest mutation to the target + .unwrap(); // fails if `copies == 0` + + // If the best mutation of this generation is better than `parent` then "the fittest + // survives" and the next parent becomes the best of this generation. + if best_fitness < parent_fitness { + parent = best_sentence; + parent_fitness = best_fitness; + println!( + "{} : generation {} with fitness {}", + parent, counter, best_fitness + ); + + if best_fitness == 0 { + return counter; + } + } + } +} + +/// Computes the fitness of a sentence against a target string, returning the number of +/// incorrect characters. +fn fitness(target: &str, sentence: &str) -> usize { + sentence + .chars() + .zip(target.chars()) + .filter(|&(c1, c2)| c1 != c2) + .count() +} + +/// Mutation algorithm. +/// +/// It mutates each character of a string, according to a `mutation_rate`. +fn mutate(rng: &mut R, sentence: &str, mutation_rate: u32) -> String { + let maybe_mutate = |c| { + if rng.gen_weighted_bool(mutation_rate) { + random_char(rng) + } else { + c + } + }; + sentence.chars().map(maybe_mutate).collect() +} + +/// Generates a random letter or space. +fn random_char(rng: &mut R) -> char { + // Returns a value in the range [A, Z] + an extra slot for the space character. (The `u8` + // values could be cast to larger integers for a better chance of the RNG hitting the proper + // range). + match rng.gen_range(b'A', b'Z' + 2) { + c if c == b'Z' + 1 => ' ', // the `char` after 'Z' + c => c as char, + } +} diff --git a/Task/Evolutionary-algorithm/Smalltalk/evolutionary-algorithm-1.st b/Task/Evolutionary-algorithm/Smalltalk/evolutionary-algorithm-1.st new file mode 100644 index 0000000000..6cacf1bc3a --- /dev/null +++ b/Task/Evolutionary-algorithm/Smalltalk/evolutionary-algorithm-1.st @@ -0,0 +1,47 @@ +String subclass: Mutant [ + + + Target := Mutant from: 'METHINKS IT IS LIKE A WEASEL'. + Letters := ' ABCDEFGHIJKLMNOPQRSTUVWXYZ'. + + Mutant class >> run: c rate: p + ["Run Evolutionary algorighm, using c copies and mutate rate p." + | pool parent | + parent := self newRandom. + pool := Array new: c+1. + + [parent displayNl. + parent = Target] whileFalse: + [1 to: c do: [:i | pool at: i put: (parent copy mutate: p)]. + pool at: c+1 put: parent. + parent := pool fold: [:winner :each | winner fittest: each]]] + + Mutant class >> newRandom + [^(self new: Target size) + initializeToRandom; + yourself] + + initializeToRandom + [self keys do: [:i | self at: i put: self randomLetter]] + + mutate: p + [self keys do: + [:i | + Random next <= p ifTrue: [self at: i put: self randomLetter]]] + + fitness + [| score | + score := 0. + self with: Target do: + [:me :you | + me = you ifTrue: [score := score + 1]]. + ^score] + + fittest: aMutant + [^self fitness > aMutant fitness + ifTrue: [self] + ifFalse: [aMutant]] + + randomLetter + [^Letters at: (Random between: 1 and: Letters size)] +] diff --git a/Task/Evolutionary-algorithm/Smalltalk/evolutionary-algorithm-2.st b/Task/Evolutionary-algorithm/Smalltalk/evolutionary-algorithm-2.st new file mode 100644 index 0000000000..935758613f --- /dev/null +++ b/Task/Evolutionary-algorithm/Smalltalk/evolutionary-algorithm-2.st @@ -0,0 +1,21 @@ +st> Mutant run: 2500 rate: 0.1 +QJUUIQHYXEZORSXGJCAHEWACH KG +QJUUIQHYXEZORSXGJCAHEWWCMSKG +QEUUIUHYXEZORSOGICAHYWWCSSKG +QETUIUHGXEZORS GICE YWWCSSEG +METUIUHSXOZORS OICE YWWCSSEG +METUIUHSXOZORS OICE Y WCSSEG +METUIUHSXOZMIS OIOE Y WCNSEG +METKIUKSTOFMIS LIOE Y WCNSEG +METKINKSTOFMIS LIKE E WCNSEG +METKINKSTOFMIS LIKE F WCNSEL +METHINKSTOF IS LIKE F WCNSEL +METHINKS OW IS LIKE F WCNSEL +METHINKS IW IS LIKE F WCNSEL +METHINKS IW IS LIKE C WCASEL +METHINKS IW IS LIKE C WCASEL +METHINKS IW IS LIKE A WCASEL +METHINKS IW IS LIKE A WCASEL +METHINKS IW IS LIKE A WEASEL +METHINKS IT IS LIKE A WEASEL +Mutant diff --git a/Task/Evolutionary-algorithm/Smalltalk/evolutionary-algorithm.st b/Task/Evolutionary-algorithm/Smalltalk/evolutionary-algorithm.st deleted file mode 100644 index 6b729b34db..0000000000 --- a/Task/Evolutionary-algorithm/Smalltalk/evolutionary-algorithm.st +++ /dev/null @@ -1,116 +0,0 @@ -Object subclass: Evolution [ - |target parent mutateRate c alphabet fitness| - - Evolution class >> newWithRate: rate andTarget: aTarget [ - |r| r := super new. - ^r initWithRate: rate andTarget: aTarget. - ] - - initWithRate: rate andTarget: aTarget [ - target := aTarget. - self mutationRate: rate. - self maxCount: 100. - self defaultAlphabet. - self changeParent. - self fitness: (self defaultFitness). - ^self - ] - - defaultFitness [ - ^ [:p :t | - |t1 t2 s| - t1 := p asOrderedCollection. - t2 := t asOrderedCollection. - s := 0. - t2 do: [:e| (e == (t1 removeFirst)) ifTrue: [ s:=s+1 ] ]. - s / (target size) - ] - ] - - defaultAlphabet [ alphabet := 'ABCDEFGHIJKLMNOPQRSTUVWXYZ ' asOrderedCollection. ] - - maxCount: anInteger [ c := anInteger ] - - mutationRate: aFloat [ mutateRate := aFloat ] - - changeParent [ - parent := self generateStringOfLength: (target size) withAlphabet: alphabet. - ^ parent. - ] - - generateStringOfLength: len withAlphabet: ab [ - |r| - r := String new. - 1 to: len do: [ :i | - r := r , ((ab at: (Random between: 1 and: (ab size))) asString) - ]. - ^r - ] - - fitness: aBlock [ fitness := aBlock ] - - randomCollection: d [ - |r| r := OrderedCollection new. - 1 to: d do: [:i| - r add: (Random next) - ]. - ^r - ] - - mutate [ - |r p nmutants s| - r := parent copy. - p := self randomCollection: (r size). - nmutants := (p select: [ :e | (e < mutateRate)]) size. - (nmutants > 0) - ifTrue: [ |t| - s := (self generateStringOfLength: nmutants withAlphabet: alphabet) asOrderedCollection. - t := 1. - (p collect: [ :e | e < mutateRate ]) do: [ :v | - v ifTrue: [ r at: t put: (s removeFirst) ]. - t := t + 1. - ] - ]. - ^r - ] - - evolve [ - |children es mi mv| - es := self getEvolutionStatus. - children := OrderedCollection new. - 1 to: c do: [ :i | - children add: (self mutate) - ]. - children add: es. - mi := children size. - mv := fitness value: es value: target. - children doWithIndex: [:e :i| - (fitness value: e value: target) > mv - ifTrue: [ mi := i. mv := fitness value: e value: target ] - ]. - parent := children at: mi. - ^es "returns the parent, not the evolution" - ] - - printgen: i [ - ('%1 %2 "%3"' % {i . (fitness value: parent value: target) . parent }) displayNl - ] - - evoluted [ ^ target = parent ] - getEvolutionStatus [ ^ parent ] - -]. - -|organism j| - -organism := Evolution newWithRate: 0.01 andTarget: 'METHINKS IT IS LIKE A WEASEL'. - -j := 0. -[ organism evoluted ] - whileFalse: [ - j := j + 1. - organism evolve. - ((j rem: 20) = 0) ifTrue: [ organism printgen: j ] - ]. - -organism getEvolutionStatus displayNl. diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/00DESCRIPTION b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/00DESCRIPTION index 17a61bb208..5c4e97501e 100644 --- a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/00DESCRIPTION +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/00DESCRIPTION @@ -1,4 +1,3 @@ -{{omit from|C}} {{omit from|GUISS}} {{omit from|M4}} {{omit from|Retro}} 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 new file mode 100644 index 0000000000..709f9fc067 --- /dev/null +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Elena/exceptions-catch-an-exception-thrown-in-a-nested-call.elena @@ -0,0 +1,46 @@ +import extensions. + +class U0 :: Exception. + +class U1 :: Exception. + +singleton Exceptions +{ + static int i. + + bar + <= baz. + + baz + [ + if (i == 0) + [ + U0 new; raise + ]; + [ + U1 new; raise + ] + ] + + foo + [ + i := 0. + while (i < 2) + [ + try($self bar) + { + on(U0 e) + [ + console printLine("U0 Caught"). + ] + }. + + i += 1. + ] + ] +} + +program = +[ + Exceptions foo. +]. diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Julia/exceptions-catch-an-exception-thrown-in-a-nested-call.julia b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Julia/exceptions-catch-an-exception-thrown-in-a-nested-call.julia new file mode 100644 index 0000000000..f4a89e2508 --- /dev/null +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Julia/exceptions-catch-an-exception-thrown-in-a-nested-call.julia @@ -0,0 +1,28 @@ +struct U0 <: Exception end +struct U1 <: Exception end + +function foo() + for i in 1:2 + try + bar() + catch err + if isa(err, U0) println("catched U0") + else rethrow(err) end + end + end +end + +function bar() + baz() +end + +function baz() + if isdefined(:_called) && _called + throw(U1()) + else + global _called = true + throw(U0()) + end +end + +foo() diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Smalltalk/exceptions-catch-an-exception-thrown-in-a-nested-call-1.st b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Smalltalk/exceptions-catch-an-exception-thrown-in-a-nested-call-1.st index bf2930ec44..540fe34a91 100644 --- a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Smalltalk/exceptions-catch-an-exception-thrown-in-a-nested-call-1.st +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Smalltalk/exceptions-catch-an-exception-thrown-in-a-nested-call-1.st @@ -1,30 +1,25 @@ -| u0 u1 foo bar baz| +Exception subclass: #U0. +Exception subclass: #U1. -u0 := Signal new. -u1 := Signal new. +Object subclass: Foo [ -foo := [ - 2 timesRepeat:[ - [ bar value ] - on: u0 - do:[ 'u0 cought' printCR ] - ] - ]. + bazCount := 0. -bar := [ - baz value - ]. + foo + [2 timesRepeat: + [ "==>" [self bar] "<==" + on: U0 + do: + [:sig | + 'Call to bar was aborted by exception U0' printNl. + sig return]]] -baz := [ - |alreadyCalled| + bar + [self baz] - [ - alreadyCalled isNil ifTrue:[ - alreadyCalled := true. u0 raise - ] ifFalse:[ - u1 raise - ] - ] - ] value. - -foo value + baz + [bazCount := bazCount + 1. + bazCount = 1 ifTrue: [U0 new signal]. + bazCount = 2 ifTrue: [U1 new signal]. + "Thirds time's a charm..."] +] diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Smalltalk/exceptions-catch-an-exception-thrown-in-a-nested-call-2.st b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Smalltalk/exceptions-catch-an-exception-thrown-in-a-nested-call-2.st index ce1d8cb1cb..b418c7ded2 100644 --- a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Smalltalk/exceptions-catch-an-exception-thrown-in-a-nested-call-2.st +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Smalltalk/exceptions-catch-an-exception-thrown-in-a-nested-call-2.st @@ -1,43 +1,11 @@ -Exception - subclass: #U0 - instanceVariableNames:'' - classVariableNames:'' - poolDictionaries:'' - category:'example'. - -Exception - subclass: #U1 - instanceVariableNames:'' - classVariableNames:'' - poolDictionaries:'' - category:'example'. - -Object - subclass: #CatchMeIfYouCan - instanceVariableNames:'bazAlreadyCalled' - classVariableNames:'' - poolDictionaries:'' - category:'example'. - -" CatchMeIfYouCan methods " - -foo - 2 timesRepeat:[ - [ self bar ] - on: U0 - do:[ 'U0 cought' printCR ] - ] - -bar - self baz - - -baz - bazAlreadyCalled isNil ifTrue:[ - bazAlreadyCalled := true. - U0 raise - ] ifFalse:[ - U1 raise - ] - -CatchMeIfYouCan new foo +st> Foo new foo +'Call to bar was aborted by exception U0' +Object: Foo new "<-0x4c9a7960>" error: An exception has occurred +U1(Exception)>>signal (ExcHandling.st:254) +Foo>>baz (catch_exception.st:32) +Foo>>bar (catch_exception.st:27) +optimized [] in Foo>>foo (catch_exception.st:19) +BlockClosure>>on:do: (BlkClosure.st:193) +Foo>>foo (catch_exception.st:20) +UndefinedObject>>executeStatements (a String:1) +nil diff --git a/Task/Exceptions/HolyC/exceptions-1.holyc b/Task/Exceptions/HolyC/exceptions-1.holyc new file mode 100644 index 0000000000..f15c1be5bd --- /dev/null +++ b/Task/Exceptions/HolyC/exceptions-1.holyc @@ -0,0 +1,8 @@ +try { + U8 *err = 'Error'; + throw(err); // throw exception +} catch { + if (err == 'Error') + Print("Raised 'Error'"); + PutExcept; // print the exception and stack trace +} diff --git a/Task/Exceptions/HolyC/exceptions-2.holyc b/Task/Exceptions/HolyC/exceptions-2.holyc new file mode 100644 index 0000000000..c588571f84 --- /dev/null +++ b/Task/Exceptions/HolyC/exceptions-2.holyc @@ -0,0 +1,17 @@ +import Exceptions + +procedure main(A) + every i := !A do { + case Try().call{ write(g(i)) } of { + Try().catch(): { + x := Try().getException() + write(x.getMessage(), ":\n", x.getLocation()) + } + } + } +end + +procedure g(i) + if numeric(i) = 3 then Exception().throw("bad value of "||i) + return i +end diff --git a/Task/Exceptions/Julia/exceptions.julia b/Task/Exceptions/Julia/exceptions.julia new file mode 100644 index 0000000000..fa12457fea --- /dev/null +++ b/Task/Exceptions/Julia/exceptions.julia @@ -0,0 +1,14 @@ +function extendedsqrt(x) + try sqrt(x) + catch + if x isa Number + sqrt(complex(x, 0)) + else + throw(DomainError()) + end + end +end + +@show extendedsqrt(1) # 1 +@show extendedsqrt(-1) # 0.0 + 1.0im +@show extendedsqrt('x') # ERROR: DomainError diff --git a/Task/Exceptions/VBA/exceptions-1.vba b/Task/Exceptions/VBA/exceptions-1.vba new file mode 100644 index 0000000000..4ecad1264f --- /dev/null +++ b/Task/Exceptions/VBA/exceptions-1.vba @@ -0,0 +1,7 @@ +Sub foo1() + err.raise(vbObjectError + 1050) +End Sub + +Sub foo2() + Error vbObjectError + 1051 +End Sub diff --git a/Task/Exceptions/VBA/exceptions-2.vba b/Task/Exceptions/VBA/exceptions-2.vba new file mode 100644 index 0000000000..c317073d1a --- /dev/null +++ b/Task/Exceptions/VBA/exceptions-2.vba @@ -0,0 +1,46 @@ +Sub bar1() +'by convention, a simple handler + On Error GoTo catch + foo1 + MsgBox " No Error" + Exit Sub +catch: + 'handle all exceptions + MsgBox Err.Number & vbCrLf & Err.Description + Exit Sub +End Sub + +Sub bar2() +'a more complex handler, illustrating some of the flexibility of VBA exception handling + On Error GoTo catch +100 foo1 +200 foo2 + 'finally block may be placed anywhere: this is complexity for it's own sake: + GoTo finally +catch: + If Erl = 100 Then + ' handle exception at first line: in this case, by ignoring it: + Resume Next + Else + Select Case Err.Number + Case vbObjectError + 1050 + ' handle exceptions of type 1050 + MsgBox "type 1050" + Case vbObjectError + 1051 + ' handle exceptions of type 1051 + MsgBox "type 1051" + Case Else + ' handle any type of exception not handled by above catches or line numbers + MsgBox Err.Number & vbCrLf & Err.Description + End Select + Resume finally + End If +finally: + 'code here occurs whether or not there was an exception + 'block may be placed anywhere + 'by convention, often just a drop through to an Exit Sub, rather tnan a code block + GoTo end_try: + +end_try: + 'by convention, often just a drop through from the catch block +End Sub diff --git a/Task/Executable-library/00DESCRIPTION b/Task/Executable-library/00DESCRIPTION index 0d25c18585..2eab143dd7 100644 --- a/Task/Executable-library/00DESCRIPTION +++ b/Task/Executable-library/00DESCRIPTION @@ -1,7 +1,12 @@ -{{omit from|Go}} {{omit from|GUISS}} +{{omit from|Go}} +{{omit from|MATLAB}} {{omit from|Maxima}} - +{{omit from|Octave}} +{{omit from|R}} +{{omit from|SAS}} +{{omit from|Scilab}} +{{omit from|Stata}} The general idea behind an executable library is to create a library that when used as a library does one thing; but has the ability to be run directly via command line. diff --git a/Task/Executable-library/Clojure/executable-library-1.clj b/Task/Executable-library/Clojure/executable-library-1.clj new file mode 100644 index 0000000000..28c109f18c --- /dev/null +++ b/Task/Executable-library/Clojure/executable-library-1.clj @@ -0,0 +1,28 @@ +(ns rosetta-code.hailstone-sequence) + +(defn next-in-hailstone + "Returns the next number in the Hailstone sequence that starts with x. + If x is less than 2, returns nil." + [x] + (when (> x 1) + (if (even? x) + (/ x 2) + (inc (* 3 x))))) + +(defn hailstone-seq + "Returns a lazy Hailstone sequence starting with the number x." + [x] + (take-while some? + (iterate next-in-hailstone x))) + +(defn -main [& args] + (let [h27 (hailstone-seq 27)] + (printf "The Hailstone sequence starting at 27 contains %s elements:\n%s ... %s.\n" + (count h27) + (vec (take 4 h27)) + (vec (take-last 4 h27))) + (let [[number length] (apply max-key second + (map (fn [x] [x (count (hailstone-seq x))]) + (range 100000)))] + (printf "The number %s has the longest Hailstone sequence under 100000, of length %s.\n" + number length)))) diff --git a/Task/Executable-library/Clojure/executable-library-2.clj b/Task/Executable-library/Clojure/executable-library-2.clj new file mode 100644 index 0000000000..679e186491 --- /dev/null +++ b/Task/Executable-library/Clojure/executable-library-2.clj @@ -0,0 +1,13 @@ +(ns rosetta-code.frequent-hailstone-lengths + (:require [rosetta-code.hailstone-sequence + :refer [hailstone-seq]])) + +(defn -main [& args] + (let [frequencies (apply merge-with + + (for [x (range 1 100000)] + {(count (hailstone-seq x)) 1})) + [most-frequent-length frequency] + (apply max-key val (seq frequencies))] + (printf (str "The most frequent Hailstone sequence length for numbers under 100000 is %s," + " with a frequency of %s.\n") + most-frequent-length frequency))) diff --git a/Task/Executable-library/Julia/executable-library.julia b/Task/Executable-library/Julia/executable-library.julia new file mode 100644 index 0000000000..f0f246e432 --- /dev/null +++ b/Task/Executable-library/Julia/executable-library.julia @@ -0,0 +1,53 @@ +############### in file hailstone.jl ############### +module Hailstone + +function hailstone(n) + ret = [n] + while n > 1 + if n & 1 > 0 + n = 3n + 1 + else + n = Int(n//2) + end + append!(ret, n) + end + return ret +end + +export hailstone + +end + +if PROGRAM_FILE == "hailstone.jl" + using Hailstone + h = hailstone(27) + n = length(h) + println("The sequence of hailstone(27) is:\n $h.\nThis sequence is of length $n. It starts with $(h[1:4]) and ends with $(h[n-3:end]).") +end +############ in file moduletest.jl #################### +include("hailstone.jl") +using Hailstone +function countstones(mi, mx) + lengths2occurences = Dict() + mostfreq = mi + maxcount = 1 + for i in mi:mx + h = hailstone(i) + n = length(h) + if haskey(lengths2occurences, n) + newoccurences = lengths2occurences[n] + 1 + if newoccurences > maxcount + maxcount = newoccurences + mostfreq = n + end + lengths2occurences[n] = newoccurences + else + lengths2occurences[n] = 1 + end + end + mostfreq, maxcount +end + +nlen, cnt = countstones(1,99999) + +print("The most common hailstone sequence length for hailstone(n) for 1 <= n < 100000 is $nlen, which occurs $cnt times.") diff --git a/Task/Execute-Brain----/Julia/execute-brain----.julia b/Task/Execute-Brain----/Julia/execute-brain----.julia new file mode 100644 index 0000000000..d719e78b39 --- /dev/null +++ b/Task/Execute-Brain----/Julia/execute-brain----.julia @@ -0,0 +1,38 @@ +using DataStructures + +function execute(src) + pointers = Dict{Int,Int}() + stack = Int[] + for (ptr, opcode) in enumerate(src) + if opcode == '[' push!(stack, ptr) end + if opcode == ']' + if isempty(stack) + src = src[1:ptr] + break + end + sptr = pop!(stack) + pointers[ptr], pointers[sptr] = sptr, ptr + end + end + if ! isempty(stack) error("unclosed loops at $stack") end + tape = DefaultDict{Int,Int}(0) + cell, ptr = 0, 1 + while ptr ≤ length(src) + opcode = src[ptr] + if opcode == '>' cell += 1 + elseif opcode == '<' cell -= 1 + elseif opcode == '+' tape[cell] += 1 + elseif opcode == '-' tape[cell] -= 1 + elseif opcode == ',' tape[cell] = Int(read(STDIN, 1)) + elseif opcode == '.' print(STDOUT, Char(tape[cell])) + elseif (opcode == '[' && tape[cell] == 0) || + (opcode == ']' && tape[cell] != 0) ptr = pointers[ptr] + end + ptr += 1 + end +end + +const src = """\ + >++++++++[<+++++++++>-]<.>>+>+>++>[-]+<[>[->+<<++++>]<<]>.+++++++..+++.> + >+++++++.<<<[[-]<[-]>]<+++++++++++++++.>>.+++.------.--------.>>+.>++++.""" +execute(src) diff --git a/Task/Execute-Brain----/Prolog/execute-brain----.pro b/Task/Execute-Brain----/Prolog/execute-brain----.pro new file mode 100644 index 0000000000..5e4623777f --- /dev/null +++ b/Task/Execute-Brain----/Prolog/execute-brain----.pro @@ -0,0 +1,97 @@ +/****************************************** + Starting point, call with program in atom. +*******************************************/ +brain(Program) :- + atom_chars(Program, Instructions), + process_bf_chars(Instructions). + +brain_from_file(File) :- % or from file... + read_file_to_codes(File, Codes, []), + maplist(char_code, Instructions, Codes), + process_bf_chars(Instructions). + +process_bf_chars(Instructions) :- + phrase(bf_to_pl(Code), Instructions, []), + Code = [C|_], + instruction(C, Code, mem([], [0])), !. + + +/******************************************** + DCG to parse the bf program into prolog form +*********************************************/ +bf_to_pl([]) --> []. +bf_to_pl([loop(Ins)|Next]) --> loop_start, bf_to_pl(Ins), loop_end, bf_to_pl(Next). +bf_to_pl([Ins|Next]) --> bf_code(Ins), bf_to_pl(Next). +bf_to_pl(Ins) --> [X], { \+ member(X, ['[',']',>,<,+,-,'.',',']) }, bf_to_pl(Ins). % skip non bf characters + +loop_start --> ['[']. +loop_end --> [']']. + +bf_code(next_addr) --> ['>']. +bf_code(prev_addr) --> ['<']. +bf_code(inc_caddr) --> ['+']. +bf_code(dec_caddr) --> ['-']. +bf_code(out_caddr) --> ['.']. +bf_code(in_caddr) --> [',']. + +/********************** + Instruction Processor +***********************/ +instruction([], _, _). +instruction(I, Code, Mem) :- + mem_instruction(I, Mem, UpdatedMem), + next_instruction(Code, NextI, NextCode), + !, % cuts are to force tail recursion, so big programs will run + instruction(NextI, NextCode, UpdatedMem). + +% to loop, add the loop code to the start of the program then execute +% when the loop has finished it will reach itself again then can retest for zero +instruction(loop(LoopCode), Code, Mem) :- + caddr(Mem, X), + dif(X, 0), + append(LoopCode, Code, [NextI|NextLoopCode]), + !, + instruction(NextI, [NextI|NextLoopCode], Mem). +instruction(loop(_), Code, Mem) :- + caddr(Mem, 0), + next_instruction(Code, NextI, NextCode), + !, + instruction(NextI, NextCode, Mem). + +% memory is stored in two parts: +% 1. a list with the current address and everything after it +% 2. a list with the previous memory in reverse order +mem_instruction(next_addr, mem(Mb, [Caddr]), mem([Caddr|Mb], [0])). +mem_instruction(next_addr, mem(Mb, [Caddr,NextAddr|Rest]), mem([Caddr|Mb], [NextAddr|Rest])). +mem_instruction(prev_addr, mem([PrevAddr|RestOfPrev], Caddrs), mem(RestOfPrev, [PrevAddr|Caddrs])). + +% wrap instructions at the byte boundaries as this is what most programmers expect to happen +mem_instruction(inc_caddr, MemIn, MemOut) :- caddr(MemIn, 255), update_caddr(MemIn, 0, MemOut). +mem_instruction(inc_caddr, MemIn, MemOut) :- caddr(MemIn, Val), succ(Val, IncVal), update_caddr(MemIn, IncVal, MemOut). +mem_instruction(dec_caddr, MemIn, MemOut) :- caddr(MemIn, 0), update_caddr(MemIn, 255, MemOut). +mem_instruction(dec_caddr, MemIn, MemOut) :- caddr(MemIn, Val), succ(DecVal, Val), update_caddr(MemIn, DecVal, MemOut). + +% input and output +mem_instruction(out_caddr, Mem, Mem) :- caddr(Mem, Val), char_code(Char, Val), write(Char). +mem_instruction(in_caddr, MemIn, MemOut) :- + get_single_char(Code), + char_code(Char, Code), + write(Char), + map_input_code(Code,MappedCode), + update_caddr(MemIn, MappedCode, MemOut). + +% need to map the newline if it is not a proper newline character (system dependent). +map_input_code(13,10) :- nl. +map_input_code(C,C). + +% The value at the current address +caddr(mem(_, [Caddr]), Caddr). +caddr(mem(_, [Caddr,_|_]), Caddr). + +% The updated value at the current address +update_caddr(mem(BackMem, [_]), Caddr, mem(BackMem, [Caddr])). +update_caddr(mem(BackMem, [_,M|Mem]), Caddr, mem(BackMem, [Caddr,M|Mem])). + +% The next instruction, and remaining code +next_instruction([_], [], []). +next_instruction([_,NextI|Rest], NextI, [NextI|Rest]). diff --git a/Task/Execute-Brain----/ZX-Spectrum-Basic/execute-brain----.zx b/Task/Execute-Brain----/ZX-Spectrum-Basic/execute-brain----.zx new file mode 100644 index 0000000000..3507820112 --- /dev/null +++ b/Task/Execute-Brain----/ZX-Spectrum-Basic/execute-brain----.zx @@ -0,0 +1,34 @@ +10 GO SUB 1000 +20 LET e=LEN p$ +30 LET a$=p$(ip) +40 IF a$=">" THEN LET dp=dp+1 +50 IF a$="<" THEN LET dp=dp-1 +60 IF a$="+" THEN LET d(dp)=d(dp)+1 +70 IF a$="-" THEN LET d(dp)=d(dp)-1 +80 IF a$="." THEN PRINT CHR$ d(dp); +90 IF a$="," THEN INPUT d(dp) +100 IF a$="[" THEN GO SUB 500 +110 IF a$="]" THEN LET bp=bp-1: IF d(dp)<>0 THEN LET ip=b(bp)-1 +120 LET ip=ip+1 +130 IF ip>e THEN PRINT "eof": STOP +140 GO TO 30 + +499 REM match close +500 LET bc=1: REM bracket counter +510 FOR x=ip+1 TO e +520 IF p$(x)="[" THEN LET bc=bc+1 +530 IF p$(x)="]" THEN LET bc=bc-1 +540 IF bc=0 THEN LET b(bp)=ip: LET be=x: LET x=e: REM bc will be 0 once all the subnests have been counted over +550 IF bc=0 AND d(dp)=0 THEN LET ip=be: LET bp=bp-1 +560 NEXT x +570 LET bp=bp+1 +580 RETURN + +999 REM initialisation +1000 DIM d(100): REM data stack +1010 LET dp=1: REM data pointer +1020 LET ip=1: REM instruction pointer +1030 DIM b(30): REM bracket stack +1040 LET bp=1: REM bracket pointer +1050 LET p$="++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>+++++.": REM program, marginally modified from Wikipedia; outputs CHR$ 13 at the end instead of CHR$ 10 as ZX Spectrum Basic handles the carriage return better than the line feed +1060 RETURN diff --git a/Task/Execute-HQ9+/Julia/execute-hq9+.julia b/Task/Execute-HQ9+/Julia/execute-hq9+.julia new file mode 100644 index 0000000000..38b9719655 --- /dev/null +++ b/Task/Execute-HQ9+/Julia/execute-hq9+.julia @@ -0,0 +1,31 @@ +hello() = println("Hello, world!") +quine() = println(src) +bottles() = for i = 99:-1:1 print("\n$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") end +acc = 0 +incr() = global acc += 1 + +const dispatch = Dict( +'h' => hello, +'q' => quine, +'9' => bottles, +'+' => incr) + +if length(ARGS) < 1 + println("Usage: julia ./HQ9+.jl file.hq9") + exit(1) +else + file = ARGS[1] +end + +try + open(file) do s + global src = readstring(s) + end +catch + warning("can't open $file") + exit(1) +end + +for i in lowercase(src) + if haskey(dispatch, i) dispatch[i]() end +end diff --git a/Task/Execute-HQ9+/OCaml/execute-hq9+.ocaml b/Task/Execute-HQ9+/OCaml/execute-hq9+.ocaml new file mode 100644 index 0000000000..d7b5d58de6 --- /dev/null +++ b/Task/Execute-HQ9+/OCaml/execute-hq9+.ocaml @@ -0,0 +1,9 @@ +let hq9p line = + let accumulator = ref 0 in + for i = 0 to (String.length line - 1) do + match line.[i] with + | 'h' | 'H' -> print_endline "Hello, world!" + | 'q' | 'Q' -> print_endline line + | '9' -> beer 99 + | '+' -> incr accumulator + done diff --git a/Task/Execute-a-Markov-algorithm/Julia/execute-a-markov-algorithm-1.julia b/Task/Execute-a-Markov-algorithm/Julia/execute-a-markov-algorithm-1.julia new file mode 100644 index 0000000000..5c0f69bbff --- /dev/null +++ b/Task/Execute-a-Markov-algorithm/Julia/execute-a-markov-algorithm-1.julia @@ -0,0 +1,48 @@ +module MarkovAlgos + +struct MarkovRule{F,T} + patt::F + repl::T + term::Bool +end + +isterminating(r::MarkovRule) = r.term +Base.show(io::IO, rule::MarkovRule) = + print(io, rule.patt, " → ", isterminating(rule) ? "." : "", rule.repl) +function Base.convert(::Type{MarkovRule}, s::AbstractString) + rmatch = match(r"^(.+)\s+->\s*(\.)?(.*)?$", s) + if rmatch ≡ nothing || isempty(rmatch.captures) + throw(ParseError("not valid rule: " * s)) + end + patt, term, repl = rmatch.captures + return MarkovRule(patt, repl ≢ nothing ? repl : "", term ≢ nothing) +end + +function ruleset(file::Union{AbstractString,IO}) + ruleset = Vector{MarkovRule}(0) + for line in eachline(file) + ismatch(r"(^#|^\s*$)", line) || push!(ruleset, MarkovRule(line)) + end + return ruleset +end + +apply(text::AbstractString, rule::MarkovRule) = replace(text, rule.patt, rule.repl) +function apply(file::Union{AbstractString,IO}, ruleset::AbstractVector{<:MarkovRule}) + text = readstring(file) + redo = !isempty(text) + while redo + matchrule = false + for rule in ruleset + if contains(text, rule.patt) + matchrule = true + text = apply(text, rule) + redo = !isterminating(rule) + break + end + end + redo = redo && matchrule + end + return text +end + +end # module MarkovAlgos diff --git a/Task/Execute-a-Markov-algorithm/Julia/execute-a-markov-algorithm-2.julia b/Task/Execute-a-Markov-algorithm/Julia/execute-a-markov-algorithm-2.julia new file mode 100644 index 0000000000..55f91388af --- /dev/null +++ b/Task/Execute-a-Markov-algorithm/Julia/execute-a-markov-algorithm-2.julia @@ -0,0 +1,11 @@ +include("module.jl") + +let rulesets = @.("data/markovrules0" * string(1:5) * ".txt"), + ruletest = @.("data/markovtest0" * string(1:5) * ".txt") + for i in eachindex(rulesets, ruletest) + rules = MarkovAlgos.ruleset(rulesets[i]) + println("# Example n.$i") + println("Original:\n", readstring(ruletest[i])) + println("Transformed:\n", MarkovAlgos.apply(ruletest[i], rules)) + end +end diff --git a/Task/Execute-a-Markov-algorithm/Kotlin/execute-a-markov-algorithm.kotlin b/Task/Execute-a-Markov-algorithm/Kotlin/execute-a-markov-algorithm.kotlin new file mode 100644 index 0000000000..c5b8b883e4 --- /dev/null +++ b/Task/Execute-a-Markov-algorithm/Kotlin/execute-a-markov-algorithm.kotlin @@ -0,0 +1,44 @@ +// version 1.1.51 + +import java.io.File +import java.util.regex.Pattern + +/* rulesets assumed to be separated by a blank line in file */ +fun readRules(path: String): List> { + val ls = System.lineSeparator() + return File(path).readText().split("$ls$ls").map { it.split(ls) } +} + +/* tests assumed to be on consecutive lines */ +fun readTests(path: String) = File(path).readLines() + +fun main(args: Array) { + val rules = readRules("markov_rules.txt") + val tests = readTests("markov_tests.txt") + val pattern = Pattern.compile("^([^#]*?)\\s+->\\s+(\\.?)(.*)") + + for ((i, origTest) in tests.withIndex()) { + val captures = mutableListOf>() + for (rule in rules[i]) { + val m = pattern.matcher(rule) + if (m.find()) { + val groups = List(m.groupCount()) { m.group(it + 1) } + captures.add(groups) + } + } + var test = origTest + + do { + val copy = test + var redo = false + for (c in captures) { + test = test.replace(c[0], c[2]) + if (c[1] == ".") break + if (test != copy) { redo = true; break } + } + } + while (redo) + + println("$origTest\n$test\n") + } +} diff --git a/Task/Execute-a-Markov-algorithm/REXX/execute-a-markov-algorithm.rexx b/Task/Execute-a-Markov-algorithm/REXX/execute-a-markov-algorithm.rexx index 3028501b0a..50254f2a54 100644 --- a/Task/Execute-a-Markov-algorithm/REXX/execute-a-markov-algorithm.rexx +++ b/Task/Execute-a-Markov-algorithm/REXX/execute-a-markov-algorithm.rexx @@ -1,41 +1,42 @@ -/*REXX program executes a Markov algorithm(s) against specified entries. */ -parse arg low high . /*allows which ruleset to process. */ -if low=='' | low==',' then low=1 /*Not specified? Then use the default.*/ -if high=='' | high==',' then high=6 /* " " " " " " */ -tellE=low<0; tellR=high<0 /*flags: used to display file contents.*/ +/*REXX program executes a Markov algorithm(s) against specified entries. */ +parse arg low high . /*allows which ruleset to process. */ +if low=='' | low=="," then low=1 /*Not specified? Then use the default.*/ +if high=='' | high=="," then high=6 /* " " " " " " */ +tellE= low<0; tellR= high<0 /*flags: used to display file contents.*/ call readEntry - do j=abs(low) to abs(high) /*process each of these rulesets. */ - call readRules j /*read a particular ruleset. */ - call execRules j /*execute " " " */ - say 'result for ruleset' j"≡"!.j - end /*j*/ -exit /*stick a fork in it, we're all done. */ -/*────────────────────────────────────────────────────────────────────────────*/ -execRules: parse arg q .; if tellE | tellR then say /*a blank line*/ - do f=1 - do k=1 while @.k\==''; if left(@.k,1)=='#' | @.k='' then iterate - parse var @.k a ' ->' b; a=strip(a); b=strip(b) - fullstop= left(b,1)=='.' /*is this a "fullstop" rule? */ - if fullstop then b=substr(b,2) /*purify the B part of the rule. */ - old=!.q /*remember the value before the change.*/ - !.q=changestr(a, !.q, b) /*implement the ruleset change. */ - if fullstop then if old\==!.q then return /*should we stop? */ - if old\==!.q then iterate f /*Has Entry changed? Then start over.*/ - end /*k*/ - leave - end /*f*/ -return -/*────────────────────────────────────────────────────────────────────────────*/ -readRules: parse arg ? .; rFID='MARKOV_R.'?; if tellR then say -@.= /*placeholder for all the Markov rules.*/ - do r=1 while lines(rFID)\==0 /*read the input file until End-Of-File*/ - @.r=linein(rFID); if tellR then say 'ruleSet' ?"."left(r,4)'≡'@.r - end /*r*/ /*(above) read and maybe echo the rule.*/ -return -/*────────────────────────────────────────────────────────────────────────────*/ -readEntry: eFID='MARKOV.ENT'; if tellE then say -!.= /*placeholder for all the test entries.*/ - do e=1 while lines(eFID)\==0 /*read the input file until End-Of-File*/ - !.e=linein(eFID); if tellE then say 'test entry' e"≡"!.e - end /*e*/ /*(above) read and maybe echo the entry*/ -return + do j=abs(low) to abs(high) /*process each of these rulesets. */ + call readRules j /*read a particular ruleset. */ + call execRules j /*execute " " " */ + say 'result for ruleset' j "───►" !.j + end /*j*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +execRules: parse arg q .; if tellE | tellR then say /*show a blank line?*/ + do f=1 + do k=1 while @.k\==''; if left(@.k, 1)=='#' | @.k='' then iterate + parse var @.k a ' ->' b /*obtain the A & B parts from rule.*/ + a=strip(a); b=strip(b) /*strip leading and/or trailing blanks.*/ + fullstop= left(b, 1)==. /*is this a "fullstop" rule? 1≡yes */ + if fullstop then b=substr(b, 2) /*purify the B part of the rule. */ + old=!.q /*remember the value before the change.*/ + !.q=changestr(a, !.q, b) /*implement the ruleset change. */ + if fullstop then if old\==!.q then return /*should we stop? */ + if old\==!.q then iterate f /*Has Entry changed? Then start over.*/ + end /*k*/ + return + end /*f*/ + return +/*──────────────────────────────────────────────────────────────────────────────────────*/ +readEntry: eFID= 'MARKOV.ENT'; if tellE then say /*show a blank line?*/ + !.= /*placeholder for all the test entries.*/ + do e=1 while lines(eFID)\==0 /*read the input file until End-Of-File*/ + !.e=linein(eFID); if tellE then say 'test entry' e "───►" !.e + end /*e*/ /* [↑] read and maybe echo the entry. */ + return +/*──────────────────────────────────────────────────────────────────────────────────────*/ +readRules: parse arg ? .; rFID= 'MARKOV_R.'?; if tellR then say /*show a blank line?*/ + @.= /*placeholder for all the Markov rules.*/ + do r=1 while lines(rFID)\==0 /*read the input file until End-Of-File*/ + @.r=linein(rFID); if tellR then say 'ruleSet' ?"."left(r,4) '───►' @.r + end /*r*/ /* [↑] read and maybe echo the rule. */ + return diff --git a/Task/Execute-a-system-command/Aime/execute-a-system-command.aime b/Task/Execute-a-system-command/Aime/execute-a-system-command.aime index 72ef92dbdc..2d8b14a8e8 100644 --- a/Task/Execute-a-system-command/Aime/execute-a-system-command.aime +++ b/Task/Execute-a-system-command/Aime/execute-a-system-command.aime @@ -1,7 +1,5 @@ sshell ss; -b_cast(ss_path(ss), "/bin/ls"); +ss.argv.insert("ls"); -lf_p_text(ss_argv(ss), "ls"); - -o_text(ss_link(ss)); +o_(ss.link); diff --git a/Task/Execute-a-system-command/HolyC/execute-a-system-command.holyc b/Task/Execute-a-system-command/HolyC/execute-a-system-command.holyc new file mode 100644 index 0000000000..9e18fc2ad6 --- /dev/null +++ b/Task/Execute-a-system-command/HolyC/execute-a-system-command.holyc @@ -0,0 +1 @@ +Dir; diff --git a/Task/Execute-a-system-command/Red/execute-a-system-command.red b/Task/Execute-a-system-command/Red/execute-a-system-command.red new file mode 100644 index 0000000000..da9e4e486e --- /dev/null +++ b/Task/Execute-a-system-command/Red/execute-a-system-command.red @@ -0,0 +1,3 @@ +call/show %pause ;The /show refinement forces the display of system's shell window (Windows only). +call/show %dir +call/show %notepad.exe diff --git a/Task/Execute-a-system-command/Stata/execute-a-system-command.stata b/Task/Execute-a-system-command/Stata/execute-a-system-command.stata index 3a75c1f778..121ab268f3 100644 --- a/Task/Execute-a-system-command/Stata/execute-a-system-command.stata +++ b/Task/Execute-a-system-command/Stata/execute-a-system-command.stata @@ -1,7 +1,7 @@ !dir * print a message and wait -!echo Ars Longa Vita Brevis && pause +!echo Ars Longa Vita Brevis & pause * load Excel from Stata !start excel diff --git a/Task/Exponentiation-operator/Perl-6/exponentiation-operator.pl6 b/Task/Exponentiation-operator/Perl-6/exponentiation-operator.pl6 new file mode 100644 index 0000000000..d5f87c4782 --- /dev/null +++ b/Task/Exponentiation-operator/Perl-6/exponentiation-operator.pl6 @@ -0,0 +1,12 @@ +subset Natural of Int where { $^n >= 0 } + +multi pow (0, 0) { fail '0**0 is undefined' } +multi pow ($base, Natural $exp) { [*] $base xx $exp } +multi pow ($base, Int $exp) { 1 / pow $base, -$exp } + +sub infix:<***> ($a, $b) { pow $a, $b } + +# Testing + +say pow .75, -5; +say .75 *** -5; diff --git a/Task/Exponentiation-operator/Stata/exponentiation-operator.stata b/Task/Exponentiation-operator/Stata/exponentiation-operator.stata new file mode 100644 index 0000000000..90ebd4780d --- /dev/null +++ b/Task/Exponentiation-operator/Stata/exponentiation-operator.stata @@ -0,0 +1,10 @@ +mata +function pow(a, n) { + x = a + for(p=1; n>0; n=floor(n/2)) { + if(mod(n,2)==1) p = p*x + x = x*x + } + return(p) +} +end diff --git a/Task/Extend-your-language/ABAP/extend-your-language.abap b/Task/Extend-your-language/ABAP/extend-your-language.abap new file mode 100644 index 0000000000..814c3057ab --- /dev/null +++ b/Task/Extend-your-language/ABAP/extend-your-language.abap @@ -0,0 +1,4 @@ +DATA(result) = COND #( WHEN condition1istrue = abap_true AND condition2istrue = abap_true THEN bothconditionsaretrue + WHEN condition1istrue = abap_true THEN firstconditionistrue + WHEN condition2istrue = abap_true THEN secondconditionistrue + ELSE noconditionistrue ). diff --git a/Task/Extend-your-language/DUP/extend-your-language-1.dup b/Task/Extend-your-language/DUP/extend-your-language-1.dup new file mode 100644 index 0000000000..0679643a73 --- /dev/null +++ b/Task/Extend-your-language/DUP/extend-your-language-1.dup @@ -0,0 +1,4 @@ +{two-conditional if operator implementation} +{ [ top cond. = true ][ top cond. = false ]} +{ [ 2nd = true ][2nd = false ] [ 2nd = true ][ 2nd = false] } +[(((([[)))!)))%%%%%][)))))!)%%%%%]?][[))))!))%%%%%][))))))!%%%%%]?]?]⇒¿ diff --git a/Task/Extend-your-language/DUP/extend-your-language-2.dup b/Task/Extend-your-language/DUP/extend-your-language-2.dup new file mode 100644 index 0000000000..d075cca669 --- /dev/null +++ b/Task/Extend-your-language/DUP/extend-your-language-2.dup @@ -0,0 +1 @@ +0 1_['t,'t,]['t,'f,]['f,'t,]['f,'f,]¿ diff --git a/Task/Extend-your-language/Fortran/extend-your-language-1.f b/Task/Extend-your-language/Fortran/extend-your-language-1.f new file mode 100644 index 0000000000..28cb831c6c --- /dev/null +++ b/Task/Extend-your-language/Fortran/extend-your-language-1.f @@ -0,0 +1,51 @@ + LOGICAL A,B !These are allocated the same storage + INTEGER IA,IB !As the default integer size. + EQUIVALENCE (IA,A),(IB,B) !So, this will cause no overlaps. + + WRITE (6,*) "Boolean tests via integers..." + DO 199 IA = 0,1 !Two states for A. + DO 199 IB = 0,1 !Two states for B. + IF (IA) 666,99,109 !Not four ways, just three. + 99 IF (IB) 666,100,101 !Negative values are surely wrong. + 100 WRITE (6,*) "FF",IA,IB + GO TO 199 + 101 WRITE (6,*) "FT",IA,IB + GO TO 199 + 109 IF (IB) 666,110,111 !A second test. + 110 WRITE (6,*) "TF",IA,IB + GO TO 199 + 111 WRITE (6,*) "TT",IA,IB + 199 CONTINUE !Both loops finish here. + + WRITE (6,*) "Boolean tests via integers and computed GO TO..." + DO 299 IA = 0,1 !Two states for A. + DO 299 IB = 0,1 !Two states for B. + GO TO (200,201,210,211) 1 + IA*2 + IB !Counting starts with one. + 200 WRITE (6,*) "FF",IA,IB + GO TO 299 + 201 WRITE (6,*) "FT",IA,IB + GO TO 299 + 210 WRITE (6,*) "TF",IA,IB + GO TO 299 + 211 WRITE (6,*) "TT",IA,IB + 299 CONTINUE !Both loops finish here. + + 300 WRITE (6,301) + 301 FORMAT (/,"Boolean tests via LOGICAL variables...",/ + 1 " AB IA IB (IA*2 + IB)") + A = .TRUE. !Syncopation. + B = .TRUE. !Via the .NOT., the first pair will be FF. + DO I = 0,1 !Step through two states. + A = .NOT.A !Thus generate F then T. + DO J = 0,1 !Step through the second two states. + B = .NOT.B !Thus generate FF, FT, TF, TT. + WRITE (6,302) A,B,IA,IB,IA*2 + IB !But with strange values. + 302 FORMAT (1X,2L1,2I6,I8) !Show both types. + END DO !Next value for B. + END DO !Next value for A. + GO TO 999 + + 666 WRITE (6,*) "Huh?" + + 999 CONTINUE + END diff --git a/Task/Extend-your-language/Fortran/extend-your-language-2.f b/Task/Extend-your-language/Fortran/extend-your-language-2.f new file mode 100644 index 0000000000..9c8e947eb3 --- /dev/null +++ b/Task/Extend-your-language/Fortran/extend-your-language-2.f @@ -0,0 +1,6 @@ + INTEGER FUNCTION IF2(A,B) !Combine two LOGICAL variables. + LOGICAL A,B !These. + IF2 = 0 !Wasted effort if A is true. + IF (A) IF2 = 2 !But it avoids IF ... THEN ... ELSE ... END IF blather. + IF (B) IF2 = IF2 + 1 !This relies on IF2 being a variable. (Standard in F90+) + END FUNCTION IF2 !Thus produce a four-way result. diff --git a/Task/Extend-your-language/Fortran/extend-your-language-3.f b/Task/Extend-your-language/Fortran/extend-your-language-3.f new file mode 100644 index 0000000000..24fe391db5 --- /dev/null +++ b/Task/Extend-your-language/Fortran/extend-your-language-3.f @@ -0,0 +1,6 @@ + SELECT CASE(IF2(A,B)) + CASE(B"00"); WRITE (6,*) "Both false." + CASE(B"01"); WRITE (6,*) "B only." + CASE(B"10"); WRITE (6,*) "A only." + CASE(B"11"); WRITE (6,*) "Both true." + END SELECT diff --git a/Task/Extend-your-language/Go/extend-your-language.go b/Task/Extend-your-language/Go/extend-your-language.go new file mode 100644 index 0000000000..4a8e4ed598 --- /dev/null +++ b/Task/Extend-your-language/Go/extend-your-language.go @@ -0,0 +1,58 @@ +package main + +import "fmt" + +type F func() + +type If2 struct {cond1, cond2 bool} + +func (i If2) else1(f F) If2 { + if i.cond1 && !i.cond2 { + f() + } + return i +} + +func (i If2) else2(f F) If2 { + if i.cond2 && !i.cond1 { + f() + } + return i +} + +func (i If2) else0(f F) If2 { + if !i.cond1 && !i.cond2 { + f() + } + return i +} + +func if2(cond1, cond2 bool, f F) If2 { + if cond1 && cond2 { + f() + } + return If2{cond1, cond2} +} + +func main() { + a, b := 0, 1 + if2 (a == 1, b == 3, func() { + fmt.Println("a = 1 and b = 3") + }).else1 (func() { + fmt.Println("a = 1 and b <> 3") + }).else2 (func() { + fmt.Println("a <> 1 and b = 3") + }).else0 (func() { + fmt.Println("a <> 1 and b <> 3") + }) + + // It's also possible to omit any (or all) of the 'else' clauses or to call them out of order + a, b = 1, 0 + if2 (a == 1, b == 3, func() { + fmt.Println("a = 1 and b = 3") + }).else0 (func() { + fmt.Println("a <> 1 and b <> 3") + }).else1 (func() { + fmt.Println("a = 1 and b <> 3") + }) +} diff --git a/Task/Extend-your-language/Idris/extend-your-language.idris b/Task/Extend-your-language/Idris/extend-your-language.idris new file mode 100644 index 0000000000..6ce9d8f453 --- /dev/null +++ b/Task/Extend-your-language/Idris/extend-your-language.idris @@ -0,0 +1,5 @@ +if2 : Bool -> Bool -> Lazy a -> Lazy a -> Lazy a -> Lazy a -> a +if2 True True v _ _ _ = v +if2 True False _ v _ _ = v +if2 False True _ _ v _ = v +if2 _ _ _ _ _ v = v diff --git a/Task/Extend-your-language/Ring/extend-your-language.ring b/Task/Extend-your-language/Ring/extend-your-language.ring new file mode 100644 index 0000000000..035a5c410c --- /dev/null +++ b/Task/Extend-your-language/Ring/extend-your-language.ring @@ -0,0 +1,26 @@ +# Project : Extend your language +# Date : 2017/11/15 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +see "a = 1, b = 1 => " +test(1, 1) +see "a = 1, b = 0 => " +test(1, 0) +see "a = 0, b = 1 => " +test(0, 1) +see "a = 0, b = 0 => " +test(0, 0) +see nl + +func test(a,b) + if a > 0 and b > 0 + see "both positive" + but a > 0 + see "first positive" + but b > 0 + see "second positive" + but a < 1 and b < 1 + see "neither positive" + ok + see nl diff --git a/Task/Extensible-prime-generator/Julia/extensible-prime-generator.julia b/Task/Extensible-prime-generator/Julia/extensible-prime-generator.julia new file mode 100644 index 0000000000..ddd6fef31a --- /dev/null +++ b/Task/Extensible-prime-generator/Julia/extensible-prime-generator.julia @@ -0,0 +1,21 @@ +using Primes + +sum = 2 +currentprime = 2 +for i in 2:100000 + currentprime = nextprime(currentprime + 1) + sum += currentprime +end +println("The sum of the first 100,000 primes is $sum") + +curprime = 1 +arr = zeros(Int, 20) +for i in 1:20 + curprime = nextprime(curprime + 1) + arr[i] = curprime +end +println("The first 20 primes are ", arr) + +println("the primes between 100 and 150 are ", primes(100,150)) +println("The number of primes between 7,700 and 8,000 is ", length(primes(7700, 8000))) +println("The 10,000th prime is ", prime(10000)) diff --git a/Task/Extensible-prime-generator/Lingo/extensible-prime-generator-1.lingo b/Task/Extensible-prime-generator/Lingo/extensible-prime-generator-1.lingo new file mode 100644 index 0000000000..8569a98324 --- /dev/null +++ b/Task/Extensible-prime-generator/Lingo/extensible-prime-generator-1.lingo @@ -0,0 +1,105 @@ +-- parent script "sieve" +property _sieve + +---------------------------------------- +-- @constructor +---------------------------------------- +on new (me) + me._sieve = [] + me._primeSieve(100) -- arbitrary initial size of sieve + return me +end + +---------------------------------------- +-- Returns sorted list of first n primes p with p >= a (default: a=1) +---------------------------------------- +on getNPrimes (me, n, a) + if voidP(a) then a = 1 + i = a + res = [] + repeat while TRUE + if i>me._sieve.count then me._primeSieve(2*i) + if me._sieve[i] then res.add(i) + if res.count=n then return res + i = i +1 + end repeat +end + +---------------------------------------- +-- Returns sorted list of primes p with a <= p <= b +---------------------------------------- +on getPrimesInRange (me, a, b) + if me._sieve.countme._sieve.count then me._primeSieve(2*i) + if me._sieve[i] then found=found+1 + if found=n then return i + end repeat +end + +---------------------------------------- +-- Sieve of Eratosthenes +---------------------------------------- +on _primeSieve (me, limit) + if me._sieve.count>=limit then + return + else if me._sieve.count>0 then + return me._complementSieve(limit) + end if + me._sieve = [0] + repeat with i = 2 to limit + me._sieve[i] = 1 + end repeat + c = sqrt(limit) + repeat with i = 2 to c + if (me._sieve[i]=0) then next repeat + j = i*i + repeat while (j<=limit) + me._sieve[j] = 0 + j = j + i + end repeat + end repeat +end + +---------------------------------------- +-- Expands existing sieve to new limit +---------------------------------------- +on _complementSieve (me, n) + n1 = me._sieve.count + repeat with i = n1+1 to n + me._sieve[i] = 1 + end repeat + c1 = sqrt(n1) + repeat with i = 2 to c1 + if (me._sieve[i]=0) then next repeat + j = n1 - (n1 mod i) + repeat while (j<=n) + me._sieve[j] = 0 + j = j + i + end repeat + end repeat + c = sqrt(n) + repeat with i = c1+1 to c + if (me._sieve[i]=0) then next repeat + j = i*i + repeat while (j<=n) + me._sieve[j] = 0 + j = j + i + end repeat + end repeat +end diff --git a/Task/Extensible-prime-generator/Lingo/extensible-prime-generator-2.lingo b/Task/Extensible-prime-generator/Lingo/extensible-prime-generator-2.lingo new file mode 100644 index 0000000000..5fc8b471ac --- /dev/null +++ b/Task/Extensible-prime-generator/Lingo/extensible-prime-generator-2.lingo @@ -0,0 +1,5 @@ +sieve = script("sieve").new() +put "First twenty primes: " & sieve.getNPrimes(20) +put "Primes between 100 and 150: "& sieve.getPrimesInRange(100, 150) +put "Number of primes between 7,700 and 8,000: " & sieve.getPrimesInRange(7700, 8000).count +put "The 10,000th prime: " & sieve.getNthPrime(10000) diff --git a/Task/Extensible-prime-generator/PicoLisp/extensible-prime-generator.l b/Task/Extensible-prime-generator/PicoLisp/extensible-prime-generator.l new file mode 100644 index 0000000000..8018521d63 --- /dev/null +++ b/Task/Extensible-prime-generator/PicoLisp/extensible-prime-generator.l @@ -0,0 +1,37 @@ +(de prime? (N Lst) + (let S (sqrt N) + (for D Lst + (T (> D S) T) + (T (=0 (% N D)) NIL) ) ) ) +(de primeseq (A B) + (let (I 1 R) + (nth + (make + (link 2) + (while (> A (inc 'I 2)) + (and (prime? I (made)) (link I)) ) + (setq R (length (made))) + (while (> B I) + (and (prime? I (made)) (link I)) + (inc 'I 2) ) ) + (inc R) ) ) ) +(de take (N) + (let I 1 + (make + (link 2) + (do (dec N) + (until (prime? (inc 'I 2) (made))) + (link I) ) ) ) ) + +(prin "First 20 primes: ") +(println (take 20)) +(prin "Primes between 100 and 150: ") +(println (primeseq 100 150)) +(prinl + "Number of primes between 7700 and 8000: " + (length (primeseq 7700 8000)) ) +(for N (10 100 1000 10000 100000 1000000) + (prinl + N + "th prime: " + (last (take N)) ) ) diff --git a/Task/Extensible-prime-generator/VBA/extensible-prime-generator.vba b/Task/Extensible-prime-generator/VBA/extensible-prime-generator.vba new file mode 100644 index 0000000000..1c99c4a819 --- /dev/null +++ b/Task/Extensible-prime-generator/VBA/extensible-prime-generator.vba @@ -0,0 +1,74 @@ +Option Explicit + +Sub Main() +Dim Primes() As Long, n As Long, temp$ +Dim t As Single + t = Timer + + n = 133218295 'limit for an Array of Longs with VBA on my computer + Primes = ListPrimes(n) + Debug.Print "For N = " & Format(n, "#,##0") & ", execution time : " & _ + Format(Timer - t, "0.000 s") & ", " & _ + Format(UBound(Primes) + 1, "#,##0") & " primes numbers." + + 'First twenty primes + For n = 0 To 19 + temp = temp & ", " & Primes(n) + Next + Debug.Print "First twenty primes : "; Mid(temp, 3) + 'Primes between 100 and 150 + n = 0: temp = vbNullString + Do While Primes(n) < 100 + n = n + 1 + Loop + Do While Primes(n) < 150 + temp = temp & ", " & Primes(n) + n = n + 1 + Loop + Debug.Print "Primes between 100 and 150 : " & Mid(temp, 3) + 'Number of primes between 7,700 and 8,000 + Dim ccount As Long + n = 0 + Do While Primes(n) < 7700 + n = n + 1 + Loop + Do While Primes(n) < 8000 + ccount = ccount + 1 + n = n + 1 + Loop + Debug.Print "Number of primes between 7,700 and 8,000 : " & ccount + 'The 10 x Xth prime + n = 1 + Do While n <= 100000 + n = n * 10 + Debug.Print "The " & n & "th prime: "; Format(Primes(n - 1), "#,##0") + Loop + Debug.Print "VBA has a limit in array's dim" + Debug.Print "With my computer, the limit for an array of Long is : 133 218 295" + Debug.Print "The last prime I could find is the : " & _ + Format(UBound(Primes), "#,##0") & "th, Value : " & _ + Format(Primes(UBound(Primes)), "#,##0") +End Sub + +Function ListPrimes(MAX As Long) As Long() +Dim t() As Boolean, L() As Long, c As Long, s As Long, i As Long, j As Long + ReDim t(2 To MAX) + ReDim L(MAX \ 2) + s = Sqr(MAX) + For i = 3 To s Step 2 + If t(i) = False Then + For j = i * i To MAX Step i + t(j) = True + Next + End If + Next i + L(0) = 2 + For i = 3 To MAX Step 2 + If t(i) = False Then + c = c + 1 + L(c) = i + End If + Next i + ReDim Preserve L(c) + ListPrimes = L +End Function diff --git a/Task/Extreme-floating-point-values/Factor/extreme-floating-point-values.factor b/Task/Extreme-floating-point-values/Factor/extreme-floating-point-values.factor new file mode 100644 index 0000000000..ee0603e4e3 --- /dev/null +++ b/Task/Extreme-floating-point-values/Factor/extreme-floating-point-values.factor @@ -0,0 +1,12 @@ +-0. . ! -0.0 literal negative zero + 0. neg . ! -0.0 neg works with floating point zeros + 0. -1. * . ! -0.0 calculating negative zero + 1/0. . ! 1/0. literal positive infinity + 1e3 1e3 ^ . ! 1/0. calculating positive infinity +-1/0. . ! -1/0. literal negative infinity +-1. 1e3 1e3 ^ * . ! -1/0. calculating negative infinity +-1/0. neg . ! 1/0. neg works with the inifinites + 0/0. . ! NAN: 8000000000000 literal NaN, configurable with + ! arbitrary 64-bit hex payload + 1/0. 1/0. - . ! NAN: 8000000000000 calculating NaN by subtracting + ! infinity from infinity diff --git a/Task/Extreme-floating-point-values/Perl-6/extreme-floating-point-values.pl6 b/Task/Extreme-floating-point-values/Perl-6/extreme-floating-point-values.pl6 index 6249ed2b4e..355cb0dbb2 100644 --- a/Task/Extreme-floating-point-values/Perl-6/extreme-floating-point-values.pl6 +++ b/Task/Extreme-floating-point-values/Perl-6/extreme-floating-point-values.pl6 @@ -1,12 +1,14 @@ print qq:to 'END' -positive infinity: {1e309} -negative infinity: {-1e309} +positive infinity: {1.8e308} +negative infinity: {-1.8e308} negative zero: {0e0 * -1} not a number: {0 * 1e309} +Inf + 2.0 = {Inf + 2} +Inf - 10.1 = {Inf - 10.1} -+Inf + -Inf = {Inf + -Inf} 0 * +Inf = {0 * Inf} ++Inf + -Inf = {Inf + -Inf} ++Inf == -Inf = {+Inf == -Inf} +(-Inf+0i)**.5 = {(-Inf+0i)**.5} NaN + 1.0 = {NaN + 1.0} NaN + NaN = {NaN + NaN} NaN == NaN = {NaN == NaN} diff --git a/Task/Extreme-floating-point-values/REXX/extreme-floating-point-values.rexx b/Task/Extreme-floating-point-values/REXX/extreme-floating-point-values.rexx new file mode 100644 index 0000000000..fe9adcbd1d --- /dev/null +++ b/Task/Extreme-floating-point-values/REXX/extreme-floating-point-values.rexx @@ -0,0 +1,31 @@ +/*REXX pgm shows smallest & largest positive numbers that can be expressed, compares 0's*/ +parse version v; say 'version=' v; say + zero= '0.0' /*a (positive) value for zero. */ +negZero= '-0.0' /*" negative " " " */ +say 'value of zero equals negZero: ' word('no yes', 1 + (zero = negZero) ) +say 'value of zero exactly equals negZero: ' word('no yes', 1 + (zero == negZero) ) +say + do digs=20 by 20 to 100; numeric digits digs /*use a range of digits. */ + say center(' number of decimal digits being used:' digs" ", 79, '═') + say 'tiny=' tiny() + say 'huge=' huge() + end /*j*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +tiny: return $xnum('1e-') +huge: return $xnum('.'copies(9, digits() )"e+") +/*──────────────────────────────────────────────────────────────────────────────────────*/ +$xnum: procedure; parse arg $ /*use the given mantissa value.*/ + !=10 /*use starting exponent value.*/ + do forever; _=$ || ! /*construct a REXX decimal num.*/ + if \datatype(_, 'N') then leave /*Not numeric? Then leave. */ + p=!; !=! * 10 /*save number; magnify mantissa*/ + end /*forever*/ + j=! % 2 /*halve the exponent (power). */ + do forever; _=$ || ! /* [+] Not numeric? Halve it.*/ + if \datatype(_, 'N') then do; !=p; j=j % 2 + if j==0 then leave + end + p=!; !=! + j /*save number; bump mantissa. */ + end /*forever*/ + return $ || ! diff --git a/Task/Extreme-floating-point-values/Ruby/extreme-floating-point-values.rb b/Task/Extreme-floating-point-values/Ruby/extreme-floating-point-values.rb index fc0523c24a..9fd0dec25d 100644 --- a/Task/Extreme-floating-point-values/Ruby/extreme-floating-point-values.rb +++ b/Task/Extreme-floating-point-values/Ruby/extreme-floating-point-values.rb @@ -1,5 +1,5 @@ -inf = 1.0 / 0.0 #=> Infinity -nan = 0.0 / 0.0 #=> NaN +inf = 1.0 / 0.0 # or Float::INFINITY +nan = 0.0 / 0.0 # or Float::NAN expression = [ "1.0 / 0.0", "-1.0 / 0.0", "0.0 / 0.0", "- 0.0", diff --git a/Task/Extreme-floating-point-values/Sidef/extreme-floating-point-values.sidef b/Task/Extreme-floating-point-values/Sidef/extreme-floating-point-values.sidef index b996116385..52131d4018 100644 --- a/Task/Extreme-floating-point-values/Sidef/extreme-floating-point-values.sidef +++ b/Task/Extreme-floating-point-values/Sidef/extreme-floating-point-values.sidef @@ -1,5 +1,5 @@ -var inf = (1 / 0) #=> Inf -var nan = (0 / 0) #=> NaN +var inf = 1/0 # same as: Inf +var nan = 0/0 # same as: NaN var exprs = [ "1.0 / 0.0", "-1.0 / 0.0", "0.0 / 0.0", "- 0.0", @@ -15,16 +15,16 @@ exprs.each { |expr| } say "-"*40 -say("NaN equality: ", NaN == nan) #=> true -say("Infinity equality: ", Inf == inf) #=> true -say("-Infinity equality: ", -Inf == -inf) #=> true +say("NaN equality: ", NaN == nan) +say("Infinity equality: ", Inf == inf) +say("-Infinity equality: ", -Inf == -inf) say "-"*40 -say("sqrt(-1) = ", sqrt(-1)); #=> i -say("tanh(-Inf) = ", tanh(-inf)); #=> -1 -say("(-Inf)**2 = ", (-inf)**2); #=> Inf -say("(-Inf)**3 = ", (-inf)**3); #=> -Inf -say("acos(Inf) = ", acos(inf)); #=> Inf*i -say("atan(Inf) = ", atan(inf)); #=> pi/2 -say("log(-1) = ", log(-1)); #=> pi*i -say("atanh(Inf) = ", atanh(inf)); #=> -pi/2*i +say("sqrt(-1) = ", sqrt(-1)) +say("tanh(-Inf) = ", tanh(-inf)) +say("(-Inf)**2 = ", (-inf)**2) +say("(-Inf)**3 = ", (-inf)**3) +say("acos(Inf) = ", acos(inf)) +say("atan(Inf) = ", atan(inf)) +say("log(-1) = ", log(-1)) +say("atanh(Inf) = ", atanh(inf)) diff --git a/Task/Factorial/00DESCRIPTION b/Task/Factorial/00DESCRIPTION index 3f49c6dda1..4e1e14b7f0 100644 --- a/Task/Factorial/00DESCRIPTION +++ b/Task/Factorial/00DESCRIPTION @@ -10,4 +10,8 @@ Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   ''n''   errors is optional. + + +;Related task: +*   [[Primorial numbers]]

diff --git a/Task/Factorial/C/factorial-2.c b/Task/Factorial/C/factorial-2.c index 8c6f303e63..79bf574bdd 100644 --- a/Task/Factorial/C/factorial-2.c +++ b/Task/Factorial/C/factorial-2.c @@ -1,3 +1,8 @@ -int factorial(int n) { - return n == 0 ? 1 : n * factorial(n - 1); +int factorialSafe(int n) { + int result = 1; + if(n<0) + return -1; + for (int i = 1; i <= n; ++i) + result *= i; + return result; } diff --git a/Task/Factorial/C/factorial-3.c b/Task/Factorial/C/factorial-3.c index 83a84276be..8c6f303e63 100644 --- a/Task/Factorial/C/factorial-3.c +++ b/Task/Factorial/C/factorial-3.c @@ -1,7 +1,3 @@ -int fac_aux(int n, int acc) { - return n < 1 ? acc : fac_aux(n - 1, acc * n); -} - int factorial(int n) { - return fac_aux(n, 1); + return n == 0 ? 1 : n * factorial(n - 1); } diff --git a/Task/Factorial/C/factorial-4.c b/Task/Factorial/C/factorial-4.c new file mode 100644 index 0000000000..fdf39231d2 --- /dev/null +++ b/Task/Factorial/C/factorial-4.c @@ -0,0 +1,3 @@ +int factorialSafe(int n) { + return n<0 ? -1 : n == 0 ? 1 : n * factorialSafe(n - 1); +} diff --git a/Task/Factorial/C/factorial-5.c b/Task/Factorial/C/factorial-5.c new file mode 100644 index 0000000000..e5bea4948c --- /dev/null +++ b/Task/Factorial/C/factorial-5.c @@ -0,0 +1,13 @@ +int fac_aux(int n, int acc) { + return n < 1 ? acc : fac_aux(n - 1, acc * n); +} + +/*Handles negative n, Abhishek Ghosh, 1st November 2017*/ + +int fac_auxSafe(int n, int acc) { + return n<0 ? -1 : n < 1 ? acc : fac_aux(n - 1, acc * n); +} + +int factorial(int n) { + return fac_aux(n, 1); +} diff --git a/Task/Factorial/C/factorial-6.c b/Task/Factorial/C/factorial-6.c new file mode 100644 index 0000000000..e3d50054e8 --- /dev/null +++ b/Task/Factorial/C/factorial-6.c @@ -0,0 +1,41 @@ +#include + +#define l11l 0xFFFF +#define ll1 for +#define ll111 if +#define l1l1 unsigned +#define l111 struct +#define lll11 short +#define ll11l long +#define ll1ll putchar +#define l1l1l(l) l=malloc(sizeof(l111 llll1));l->lll1l=1-1;l->ll1l1=1-1; +#define l1ll1 *lllll++=l1ll%10000;l1ll/=10000; +#define l1lll ll111(!l1->lll1l){l1l1l(l1->lll1l);l1->lll1l->ll1l1=l1;}\ +lllll=(l1=l1->lll1l)->lll;ll=1-1; +#define llll 1000 + + + + + l111 llll1 { + l111 llll1 * + lll1l,*ll1l1 ;l1l1 lll11 lll [ + llll];};main (){l111 llll1 *ll11,*l1l,* + l1, *ll1l, * malloc ( ) ; l1l1 ll11l l1ll ; + ll11l l11,ll ,l;l1l1 lll11 *lll1,* lllll; ll1(l + =1-1 ;l< 14; ll1ll("\t\"8)>l\"9!.)>vl" [l]^'L'),++l + );scanf("%d",&l);l1l1l(l1l) l1l1l(ll11 ) (l1=l1l)-> + lll[l1l->lll[1-1] =1]=l11l;ll1(l11 =1+1;l11<=l; + ++l11){l1=ll11; lll1 = (ll1l=( ll11=l1l))-> + lll; lllll =( l1l=l1)->lll; ll=(l1ll=1-1 + );ll1(;ll1l-> lll1l||l11l!= *lll1;){l1ll + +=l11**lll1++ ;l1ll1 ll111 (++ll>llll){ + l1lll lll1=( ll1l =ll1l-> lll1l)->lll; + }}ll1(;l1ll; ){l1ll1 ll111 (++ll>=llll) + { l1lll} } * lllll=l11l;} + ll1(l=(ll=1- 1);(llll[ l] !=l11l);++l); ll1 (;l1;l1= + l1->ll1l1,l= llll){ll1(--l ;l>=1-1;--l, + ++ll)printf( (ll)?((ll%19) ?"%04d":(ll= + 19,"\n%04d") ):"%4d",l1-> lll[l] ) ; } + ll1ll(10); } diff --git a/Task/Factorial/Common-Lisp/factorial-4.lisp b/Task/Factorial/Common-Lisp/factorial-4.lisp new file mode 100644 index 0000000000..aa6aa80cf3 --- /dev/null +++ b/Task/Factorial/Common-Lisp/factorial-4.lisp @@ -0,0 +1,10 @@ +;; Project : Factorial +;; Date : 2018/03/09 +;; Author : Gal Zsolt [~ CalmoSoft ~] +;; Email : + +(defun factorial (n) + (cond ((= n 1) 1) + (t (* n (factorial (- n 1)))))) +(format t "~a" "factorial of 8: ") +(factorial 8) diff --git a/Task/Factorial/Elm/factorial.elm b/Task/Factorial/Elm/factorial-1.elm similarity index 100% rename from Task/Factorial/Elm/factorial.elm rename to Task/Factorial/Elm/factorial-1.elm diff --git a/Task/Factorial/Elm/factorial-2.elm b/Task/Factorial/Elm/factorial-2.elm new file mode 100644 index 0000000000..4c0bbf2132 --- /dev/null +++ b/Task/Factorial/Elm/factorial-2.elm @@ -0,0 +1,7 @@ +factorialAux : Int -> Int -> Int +factorialAux a acc = + if a < 2 then acc else factorialAux (a - 1) (a * acc) + +factorial : Int -> Int +factorial a = + factorialAux a 1 diff --git a/Task/Factorial/Elm/factorial-3.elm b/Task/Factorial/Elm/factorial-3.elm new file mode 100644 index 0000000000..fb76dde84a --- /dev/null +++ b/Task/Factorial/Elm/factorial-3.elm @@ -0,0 +1,5 @@ +import List exposing (product, range) + +factorial : Int -> Int +factorial a = + product (range 1 a) diff --git a/Task/Factorial/Go/factorial-3.go b/Task/Factorial/Go/factorial-3.go new file mode 100644 index 0000000000..36497369ba --- /dev/null +++ b/Task/Factorial/Go/factorial-3.go @@ -0,0 +1,17 @@ +package main + +import ( + "fmt" + "math" +) + +func factorial(n float64) float64 { + return math.Gamma(n + 1) +} + +func main() { + for i := 0.; i <= 10; i++ { + fmt.Println(i, factorial(i)) + } + fmt.Println(100, factorial(100)) +} diff --git a/Task/Factorial/Go/factorial-4.go b/Task/Factorial/Go/factorial-4.go new file mode 100644 index 0000000000..6ca4957abd --- /dev/null +++ b/Task/Factorial/Go/factorial-4.go @@ -0,0 +1,26 @@ +package main + +import ( + "fmt" + "math" + "math/big" +) + +func lfactorial(n float64) float64 { + l, _ := math.Lgamma(n + 1) + return l +} + +func factorial(n float64) *big.Float { + i, frac := math.Modf(lfactorial(n) * math.Log2E) + z := big.NewFloat(math.Exp2(frac)) + return z.SetMantExp(z, int(i)) +} + +func main() { + for i := 0.; i <= 10; i++ { + fmt.Println(i, factorial(i)) + } + fmt.Println(100, factorial(100)) + fmt.Println(800, factorial(800)) +} diff --git a/Task/Factorial/HolyC/factorial-1.holyc b/Task/Factorial/HolyC/factorial-1.holyc new file mode 100644 index 0000000000..854ee0a5ae --- /dev/null +++ b/Task/Factorial/HolyC/factorial-1.holyc @@ -0,0 +1,9 @@ +U64 Factorial(U64 n) { + U64 i, result = 1; + for (i = 1; i <= n; ++i) + result *= i; + return result; +} + +Print("1: %d\n", Factorial(1)); +Print("10: %d\n", Factorial(10)); diff --git a/Task/Factorial/HolyC/factorial-2.holyc b/Task/Factorial/HolyC/factorial-2.holyc new file mode 100644 index 0000000000..8615643979 --- /dev/null +++ b/Task/Factorial/HolyC/factorial-2.holyc @@ -0,0 +1,11 @@ +I64 Factorial(I64 n) { + if (n == 0) + return 1; + if (n < 0) + return -1 * ((-1 * n) * Factorial((-1 * n) - 1)); + return n * Factorial(n - 1)); +} + +Print("+1: %d\n", Factorial(1)); +Print("+10: %d\n", Factorial(10)); +Print("-10: %d\n", Factorial(-10)); diff --git a/Task/Factorial/JavaScript/factorial-7.js b/Task/Factorial/JavaScript/factorial-7.js index 1909b7d333..f063d40582 100644 --- a/Task/Factorial/JavaScript/factorial-7.js +++ b/Task/Factorial/JavaScript/factorial-7.js @@ -1,20 +1,28 @@ -(function (n) { +(() => { 'use strict'; // factorial :: Int -> Int - let factorial = (n) => range(1, n).reduce(product, 1); + const factorial = n => + enumFromTo(1, n) + .reduce(product, 1); + const test = () => + factorial(18); + // --> 6402373705728000 + + + // GENERIC FUNCTIONS ---------------------------------- + // product :: Num -> Num -> Num - let product = (a, b) => a * b, + const product = (a, b) => a * b; - // range :: Int -> Int -> [Int] - range = (m, n) => - Array.from({ - length: (n - m) + 1 - }, (_, i) => m + i) + // range :: Int -> Int -> [Int] + const enumFromTo = (m, n) => + Array.from({ + length: (n - m) + 1 + }, (_, i) => m + i); - - return factorial(n); - -})(18); + // MAIN ------ + return test(); +})(); diff --git a/Task/Factorial/Julia/factorial-1.julia b/Task/Factorial/Julia/factorial-1.julia index c799df9152..6901331796 100644 --- a/Task/Factorial/Julia/factorial-1.julia +++ b/Task/Factorial/Julia/factorial-1.julia @@ -1,9 +1,12 @@ -julia> help(factorial) -Loading help data... -Base.factorial(n) +function fact(n::Integer) + n < 0 && return zero(n) + f = one(n) + for i in 2:n + f *= i + end + return f +end - Factorial of n - -Base.factorial(n, k) - - Compute "factorial(n)/factorial(k)" +for i in 10:20 + println("$i -> ", fact(i)) +end diff --git a/Task/Factorial/Julia/factorial-2.julia b/Task/Factorial/Julia/factorial-2.julia index efd40f8bec..27fca4d844 100644 --- a/Task/Factorial/Julia/factorial-2.julia +++ b/Task/Factorial/Julia/factorial-2.julia @@ -1,10 +1,2 @@ -function factorial(n::Integer) - if n < 0 - return zero(n) - end - f = one(n) - for i = 2:n - f *= i - end - return f -end +fact2(n::Integer) = prod(Base.OneTo(n)) +@show fact2(20) diff --git a/Task/Factorial/Modula-2/factorial.mod2 b/Task/Factorial/Modula-2/factorial.mod2 new file mode 100644 index 0000000000..702b94d76a --- /dev/null +++ b/Task/Factorial/Modula-2/factorial.mod2 @@ -0,0 +1,26 @@ +MODULE Factorial; +FROM FormatString IMPORT FormatString; +FROM Terminal IMPORT WriteString,ReadChar; + +PROCEDURE Factorial(n : CARDINAL) : CARDINAL; +VAR result : CARDINAL; +BEGIN + result := 1; + WHILE n#0 DO + result := result * n; + DEC(n) + END; + RETURN result +END Factorial; + +VAR + buf : ARRAY[0..63] OF CHAR; + n : CARDINAL; +BEGIN + FOR n:=0 TO 10 DO + FormatString("%2c! = %7c\n", buf, n, Factorial(n)); + WriteString(buf) + END; + + ReadChar +END Factorial. diff --git a/Task/Factorial/Nim/factorial-1.nim b/Task/Factorial/Nim/factorial-1.nim index bc5ab752d8..81e4b791f1 100644 --- a/Task/Factorial/Nim/factorial-1.nim +++ b/Task/Factorial/Nim/factorial-1.nim @@ -1,3 +1,2 @@ -proc factorial(x): int = - if x > 0: x * factorial(x - 1) - else: 1 +import math +let i:int = fac(x) diff --git a/Task/Factorial/Nim/factorial-2.nim b/Task/Factorial/Nim/factorial-2.nim index 674f69e8f0..bc5ab752d8 100644 --- a/Task/Factorial/Nim/factorial-2.nim +++ b/Task/Factorial/Nim/factorial-2.nim @@ -1,4 +1,3 @@ proc factorial(x): int = - result = 1 - for i in 1..x+1: - result *= i + if x > 0: x * factorial(x - 1) + else: 1 diff --git a/Task/Factorial/Nim/factorial-3.nim b/Task/Factorial/Nim/factorial-3.nim new file mode 100644 index 0000000000..1671403b82 --- /dev/null +++ b/Task/Factorial/Nim/factorial-3.nim @@ -0,0 +1,4 @@ +proc factorial(x: int): int = + result = 1 + for i in 2..x: + result *= i diff --git a/Task/Factorial/OCaml/factorial-4.ocaml b/Task/Factorial/OCaml/factorial-4.ocaml new file mode 100644 index 0000000000..c4c29561b0 --- /dev/null +++ b/Task/Factorial/OCaml/factorial-4.ocaml @@ -0,0 +1,12 @@ +let rec factorial n = + let rec loop acc = function + | 0 -> acc + | n -> loop (Z.mul (Z.of_int n) acc) (n - 1) + in loop Z.one n + +let () = + if not !Sys.interactive then + begin + Sys.argv.(1) |> int_of_string |> factorial |> Z.print; + print_newline () + end diff --git a/Task/Factorial/Processing/factorial b/Task/Factorial/Processing/factorial new file mode 100644 index 0000000000..4604f8bba9 --- /dev/null +++ b/Task/Factorial/Processing/factorial @@ -0,0 +1,7 @@ +int fact(int n){ + if(n <= 1){ + return 1; + } else{ + return n*fact(n-1); + } +} diff --git a/Task/Factorial/Simula/factorial.simula b/Task/Factorial/Simula/factorial.simula index e221db265c..fbd2adbbc7 100644 --- a/Task/Factorial/Simula/factorial.simula +++ b/Task/Factorial/Simula/factorial.simula @@ -1,14 +1,15 @@ begin - integer procedure factorial( n ); + integer procedure factorial(n); integer n; begin integer fact, i; fact := 1; - if n > 1 then - for i := 2 step 1 until n do - fact := fact * i; + for i := 2 step 1 until n do + fact := fact * i; factorial := fact end; - outint( factorial( 6 ), 5); - outimage + integer f; outtext("factorials:"); outimage; + for f := 0, 1, 2, 6, 9 do begin + outint(f, 2); outint(factorial(f), 8); outimage + end end diff --git a/Task/Factorial/VBA/factorial.vba b/Task/Factorial/VBA/factorial.vba new file mode 100644 index 0000000000..e96603daff --- /dev/null +++ b/Task/Factorial/VBA/factorial.vba @@ -0,0 +1,28 @@ +Option Explicit + +Sub Main() +Dim i As Integer +For i = 1 To 17 + Debug.Print "Factorial " & i & " , recursive : " & FactRec(i) & ", iterative : " & FactIter(i) +Next +Debug.Print "Factorial 120, recursive : " & FactRec(120) & ", iterative : " & FactIter(120) +End Sub + +Private Function FactRec(Nb As Integer) As String +If Nb > 170 Or Nb < 0 Then FactRec = 0: Exit Function + If Nb = 1 Or Nb = 0 Then + FactRec = 1 + Else + FactRec = Nb * FactRec(Nb - 1) + End If +End Function + +Private Function FactIter(Nb As Integer) +If Nb > 170 Or Nb < 0 Then FactIter = 0: Exit Function +Dim i As Integer, F + F = 1 + For i = 1 To Nb + F = F * i + Next i + FactIter = F +End Function diff --git a/Task/Factorial/VHDL/factorial.vhdl b/Task/Factorial/VHDL/factorial.vhdl index 25315ccdd4..d10cd76000 100644 --- a/Task/Factorial/VHDL/factorial.vhdl +++ b/Task/Factorial/VHDL/factorial.vhdl @@ -1,30 +1,74 @@ -use std.textio.all; +LIBRARY ieee; +USE ieee.std_logic_1164.ALL; +USE ieee.numeric_std.ALL; -entity rc is -end entity rc; +ENTITY Factorial IS + GENERIC ( + Nbin : INTEGER := 3 ; -- number of bit to input number + Nbou : INTEGER := 13) ; -- number of bit to output factorial + + PORT ( + clk : IN STD_LOGIC ; -- clock of circuit + sr : IN STD_LOGIC_VECTOR(1 DOWNTO 0); -- set and reset + N : IN STD_LOGIC_VECTOR(Nbin-1 DOWNTO 0) ; -- max number + Fn : OUT STD_LOGIC_VECTOR(Nbou-1 DOWNTO 0)); -- factorial of "n" + +END Factorial ; -architecture beh of rc is -function fact(n:integer) return integer is - variable f: integer := 1; - variable i: integer; -begin - for i in 2 to n loop - f := f*i; - end loop; - return f; -end; +ARCHITECTURE Behavior OF Factorial IS +---------------------- Program Multiplication -------------------------------- + FUNCTION Mult ( CONSTANT MFa : IN UNSIGNED ; + CONSTANT MI : IN UNSIGNED ) RETURN UNSIGNED IS + VARIABLE Z : UNSIGNED(MFa'RANGE) ; + VARIABLE U : UNSIGNED(MI'RANGE) ; + BEGIN + Z := TO_UNSIGNED(0, MFa'LENGTH) ; -- to obtain the multiplication + U := MI ; -- regressive counter + LOOP + Z := Z + MFa ; -- make multiplication + U := U - 1 ; + EXIT WHEN U = 0 ; + END LOOP ; + RETURN Z ; + END Mult ; +-------------------Program Factorial --------------------------------------- + FUNCTION Fact (CONSTANT Nx : IN NATURAL ) RETURN UNSIGNED IS + VARIABLE C : NATURAL RANGE 0 TO 2**Nbin-1 ; + VARIABLE I : UNSIGNED(Nbin-1 DOWNTO 0) ; + VARIABLE Fa : UNSIGNED(Nbou-1 DOWNTO 0) ; + BEGIN + C := 0 ; -- counter + I := TO_UNSIGNED(1, Nbin) ; + Fa := TO_UNSIGNED(1, Nbou) ; + LOOP + EXIT WHEN C = Nx ; -- end loop + C := C + 1 ; -- progressive couter + Fa := Mult (Fa , I ); -- call function to make a multiplication + I := I + 1 ; -- + END LOOP ; + RETURN Fa ; + END Fact ; +--------------------- Program TO Call Factorial Function ------------------------------------------------------ + TYPE Table IS ARRAY (0 TO 2**Nbin-1) OF UNSIGNED(Nbou-1 DOWNTO 0) ; + FUNCTION Call_Fact RETURN Table IS + VARIABLE Fc : Table ; + BEGIN + FOR c IN 0 TO 2**Nbin-1 LOOP + Fc(c) := Fact(c) ; + END LOOP ; + RETURN Fc ; + END FUNCTION Call_Fact; + + CONSTANT Result : Table := Call_Fact ; + ------------------------------------------------------------------------------------------------------------ +SIGNAL Nin : STD_LOGIC_VECTOR(N'RANGE) ; +BEGIN -- start of architecture -begin -process - variable i: integer; - variable l: line; -begin - for i in 0 to 5 loop - write(l, i); - write(l, string'(" ")); - write(l, fact(i)); - writeline(output, l); - end loop; - wait; -end process; -end; + +Nin <= N WHEN RISING_EDGE(clk) AND sr = "10" ELSE + (OTHERS => '0') WHEN RISING_EDGE(clk) AND sr = "01" ELSE + UNAFFECTED; + +Fn <= STD_LOGIC_VECTOR(Result(TO_INTEGER(UNSIGNED(Nin)))) WHEN RISING_EDGE(clk) ; + +END Behavior ; diff --git a/Task/Factors-of-a-Mersenne-number/00DESCRIPTION b/Task/Factors-of-a-Mersenne-number/00DESCRIPTION index dfc86bf8a1..32d744d65c 100644 --- a/Task/Factors-of-a-Mersenne-number/00DESCRIPTION +++ b/Task/Factors-of-a-Mersenne-number/00DESCRIPTION @@ -50,5 +50,8 @@ Using the above method find a factor of 2929-1 (aka M929) *   [[trial factoring of a Mersenne number]] *   [[partition an integer X into N primes]] *   [[sequence of primes by Trial Division]] + + +;See also: *   [https://www.youtube.com/watch?v=SNwvJ7psoow Computers in 1948: 2¹²⁷-1]

diff --git a/Task/Factors-of-a-Mersenne-number/Lingo/factors-of-a-mersenne-number-1.lingo b/Task/Factors-of-a-Mersenne-number/Lingo/factors-of-a-mersenne-number-1.lingo new file mode 100644 index 0000000000..50863534e1 --- /dev/null +++ b/Task/Factors-of-a-Mersenne-number/Lingo/factors-of-a-mersenne-number-1.lingo @@ -0,0 +1,23 @@ +on modPow (b, e, m) + bits = getBits(e) + sq = 1 + repeat while TRUE + tb = bits[1] + bits.deleteAt(1) + sq = sq*sq + if tb then sq=sq*b + sq = sq mod m + if bits.count=0 then return sq + end repeat +end + +on getBits (n) + bits = [] + f = 1 + repeat while TRUE + bits.addAt(1, bitAnd(f, n)>0) + f = f * 2 + if f>n then exit repeat + end repeat + return bits +end diff --git a/Task/Factors-of-a-Mersenne-number/Lingo/factors-of-a-mersenne-number-2.lingo b/Task/Factors-of-a-Mersenne-number/Lingo/factors-of-a-mersenne-number-2.lingo new file mode 100644 index 0000000000..57ea03717d --- /dev/null +++ b/Task/Factors-of-a-Mersenne-number/Lingo/factors-of-a-mersenne-number-2.lingo @@ -0,0 +1,6 @@ +repeat with i = 2 to the maxInteger + if modPow(2, 929, i)=1 then + put "M929 has a factor: " & i + exit repeat + end if +end repeat diff --git a/Task/Factors-of-a-Mersenne-number/REXX/factors-of-a-mersenne-number.rexx b/Task/Factors-of-a-Mersenne-number/REXX/factors-of-a-mersenne-number.rexx index b8d47817ec..34849e11da 100644 --- a/Task/Factors-of-a-Mersenne-number/REXX/factors-of-a-mersenne-number.rexx +++ b/Task/Factors-of-a-Mersenne-number/REXX/factors-of-a-mersenne-number.rexx @@ -1,38 +1,48 @@ -/*REXX program uses exponent─&─mod operator to test possible Mersenne numbers.*/ -numeric digits 500 /*dealing with some ginormous numbers. */ - - do j=1 to 61; z=j /*when J reaches 61, it turns into 929.*/ - if z==61 then z=929 /*now, a switcheroo, 61 turns into 929.*/ - if \isPrime(z) then iterate /*if Z isn't a prime, keep plugging.*/ - r=testM(z) /*If Z is prime, give Z the 3rd degree.*/ - if r==0 then say right('M'z,8) "──────── is a Mersenne prime." - else say right('M'z,48) "is composite, a factor:" r +/*REXX program uses exponent─and─mod operator to test possible Mersenne numbers. */ +numeric digits 20 /*this will be increased if necessary. */ +parse arg N spec /*obtain optional arguments from the CL*/ +if N=='' | N=="," then N= 88 /*Not specified? Then use the default.*/ +if spec=='' | spec=="," then spec= 920 970 /* " " " " " " */ + do j=1; z=j /*process a range, & then do one more #*/ + if j=N then j=word(spec, 1); /*now, use the high range of numbers. */ + if j>word(spec, 2) then leave /*done with the high range of numbers? */ + if \isPrime(z) then iterate /*if Z isn't a prime, keep plugging.*/ + r=testMer(z) /*If Z is prime, give Z the 3rd degree.*/ + r=commas(r); L=length(r) /*add commas to R; get it's new length.*/ + if r==0 then say right('M'z, 10) "──────── is a Mersenne prime." + else say right('M'z, 50) "is composite, a factor:" right(r, max(L, 11) ) end /*j*/ -exit /*stick a fork in it, we're all done. */ -/*────────────────────────────────────────────────────────────────────────────*/ -isPrime: procedure; parse arg x; if wordpos(x,'2 3 5 7')\==0 then return 1 - if x<11 then return 0; if x//2==0 | x//3 ==0 then return 0 - do j=5 by 6; if x//j==0 | x//(j+2)==0 then return 0 - if j*j>x then return 1 - end /*j*/ -/*────────────────────────────────────────────────────────────────────────────*/ -iSqrt: procedure; parse arg x; r=0; q=1; do while q<=x; q=q*4; end - do while q>1; q=q%4; _=x-r-q; r=r%2; if _>=0 then do;x=_;r=r+q; end;end - return r -/*────────────────────────────────────────────────────────────────────────────*/ -modPow: procedure; parse arg base,n,div; sq=1; $=x2b(d2x(n))+0 - do until $==''; sq=sq**2 - if left($,1) then sq=sq*base//div; $=substr($,2) - end /*until ··· */ - return sq -/*────────────────────────────────────────────────────────────────────────────*/ -testM: procedure; parse arg x /*test a possible Mersenne prime*/ - sqRoot=iSqrt(2**x) /*iSqrt is: integer square root*/ - /*───── ─ ── ─ ─ */ - do k=1; q=2*k*x + 1 /* _____ */ - if q>sqRoot then return 0 /*Is q>√(2^x)? A Mersenne prime*/ - _=q // 8 /*obtain the remainder when ÷ 8.*/ - if _\==1 & _\==7 then iterate /*must be either one or seven*/ - if \isPrime(q) then iterate /*Q ¬prime? Then keep on looking*/ - if modPow(2,x,q)==1 then return q /*Not a prime? Return a factor.*/ - end /*k*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +commas: parse arg _; do jc=length(_)-3 to 1 by -3; _=insert(',', _, jc); end; return _ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +isPrime: procedure; parse arg x; if wordpos(x, '2 3 5 7') \== 0 then return 1 + if x<11 then return 0; if x//2 == 0 | x//3 == 0 then return 0 + do j=5 by 6; if x//j == 0 | x//(j+2) == 0 then return 0 + if j*j>x then return 1 /*◄─┐ ___ */ + end /*j*/ /* └─◄ Is j>√ x ? Then return 1*/ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +iSqrt: procedure; parse arg x; #=1; r=0; do while #<=x; #=#*4; end + do while #>1; #=#%4; _=x-r-#; r=r%2; if _>=0 then do; x=_; r=r+#; end + end /*while*/ /*iSqrt ≡ integer square root.*/ + return r /*───── ─ ── ─ ─ */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +testMer: procedure; parse arg x; p=2**x /* [↓] do we have enough digits?*/ + $$=x2b( d2x(x) ) + 0 + if pos('E',p)\==0 then do; parse var p "E" _; numeric digits _+2; p=2**x; end + !.=1; !.1=0; !.7=0 /*array used for a quicker test. */ + R=iSqrt(p) /*obtain integer square root of P*/ + do k=2 by 2; q=k*x + 1 /*(shortcut) compute value of Q. */ + m=q // 8 /*obtain the remainder when ÷ 8. */ + if !.m then iterate /*M must be either one or seven.*/ + parse var q '' -1 _; if _==5 then iterate /*last digit a five ? */ + if q//3==0 then iterate /*divisible by three? */ + if q//7==0 then iterate /* ____ " " seven? */ + if q>R then return 0 /*Is q>√2**x ? A Mersenne prime*/ + sq=1; $=$$ /*obtain binary version from $. */ + do until $==''; sq=sq*sq + parse var $ _ 2 $ /*obtain 1st digit and the rest. */ + if _ then sq=(sq+sq) // q + end /*until*/ + if sq==1 then return q /*Not a prime? Return a factor.*/ + end /*k*/ diff --git a/Task/Factors-of-a-Mersenne-number/Ring/factors-of-a-mersenne-number.ring b/Task/Factors-of-a-Mersenne-number/Ring/factors-of-a-mersenne-number.ring new file mode 100644 index 0000000000..1f2101edf8 --- /dev/null +++ b/Task/Factors-of-a-Mersenne-number/Ring/factors-of-a-mersenne-number.ring @@ -0,0 +1,44 @@ +# Project : Factors of a Mersenne number +# Date : 2018/04/02 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : + +see "A factor of M929 is " + mersennefactor(929) + nl +see "A factor of M937 is " + mersennefactor(937) + nl + +func mersennefactor(p) + if not isprime(p) + return -1 + ok + for k = 1 to 50 + q = 2*k*p + 1 + if (q && 7) = 1 or (q && 7) = 7 + if isprime(q) + if modpow(2, p, q) = 1 + return q + ok + ok + ok + next + return 0 + +func isprime(num) + if (num <= 1) return 0 ok + if (num % 2 = 0) and num != 2 return 0 ok + for i = 3 to floor(num / 2) -1 step 2 + if (num % i = 0) return 0 ok + next + return 1 + +func modpow(x,n,m) + i = n + y = 1 + z = x + while i > 0 + if i & 1 + y = (y * z) % m + ok + z = (z * z) % m + i = (i >> 1) + end + return y diff --git a/Task/Factors-of-an-integer/Ruby/factors-of-an-integer-3.rb b/Task/Factors-of-an-integer/Ruby/factors-of-an-integer-3.rb new file mode 100644 index 0000000000..e16626de7b --- /dev/null +++ b/Task/Factors-of-an-integer/Ruby/factors-of-an-integer-3.rb @@ -0,0 +1,12 @@ +require 'prime' + +def factors m + return [1] if 1==m + primes, powers = Prime.prime_division(m).transpose + ranges = powers.map{|n| (0..n).to_a} + ranges[0].product( *ranges[1..-1] ). + map{|es| primes.zip(es).map{|p,e| p**e}.reduce :*}. + sort +end + +[1, 7, 45, 100].each{|n| p factors n} diff --git a/Task/Fast-Fourier-transform/APL/fast-fourier-transform-1.apl b/Task/Fast-Fourier-transform/APL/fast-fourier-transform-1.apl new file mode 100644 index 0000000000..69f150c0c3 --- /dev/null +++ b/Task/Fast-Fourier-transform/APL/fast-fourier-transform-1.apl @@ -0,0 +1,10 @@ +fft←{ + N←⍴⍵ + N≤1:⍵ + (1|2⍟N)≠0:'Argument must be a power of 2 in length' + even←fft(N⍴0 1)/⍵ + odd←fft(N⍴1 0)/⍵ + k←N÷2 + T←even×*(0J¯2×(○1)×(¯1+⍳k)÷N) + (odd+T),odd-T +} diff --git a/Task/Fast-Fourier-transform/APL/fast-fourier-transform-2.apl b/Task/Fast-Fourier-transform/APL/fast-fourier-transform-2.apl new file mode 100644 index 0000000000..35da765d46 --- /dev/null +++ b/Task/Fast-Fourier-transform/APL/fast-fourier-transform-2.apl @@ -0,0 +1 @@ + fft 1 1 1 1 0 0 0 0 diff --git a/Task/Fast-Fourier-transform/Perl/fast-fourier-transform.pl b/Task/Fast-Fourier-transform/Perl/fast-fourier-transform.pl index f901d8dfc9..d3b15ed47f 100644 --- a/Task/Fast-Fourier-transform/Perl/fast-fourier-transform.pl +++ b/Task/Fast-Fourier-transform/Perl/fast-fourier-transform.pl @@ -7,7 +7,7 @@ sub fft { my @evn = fft(@_[grep { not $_ % 2 } 0 .. $#_ ]); my @odd = fft(@_[grep { $_ % 2 } 1 .. $#_ ]); my $twd = 2*i* pi / @_; - $odd[$_] *= exp( $_ * $twd ) for 0 .. $#odd; + $odd[$_] *= exp( $_ * -$twd ) for 0 .. $#odd; return (map { $evn[$_] + $odd[$_] } 0 .. $#evn ), (map { $evn[$_] - $odd[$_] } 0 .. $#evn ); diff --git a/Task/Fast-Fourier-transform/Stata/fast-fourier-transform.stata b/Task/Fast-Fourier-transform/Stata/fast-fourier-transform-1.stata similarity index 100% rename from Task/Fast-Fourier-transform/Stata/fast-fourier-transform.stata rename to Task/Fast-Fourier-transform/Stata/fast-fourier-transform-1.stata diff --git a/Task/Fast-Fourier-transform/Stata/fast-fourier-transform-2.stata b/Task/Fast-Fourier-transform/Stata/fast-fourier-transform-2.stata new file mode 100644 index 0000000000..5db3287c09 --- /dev/null +++ b/Task/Fast-Fourier-transform/Stata/fast-fourier-transform-2.stata @@ -0,0 +1,8 @@ +clear +set obs 4 +gen t=_n +gen x=_n +gen y=0 +tsset t +fft y x, gen(v u) +list u v, noobs diff --git a/Task/Fast-Fourier-transform/SystemVerilog/fast-fourier-transform-1.v b/Task/Fast-Fourier-transform/SystemVerilog/fast-fourier-transform-1.v new file mode 100644 index 0000000000..4f8bdf4ed8 --- /dev/null +++ b/Task/Fast-Fourier-transform/SystemVerilog/fast-fourier-transform-1.v @@ -0,0 +1,90 @@ +/// @Author: Alexandre Felipe (o.alexandre.felipe@gmail.com) +/// @Date: 2018-Jan-25 +/// + +package math_pkg; + // Inspired by the post + // https://community.cadence.com/cadence_blogs_8/b/fv/posts/create-a-sine-wave-generator-using-systemverilog + // import functions directly from C library + //import dpi task C Name = SV function name + import "DPI" pure function real cos (input real rTheta); + import "DPI" pure function real sin(input real y); + import "DPI" pure function real atan2(input real y, input real x); +endpackage : math_pkg + + +// Encapsulates the functions in a parameterized class +// The FFT is implemented using floating point arithmetic (systemverilog real) +// Complex values are represented as a real vector [1:0], the index 0 is the real part +// and the index 1 is the imaginary part. +class fft_fp #( + parameter LOG2_NS = 7, + parameter NS = 1< + +f = list(12) + +see "Fibonacci:" + nl +f2 = [1,1] +for nr2 = 1 to 10 + see "" + f2[1] + " " + fibn(f2) +next +showarray(f2) +see " ..." + nl + nl + +see "Tribonacci:" + nl +f3 = [1,1,2] +for nr3 = 1 to 9 + see "" + f3[1] + " " + fibn(f3) +next +showarray(f3) +see " ..." + nl + nl + +see "Tetranacci:" + nl +f4 = [1,1,2,4] +for nr4 = 1 to 8 + see "" + f4[1] + " " + fibn(f4) +next +showarray(f4) +see " ..." + nl + nl + +see "Lucas:" + nl +f5 = [2,1] +for nr5 = 1 to 10 + see "" + f5[1] + " " + fibn(f5) +next +showarray(f5) +see " ..." + nl + nl + +func fibn(fs) + s = sum(fs) + for i = 2 to len(fs) + fs[i-1] = fs[i] + next + fs[i-1] = s + return fs + +func sum(arr) + sm = 0 + for sn = 1 to len(arr) + sm = sm + arr[sn] + next + return sm + +func showarray(fn) + svect = "" + for p = 1 to len(fn) + svect = svect + fn[p] + " " + next + see svect diff --git a/Task/Fibonacci-n-step-number-sequences/VBA/fibonacci-n-step-number-sequences.vba b/Task/Fibonacci-n-step-number-sequences/VBA/fibonacci-n-step-number-sequences.vba new file mode 100644 index 0000000000..a4e0ac86ae --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/VBA/fibonacci-n-step-number-sequences.vba @@ -0,0 +1,62 @@ +Option Explicit + +Sub Main() +Dim temp$, T() As Long, i& + 'Fibonacci: + T = Fibonacci_Step(1, 15, 1) + For i = LBound(T) To UBound(T) + temp = temp & ", " & T(i) + Next + Debug.Print "Fibonacci: " & Mid(temp, 3) + temp = "" + + 'Tribonacci: + T = Fibonacci_Step(1, 15, 2) + For i = LBound(T) To UBound(T) + temp = temp & ", " & T(i) + Next + Debug.Print "Tribonacci: " & Mid(temp, 3) + temp = "" + + 'Tetranacci: + T = Fibonacci_Step(1, 15, 3) + For i = LBound(T) To UBound(T) + temp = temp & ", " & T(i) + Next + Debug.Print "Tetranacci: " & Mid(temp, 3) + temp = "" + + 'Lucas: + T = Fibonacci_Step(1, 15, 1, 2) + For i = LBound(T) To UBound(T) + temp = temp & ", " & T(i) + Next + Debug.Print "Lucas: " & Mid(temp, 3) + temp = "" +End Sub + +Private Function Fibonacci_Step(First As Long, Count As Long, S As Long, Optional Second As Long) As Long() +Dim T() As Long, R() As Long, i As Long, Su As Long, C As Long + + If Second <> 0 Then S = 1 + ReDim T(1 - S To Count) + For i = LBound(T) To 0 + T(i) = 0 + Next i + T(1) = IIf(Second <> 0, Second, 1) + T(2) = 1 + For i = 3 To Count + Su = 0 + C = S + 1 + Do While C >= 0 + Su = Su + T(i - C) + C = C - 1 + Loop + T(i) = Su + Next + ReDim R(1 To Count) + For i = 1 To Count + R(i) = T(i) + Next + Fibonacci_Step = R +End Function diff --git a/Task/Fibonacci-sequence/CoffeeScript/fibonacci-sequence-1.coffee b/Task/Fibonacci-sequence/CoffeeScript/fibonacci-sequence-1.coffee index 23fd97bf7b..f3325c70f0 100644 --- a/Task/Fibonacci-sequence/CoffeeScript/fibonacci-sequence-1.coffee +++ b/Task/Fibonacci-sequence/CoffeeScript/fibonacci-sequence-1.coffee @@ -1,4 +1,4 @@ fib_ana = (n) -> sqrt = Math.sqrt phi = ((1 + sqrt(5))/2) - return Math.round((Math.pow(phi, n)/sqrt(5))) + Math.round((Math.pow(phi, n)/sqrt(5))) diff --git a/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-7.lisp b/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-7.lisp new file mode 100644 index 0000000000..e80aa75c73 --- /dev/null +++ b/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-7.lisp @@ -0,0 +1,16 @@ +;; Project : Fibonacci sequence +;; Date : 2018/03/05 +;; Author : Gal Zsolt [~ CalmoSoft ~] +;; Email : fib(N, 0, 1). + +fib(0, Result, _Next) -> Result; +fib(Iter, Result, Next) -> fib(Iter-1, Next, Result+Next). diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-10.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-10.hs index 7d1f929f9b..170aaccf3f 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-10.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-10.hs @@ -1,44 +1 @@ -import Data.List (transpose) - -fib - :: (Integral b, Num a) - => b -> a -fib 0 = 0 -- this line is necessary because "something ^ 0" returns "fromInteger 1", which unfortunately --- in our case is not our multiplicative identity (the identity matrix) but just a 1x1 matrix of 1 -fib n = (last . head . unMat) (Mat [[1, 1], [1, 0]] ^ n) - --- Code adapted from Matrix exponentiation operator task --------------------- -(<+>) - :: Num c - => [c] -> [c] -> [c] -(<+>) = zipWith (+) - -(<*>) - :: Num a - => [a] -> [a] -> a -(<*>) = (sum .) . zipWith (*) - -newtype Mat a = Mat - { unMat :: [[a]] - } deriving (Eq) - -instance Show a => - Show (Mat a) where - show xm = "Mat " ++ show (unMat xm) - -instance Num a => - Num (Mat a) where - negate xm = Mat $ map (map negate) $ unMat xm - xm + ym = Mat $ zipWith (<+>) (unMat xm) (unMat ym) - xm * ym = - Mat - [ [ xs Main.<*> ys -- to distinguish from standard applicative operator - | ys <- transpose $ unMat ym ] - | xs <- unMat xm ] - fromInteger n = Mat [[fromInteger n]] - abs = undefined - signum = undefined - --- TEST ---------------------------------------------------------------------- -main :: IO () -main = (print . take 10 . show . fib) (10 ^ 5) +fib = 0 : 1 : (zipWith (+) <*> tail) fib diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-11.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-11.hs index 593d8551aa..bac976bc03 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-11.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-11.hs @@ -1,35 +1 @@ -import Control.Arrow ((&&&)) - -fibstep :: (Integer, Integer) -> (Integer, Integer) -fibstep (a, b) = (b, a + b) - -fibnums :: [Integer] -fibnums = map fst $ iterate fibstep (0, 1) - -fibN2 :: Integer -> (Integer, Integer) -fibN2 m - | m < 10 = iterate fibstep (0, 1) !! fromIntegral m -fibN2 m = fibN2_next (n, r) (fibN2 n) - where - (n, r) = quotRem m 3 - -fibN2_next (n, r) (f, g) - | r == 0 = (a, b) -- 3n ,3n+1 - | r == 1 = (b, c) -- 3n+1,3n+2 - | r == 2 = (c, d) -- 3n+2,3n+3 (*) - where - a = - 5 * f ^ 3 + - if even n - then 3 * f - else (-3 * f) -- 3n - b = g ^ 3 + 3 * g * f ^ 2 - f ^ 3 -- 3n+1 - c = g ^ 3 + 3 * g ^ 2 * f + f ^ 3 -- 3n+2 - d = - 5 * g ^ 3 + - if even n - then (-3 * g) - else 3 * g -- 3(n+1) (*) - -main :: IO () -main = print $ (length &&& take 20) . show . fst $ fibN2 (10 ^ 2) +fib = 0 : 1 : next fib where next (a: t@(b:_)) = (a+b) : next t diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-12.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-12.hs index c69d736bc9..093c22af12 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-12.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-12.hs @@ -1,2 +1 @@ - *Main> (length &&& take 20) . show . fst $ fibN2 (10^6) -(208988,"19532821287077577316") +fib = 0 : scanl (+) 1 fib diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-13.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-13.hs index 7f0a39dbc2..754992047c 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-13.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-13.hs @@ -1 +1,9 @@ -f (n,(a,b)) = (2*n,(a*a+b*b,2*a*b+b*b)) -- iterate f (1,(0,1)) ; b is nth +import Data.List (foldl') --' + +fib :: Integer -> Integer +fib n = + fst $ + foldl' --' + (\(a, b) _ -> (b, a + b)) + (0, 1) + [1 .. n] diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-14.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-14.hs index dd052ec7a3..7d1f929f9b 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-14.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-14.hs @@ -1 +1,44 @@ -g (n,(a,b)) = (2*n,(2*a*b-a*a,a*a+b*b)) -- iterate g (1,(1,1)) ; a is nth +import Data.List (transpose) + +fib + :: (Integral b, Num a) + => b -> a +fib 0 = 0 -- this line is necessary because "something ^ 0" returns "fromInteger 1", which unfortunately +-- in our case is not our multiplicative identity (the identity matrix) but just a 1x1 matrix of 1 +fib n = (last . head . unMat) (Mat [[1, 1], [1, 0]] ^ n) + +-- Code adapted from Matrix exponentiation operator task --------------------- +(<+>) + :: Num c + => [c] -> [c] -> [c] +(<+>) = zipWith (+) + +(<*>) + :: Num a + => [a] -> [a] -> a +(<*>) = (sum .) . zipWith (*) + +newtype Mat a = Mat + { unMat :: [[a]] + } deriving (Eq) + +instance Show a => + Show (Mat a) where + show xm = "Mat " ++ show (unMat xm) + +instance Num a => + Num (Mat a) where + negate xm = Mat $ map (map negate) $ unMat xm + xm + ym = Mat $ zipWith (<+>) (unMat xm) (unMat ym) + xm * ym = + Mat + [ [ xs Main.<*> ys -- to distinguish from standard applicative operator + | ys <- transpose $ unMat ym ] + | xs <- unMat xm ] + fromInteger n = Mat [[fromInteger n]] + abs = undefined + signum = undefined + +-- TEST ---------------------------------------------------------------------- +main :: IO () +main = (print . take 10 . show . fib) (10 ^ 5) diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-15.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-15.hs new file mode 100644 index 0000000000..593d8551aa --- /dev/null +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-15.hs @@ -0,0 +1,35 @@ +import Control.Arrow ((&&&)) + +fibstep :: (Integer, Integer) -> (Integer, Integer) +fibstep (a, b) = (b, a + b) + +fibnums :: [Integer] +fibnums = map fst $ iterate fibstep (0, 1) + +fibN2 :: Integer -> (Integer, Integer) +fibN2 m + | m < 10 = iterate fibstep (0, 1) !! fromIntegral m +fibN2 m = fibN2_next (n, r) (fibN2 n) + where + (n, r) = quotRem m 3 + +fibN2_next (n, r) (f, g) + | r == 0 = (a, b) -- 3n ,3n+1 + | r == 1 = (b, c) -- 3n+1,3n+2 + | r == 2 = (c, d) -- 3n+2,3n+3 (*) + where + a = + 5 * f ^ 3 + + if even n + then 3 * f + else (-3 * f) -- 3n + b = g ^ 3 + 3 * g * f ^ 2 - f ^ 3 -- 3n+1 + c = g ^ 3 + 3 * g ^ 2 * f + f ^ 3 -- 3n+2 + d = + 5 * g ^ 3 + + if even n + then (-3 * g) + else 3 * g -- 3(n+1) (*) + +main :: IO () +main = print $ (length &&& take 20) . show . fst $ fibN2 (10 ^ 2) diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-16.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-16.hs new file mode 100644 index 0000000000..c69d736bc9 --- /dev/null +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-16.hs @@ -0,0 +1,2 @@ + *Main> (length &&& take 20) . show . fst $ fibN2 (10^6) +(208988,"19532821287077577316") diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-17.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-17.hs new file mode 100644 index 0000000000..7f0a39dbc2 --- /dev/null +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-17.hs @@ -0,0 +1 @@ +f (n,(a,b)) = (2*n,(a*a+b*b,2*a*b+b*b)) -- iterate f (1,(0,1)) ; b is nth diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-18.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-18.hs new file mode 100644 index 0000000000..dd052ec7a3 --- /dev/null +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-18.hs @@ -0,0 +1 @@ +g (n,(a,b)) = (2*n,(2*a*b-a*a,a*a+b*b)) -- iterate g (1,(1,1)) ; a is nth diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-4.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-4.hs index 3e0209338c..cbe4522a68 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-4.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-4.hs @@ -1,5 +1,6 @@ -fib n = go n 0 1 - where - go n a b - | n == 0 = a - | otherwise = go (n - 1) b (a + b) +import Data.MemoTrie +fib :: Integer -> Integer +fib = memo f where + f 0 = 0 + f 1 = 1 + f n = fib (n-1) + fib (n-2) diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-5.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-5.hs index eb85845a7f..58f31b8024 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-5.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-5.hs @@ -1 +1,6 @@ -fib = 0 : 1 : zipWith (+) fib (tail fib) +import Data.MemoTrie +fib :: Integer -> Integer +fib = memo $ \x -> case x of + 0 -> 0 + 1 -> 1 + n -> fib (n-1) + fib (n-2) diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-6.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-6.hs index 170aaccf3f..8b5d19f460 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-6.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-6.hs @@ -1 +1,7 @@ -fib = 0 : 1 : (zipWith (+) <*> tail) fib +{-# Language LambdaCase #-} +import Data.MemoTrie +fib :: Integer -> Integer +fib = memo $ \case + 0 -> 0 + 1 -> 1 + n -> fib (n-1) + fib (n-2) diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-7.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-7.hs index bac976bc03..1f5b1fa3e7 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-7.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-7.hs @@ -1 +1,8 @@ -fib = 0 : 1 : next fib where next (a: t@(b:_)) = (a+b) : next t +{-# Language LambdaCase #-} +import Data.MemoTrie +fib :: Integer -> Integer +fib = memo $ \case + 0 -> 0 + 1 -> 1 + n | n>0 -> fib (n-1) + fib (n-2) + | otherwise -> fib (n+2) - fib (n+1) diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-8.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-8.hs index 093c22af12..3e0209338c 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-8.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-8.hs @@ -1 +1,5 @@ -fib = 0 : scanl (+) 1 fib +fib n = go n 0 1 + where + go n a b + | n == 0 = a + | otherwise = go (n - 1) b (a + b) diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-9.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-9.hs index 754992047c..eb85845a7f 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-9.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-9.hs @@ -1,9 +1 @@ -import Data.List (foldl') --' - -fib :: Integer -> Integer -fib n = - fst $ - foldl' --' - (\(a, b) _ -> (b, a + b)) - (0, 1) - [1 .. n] +fib = 0 : 1 : zipWith (+) fib (tail fib) diff --git a/Task/Fibonacci-sequence/MATLAB/fibonacci-sequence-4.m b/Task/Fibonacci-sequence/MATLAB/fibonacci-sequence-4.m new file mode 100644 index 0000000000..2c1ad95b54 --- /dev/null +++ b/Task/Fibonacci-sequence/MATLAB/fibonacci-sequence-4.m @@ -0,0 +1,12 @@ +function number = fibonacci(n) +%construct the Tartaglia/Pascal Triangle + pt=tril(ones(n)); + for r = 3 : n + % Every element is the addition of the two elements + % on top of it. That means the previous row. + for c = 2 : r-1 + pt(r, c) = pt(r-1, c-1) + pt(r-1, c); + end + end + number=trace(rot90(pt)); +end diff --git a/Task/Fibonacci-sequence/Mathematica/fibonacci-sequence-7.math b/Task/Fibonacci-sequence/Mathematica/fibonacci-sequence-7.math new file mode 100644 index 0000000000..ae2f610829 --- /dev/null +++ b/Task/Fibonacci-sequence/Mathematica/fibonacci-sequence-7.math @@ -0,0 +1,2 @@ +fib[n] /. RSolve[{fib[n] == fib[n - 1] + fib[n - 2], fib[0] == 0, + fib[1] == 1}, fib[n], n][[1]] diff --git a/Task/Fibonacci-sequence/Mathematica/fibonacci-sequence-8.math b/Task/Fibonacci-sequence/Mathematica/fibonacci-sequence-8.math new file mode 100644 index 0000000000..833b606b99 --- /dev/null +++ b/Task/Fibonacci-sequence/Mathematica/fibonacci-sequence-8.math @@ -0,0 +1 @@ +Fibonacci[n] // FunctionExpand // FullSimplify diff --git a/Task/Fibonacci-sequence/Mathematica/fibonacci-sequence-9.math b/Task/Fibonacci-sequence/Mathematica/fibonacci-sequence-9.math new file mode 100644 index 0000000000..735e538818 --- /dev/null +++ b/Task/Fibonacci-sequence/Mathematica/fibonacci-sequence-9.math @@ -0,0 +1 @@ +(2^-n ((1 + Sqrt[5])^n - (-1 + Sqrt[5])^n Cos[n π]))/Sqrt[5] diff --git a/Task/Fibonacci-sequence/Modula-2/fibonacci-sequence.mod2 b/Task/Fibonacci-sequence/Modula-2/fibonacci-sequence.mod2 new file mode 100644 index 0000000000..72c0a46c84 --- /dev/null +++ b/Task/Fibonacci-sequence/Modula-2/fibonacci-sequence.mod2 @@ -0,0 +1,37 @@ +MODULE Fibonacci; +FROM FormatString IMPORT FormatString; +FROM Terminal IMPORT WriteString,WriteLn,ReadChar; + +PROCEDURE Fibonacci(n : LONGINT) : LONGINT; +VAR + a,b,c : LONGINT; +BEGIN + IF n<0 THEN RETURN 0 END; + + a:=1; + b:=1; + + WHILE n>0 DO + c := a + b; + a := b; + b := c; + DEC(n) + END; + + RETURN a +END Fibonacci; + +VAR + buf : ARRAY[0..63] OF CHAR; + i : INTEGER; + r : LONGINT; +BEGIN + FOR i:=0 TO 10 DO + r := Fibonacci(i); + + FormatString("%l\n", buf, r); + WriteString(buf); + END; + + ReadChar +END Fibonacci. diff --git a/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-14.pari b/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-14.pari index 49a2f5b231..5af4b4f310 100644 --- a/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-14.pari +++ b/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-14.pari @@ -1,7 +1 @@ -matantihadamard(n)={ - matrix(n,n,i,j, - my(t=j-i+1); - if(t<1,t%2,t<3) - ); -} -fib(n)=matdet(matantihadamard(n)) +fib(n)=n--;polchebyshev(n,2,I/2)*I^n; diff --git a/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-15.pari b/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-15.pari index 78ccd47534..8620df4d05 100644 --- a/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-15.pari +++ b/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-15.pari @@ -1,7 +1 @@ -fib(n)= -{ - my(g=2^(n+1)-1); - sum(i=2^(n-1),2^n-1, - bitor(i,i<<1)==g - ); -} +fib(n)=abs(polchebyshev(n-1,2,I/2)); diff --git a/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-16.pari b/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-16.pari index 2f2e9ab577..49a2f5b231 100644 --- a/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-16.pari +++ b/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-16.pari @@ -1 +1,7 @@ -fib(n)=my(k=0);while(n--,k++;while(!issquare(5*k^2+4)&&!issquare(5*k^2-4),k++));k +matantihadamard(n)={ + matrix(n,n,i,j, + my(t=j-i+1); + if(t<1,t%2,t<3) + ); +} +fib(n)=matdet(matantihadamard(n)) diff --git a/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-17.pari b/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-17.pari new file mode 100644 index 0000000000..78ccd47534 --- /dev/null +++ b/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-17.pari @@ -0,0 +1,7 @@ +fib(n)= +{ + my(g=2^(n+1)-1); + sum(i=2^(n-1),2^n-1, + bitor(i,i<<1)==g + ); +} diff --git a/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-18.pari b/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-18.pari new file mode 100644 index 0000000000..2f2e9ab577 --- /dev/null +++ b/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-18.pari @@ -0,0 +1 @@ +fib(n)=my(k=0);while(n--,k++;while(!issquare(5*k^2+4)&&!issquare(5*k^2-4),k++));k diff --git a/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-5.pl6 b/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-5.pl6 index 1df565daca..533b1a7bde 100644 --- a/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-5.pl6 +++ b/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-5.pl6 @@ -1,5 +1,4 @@ -use experimental :cached; -proto fib (Int $n --> Int) is cached {*} +proto fib (Int $n --> Int) {*} multi fib (0) { 0 } multi fib (1) { 1 } multi fib ($n) { fib($n - 1) + fib($n - 2) } diff --git a/Task/Fibonacci-sequence/Perl/fibonacci-sequence-3.pl b/Task/Fibonacci-sequence/Perl/fibonacci-sequence-3.pl index 0f9fe0a32f..7cf95e568b 100644 --- a/Task/Fibonacci-sequence/Perl/fibonacci-sequence-3.pl +++ b/Task/Fibonacci-sequence/Perl/fibonacci-sequence-3.pl @@ -1,11 +1,15 @@ +# Uses GMP method so very fast +use Math::AnyNum qw/fibonacci/; +say fibonacci(10000); + +# Uses GMP method, so also very fast +use Math::GMP; +say Math::GMP::fibonacci(10000); + # Binary ladder, GMP if available, Pure Perl otherwise use ntheory qw/lucasu/; say lucasu(1, -1, 10000); -# Uses GMP internal method, so similar performance as above -use Math::GMP; -say Math::GMP::fibonacci(10000); - # All Perl use Math::NumSeq::Fibonacci; my $seq = Math::NumSeq::Fibonacci->new; diff --git a/Task/Fibonacci-sequence/PicoLisp/fibonacci-sequence-4.l b/Task/Fibonacci-sequence/PicoLisp/fibonacci-sequence-4.l index 2eff7c24f2..5547f77ea7 100644 --- a/Task/Fibonacci-sequence/PicoLisp/fibonacci-sequence-4.l +++ b/Task/Fibonacci-sequence/PicoLisp/fibonacci-sequence-4.l @@ -1,7 +1,4 @@ -(de fibo (N) - (let (I 1 J 0) +(de fib (N) + (let (A 0 B 1) (do N - (let (Tmp J) - (inc 'J I) - (setq I Tmp) ) ) - J) ) + (prog1 B (setq B (+ A B) A @)) ) ) ) diff --git a/Task/Fibonacci-sequence/PicoLisp/fibonacci-sequence-5.l b/Task/Fibonacci-sequence/PicoLisp/fibonacci-sequence-5.l new file mode 100644 index 0000000000..4b8d1f2387 --- /dev/null +++ b/Task/Fibonacci-sequence/PicoLisp/fibonacci-sequence-5.l @@ -0,0 +1,11 @@ +(co 'fibo + (let (A 0 B 1) + (yield 'ready) + (while + (yield + (swap 'B (+ (swap 'A B) B)) ) ) ) ) + +(do 15 + (printsp (yield 'next 'fibo)) ) +(prinl) +(yield NIL 'fibo) diff --git a/Task/Fibonacci-sequence/Python/fibonacci-sequence-11.py b/Task/Fibonacci-sequence/Python/fibonacci-sequence-11.py index dae759acba..6a63d4d38c 100644 --- a/Task/Fibonacci-sequence/Python/fibonacci-sequence-11.py +++ b/Task/Fibonacci-sequence/Python/fibonacci-sequence-11.py @@ -1,10 +1,8 @@ -def fib(): - """Yield fib[n+1] + fib[n]""" - yield 1 # have to start somewhere - lhs, rhs = fib(), fib() - yield next(lhs) # move lhs one iteration ahead - while True: - yield next(lhs)+next(rhs) - -f=fib() -print [next(f) for _ in range(9)] +F = {0: 0, 1: 1, 2: 1} +def fib(n): + if n in F: + return F[n] + f1 = fib(n // 2 + 1) + f2 = fib((n - 1) // 2) + F[n] = (f1 * f1 + f2 * f2 if n & 1 else f1 * f1 - f2 * f2) + return F[n] diff --git a/Task/Fibonacci-sequence/Python/fibonacci-sequence-12.py b/Task/Fibonacci-sequence/Python/fibonacci-sequence-12.py index 0c83030578..dae759acba 100644 --- a/Task/Fibonacci-sequence/Python/fibonacci-sequence-12.py +++ b/Task/Fibonacci-sequence/Python/fibonacci-sequence-12.py @@ -1,11 +1,10 @@ -from itertools import islice - def fib(): - yield 0 - yield 1 - a, b = fib(), fib() - next(b) + """Yield fib[n+1] + fib[n]""" + yield 1 # have to start somewhere + lhs, rhs = fib(), fib() + yield next(lhs) # move lhs one iteration ahead while True: - yield next(a)+next(b) + yield next(lhs)+next(rhs) -print(tuple(islice(fib(), 10))) +f=fib() +print [next(f) for _ in range(9)] diff --git a/Task/Fibonacci-sequence/Python/fibonacci-sequence-13.py b/Task/Fibonacci-sequence/Python/fibonacci-sequence-13.py new file mode 100644 index 0000000000..0c83030578 --- /dev/null +++ b/Task/Fibonacci-sequence/Python/fibonacci-sequence-13.py @@ -0,0 +1,11 @@ +from itertools import islice + +def fib(): + yield 0 + yield 1 + a, b = fib(), fib() + next(b) + while True: + yield next(a)+next(b) + +print(tuple(islice(fib(), 10))) diff --git a/Task/Fibonacci-sequence/REALbasic/fibonacci-sequence.realbasic b/Task/Fibonacci-sequence/REALbasic/fibonacci-sequence.realbasic index a1b2714ac5..4bc41b4f66 100644 --- a/Task/Fibonacci-sequence/REALbasic/fibonacci-sequence.realbasic +++ b/Task/Fibonacci-sequence/REALbasic/fibonacci-sequence.realbasic @@ -4,7 +4,7 @@ Function fibo(n as integer) As UInt64 dim noTwo as UInt64 = 1 dim sum As UInt64 - for i as integer = 1 to n + for i as integer = 3 to n sum = noOne + noTwo noTwo = noOne noOne = sum diff --git a/Task/Fibonacci-sequence/Racket/fibonacci-sequence-2.rkt b/Task/Fibonacci-sequence/Racket/fibonacci-sequence-2.rkt index a655d2441e..c40571eb36 100644 --- a/Task/Fibonacci-sequence/Racket/fibonacci-sequence-2.rkt +++ b/Task/Fibonacci-sequence/Racket/fibonacci-sequence-2.rkt @@ -1,11 +1,4 @@ -#lang racket - -(require math/matrix) - -(define (fibmat n) (matrix-ref - (matrix-expt (matrix ([1 1] - [1 0])) - n) - 1 0)) - -(fibmat 1000) +(define (fib n (a 0) (b 1)) + (if (< n 2) + 1 + (+ a (fib (- n 1) b (+ a b))))) diff --git a/Task/Fibonacci-sequence/Racket/fibonacci-sequence-3.rkt b/Task/Fibonacci-sequence/Racket/fibonacci-sequence-3.rkt new file mode 100644 index 0000000000..a655d2441e --- /dev/null +++ b/Task/Fibonacci-sequence/Racket/fibonacci-sequence-3.rkt @@ -0,0 +1,11 @@ +#lang racket + +(require math/matrix) + +(define (fibmat n) (matrix-ref + (matrix-expt (matrix ([1 1] + [1 0])) + n) + 1 0)) + +(fibmat 1000) diff --git a/Task/Fibonacci-sequence/Scala/fibonacci-sequence-3.scala b/Task/Fibonacci-sequence/Scala/fibonacci-sequence-3.scala index 58f0cb96ba..1922a468ad 100644 --- a/Task/Fibonacci-sequence/Scala/fibonacci-sequence-3.scala +++ b/Task/Fibonacci-sequence/Scala/fibonacci-sequence-3.scala @@ -1,5 +1,4 @@ def fib(x:Int, prev: BigInt = 0, next: BigInt = 1):BigInt = x match { case 0 => prev - case 1 => next - case _ => fib(x-1, next, (next + prev)) + case _ => fib(x-1, next, next + prev) } diff --git a/Task/Fibonacci-sequence/Stata/fibonacci-sequence-1.stata b/Task/Fibonacci-sequence/Stata/fibonacci-sequence-1.stata new file mode 100644 index 0000000000..ae9b3d2822 --- /dev/null +++ b/Task/Fibonacci-sequence/Stata/fibonacci-sequence-1.stata @@ -0,0 +1,7 @@ +program fib +args n +clear +qui set obs `n' +qui gen a=1 +qui replace a=a[_n-1]+a[_n-2] in 3/l +end diff --git a/Task/Fibonacci-sequence/Stata/fibonacci-sequence-2.stata b/Task/Fibonacci-sequence/Stata/fibonacci-sequence-2.stata new file mode 100644 index 0000000000..dc6c807168 --- /dev/null +++ b/Task/Fibonacci-sequence/Stata/fibonacci-sequence-2.stata @@ -0,0 +1,12 @@ +program fib +args n +clear +qui set obs `n' +qui gen a=. +dyngen { + update a=a[_n-1]+a[_n-2], missval(1) +} +end + +fib 10 +list diff --git a/Task/Fibonacci-sequence/Stata/fibonacci-sequence.stata b/Task/Fibonacci-sequence/Stata/fibonacci-sequence-3.stata similarity index 100% rename from Task/Fibonacci-sequence/Stata/fibonacci-sequence.stata rename to Task/Fibonacci-sequence/Stata/fibonacci-sequence-3.stata diff --git a/Task/Fibonacci-word-fractal/Julia/fibonacci-word-fractal.julia b/Task/Fibonacci-word-fractal/Julia/fibonacci-word-fractal.julia new file mode 100644 index 0000000000..4931d373c3 --- /dev/null +++ b/Task/Fibonacci-word-fractal/Julia/fibonacci-word-fractal.julia @@ -0,0 +1,23 @@ +using Luxor, Colors + +function fwfractal!(word::AbstractString, t::Turtle) + left = 90 + right = -90 + for (n, c) in enumerate(word) + Forward(t) + if c == '0' + Turn(t, ifelse(iseven(n), left, right)) + end + end + return t +end + +word = last(fiboword(25)) + +touch("data/fibonaccifractal.png") +Drawing(800, 800, "data/fibonaccifractal.png"); +background(colorant"white") +t = Turtle(100, 300) +fwfractal!(word, t) +finish() +preview() diff --git a/Task/Fibonacci-word/Aime/fibonacci-word.aime b/Task/Fibonacci-word/Aime/fibonacci-word.aime index 986d5fe340..a94571136a 100644 --- a/Task/Fibonacci-word/Aime/fibonacci-word.aime +++ b/Task/Fibonacci-word/Aime/fibonacci-word.aime @@ -6,7 +6,7 @@ entropy(data b) ones = zeros = 0; - i = -(count = b_length(b)); + i = -(count = ~b); while (i) { if (b[i] == '0') { zeros += 1; @@ -29,15 +29,15 @@ main(void) a = "1"; b = "0"; - o_form("%2d %9d /w12p10d10/ ~\n", 1, b_length(a), 0r, a); - o_form("%2d %9d /w12p10d10/ ~\n", 2, b_length(b), 0r, b); + o_form("%2d %9d /w12p10d10/ ~\n", 1, ~a, 0r, a); + o_form("%2d %9d /w12p10d10/ ~\n", 2, ~b, 0r, b); i = 3; while (i <= 37) { - b_stock(a, 0, b); - o_form("%2d %9d /w12p10d10/ ~\n", i, b_length(a), entropy(a), - __hold(i < 10, a, "")); + bu_copy(a, 0, b); + o_form("%2d %9d /w12p10d10/ ~\n", i, ~a, entropy(a), + i < 10 ? a.string : ""); i += 1; - b_swap(a, b); + b.swap(a); } return 0; diff --git a/Task/Fibonacci-word/C-sharp/fibonacci-word.cs b/Task/Fibonacci-word/C-sharp/fibonacci-word.cs new file mode 100644 index 0000000000..8a62fea1d7 --- /dev/null +++ b/Task/Fibonacci-word/C-sharp/fibonacci-word.cs @@ -0,0 +1,71 @@ +using SYS = System; +using SCG = System.Collections.Generic; + +// +// Basically a port of the C++ solution as posted +// 2017-11-12. +// +namespace FibonacciWord +{ + class Program + { + static void Main( string[] args ) + { + PrintHeading(); + string firstString = "1"; + int n = 1; + PrintLine( n, firstString ); + string secondString = "0"; + ++n; + PrintLine( n, secondString ); + while ( n < 37 ) + { + string resultString = firstString + secondString; + firstString = secondString; + secondString = resultString; + ++n; + PrintLine( n, resultString ); + } + } + + private static void PrintLine( int n, string result ) + { + SYS.Console.Write( "{0,-5}", n ); + SYS.Console.Write( "{0,12}", result.Length ); + SYS.Console.WriteLine( " {0,-16}", GetEntropy( result ) ); + } + + private static double GetEntropy( string result ) + { + SCG.Dictionary frequencies = new SCG.Dictionary(); + foreach ( char c in result ) + { + if ( frequencies.ContainsKey( c ) ) + { + ++frequencies[c]; + } + else + { + frequencies[c] = 1; + } + } + + int length = result.Length; + double entropy = 0; + foreach ( var keyValue in frequencies ) + { + double freq = (double)keyValue.Value / length; + entropy += freq * SYS.Math.Log( freq, 2 ); + } + + return -entropy; + } + + private static void PrintHeading() + { + SYS.Console.Write( "{0,-5}", "N" ); + SYS.Console.Write( "{0,12}", "Length" ); + SYS.Console.WriteLine( " {0,-16}", "Entropy" ); + } + } +} diff --git a/Task/Fibonacci-word/Factor/fibonacci-word.factor b/Task/Fibonacci-word/Factor/fibonacci-word.factor new file mode 100644 index 0000000000..4f0e348577 --- /dev/null +++ b/Task/Fibonacci-word/Factor/fibonacci-word.factor @@ -0,0 +1,36 @@ +USING: assocs combinators formatting kernel math math.functions +math.ranges math.statistics namespaces pair-rocket sequences ; +IN: rosetta-code.fibonacci-word + +SYMBOL: 37th-fib-word + +: fib ( n -- m ) + { + 1 => [ 1 ] + 2 => [ 1 ] + [ [ 1 - fib ] [ 2 - fib ] bi + ] + } case ; + +: fib-word ( n -- seq ) + { + 1 => [ "1" ] + 2 => [ "0" ] + [ [ 1 - fib-word ] [ 2 - fib-word ] bi append ] + } case ; + +: nth-fib-word ( n -- seq ) + dup 1 = + [ drop "1" ] [ 37th-fib-word get swap fib head ] if ; + +: entropy ( seq -- entropy ) + [ length ] [ histogram >alist [ second ] map ] bi + [ swap / ] with map + [ dup log 2 log / * ] map-sum + dup 0. = [ neg ] unless ; + +37 fib-word 37th-fib-word set +"N" "Length" "Entropy" "%2s %8s %10s\n" printf +37 [1,b] [ + dup nth-fib-word [ length ] [ entropy ] bi + "%2d %8d %.8f\n" printf +] each diff --git a/Task/Fibonacci-word/Julia/fibonacci-word.julia b/Task/Fibonacci-word/Julia/fibonacci-word.julia index 0000460053..e5f7436b3b 100644 --- a/Task/Fibonacci-word/Julia/fibonacci-word.julia +++ b/Task/Fibonacci-word/Julia/fibonacci-word.julia @@ -1,26 +1,27 @@ -# Code for "entropy" taken from https://rosettacode.org/wiki/Entropy#Julia -entropy(s::String)::Float32 = -sum(x -> x * log(2, x), [count(x -> x == c, s) / length(s) for c in unique(s)]) +using DataStructures +entropy(s::AbstractString) = -sum(x -> x / length(s) * log2(x / length(s)), values(counter(s))) -function fibboword(n::Int64)::Array{String} - # Initialize the result - r = Array{String}(n) - # First element - r[1] = "0" - # If more than 2, set the second element - if (n ≥ 2) - r[2] = "1" - end - # Recursively create elements > 3 - for i in 3:n - r[i] = r[i - 1] * r[i - 2] - end - return r +function fibboword(n::Int64) + # Initialize the result + r = Array{String}(n) + # First element + r[1] = "0" + # If more than 2, set the second element + if n ≥ 2 r[2] = "1" end + # Recursively create elements > 3 + for i in 3:n + r[i] = r[i - 1] * r[i - 2] + end + return r end -function testfibbo(n::Int64) - fib = fibboword(n) - for i in 1:length(fib) - println(i, "\t", length(fib[i]), "\t", entropy(fib[i])) - end - return 0 +function testfibbo(n::Integer) + fib = fibboword(n) + for i in 1:length(fib) + @printf("%3d%9d%12.6f\n", i, length(fib[i]), entropy(fib[i])) + end + return 0 end + +println(" n\tlength\tentropy") +testfibbo(37) diff --git a/Task/Fibonacci-word/Objeck/fibonacci-word.objeck b/Task/Fibonacci-word/Objeck/fibonacci-word.objeck new file mode 100644 index 0000000000..9dd83fae32 --- /dev/null +++ b/Task/Fibonacci-word/Objeck/fibonacci-word.objeck @@ -0,0 +1,58 @@ +use Collection; + +class FibonacciWord { + function : native : GetEntropy(result : String) ~ Float { + frequencies := IntMap->New(); + + each(i : result) { + c := result->Get(i); + + if(frequencies->Has(c)) { + count := frequencies->Find(c)->As(IntHolder); + count->Set(count->Get() + 1); + } + else { + frequencies->Insert(c, IntHolder->New(1)); + }; + }; + + length := result->Size(); + entropy := 0.0; + + counts := frequencies->GetValues(); + each(i : counts) { + count := counts->Get(i)->As(IntHolder)->Get(); + freq := count->As(Float) / length; + entropy += freq * (freq->Log() / 2.0->Log()); + }; + + return -1 * entropy; + } + + function : native : PrintLine(n : Int, result : String) ~ Nil { + n->Print(); + '\t'->Print(); + + result->Size()->Print(); + "\t\t"->Print(); + + GetEntropy(result)->PrintLine(); + } + + function : Main(args : String[]) ~ Nil { + firstString := "1"; + n := 1; + PrintLine( n, firstString ); + secondString := "0"; + n += 1; + PrintLine( n, secondString ); + + while(n < 37) { + resultString := "{$secondString}{$firstString}"; + firstString := secondString; + secondString := resultString; + n += 1; + PrintLine( n, resultString ); + }; + } +} diff --git a/Task/Fibonacci-word/Ring/fibonacci-word.ring b/Task/Fibonacci-word/Ring/fibonacci-word.ring new file mode 100644 index 0000000000..e987bf9ebb --- /dev/null +++ b/Task/Fibonacci-word/Ring/fibonacci-word.ring @@ -0,0 +1,54 @@ +# Project : Fibonacci word +# Date : 2018/01/23 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : + +fw1 = "1" +fw2 = "0" + +see "N Length Entropy Word" + nl +n = 1 +see "" + n + " " + len(fw1) + " " + calcentropy(fw1,2) + " " + fw1 + nl +n = 2 +see "" + n + " " + len(fw2) + " " + calcentropy(fw2,2) + " " + fw2 + nl + +for n = 1 to 55 + fw3 = fw2 + fw1 + temp = fw2 + fw2 = fw3 + fw1 = temp + if len(fw3) < 55 + see "" + (n+2) + " " + len(fw3) + " " + calcentropy(fw3,2) + " " + fw3 + nl + ok +next + +func calcentropy(source,b) + decimals(11) + entropy = 0 + countOfChar = list(255) + charCount =len( source) + usedChar ="" + for i =1 to len( source) + ch =substr(source, i, 1) + if not(substr( usedChar, ch)) + usedChar =usedChar +ch + ok + j =substr( usedChar, ch) + countOfChar[j] =countOfChar[j] +1 + next + l =len(usedChar) + for i =1 to l + probability =countOfChar[i] /charCount + entropy =entropy - (probability *logBase(probability, 2)) + next + return entropy + +func swap(a, b) + temp = a + a = b + b = temp + return [a, b] + +func logBase (x, b) + logBase =log( x) /log( 2) + return logBase diff --git a/Task/File-input-output/Aime/file-input-output.aime b/Task/File-input-output/Aime/file-input-output.aime index ff793a1e32..9b4a4b4a8e 100644 --- a/Task/File-input-output/Aime/file-input-output.aime +++ b/Task/File-input-output/Aime/file-input-output.aime @@ -1,11 +1,11 @@ file i, o; text s; -f_open(i, "input.txt", OPEN_READONLY, 0); -f_open(o, "output.txt", OPEN_CREATE | OPEN_TRUNCATE | OPEN_WRITEONLY, +i.open("input.txt", OPEN_READONLY, 0); +o.open("output.txt", OPEN_CREATE | OPEN_TRUNCATE | OPEN_WRITEONLY, 0644); -while (f_line(i, s) ^ -1) { - f_text(o, s); - f_byte(o, '\n'); +while (i.line(s) ^ -1) { + o.text(s); + o.byte('\n'); } diff --git a/Task/File-input-output/COBOL/file-input-output-1.cobol b/Task/File-input-output/COBOL/file-input-output-1.cobol index 9c354b49f6..84d625e009 100644 --- a/Task/File-input-output/COBOL/file-input-output-1.cobol +++ b/Task/File-input-output/COBOL/file-input-output-1.cobol @@ -1,48 +1,40 @@ - IDENTIFICATION DIVISION. - PROGRAM-ID. file-io. - - ENVIRONMENT DIVISION. - INPUT-OUTPUT SECTION. - FILE-CONTROL. - SELECT in-file ASSIGN "input.txt" - ORGANIZATION LINE SEQUENTIAL. - - SELECT OPTIONAL out-file ASSIGN "output.txt" - ORGANIZATION LINE SEQUENTIAL. - - DATA DIVISION. - FILE SECTION. - FD in-file. - 01 in-line PIC X(256). - - FD out-file. - 01 out-line PIC X(256). - - PROCEDURE DIVISION. - DECLARATIVES. - in-file-error SECTION. - USE AFTER ERROR ON in-file. - DISPLAY "An error occurred while using input.txt." - GOBACK + identification division. + program-id. copyfile. + environment division. + input-output section. + file-control. + select input-file assign to "input.txt" + organization sequential . - out-file-error SECTION. - USE AFTER ERROR ON out-file. - DISPLAY "An error occurred while using output.txt." - GOBACK + select output-file assign to "output.txt" + organization sequential . - END DECLARATIVES. - - mainline. - OPEN INPUT in-file - OPEN OUTPUT out-file - - PERFORM FOREVER - READ in-file - AT END - EXIT PERFORM - END-READ - WRITE out-line FROM in-line - END-PERFORM - - CLOSE in-file, out-file + data division. + file section. + fd input-file. + 1 input-record pic x(80). + fd output-file. + 1 output-record pic x(80). + working-storage section. + 1 end-of-file-flag pic 9 value 0. + 88 eof value 1. + 1 text-line pic x(80). + procedure division. + begin. + open input input-file + output output-file + perform read-input + perform until eof + write output-record from text-line + perform read-input + end-perform + close input-file output-file + stop run . + read-input. + read input-file into text-line + at end + set eof to true + end-read + . + end program copyfile. diff --git a/Task/File-input-output/COBOL/file-input-output-2.cobol b/Task/File-input-output/COBOL/file-input-output-2.cobol index 7ee3f840f6..9c354b49f6 100644 --- a/Task/File-input-output/COBOL/file-input-output-2.cobol +++ b/Task/File-input-output/COBOL/file-input-output-2.cobol @@ -1,2 +1,48 @@ -*> Originally from ACUCOBOL-GT -CALL "C$COPY" USING "input.txt", "output.txt", 0 + IDENTIFICATION DIVISION. + PROGRAM-ID. file-io. + + ENVIRONMENT DIVISION. + INPUT-OUTPUT SECTION. + FILE-CONTROL. + SELECT in-file ASSIGN "input.txt" + ORGANIZATION LINE SEQUENTIAL. + + SELECT OPTIONAL out-file ASSIGN "output.txt" + ORGANIZATION LINE SEQUENTIAL. + + DATA DIVISION. + FILE SECTION. + FD in-file. + 01 in-line PIC X(256). + + FD out-file. + 01 out-line PIC X(256). + + PROCEDURE DIVISION. + DECLARATIVES. + in-file-error SECTION. + USE AFTER ERROR ON in-file. + DISPLAY "An error occurred while using input.txt." + GOBACK + . + out-file-error SECTION. + USE AFTER ERROR ON out-file. + DISPLAY "An error occurred while using output.txt." + GOBACK + . + END DECLARATIVES. + + mainline. + OPEN INPUT in-file + OPEN OUTPUT out-file + + PERFORM FOREVER + READ in-file + AT END + EXIT PERFORM + END-READ + WRITE out-line FROM in-line + END-PERFORM + + CLOSE in-file, out-file + . diff --git a/Task/File-input-output/COBOL/file-input-output-3.cobol b/Task/File-input-output/COBOL/file-input-output-3.cobol index 453cebf36a..7ee3f840f6 100644 --- a/Task/File-input-output/COBOL/file-input-output-3.cobol +++ b/Task/File-input-output/COBOL/file-input-output-3.cobol @@ -1,2 +1,2 @@ -*> Originally from Micro Focus COBOL -CALL "CBL_COPY_FILE" USING "input.txt", "output.txt" +*> Originally from ACUCOBOL-GT +CALL "C$COPY" USING "input.txt", "output.txt", 0 diff --git a/Task/File-input-output/COBOL/file-input-output-4.cobol b/Task/File-input-output/COBOL/file-input-output-4.cobol new file mode 100644 index 0000000000..453cebf36a --- /dev/null +++ b/Task/File-input-output/COBOL/file-input-output-4.cobol @@ -0,0 +1,2 @@ +*> Originally from Micro Focus COBOL +CALL "CBL_COPY_FILE" USING "input.txt", "output.txt" diff --git a/Task/File-input-output/Elena/file-input-output.elena b/Task/File-input-output/Elena/file-input-output.elena new file mode 100644 index 0000000000..c00f2f54da --- /dev/null +++ b/Task/File-input-output/Elena/file-input-output.elena @@ -0,0 +1,8 @@ +import system'io. + +program = +[ + var text := File new("input.txt"); content. + + File new("output.txt"); saveContent(text). +]. diff --git a/Task/File-input-output/Forth/file-input-output.fth b/Task/File-input-output/Forth/file-input-output-1.fth similarity index 100% rename from Task/File-input-output/Forth/file-input-output.fth rename to Task/File-input-output/Forth/file-input-output-1.fth diff --git a/Task/File-input-output/Forth/file-input-output-2.fth b/Task/File-input-output/Forth/file-input-output-2.fth new file mode 100644 index 0000000000..c9dc4d2722 --- /dev/null +++ b/Task/File-input-output/Forth/file-input-output-2.fth @@ -0,0 +1,10 @@ +: INPUT$ ( text -- n n ) + pad swap accept pad swap ; +cr ." Enter file name : " 20 INPUT$ w/o create-file throw Value fd-out +: get-content cr ." Enter your nickname : " 20 INPUT$ fd-out write-file cr ; +: close-output ( -- ) fd-out close-file throw ; +get-content +\ Inject a carriage return at end of file +s\" \n" fd-out write-file +close-output +bye diff --git a/Task/File-input-output/Red/file-input-output.red b/Task/File-input-output/Red/file-input-output.red new file mode 100644 index 0000000000..941aafe5f7 --- /dev/null +++ b/Task/File-input-output/Red/file-input-output.red @@ -0,0 +1,2 @@ +file: read %input.txt +write %output.txt file diff --git a/Task/File-input-output/VBA/file-input-output.vba b/Task/File-input-output/VBA/file-input-output.vba new file mode 100644 index 0000000000..7b8623b261 --- /dev/null +++ b/Task/File-input-output/VBA/file-input-output.vba @@ -0,0 +1,27 @@ +Option Explicit + +Sub Main() +Dim s As String, FF As Integer + +'read a file line by line +FF = FreeFile +Open "C:\Users\" & Environ("username") & "\Desktop\input.txt" For Input As #FF +While Not EOF(FF) + Line Input #FF, s + Debug.Print s +Wend +Close #FF + +'read a file +FF = FreeFile +Open "C:\Users\" & Environ("username") & "\Desktop\input.txt" For Input As #FF + s = Input(LOF(1), #FF) +Close #FF +Debug.Print s + +'write a file +FF = FreeFile +Open "C:\Users\" & Environ("username") & "\Desktop\output.txt" For Output As #FF + Print #FF, s +Close #FF +End Sub diff --git a/Task/File-modification-time/Julia/file-modification-time.julia b/Task/File-modification-time/Julia/file-modification-time.julia index 264f5a8be0..efb007d6ed 100644 --- a/Task/File-modification-time/Julia/file-modification-time.julia +++ b/Task/File-modification-time/Julia/file-modification-time.julia @@ -1,11 +1,6 @@ -fname = "fool.txt" -tfmt = "%FT%T%z" - -println("The modification time of ", fname, " is ") -println(" ", strftime(tfmt, mtime(fname))) +fname, _ = mktemp() +println("The modification time of $fname is ", Dates.unix2datetime(mtime(fname))) println("\nTouch this file.") touch(fname) - -println("The modification time of ", fname, " is now ") -println(" ", strftime(tfmt, mtime(fname))) +println("The modification time of $fname is now ", Dates.unix2datetime(mtime(fname))) diff --git a/Task/File-modification-time/Perl-6/file-modification-time.pl6 b/Task/File-modification-time/Perl-6/file-modification-time.pl6 index 309f461eda..1fcdd2eee9 100644 --- a/Task/File-modification-time/Perl-6/file-modification-time.pl6 +++ b/Task/File-modification-time/Perl-6/file-modification-time.pl6 @@ -10,7 +10,7 @@ class utimbuf is repr('CStruct') { } } -sub sysutime(Str, utimbuf --> int) is native is symbol('utime') {*} +sub sysutime(Str, utimbuf --> int32) is native is symbol('utime') {*} sub MAIN (Str $file) { my $mtime = $file.IO.modified // die "Can't stat $file: $!"; diff --git a/Task/File-size/AWK/file-size-2.awk b/Task/File-size/AWK/file-size-2.awk index 32c9cc2c02..aa81e09be4 100644 --- a/Task/File-size/AWK/file-size-2.awk +++ b/Task/File-size/AWK/file-size-2.awk @@ -1,18 +1,12 @@ BEGIN { # Windows - out = system2var("for %I in (input.txt) do @echo %~zI") - printf("input.txt\t%s\n", out) - out = system2var("for %I in (\input.txt) do @echo %~zI") - printf("\input.txt\t%s\n", out) + printf("input.txt\t%s\n", system2var("for %I in (input.txt) do @echo %~zI")) + printf("\input.txt\t%s\n", system2var("for %I in (\input.txt) do @echo %~zI")) # Non-Windows - out = getline2var("ls -l input.txt") - split(out, size, " ") - printf("input.txt\t%s\n", size[5]) - out = getline2var("ls -l /input.txt") - split(out, size, " ") - printf("/input.txt\t%s\n", size[5]) + printf("input.txt\t%s\n", getline2var("stat --printf=\"%s\" input.txt")) + printf("/input.txt\t%s\n", getline2var("stat --printf=\"%s\" /input.txt")) } # Windows system() method diff --git a/Task/File-size/Fortran/file-size-1.f b/Task/File-size/Fortran/file-size-1.f new file mode 100644 index 0000000000..2a240af0d7 --- /dev/null +++ b/Task/File-size/Fortran/file-size-1.f @@ -0,0 +1,9 @@ + use :: iso_fortran_env, only : FILE_STORAGE_SIZE + implicit none + character(len=*),parameter :: filename(*)=[character(len=256) :: 'input.txt', '/input.txt'] + integer :: file_size, i + do i=1,size(filename) + INQUIRE(FILE=filename(i), SIZE=file_size) ! return -1 if cannot determine file size + write(*,*)'size of file '//trim(filename(i))//' is ',file_size * FILE_STORAGE_SIZE /8,' bytes' + enddo + end diff --git a/Task/File-size/Fortran/file-size.f b/Task/File-size/Fortran/file-size-2.f similarity index 100% rename from Task/File-size/Fortran/file-size.f rename to Task/File-size/Fortran/file-size-2.f diff --git a/Task/File-size/Red/file-size.red b/Task/File-size/Red/file-size.red new file mode 100644 index 0000000000..e47041f48b --- /dev/null +++ b/Task/File-size/Red/file-size.red @@ -0,0 +1,4 @@ +>> size? %input.txt +== 39244 +>> size? %/c/input.txt +== 39244 diff --git a/Task/Filter/Elena/filter.elena b/Task/Filter/Elena/filter.elena new file mode 100644 index 0000000000..7f2ee096a1 --- /dev/null +++ b/Task/Filter/Elena/filter.elena @@ -0,0 +1,13 @@ +import system'routines. +import system'math. +import extensions. +import extensions'routines. + +program = +[ + var array := (1,2,3,4,5). + + var evens := array filterBy(:n)(n mod:2 == 0); toArray. + + evens forEach:printingLn. +]. diff --git a/Task/Filter/Java/filter.java b/Task/Filter/Java/filter-1.java similarity index 100% rename from Task/Filter/Java/filter.java rename to Task/Filter/Java/filter-1.java diff --git a/Task/Filter/Java/filter-2.java b/Task/Filter/Java/filter-2.java new file mode 100644 index 0000000000..bb8d7644db --- /dev/null +++ b/Task/Filter/Java/filter-2.java @@ -0,0 +1,5 @@ +public static T[] filter(T[] input, Predicate filterMethod) { + return Arrays.stream(input) + .filter(filterMethod) + .toArray(size -> (T[]) Array.newInstance(input.getClass().getComponentType(), size)); +} diff --git a/Task/Filter/Java/filter-3.java b/Task/Filter/Java/filter-3.java new file mode 100644 index 0000000000..88e7a00edf --- /dev/null +++ b/Task/Filter/Java/filter-3.java @@ -0,0 +1,2 @@ +Integer[] array = {1, 2, 3, 4, 5}; +Integer[] result = filter(array, i -> (i % 2) == 0); diff --git a/Task/Filter/Julia/filter.julia b/Task/Filter/Julia/filter.julia index 072deaaac3..302795398d 100644 --- a/Task/Filter/Julia/filter.julia +++ b/Task/Filter/Julia/filter.julia @@ -1,8 +1 @@ -julia> filter(iseven, [1,2,3,4,5,6,7,8,9]) -4-element Array{Int64,1}: - 2 - 4 - 6 - 8 - -julia> +@show filter(iseven, 1:10) diff --git a/Task/Filter/Perl-6/filter-2.pl6 b/Task/Filter/Perl-6/filter-2.pl6 index 35a2110083..9c19cdf385 100644 --- a/Task/Filter/Perl-6/filter-2.pl6 +++ b/Task/Filter/Perl-6/filter-2.pl6 @@ -1 +1,2 @@ +my @a = 1..6; my @even = @a.grep(* %% 2); diff --git a/Task/Filter/Perl-6/filter-3.pl6 b/Task/Filter/Perl-6/filter-3.pl6 index 2c11c2adbb..356c88e9eb 100644 --- a/Task/Filter/Perl-6/filter-3.pl6 +++ b/Task/Filter/Perl-6/filter-3.pl6 @@ -1 +1,2 @@ +my @a = 1..6; @a .= grep(* %% 2); diff --git a/Task/Filter/Red/filter.red b/Task/Filter/Red/filter.red new file mode 100644 index 0000000000..6644d8edff --- /dev/null +++ b/Task/Filter/Red/filter.red @@ -0,0 +1,9 @@ +Red [] +orig: [] repeat i 10 [append orig i] +?? orig +cpy: [] forall orig [if even? orig/1 [append cpy orig/1]] +;; or - because we know each second element is even :- ) +;; cpy: extract next orig 2 +?? cpy +remove-each ele orig [odd? ele] ;; destructive +?? orig diff --git a/Task/Filter/VBA/filter.vba b/Task/Filter/VBA/filter.vba new file mode 100644 index 0000000000..c052cc9595 --- /dev/null +++ b/Task/Filter/VBA/filter.vba @@ -0,0 +1,47 @@ +Option Explicit + +Sub Main() +Dim evens() As Long, i As Long +Dim numbers() As Long + + For i = 1 To 100000 + ReDim Preserve numbers(1 To i) + numbers(i) = i + Next i + + evens = FilterInNewArray(numbers) + + Debug.Print "Count of initial array : " & UBound(numbers) & ", first item : " & numbers(LBound(numbers)) & ", last item : " & numbers(UBound(numbers)) + Debug.Print "Count of new array : " & UBound(evens) & ", first item : " & evens(LBound(evens)) & ", last item : " & evens(UBound(evens)) + + FilterInPlace numbers + + Debug.Print "Count of initial array (filtered): " & UBound(numbers) & ", first item : " & numbers(LBound(numbers)) & ", last item : " & numbers(UBound(numbers)) +End Sub + +Private Function FilterInNewArray(arr() As Long) As Long() +Dim i As Long, t() As Long, cpt As Long + For i = LBound(arr) To UBound(arr) + If IsEven(arr(i)) Then + cpt = cpt + 1 + ReDim Preserve t(1 To cpt) + t(cpt) = i + End If + Next i + FilterInNewArray = t +End Function + +Private Sub FilterInPlace(arr() As Long) +Dim i As Long, cpt As Long + For i = LBound(arr) To UBound(arr) + If IsEven(arr(i)) Then + cpt = cpt + 1 + arr(cpt) = i + End If + Next i + ReDim Preserve arr(1 To cpt) +End Sub + +Private Function IsEven(Number As Long) As Boolean + IsEven = (CLng(Right(CStr(Number), 1)) And 1) = 0 +End Function diff --git a/Task/Find-common-directory-path/Julia/find-common-directory-path.julia b/Task/Find-common-directory-path/Julia/find-common-directory-path.julia index 0b9d42a342..cbcbe1c90d 100644 --- a/Task/Find-common-directory-path/Julia/find-common-directory-path.julia +++ b/Task/Find-common-directory-path/Julia/find-common-directory-path.julia @@ -1,27 +1,20 @@ -function commonpath{T<:String}(ds::Array{T,1}, delim::Char='/') - 0 < length(ds) || return convert(T, "") - 1 < length(ds) || return ds[1] - p = split(ds[1], delim) - mcnt = length(p) +function commonpath(ds::Vector{<:AbstractString}, dlm::Char='/') + 0 < length(ds) || return "" + 1 < length(ds) || return String(ds[1]) + p = split(ds[1], dlm) + mincnt = length(p) for d in ds[2:end] - q = split(d, delim) - mcnt = min(mcnt, length(q)) - hits = findfirst(p[1:mcnt] .== q[1:mcnt], false) - hits != 0 || continue - mcnt = hits - 1 - mcnt != 0 || return convert(T, "") + q = split(d, dlm) + mincnt = min(mincnt, length(q)) + hits = findfirst(p[1:mincnt] .!= q[1:mincnt]) + if hits != 0 mincnt = hits - 1 end + if mincnt == 0 return "" end end - 1 < mcnt || p[1] != "" || return convert(T, string(delim)) - convert(T, join(p[1:mcnt], delim)) + 1 < mincnt || p[1] != "" || return convert(T, string(dlm)) + return join(p[1:mincnt], dlm) end -test = ["/home/user1/tmp/coverage/test", - "/home/user1/tmp/covert/operator", - "/home/user1/tmp/coven/members"] +test = ["/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members"] -println("Comparing") -for s in test - println(" ", s) -end -println("for their common directory path yields:") -println(" ", commonpath(test)) +println("Comparing:\n - ", join(test, "\n - ")) +println("for their common directory path yields:\n", commonpath(test)) diff --git a/Task/Find-common-directory-path/Kotlin/find-common-directory-path.kotlin b/Task/Find-common-directory-path/Kotlin/find-common-directory-path.kotlin new file mode 100644 index 0000000000..336f5add70 --- /dev/null +++ b/Task/Find-common-directory-path/Kotlin/find-common-directory-path.kotlin @@ -0,0 +1,28 @@ +// version 1.1.51 + +fun findCommonDirPath(paths: List, separator: Char): String { + if (paths.isEmpty()) return "" + if (paths.size == 1) return paths[0] + val splits = paths[0].split(separator) + val n = splits.size + val paths2 = paths.drop(1) + var k = 0 + var common = "" + while (true) { + val prevCommon = common + common += if (k == 0) splits[0] else separator + splits[k] + if (!paths2.all { it.startsWith(common + separator) || it == common } ) return prevCommon + if (++k == n) return common + } +} + +fun main(args: Array) { + val paths = listOf( + "/home/user1/tmp/coverage/test", + "/home/user1/tmp/covert/operator", + "/home/user1/tmp/coven/members" + ) + val pathsToPrint = paths.map { " '$it'" }.joinToString("\n") + println("The common directory path of:\n\n$pathsToPrint\n") + println("is '${findCommonDirPath(paths, '/')}'") +} diff --git a/Task/Find-largest-left-truncatable-prime-in-a-given-base/Go/find-largest-left-truncatable-prime-in-a-given-base.go b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Go/find-largest-left-truncatable-prime-in-a-given-base.go new file mode 100644 index 0000000000..03f61affb1 --- /dev/null +++ b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Go/find-largest-left-truncatable-prime-in-a-given-base.go @@ -0,0 +1,57 @@ +package main + +import ( + "fmt" + "math/big" +) + +var smallPrimes = [...]int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29} + +const maxStack = 128 + +var ( + tens, values [maxStack]big.Int + bigTemp, answer = new(big.Int), new(big.Int) + base, seenDepth int +) + +func addDigit(i int) { + for d := 1; d < base; d++ { + values[i].Set(&values[i-1]) + bigTemp.SetUint64(uint64(d)) + bigTemp.Mul(bigTemp, &tens[i]) + values[i].Add(&values[i], bigTemp) + if !values[i].ProbablyPrime(0) { + continue + } + if i > seenDepth || (i == seenDepth && values[i].Cmp(answer) == 1) { + if !values[i].ProbablyPrime(0) { + continue + } + answer.Set(&values[i]) + seenDepth = i + } + addDigit(i + 1) + } +} + +func doBase() { + answer.SetUint64(0) + tens[0].SetUint64(1) + bigTemp.SetUint64(uint64(base)) + seenDepth = 0 + for i := 1; i < maxStack; i++ { + tens[i].Mul(&tens[i-1], bigTemp) + } + for i := 0; smallPrimes[i] < base; i++ { + values[0].SetUint64(uint64(smallPrimes[i])) + addDigit(1) + } + fmt.Printf("%2d: %s\n", base, answer.String()) +} + +func main() { + for base = 3; base <= 17; base++ { + doBase() + } +} 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 860a7b7b3d..858802b8ce 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,5 +1,7 @@ -function addmsdigit{T<:Integer}(p::T, b::T, s::T) - a = T[] +using Primes + +function addmsdigit(p::Integer, b::Integer, s::Integer) + a = Vector{typeof(p)}(0) q = p for i in 1:(b-1) q += s @@ -9,27 +11,25 @@ function addmsdigit{T<:Integer}(p::T, b::T, s::T) return a end -function lefttruncprime{T<:Integer}(pbase::T) - b = convert(BigInt, pbase) - a = BigInt[] - append!(a, primes(b-1)) +function lefttruncprime(pbase::Integer) + a = Vector{BigInt}(0) + append!(a, primes(pbase - 1)) mlt = zero(BigInt) s = one(BigInt) while !isempty(a) mlt = maximum(a) - s *= b + s *= pbase for i in 1:length(a) p = shift!(a) - append!(a, addmsdigit(p, b, s)) + append!(a, addmsdigit(p, pbase, s)) end end return mlt end lo, hi = 3, 17 -print("The largest left truncatable primes for bases") -println(@sprintf " %d to %d." lo hi) +println("The largest left truncatable primes for bases", @sprintf(" %d to %d.", lo, hi)) for i in lo:hi mlt = lefttruncprime(i) - println(@sprintf " %3d %d (%s)" i mlt base(i, mlt)) + @printf("%10d %-30d (%s)\n", i, mlt, base(i, mlt)) end diff --git a/Task/Find-largest-left-truncatable-prime-in-a-given-base/Maple/find-largest-left-truncatable-prime-in-a-given-base.maple b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Maple/find-largest-left-truncatable-prime-in-a-given-base.maple new file mode 100644 index 0000000000..dbe86cef94 --- /dev/null +++ b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Maple/find-largest-left-truncatable-prime-in-a-given-base.maple @@ -0,0 +1,35 @@ +MaxLeftTruncatablePrime := proc(b, $) +local i, j, c, p, sdprimes; +local tprimes := table(); + sdprimes := select(isprime, [seq(1..b-1)]); + for p in sdprimes do + if assigned(tprimes[p]) then + next; + end if; + i := ilog[b](p)+1; + j := 1; + do + c := j*b^i + p; + if j >= b then + # we have tried all 1 digit extensions of p, add p to tprimes and move back 1 digit + tprimes[p] := p; + if i = 1 then + # if we are at the first digit, go to the next 1 digit prime + break; + end if; + i := i - 1; + j := 1; + p := p - iquo(p, b^i)*b^i; + elif assigned(tprimes[c]) then + j := j + 1; + elif isprime(c) then + p := c; + i := i + 1; + j := 1; + else + j := j+1; + end if; + end do; + end do; + return max(indices(tprimes, 'nolist')); +end proc; diff --git a/Task/Find-limit-of-recursion/HolyC/find-limit-of-recursion.holyc b/Task/Find-limit-of-recursion/HolyC/find-limit-of-recursion.holyc new file mode 100644 index 0000000000..d17aa4b843 --- /dev/null +++ b/Task/Find-limit-of-recursion/HolyC/find-limit-of-recursion.holyc @@ -0,0 +1,6 @@ +U0 Recurse(U64 i) { + Print("%d\n", i); + Recurse(i + 1); +} + +Recurse(0); diff --git a/Task/Find-limit-of-recursion/Swift/find-limit-of-recursion.swift b/Task/Find-limit-of-recursion/Swift/find-limit-of-recursion.swift new file mode 100644 index 0000000000..8bac6ad560 --- /dev/null +++ b/Task/Find-limit-of-recursion/Swift/find-limit-of-recursion.swift @@ -0,0 +1,9 @@ +var n = 1 + +func recurse() { + print(n) + n += 1 + recurse() +} + +recurse() diff --git a/Task/Find-limit-of-recursion/VBA/find-limit-of-recursion.vba b/Task/Find-limit-of-recursion/VBA/find-limit-of-recursion.vba new file mode 100644 index 0000000000..ad409b3e28 --- /dev/null +++ b/Task/Find-limit-of-recursion/VBA/find-limit-of-recursion.vba @@ -0,0 +1,13 @@ +Option Explicit + +Sub Main() + Debug.Print "The limit is : " & Limite_Recursivite(0) +End Sub + +Function Limite_Recursivite(Cpt As Long) As Long + Cpt = Cpt + 1 'Count + On Error Resume Next + Limite_Recursivite Cpt 'recurse + On Error GoTo 0 + Limite_Recursivite = Cpt 'return +End Function diff --git a/Task/Find-the-last-Sunday-of-each-month/C/find-the-last-sunday-of-each-month.c b/Task/Find-the-last-Sunday-of-each-month/C/find-the-last-sunday-of-each-month.c index 89d577aa69..8856af0eca 100644 --- a/Task/Find-the-last-Sunday-of-each-month/C/find-the-last-sunday-of-each-month.c +++ b/Task/Find-the-last-Sunday-of-each-month/C/find-the-last-sunday-of-each-month.c @@ -12,8 +12,7 @@ int main(int argc, char *argv[]) for(m = 0; m < 12; m++) { w = (w + days[m]) % 7; - printf("%d-%02d-%d\n", y, m + 1, - days[m] + (w < 5 ? -2 : 5) - w); + printf("%d-%02d-%d\n", y, m + 1,days[m] - w); } return 0; diff --git a/Task/Find-the-last-Sunday-of-each-month/Erlang/find-the-last-sunday-of-each-month.erl b/Task/Find-the-last-Sunday-of-each-month/Erlang/find-the-last-sunday-of-each-month.erl index 41ebe4dc74..a9d3c69676 100644 --- a/Task/Find-the-last-Sunday-of-each-month/Erlang/find-the-last-sunday-of-each-month.erl +++ b/Task/Find-the-last-Sunday-of-each-month/Erlang/find-the-last-sunday-of-each-month.erl @@ -1,18 +1,13 @@ --module( last_date_each_month ). +-module(last_sundays). --export( [monday/1, tuesday/1, wednesday/1, thursday/1, friday/1, saturday/1, sunday/1] ). +-export([in_year/1]). -monday( Year ) -> last( Year, 1 ). -tuesday( Year ) -> last( Year, 2 ). -wednesday( Year ) -> last( Year, 3 ). -thursday( Year ) -> last( Year, 4 ). -friday( Year ) -> last( Year, 5 ). -saturday( Year ) -> last( Year, 6 ). -sunday( Year ) -> last( Year, 7 ). +% calculate all the last sundays in a particular year +in_year(Year) -> + [lastday(Year, Month, 7) || Month <- lists:seq(1, 12)]. - - -last( Year, Week_day ) -> - Months = lists:seq( 1, 12 ), - Months_days = [{X, Y} || X <- Months, Y <- lists:seq(calendar:last_day_of_the_month(Year, X), calendar:last_day_of_the_month(Year, X) - 7, -1), calendar:valid_date(Year, X, Y), calendar:day_of_the_week(Year, X, Y) =:= Week_day], - [{Year, X, proplists:get_value(X, Months_days)} || X <- Months]. +% calculate the date of the last occurrence of a particular weekday +lastday(Year, Month, WeekDay) -> + Ldm = calendar:last_day_of_the_month(Year, Month), + Diff = calendar:day_of_the_week(Year, Month, Ldm) rem WeekDay, + {Year, Month, Ldm - Diff}. 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 new file mode 100644 index 0000000000..4628f18273 --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Factor/find-the-last-sunday-of-each-month.factor @@ -0,0 +1,11 @@ +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 ; +: 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: main diff --git a/Task/Find-the-last-Sunday-of-each-month/Maple/find-the-last-sunday-of-each-month.maple b/Task/Find-the-last-Sunday-of-each-month/Maple/find-the-last-sunday-of-each-month.maple new file mode 100644 index 0000000000..29df47069f --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Maple/find-the-last-sunday-of-each-month.maple @@ -0,0 +1,18 @@ +sundays := proc(year) + local i, dt, change, last_days; + last_days := [31,28,31,30,31,30,31,31,30,31,30,31]; + if (Calendar:-IsLeapYear(year)) then + last_days[2] := 28; + end if; + for i to 12 do + dt := Date(year, i, last_days[i]); + change := 0; + if not(Calendar:-DayOfWeek(dt) = 1) then + change := -Calendar:-DayOfWeek(dt) + 1; + end if; + dt := Calendar:-AdjustDateField(dt, "date", change); + printf("%d-%d-%d\n", year, Month(dt), DayOfMonth(dt)); + end do; +end proc; + +sundays(2013); diff --git a/Task/Find-the-last-Sunday-of-each-month/Perl-6/find-the-last-sunday-of-each-month.pl6 b/Task/Find-the-last-Sunday-of-each-month/Perl-6/find-the-last-sunday-of-each-month.pl6 index 96b24c44cf..17e6339183 100644 --- a/Task/Find-the-last-Sunday-of-each-month/Perl-6/find-the-last-sunday-of-each-month.pl6 +++ b/Task/Find-the-last-Sunday-of-each-month/Perl-6/find-the-last-sunday-of-each-month.pl6 @@ -1,6 +1,6 @@ sub MAIN ($year = Date.today.year) { - for 1..12 -> $mo { - my $month-end = Date.new($year, $mo, Date.days-in-month($year, $mo)); + for 1..12 -> $month { + my $month-end = Date.new($year, $month, Date.new($year,$month,1).days-in-month); say $month-end - $month-end.day-of-week % 7; } } diff --git a/Task/Find-the-last-Sunday-of-each-month/Stata/find-the-last-sunday-of-each-month.stata b/Task/Find-the-last-Sunday-of-each-month/Stata/find-the-last-sunday-of-each-month.stata new file mode 100644 index 0000000000..f99c58c77a --- /dev/null +++ b/Task/Find-the-last-Sunday-of-each-month/Stata/find-the-last-sunday-of-each-month.stata @@ -0,0 +1,27 @@ +program last_sundays + args year + clear + qui set obs 12 + gen day=dofm(mofd(mdy(_n,1,`year'))+1)-1 + qui replace day=day-mod(dow(day),7) + format %td day + list, noobs noheader sep(6) +end + +last_sundays 2013 + + +-----------+ + | 27jan2013 | + | 24feb2013 | + | 31mar2013 | + | 28apr2013 | + | 26may2013 | + | 30jun2013 | + |-----------| + | 28jul2013 | + | 25aug2013 | + | 29sep2013 | + | 27oct2013 | + | 24nov2013 | + | 29dec2013 | + +-----------+ diff --git a/Task/Find-the-missing-permutation/Aime/find-the-missing-permutation.aime b/Task/Find-the-missing-permutation/Aime/find-the-missing-permutation.aime index b62e58e26b..cff4cad093 100644 --- a/Task/Find-the-missing-permutation/Aime/find-the-missing-permutation.aime +++ b/Task/Find-the-missing-permutation/Aime/find-the-missing-permutation.aime @@ -1,12 +1,12 @@ void -paste(record r, index x, data p, integer a,) +paste(record r, index x, text p, integer a) { - i_delete(x, a); - p[i_size(x)] = a; - if (i_size(x)) { - i_wcall(x, paste, -1, -1, r, x, p); + p = insert(p, -1, a); + x.delete(a); + if (~x) { + x.vcall(paste, -1, r, x, p); } else { - r[b_string(p)] = 0; + r[p] = 0; } x[a] = 0; } @@ -17,20 +17,18 @@ main(void) record r; list l; index x; - data p; - l_bill(l, 0, "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", + l.bill(0, "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"); - i_fit(x, 'A', 0, 'B', 0, 'C', 0, 'D', 0); + x['A'] = x['B'] = x['C'] = x['D'] = 0; - b_size(p, 4); - i_wcall(x, paste, -1, -1, r, x, p); + x.vcall(paste, -1, r, x, ""); - l_ucall(l, r_delete, 1, r); + l.ucall(r_delete, 1, r); - o_(r_low(r), "\n"); + o_(r.low, "\n"); return 0; } diff --git a/Task/Find-the-missing-permutation/AppleScript/find-the-missing-permutation.applescript b/Task/Find-the-missing-permutation/AppleScript/find-the-missing-permutation.applescript index 9b864c7c09..273ae8c201 100644 --- a/Task/Find-the-missing-permutation/AppleScript/find-the-missing-permutation.applescript +++ b/Task/Find-the-missing-permutation/AppleScript/find-the-missing-permutation.applescript @@ -1,143 +1,131 @@ use framework "Foundation" -- ( sort ) --- RAREST LETTER IN EACH COLUMN ----------------------------------------------- +-- RAREST LETTER IN EACH COLUMN ---------------------------------------------- on run intercalate("", ¬ - map(compose({¬ - sort, ¬ + map(composeAll({¬ + head, ¬ + curry(minimumBy)'s |λ|(comparing(|length|)), ¬ group, ¬ - curry(minimumBy)'s lambda(comparing(_length)), ¬ - head}), ¬ - transpose(map(stringChars, (splitOn(space, ¬ - "ABCD CABD ACDB DACB BCDA ACBD " & ¬ - "ADCB CDAB DABC BCAD CADB CDBA " & ¬ - "CBAD ABDC ADBC BDCA DCBA BACD " & ¬ - "BADC BDAC CBDA DBCA DCAB")))))) + sort}), ¬ + transpose(map(chars, ¬ + |words|("ABCD CABD ACDB DACB BCDA ACBD " & ¬ + "ADCB CDAB DABC BCAD CADB CDBA " & ¬ + "CBAD ABDC ADBC BDCA DCBA BACD " & ¬ + "BADC BDAC CBDA DBCA DCAB"))))) --> "DBAC" end run - -- GENERIC FUNCTIONS ---------------------------------------------------------- --- compose :: [(a -> a)] -> (a -> a) -on compose(fs) - script - on lambda(x) - script - on lambda(a, f) - mReturn(f)'s lambda(a) - end lambda - end script +-- chars :: String -> [String] +on chars(s) + characters of s +end chars - foldl(result, x, fs) - end lambda - end script -end compose - --- transpose :: [[a]] -> [[a]] -on transpose(xss) - script column - on lambda(_, iCol) - script row - on lambda(xs) - item iCol of xs - end lambda - end script - - map(row, xss) - end lambda - end script - - map(column, item 1 of xss) -end transpose - --- sort :: [a] -> [a] -on sort(lst) - ((current application's NSArray's arrayWithArray:lst)'s ¬ - sortedArrayUsingSelector:"compare:") as list -end sort - --- group :: Eq a => [a] -> [[a]] -on group(xs) - script eq - on lambda(a, b) - a = b - end lambda - end script - - groupBy(eq, xs) -end group - --- minimumBy :: (a -> a -> Ordering) -> [a] -> a -on minimumBy(f, xs) - set mf to mReturn(f) - script min - on lambda(a, b) - if a is missing value then - b - else if mf's lambda(a, b) < 0 then - a - else - b - end if - end lambda - end script - - foldl(min, missing value, xs) -end minimumBy +-- Ordering :: (-1 | 0 | 1) +-- compare :: a -> a -> Ordering +on compare(a, b) + if a < b then + -1 + else if a > b then + 1 + else + 0 + end if +end compare -- comparing :: (a -> b) -> (a -> a -> Ordering) on comparing(f) - set mf to mReturn(f) script - on lambda(a, b) - set x to mf's lambda(a) - set y to mf's lambda(b) - if x < y then - -1 - else - if x > y then - 1 - else - 0 - end if - end if - end lambda + on |λ|(a, b) + tell mReturn(f) to compare(|λ|(a), |λ|(b)) + end |λ| end script end comparing +-- composeAll :: [(a -> a)] -> (a -> a) +on composeAll(fs) + script + on |λ|(x) + script + on |λ|(f, a) + mReturn(f)'s |λ|(a) + end |λ| + end script + + foldr(result, x, fs) + end |λ| + end script +end composeAll + -- curry :: (Script|Handler) -> Script on curry(f) script - on lambda(a) + on |λ|(a) script - on lambda(b) - lambda(a, b) of mReturn(f) - end lambda + on |λ|(b) + |λ|(a, b) of mReturn(f) + end |λ| end script - end lambda + end |λ| end script end curry +-- foldl :: (a -> b -> a) -> a -> [b] -> a +on foldl(f, startValue, xs) + tell mReturn(f) + set v to startValue + set lng to length of xs + repeat with i from 1 to lng + set v to |λ|(v, item i of xs, i, xs) + end repeat + return v + end tell +end foldl + +-- foldr :: (b -> a -> a) -> a -> [b] -> a +on foldr(f, startValue, xs) + tell mReturn(f) + set v to startValue + set lng to length of xs + repeat with i from lng to 1 by -1 + set v to |λ|(item i of xs, v, i, xs) + end repeat + return v + end tell +end foldr + +-- group :: Eq a => [a] -> [[a]] +on group(xs) + script eq + on |λ|(a, b) + a = b + end |λ| + end script + + groupBy(eq, xs) +end group + -- groupBy :: (a -> a -> Bool) -> [a] -> [[a]] on groupBy(f, xs) set mf to mReturn(f) script enGroup - on lambda(a, x) + on |λ|(a, x) if length of (active of a) > 0 then set h to item 1 of active of a else set h to missing value end if - if h is not missing value and mf's lambda(h, x) then + if h is not missing value and mf's |λ|(h, x) then {active:(active of a) & x, sofar:sofar of a} else {active:{x}, sofar:(sofar of a) & {active of a}} end if - end lambda + end |λ| end script if length of xs > 0 then @@ -161,6 +149,61 @@ on head(xs) end if end head +-- intercalate :: Text -> [Text] -> Text +on intercalate(strText, lstText) + set {dlm, my text item delimiters} to {my text item delimiters, strText} + set strJoined to lstText as text + set my text item delimiters to dlm + return strJoined +end intercalate + +-- length :: [a] -> Int +on |length|(xs) + length of xs +end |length| + +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map + +-- minimumBy :: (a -> a -> Ordering) -> [a] -> a +on minimumBy(f, xs) + if length of xs < 1 then return missing value + tell mReturn(f) + set v to item 1 of xs + repeat with x in xs + if |λ|(x, v) < 0 then set v to x + end repeat + return v + end tell +end minimumBy + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn + +-- sort :: [a] -> [a] +on sort(xs) + ((current application's NSArray's arrayWithArray:xs)'s ¬ + sortedArrayUsingSelector:"compare:") as list +end sort + -- tail :: [a] -> [a] on tail(xs) if length of xs > 1 then @@ -170,64 +213,24 @@ on tail(xs) end if end tail --- splitOn :: Text -> Text -> [Text] -on splitOn(strDelim, strMain) - set {dlm, my text item delimiters} to {my text item delimiters, strDelim} - set xs to text items of strMain - set my text item delimiters to dlm - return xs -end splitOn +-- transpose :: [[a]] -> [[a]] +on transpose(xss) + script column + on |λ|(_, iCol) + script row + on |λ|(xs) + item iCol of xs + end |λ| + end script --- stringChars :: String -> [Char] -on stringChars(s) - characters of s -end stringChars + map(row, xss) + end |λ| + end script --- length :: [a] -> Int -on _length(xs) - length of xs -end _length + map(column, item 1 of xss) +end transpose --- intercalate :: Text -> [Text] -> Text -on intercalate(strText, lstText) - set {dlm, my text item delimiters} to {my text item delimiters, strText} - set strJoined to lstText as text - set my text item delimiters to dlm - return strJoined -end intercalate - --- map :: (a -> b) -> [a] -> [b] -on map(f, xs) - tell mReturn(f) - set lng to length of xs - set lst to {} - repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) - end repeat - return lst - end tell -end map - --- foldl :: (a -> b -> a) -> a -> [b] -> a -on foldl(f, startValue, xs) - tell mReturn(f) - set v to startValue - set lng to length of xs - repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) - end repeat - return v - end tell -end foldl - --- Lift 2nd class handler function into 1st class script wrapper --- mReturn :: Handler -> Script -on mReturn(f) - if class of f is script then - f - else - script - property lambda : f - end script - end if -end mReturn +-- words :: String -> [String] +on |words|(s) + words of s +end |words| diff --git a/Task/Find-the-missing-permutation/Factor/find-the-missing-permutation.factor b/Task/Find-the-missing-permutation/Factor/find-the-missing-permutation.factor new file mode 100644 index 0000000000..aeac1617d8 --- /dev/null +++ b/Task/Find-the-missing-permutation/Factor/find-the-missing-permutation.factor @@ -0,0 +1,3 @@ +USING: io math.combinatorics sequences sets ; + +"ABCD" all-permutations lines diff first print 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 8e2f3e2a4d..248f785cbd 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,15 +1,13 @@ -function find_missing_permutations{T<:String}(a::Array{T,1}) - std = unique(sort(split(a[1], ""))) - needsperm = trues(factorial(length(std))) - for s in a - b = split(s, "") - p = map(x->findfirst(std, x), b) - isperm(p) || throw(DomainError()) - needsperm[nthperm(p)] = false +using Combinatorics +function missingperm(arr::Vector) + allperms = permutations(arr[1]) + for perm in allperms + perm = convert(eltype(arr), perm) + if perm ∉ arr return perm end end - mperms = T[] - for i in findn(needsperm)[1] - push!(mperms, join(nthperm(std, i), "")) - end - return mperms end + +arr = ["ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD", + "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC", "BDAC", + "CBDA", "DBCA", "DCAB"] +@show missingperm(arr) 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 5bb63072ef..da8c559608 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 @@ -1,24 +1,17 @@ -test = ["ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", - "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA", - "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", - "BADC", "BDAC", "CBDA", "DBCA", "DCAB"] - -missperms = find_missing_permutations(test) - -print("The test list is:\n ") -i = 0 -for s in test - print(s, " ") - i += 1 - i %= 5 - i != 0 || print("\n ") -end -i == 0 || println() -if length(missperms) > 0 - println("The following permutations are missing:") - for s in missperms - println(" ", s) +function missingperm1(arr::Vector{<:AbstractString}) + missperm = string() + for pos in 1:length(arr[1]) + s = Set() + for perm in arr + c = perm[pos] + if c ∈ s pop!(s, c) else push!(s, c) end + end + missperm *= first(s) end -else - println("There are no missing permutations.") + return missperm end + +using BenchmarkTools + +@btime missingperm(arr) +@btime missingperm1(arr) diff --git a/Task/Find-the-missing-permutation/Maple/find-the-missing-permutation.maple b/Task/Find-the-missing-permutation/Maple/find-the-missing-permutation.maple new file mode 100644 index 0000000000..0a95975487 --- /dev/null +++ b/Task/Find-the-missing-permutation/Maple/find-the-missing-permutation.maple @@ -0,0 +1,11 @@ +lst := ["ABCD","CABD","ACDB","DACB","BCDA","ACBD","ADCB","CDAB","DABC","BCAD","CADB","CDBA","CBAD","ABDC","ADBC","BDCA","DCBA","BACD","BADC","BDAC","CBDA","DBCA","DCAB"]: +perm := table(): +for letter in "ABCD" do + perm[letter] := 0: +end do: +for item in lst do + for letter in "ABCD" do + perm[letter] += StringTools:-FirstFromLeft(letter, item): + end do: +end do: +print(StringTools:-Join(ListTools:-Flatten([indices(perm)], 4)[sort(map(x->60-x, ListTools:-Flatten([entries(perm)],4)),'output=permutation')], "")): diff --git a/Task/Find-the-missing-permutation/Perl-6/find-the-missing-permutation-2.pl6 b/Task/Find-the-missing-permutation/Perl-6/find-the-missing-permutation-2.pl6 index dd62435d71..5a049460dc 100644 --- a/Task/Find-the-missing-permutation/Perl-6/find-the-missing-permutation-2.pl6 +++ b/Task/Find-the-missing-permutation/Perl-6/find-the-missing-permutation-2.pl6 @@ -1 +1,2 @@ -say [~^] @givens; +say [~^] ; 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 ba652a9d07..6f4b1c5927 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 @@ -15,5 +15,5 @@ symbol program = var multiplied := numlist zip:numlisti by(:n1:n2)( (:m)(n1 * n2 * m) ); toArray. - multiplied forEach(:multiplier)[ console printLine(multiplier eval(0.5r)) ]. + multiplied forEach(:multiplier)[ console printLine(multiplier(0.5r)) ]. ]. diff --git a/Task/First-class-functions-Use-numbers-analogously/Julia/first-class-functions-use-numbers-analogously.julia b/Task/First-class-functions-Use-numbers-analogously/Julia/first-class-functions-use-numbers-analogously.julia new file mode 100644 index 0000000000..dc045289d9 --- /dev/null +++ b/Task/First-class-functions-Use-numbers-analogously/Julia/first-class-functions-use-numbers-analogously.julia @@ -0,0 +1,10 @@ +x, xi = 2.0, 0.5 +y, yi = 4.0, 0.25 +z, zi = x + y, 1.0 / ( x + y ) + +multiplier = (n1, n2) -> (m) -> n1 * n2 * m + +numlist = [x , y, z] +numlisti = [xi, yi, zi] + +@show collect(multiplier(n, invn)(0.5) for (n, invn) in zip(numlist, numlisti)) diff --git a/Task/First-class-functions/Elena/first-class-functions.elena b/Task/First-class-functions/Elena/first-class-functions.elena index 7b9a493263..ec4d4ecd23 100644 --- a/Task/First-class-functions/Elena/first-class-functions.elena +++ b/Task/First-class-functions/Elena/first-class-functions.elena @@ -10,8 +10,8 @@ extension op program = [ - var fs := (%"mathOp.sin[0]", %"mathOp.cos[0]", [ ^ closure power:3.0r ]). - var gs := (%"mathOp.arcsin[0]", %"mathOp.arccos[0]", [ ^ closure power:(1.0r / 3) ]). + var fs := (%"mathOp.sin[0]", %"mathOp.cos[0]", { eval [ ^ self power:3.0r ] }). + var gs := (%"mathOp.arcsin[0]", %"mathOp.arccos[0]", { eval[ ^ self power:(1.0r / 3) ]}). fs zip:gs by(:f:g)( 0.5r compose(f,g) ); forEach:printingLn. diff --git a/Task/Five-weekends/Factor/five-weekends.factor b/Task/Five-weekends/Factor/five-weekends.factor new file mode 100644 index 0000000000..7b71ec4d6c --- /dev/null +++ b/Task/Five-weekends/Factor/five-weekends.factor @@ -0,0 +1,17 @@ +USING: calendar calendar.format formatting fry io kernel math +sequences ; +IN: rosetta-code.five-weekends + +: timestamps>my ( months -- ) + [ { MONTH bl YYYY nl } formatted 2drop ] each ; + +: month-range ( start-year #months -- seq ) + '[ _ _ ] call [ months time+ ] with map ; + +: find-five-weekend-months ( months -- months' ) + [ [ friday? ] [ days-in-month ] bi 31 = and ] filter ; + +1900 12 201 * month-range find-five-weekend-months +[ length "%d five-weekend months found.\n" printf ] +[ 5 head timestamps>my "..." print ] +[ 5 tail* timestamps>my ] tri diff --git a/Task/Five-weekends/Julia/five-weekends.julia b/Task/Five-weekends/Julia/five-weekends.julia index b16692c175..e5aae42847 100644 --- a/Task/Five-weekends/Julia/five-weekends.julia +++ b/Task/Five-weekends/Julia/five-weekends.julia @@ -1,26 +1,21 @@ -isdefined(:Date) || using Dates +isweekend(dt::Date) = Dates.dayofweek(dt) ∈ (Dates.Friday, Dates.Saturday, Dates.Sunday) -const wday = Dates.Fri -const lo = 1900 -const hi = 2100 -const showres = 5 - -mfive = recur(Date(lo, 1):Month(1):Date(hi, 12)) do m - Dates.daysinmonth(m) == 31 && Dates.dayofweek(m) == wday +function hasfiveweekend(month::Integer, year::Integer) + dmin = Date(year, month, 1) + dmax = dmin + Dates.Day(Dates.daysinmonth(dmin) - 1) + return count(isweekend, dmin:dmax) ≥ 15 end -println("Considering the years from ", lo, " to ", hi, ".\n") -println("There are ", length(mfive), " months having 5 3-day weekends.") +months = collect((y, m) for y in 1900:2100, m in 1:12 if hasfiveweekend(m, y)) -println("The first ", showres, " such months are:") -for m in mfive[1:showres] - println(" ", Dates.monthname(m), " ", Dates.year(m)) -end +println("Number of months with 5 full-weekends: $(length(months))") +println("First five such months:") +for (y, m) in months[1:5] println(" - $y-$m") end +println("Last five such months:") +for (y, m) in months[end-4:end] println(" - $y-$m") end -println("\nThe last ", showres, " such months are:") -for m in mfive[end-showres+1:end] - println(" ", Dates.monthname(m), " ", Dates.year(m)) -end +# extra credit +yrs = getindex.(months, 1) +nyrs = 2100 - 1899 - length(unique(yrs)) -print("\nThere are ", length(filter(y -> !(y in year(mfive)), lo:hi))) -println(" years that have no such months.") +println("Number of year with not one 5-full-weekend month: $nyrs") diff --git a/Task/Five-weekends/Maple/five-weekends.maple b/Task/Five-weekends/Maple/five-weekends.maple new file mode 100644 index 0000000000..860a1f013d --- /dev/null +++ b/Task/Five-weekends/Maple/five-weekends.maple @@ -0,0 +1,17 @@ +five_weekends:= proc() + local i, month, count; + #Only months with 31 days can possibly satisfy the condition + local long_months := [1,3,5,7,8,10,12]; + local months := ["January","February","March","April","May","June","July","August","September","October","November","December"]; + count := 0; + for i from 1900 to 2100 by 1 do + for month in long_months do + if Calendar:-DayOfWeek(Date(i, month, 1)) = 6 then + printf("%d-%s\n", i, months[month]); + count++; + end if; + end do; + end do; + printf("%d months have five full weekends.\n", count); +end proc; +five_weekends(); diff --git a/Task/Five-weekends/Stata/five-weekends.stata b/Task/Five-weekends/Stata/five-weekends.stata new file mode 100644 index 0000000000..01ec787866 --- /dev/null +++ b/Task/Five-weekends/Stata/five-weekends.stata @@ -0,0 +1,30 @@ +clear +set obs `=tm(2101m1)-tm(1900m1)' +gen month=tm(1900m1)+_n-1 +format %tm month +gen day=dofm(month) +keep if dofm(month+1)-day==31 & dow(day)==5 +drop day + +count + 201 + +list in f/5, noobs noheader + + +--------+ + | 1901m3 | + | 1902m8 | + | 1903m5 | + | 1904m1 | + | 1904m7 | + +--------+ + +list in -5/l, noobs noheader + + +---------+ + | 2097m3 | + | 2098m8 | + | 2099m5 | + | 2100m1 | + | 2100m10 | + +---------+ diff --git a/Task/Five-weekends/VBA/five-weekends.vba b/Task/Five-weekends/VBA/five-weekends.vba new file mode 100644 index 0000000000..19f44533de --- /dev/null +++ b/Task/Five-weekends/VBA/five-weekends.vba @@ -0,0 +1,22 @@ +Option Explicit + +Sub Main() +Dim y As Long, m As Long, t As String, cpt As Long, cptm As Long + For y = 1900 To 2100 + t = vbNullString + For m = 1 To 12 Step 2 + If m = 9 Then m = 8 + If Weekday(DateSerial(y, m, 1)) = vbFriday Then + t = t & ", " & m + cptm = cptm + 1 + End If + Next + If t <> "" Then + Debug.Print y & t + Else + cpt = cpt + 1 + End If + Next + Debug.Print "There is " & cptm & " months with five full weekends from the year 1900 through 2100" + Debug.Print "There is " & cpt & " years which don't have months with five weekends" +End Sub diff --git a/Task/FizzBuzz/ARM-Assembly/fizzbuzz.arm b/Task/FizzBuzz/ARM-Assembly/fizzbuzz.arm new file mode 100644 index 0000000000..3fa8ef4410 --- /dev/null +++ b/Task/FizzBuzz/ARM-Assembly/fizzbuzz.arm @@ -0,0 +1,119 @@ +/ * linux GAS */ + +.global _start + +.data + +Fizz: .ascii "Fizz\n" +Buzz: .ascii "Buzz\n" +FizzAndBuzz: .ascii "FizzBuzz\n" + +numstr_buffer: .skip 3 +newLine: .ascii "\n" + +.text + +_start: + + bl FizzBuzz + + mov r7, #1 + mov r0, #0 + svc #0 + +FizzBuzz: + + push {lr} + mov r9, #100 + + fizzbuzz_loop: + + mov r0, r9 + mov r1, #15 + bl divide + cmp r1, #0 + ldreq r1, =FizzAndBuzz + moveq r2, #9 + beq fizzbuzz_print + + mov r0, r9 + mov r1, #3 + bl divide + cmp r1, #0 + ldreq r1, =Fizz + moveq r2, #5 + beq fizzbuzz_print + + mov r0, r9 + mov r1, #5 + bl divide + cmp r1, #0 + ldreq r1, =Buzz + moveq r2, #5 + beq fizzbuzz_print + + mov r0, r9 + bl make_num + mov r2, r1 + mov r1, r0 + + fizzbuzz_print: + + mov r0, #1 + mov r7, #4 + svc #0 + + sub r9, #1 + cmp r9, #0 + + bgt fizzbuzz_loop + + pop {lr} + mov pc, lr + +make_num: + + push {lr} + ldr r4, =numstr_buffer + mov r5, #4 + mov r6, #1 + + mov r1, #100 + bl divide + + cmp r0, #0 + subeq r5, #1 + movne r6, #0 + + add r0, #48 + strb r0, [r4, #0] + + mov r0, r1 + mov r1, #10 + bl divide + + cmp r0, #0 + movne r6, #0 + cmp r6, #1 + subeq r5, #1 + + add r0, #48 + strb r0, [r4, #1] + + add r1, #48 + strb r1, [r4, #2] + + mov r2, #4 + sub r0, r2, r5 + add r0, r4, r0 + mov r1, r5 + + pop {lr} + mov pc, lr + +divide: + udiv r2, r0, r1 + mul r3, r1, r2 + sub r1, r0, r3 + mov r0, r2 + mov pc, lr diff --git a/Task/FizzBuzz/ATS/fizzbuzz.ats b/Task/FizzBuzz/ATS/fizzbuzz.ats new file mode 100644 index 0000000000..316a405da4 --- /dev/null +++ b/Task/FizzBuzz/ATS/fizzbuzz.ats @@ -0,0 +1,18 @@ +#include "share/atspre_staload.hats" + +implement main0() = loop(1, 100) where { + fun loop(from: int, to: int): void = + if from > to then () else + let + val by3 = (from % 3 = 0) + val by5 = (from % 5 = 0) + in + case+ (by3, by5) of + | (true, true) => print_string("FizzBuzz") + | (true, false) => print_string("Fizz") + | (false, true) => print_string("Buzz") + | (false, false) => print_int(from); + print_newline(); + loop(from+1, to) + end +} diff --git a/Task/FizzBuzz/BASIC/fizzbuzz.basic b/Task/FizzBuzz/BASIC/fizzbuzz.basic new file mode 100644 index 0000000000..9e10214a30 --- /dev/null +++ b/Task/FizzBuzz/BASIC/fizzbuzz.basic @@ -0,0 +1,16 @@ +'Free BASIC +DIM AS ULong n + +FOR n = 1 TO 100 + + If n MOD 15 = 0 Then + PRINT "FizzBuzz" + ElseIF n MOD 3 = 0 Then + PRINT "Fizz" + ElseIF n MOD 5 = 0 Then + PRINT "Buzz" + Else + PRINT ; n + End If + + NEXT n diff --git a/Task/FizzBuzz/Clojure/fizzbuzz-1.clj b/Task/FizzBuzz/Clojure/fizzbuzz-1.clj index c4fff08cd1..52098f7ef8 100644 --- a/Task/FizzBuzz/Clojure/fizzbuzz-1.clj +++ b/Task/FizzBuzz/Clojure/fizzbuzz-1.clj @@ -1,9 +1 @@ -(defn fizzbuzz [start finish] - (map (fn [n] - (cond - (zero? (mod n 15)) "FizzBuzz" - (zero? (mod n 3)) "Fizz" - (zero? (mod n 5)) "Buzz" - :else n)) - (range start finish))) -(fizzbuzz 1 100) +(doseq [x (range 1 101)] (println x (str (when (zero? (mod x 3)) "fizz") (when (zero? (mod x 5)) "buzz")))) diff --git a/Task/FizzBuzz/Clojure/fizzbuzz-10.clj b/Task/FizzBuzz/Clojure/fizzbuzz-10.clj index f678c67e88..ee5abb51f9 100644 --- a/Task/FizzBuzz/Clojure/fizzbuzz-10.clj +++ b/Task/FizzBuzz/Clojure/fizzbuzz-10.clj @@ -1,4 +1,2 @@ -(take 100 - (map #(if (pos? (compare %1 %2)) %1 %2) - (map str (drop 1 (range))) - (map str (cycle ["" "" "Fizz"]) (cycle ["" "" "" "" "Buzz"])))) +(let [n nil fizz (cycle [n n "fizz"]) buzz (cycle [n n n n "buzz"]) nums (iterate inc 1)] + (take 20 (map #(if (or %1 %2) (str %1 %2) %3) fizz buzz nums))) diff --git a/Task/FizzBuzz/Clojure/fizzbuzz-11.clj b/Task/FizzBuzz/Clojure/fizzbuzz-11.clj index 671b053149..f678c67e88 100644 --- a/Task/FizzBuzz/Clojure/fizzbuzz-11.clj +++ b/Task/FizzBuzz/Clojure/fizzbuzz-11.clj @@ -1,19 +1,4 @@ -;;Using clojure maps -(defn fizzbuzz - [n] - (let [rule {3 "Fizz" - 5 "Buzz"} - divs (->> rule - (map first) - sort - (filter (comp (partial = 0) - (partial rem n))))] - (if (empty? divs) - (str n) - (->> divs - (map rule) - (apply str))))) - -(defn allfizzbuzz - [max] - (map fizzbuzz (range 1 (inc max)))) +(take 100 + (map #(if (pos? (compare %1 %2)) %1 %2) + (map str (drop 1 (range))) + (map str (cycle ["" "" "Fizz"]) (cycle ["" "" "" "" "Buzz"])))) diff --git a/Task/FizzBuzz/Clojure/fizzbuzz-12.clj b/Task/FizzBuzz/Clojure/fizzbuzz-12.clj index d45f70ec49..671b053149 100644 --- a/Task/FizzBuzz/Clojure/fizzbuzz-12.clj +++ b/Task/FizzBuzz/Clojure/fizzbuzz-12.clj @@ -1,6 +1,19 @@ -(take 100 - (map #(str %1 %2 (if-not (or %1 %2) %3)) - (cycle [nil nil "Fizz"]) - (cycle [nil nil nil nil "Buzz"]) - (rest (range)) - )) +;;Using clojure maps +(defn fizzbuzz + [n] + (let [rule {3 "Fizz" + 5 "Buzz"} + divs (->> rule + (map first) + sort + (filter (comp (partial = 0) + (partial rem n))))] + (if (empty? divs) + (str n) + (->> divs + (map rule) + (apply str))))) + +(defn allfizzbuzz + [max] + (map fizzbuzz (range 1 (inc max)))) diff --git a/Task/FizzBuzz/Clojure/fizzbuzz-13.clj b/Task/FizzBuzz/Clojure/fizzbuzz-13.clj index 39eab38623..d45f70ec49 100644 --- a/Task/FizzBuzz/Clojure/fizzbuzz-13.clj +++ b/Task/FizzBuzz/Clojure/fizzbuzz-13.clj @@ -1,18 +1,6 @@ (take 100 - ( - (fn [& fbspec] - (let [ - fbseq #(->> (repeat nil) (cons %2) (take %1) reverse cycle) - strfn #(apply str (if (every? nil? (rest %&)) (first %&)) (rest %&)) - ] - (->> - fbspec - (partition 2) - (map #(apply fbseq %)) - (apply map strfn (rest (range))) - ) ;;endthread - ) ;;endlet - ) ;;endfn - 3 "Fizz" 5 "Buzz" 7 "Bazz" - ) ;;endfn apply -) ;;endtake + (map #(str %1 %2 (if-not (or %1 %2) %3)) + (cycle [nil nil "Fizz"]) + (cycle [nil nil nil nil "Buzz"]) + (rest (range)) + )) diff --git a/Task/FizzBuzz/Clojure/fizzbuzz-14.clj b/Task/FizzBuzz/Clojure/fizzbuzz-14.clj new file mode 100644 index 0000000000..39eab38623 --- /dev/null +++ b/Task/FizzBuzz/Clojure/fizzbuzz-14.clj @@ -0,0 +1,18 @@ +(take 100 + ( + (fn [& fbspec] + (let [ + fbseq #(->> (repeat nil) (cons %2) (take %1) reverse cycle) + strfn #(apply str (if (every? nil? (rest %&)) (first %&)) (rest %&)) + ] + (->> + fbspec + (partition 2) + (map #(apply fbseq %)) + (apply map strfn (rest (range))) + ) ;;endthread + ) ;;endlet + ) ;;endfn + 3 "Fizz" 5 "Buzz" 7 "Bazz" + ) ;;endfn apply +) ;;endtake diff --git a/Task/FizzBuzz/Clojure/fizzbuzz-2.clj b/Task/FizzBuzz/Clojure/fizzbuzz-2.clj index 086b301e3c..c4fff08cd1 100644 --- a/Task/FizzBuzz/Clojure/fizzbuzz-2.clj +++ b/Task/FizzBuzz/Clojure/fizzbuzz-2.clj @@ -1,5 +1,9 @@ -(map (fn [x] (cond (zero? (mod x 15)) "FizzBuzz" - (zero? (mod x 5)) "Buzz" - (zero? (mod x 3)) "Fizz" - :else x)) - (range 1 101)) +(defn fizzbuzz [start finish] + (map (fn [n] + (cond + (zero? (mod n 15)) "FizzBuzz" + (zero? (mod n 3)) "Fizz" + (zero? (mod n 5)) "Buzz" + :else n)) + (range start finish))) +(fizzbuzz 1 100) diff --git a/Task/FizzBuzz/Clojure/fizzbuzz-3.clj b/Task/FizzBuzz/Clojure/fizzbuzz-3.clj index 5e8e028b11..086b301e3c 100644 --- a/Task/FizzBuzz/Clojure/fizzbuzz-3.clj +++ b/Task/FizzBuzz/Clojure/fizzbuzz-3.clj @@ -1 +1,5 @@ -(map #(let [s (str (if (zero? (mod % 3)) "Fizz") (if (zero? (mod % 5)) "Buzz"))] (if (empty? s) % s)) (range 1 101)) +(map (fn [x] (cond (zero? (mod x 15)) "FizzBuzz" + (zero? (mod x 5)) "Buzz" + (zero? (mod x 3)) "Fizz" + :else x)) + (range 1 101)) diff --git a/Task/FizzBuzz/Clojure/fizzbuzz-4.clj b/Task/FizzBuzz/Clojure/fizzbuzz-4.clj index 4021e6960c..5e8e028b11 100644 --- a/Task/FizzBuzz/Clojure/fizzbuzz-4.clj +++ b/Task/FizzBuzz/Clojure/fizzbuzz-4.clj @@ -1,6 +1 @@ -(def fizzbuzz (map - #(cond (zero? (mod % 15)) "FizzBuzz" - (zero? (mod % 5)) "Buzz" - (zero? (mod % 3)) "Fizz" - :else %) - (iterate inc 1))) +(map #(let [s (str (if (zero? (mod % 3)) "Fizz") (if (zero? (mod % 5)) "Buzz"))] (if (empty? s) % s)) (range 1 101)) diff --git a/Task/FizzBuzz/Clojure/fizzbuzz-5.clj b/Task/FizzBuzz/Clojure/fizzbuzz-5.clj index d104442437..4021e6960c 100644 --- a/Task/FizzBuzz/Clojure/fizzbuzz-5.clj +++ b/Task/FizzBuzz/Clojure/fizzbuzz-5.clj @@ -1,13 +1,6 @@ -(defn fizz-buzz - ([] (fizz-buzz (range 1 101))) - ([lst] - (letfn [(fizz? [n] (zero? (mod n 3))) - (buzz? [n] (zero? (mod n 5)))] - (let [f "Fizz" - b "Buzz" - items (map (fn [n] - (cond (and (fizz? n) (buzz? n)) (str f b) - (fizz? n) f - (buzz? n) b - :else n)) - lst)] items)))) +(def fizzbuzz (map + #(cond (zero? (mod % 15)) "FizzBuzz" + (zero? (mod % 5)) "Buzz" + (zero? (mod % 3)) "Fizz" + :else %) + (iterate inc 1))) diff --git a/Task/FizzBuzz/Clojure/fizzbuzz-6.clj b/Task/FizzBuzz/Clojure/fizzbuzz-6.clj index 95073f3e20..d104442437 100644 --- a/Task/FizzBuzz/Clojure/fizzbuzz-6.clj +++ b/Task/FizzBuzz/Clojure/fizzbuzz-6.clj @@ -1,6 +1,13 @@ -(map (fn [n] - (if-let [fb (seq (concat (when (zero? (mod n 3)) "Fizz") - (when (zero? (mod n 5)) "Buzz")))] - (apply str fb) - n)) - (range 1 101)) +(defn fizz-buzz + ([] (fizz-buzz (range 1 101))) + ([lst] + (letfn [(fizz? [n] (zero? (mod n 3))) + (buzz? [n] (zero? (mod n 5)))] + (let [f "Fizz" + b "Buzz" + items (map (fn [n] + (cond (and (fizz? n) (buzz? n)) (str f b) + (fizz? n) f + (buzz? n) b + :else n)) + lst)] items)))) diff --git a/Task/FizzBuzz/Clojure/fizzbuzz-7.clj b/Task/FizzBuzz/Clojure/fizzbuzz-7.clj index b637918e95..95073f3e20 100644 --- a/Task/FizzBuzz/Clojure/fizzbuzz-7.clj +++ b/Task/FizzBuzz/Clojure/fizzbuzz-7.clj @@ -1,4 +1,6 @@ -(take 100 (map #(let [s (str %2 %3) ] (if (seq s) s (inc %)) ) - (range) - (cycle [ "" "" "Fizz" ]) - (cycle [ "" "" "" "" "Buzz" ]))) +(map (fn [n] + (if-let [fb (seq (concat (when (zero? (mod n 3)) "Fizz") + (when (zero? (mod n 5)) "Buzz")))] + (apply str fb) + n)) + (range 1 101)) diff --git a/Task/FizzBuzz/Clojure/fizzbuzz-8.clj b/Task/FizzBuzz/Clojure/fizzbuzz-8.clj index f1ded0180f..b637918e95 100644 --- a/Task/FizzBuzz/Clojure/fizzbuzz-8.clj +++ b/Task/FizzBuzz/Clojure/fizzbuzz-8.clj @@ -1 +1,4 @@ -(map #(nth (conj (cycle [% % "Fizz" % "Buzz" "Fizz" % % "Fizz" "Buzz" % "Fizz" % % "FizzBuzz"]) %) %) (range 1 101)) +(take 100 (map #(let [s (str %2 %3) ] (if (seq s) s (inc %)) ) + (range) + (cycle [ "" "" "Fizz" ]) + (cycle [ "" "" "" "" "Buzz" ]))) diff --git a/Task/FizzBuzz/Clojure/fizzbuzz-9.clj b/Task/FizzBuzz/Clojure/fizzbuzz-9.clj index ee5abb51f9..f1ded0180f 100644 --- a/Task/FizzBuzz/Clojure/fizzbuzz-9.clj +++ b/Task/FizzBuzz/Clojure/fizzbuzz-9.clj @@ -1,2 +1 @@ -(let [n nil fizz (cycle [n n "fizz"]) buzz (cycle [n n n n "buzz"]) nums (iterate inc 1)] - (take 20 (map #(if (or %1 %2) (str %1 %2) %3) fizz buzz nums))) +(map #(nth (conj (cycle [% % "Fizz" % "Buzz" "Fizz" % % "Fizz" "Buzz" % "Fizz" % % "FizzBuzz"]) %) %) (range 1 101)) diff --git a/Task/FizzBuzz/Common-Lisp/fizzbuzz-8.lisp b/Task/FizzBuzz/Common-Lisp/fizzbuzz-8.lisp new file mode 100644 index 0000000000..1679fec4f9 --- /dev/null +++ b/Task/FizzBuzz/Common-Lisp/fizzbuzz-8.lisp @@ -0,0 +1,23 @@ +;; Project : FizzBuzz +;; Date : 2018/03/07 +;; Author : Gal Zsolt [~ CalmoSoft ~] +;; Email : + +(defun fizzbuzz (&optional n) + (let ((n (or n 1))) + (if (> n 100) + nil + (progn + (let ((mult-3 (is-mult-p n 3)) + (mult-5 (is-mult-p n 5))) + (if mult-3 + (princ "Fizz")) + (if mult-5 + (princ "Buzz")) + (if (not (or mult-3 mult-5)) + (princ n)) + (princ #\linefeed) + (fizzbuzz (+ n 1))))))) +(defun is-mult-p (n multiple) + (= (rem n multiple) 0)) +(fizzbuzz 1) diff --git a/Task/FizzBuzz/Factor/fizzbuzz.factor b/Task/FizzBuzz/Factor/fizzbuzz.factor index d9b4ac39c9..e761b31263 100644 --- a/Task/FizzBuzz/Factor/fizzbuzz.factor +++ b/Task/FizzBuzz/Factor/fizzbuzz.factor @@ -1,4 +1,4 @@ -USING: math kernel io math.ranges ; +USING: math kernel io math.functions math.parser math.ranges ; IN: fizzbuzz : fizz ( n -- str ) 3 divisor? "Fizz" "" ? ; : buzz ( n -- str ) 5 divisor? "Buzz" "" ? ; diff --git a/Task/FizzBuzz/Groovy/fizzbuzz.groovy b/Task/FizzBuzz/Groovy/fizzbuzz.groovy index 6d5bb3f115..c7e1ff5daa 100644 --- a/Task/FizzBuzz/Groovy/fizzbuzz.groovy +++ b/Task/FizzBuzz/Groovy/fizzbuzz.groovy @@ -1 +1 @@ -1.upto(100, { i -> println "${i % 3 ? '' : 'Fizz'}${i % 5 ? '' : 'Buzz'}" ?: i }) +1.upto(100) { i -> println "${i % 3 ? '' : 'Fizz'}${i % 5 ? '' : 'Buzz'}" ?: i } diff --git a/Task/FizzBuzz/Julia/fizzbuzz-1.julia b/Task/FizzBuzz/Julia/fizzbuzz-1.julia index e769a21619..1734559153 100644 --- a/Task/FizzBuzz/Julia/fizzbuzz-1.julia +++ b/Task/FizzBuzz/Julia/fizzbuzz-1.julia @@ -1,4 +1,4 @@ -for i = 1:100 +for i in 1:100 if i % 15 == 0 println("FizzBuzz") elseif i % 3 == 0 diff --git a/Task/FizzBuzz/Julia/fizzbuzz-2.julia b/Task/FizzBuzz/Julia/fizzbuzz-2.julia index bd13179641..8debdfcc96 100644 --- a/Task/FizzBuzz/Julia/fizzbuzz-2.julia +++ b/Task/FizzBuzz/Julia/fizzbuzz-2.julia @@ -1,4 +1 @@ -println( [ i%15 == 0? "FizzBuzz" : - i%5 == 0? "Buzz" : - i%3 == 0? "Fizz" : - i for i = 1:100 ] ) +collect(i % 15 == 0 ? "FizzBuzz" : i % 5 == 0 ? "Buzz" : i % 3 == 0 ? "Fizz" : i for i in 1:100) |> println diff --git a/Task/FizzBuzz/Julia/fizzbuzz-3.julia b/Task/FizzBuzz/Julia/fizzbuzz-3.julia index e6c6d7751f..f9c2881238 100644 --- a/Task/FizzBuzz/Julia/fizzbuzz-3.julia +++ b/Task/FizzBuzz/Julia/fizzbuzz-3.julia @@ -1,4 +1,2 @@ -fb(i::Int) = "Fizz" ^ (i%3==0) * - "Buzz" ^ (i%5==0) * - string(i) ^ (i%3!=0 && i%5!=0) -for i=1:100 println(fb(i)) end +fb(i::Integer) = "Fizz" ^ (i % 3 == 0) * "Buzz" ^ (i % 5 == 0) * dec(i) ^ (i % 3 != 0 && i % 5 != 0) +for i in 1:100 println(fb(i)) end diff --git a/Task/FizzBuzz/Julia/fizzbuzz-4.julia b/Task/FizzBuzz/Julia/fizzbuzz-4.julia index 01fe37eeb5..b162e30ac6 100644 --- a/Task/FizzBuzz/Julia/fizzbuzz-4.julia +++ b/Task/FizzBuzz/Julia/fizzbuzz-4.julia @@ -1 +1 @@ -map((x) -> x % 15 == 0 ? "FizzBuzz" : (x % 5 == 0 ? "Buzz" : (x % 3 == 0 ? "Fizz" : x)), 1:100) +println.(map(fb, 1:100)) diff --git a/Task/FizzBuzz/Julia/fizzbuzz-5.julia b/Task/FizzBuzz/Julia/fizzbuzz-5.julia index a714f5c4af..5f05889ad2 100644 --- a/Task/FizzBuzz/Julia/fizzbuzz-5.julia +++ b/Task/FizzBuzz/Julia/fizzbuzz-5.julia @@ -1,7 +1,4 @@ -fib(i) = let result = "" - (i%3 == 0 && (result *="Fizz" ; true)) | - (i%5 == 0 && (result *="Buzz" ; true)) || - (result = string(i)) - result - end -println([fib(i) for i = 1:100]) +for i in 1:100 + msg = "Fizz" ^ (i % 3 == 0) * "Buzz" ^ (i % 5 == 0) + println(isempty(msg) ? i : msg) +end diff --git a/Task/FizzBuzz/Modula-2/fizzbuzz.mod2 b/Task/FizzBuzz/Modula-2/fizzbuzz.mod2 new file mode 100644 index 0000000000..ff9e27a368 --- /dev/null +++ b/Task/FizzBuzz/Modula-2/fizzbuzz.mod2 @@ -0,0 +1,46 @@ +MODULE Fizzbuzz; +FROM FormatString IMPORT FormatString; +FROM Terminal IMPORT WriteString,WriteLn,ReadChar; + +TYPE CB = PROCEDURE(INTEGER); + +PROCEDURE Fizz(n : INTEGER); +BEGIN + IF n MOD 3 = 0 THEN + WriteString("Fizz"); + Buzz(n,Newline) + ELSE + Buzz(n,WriteInt) + END +END Fizz; + +PROCEDURE Buzz(n : INTEGER; f : CB); +BEGIN + IF n MOD 5 = 0 THEN + WriteString("Buzz"); + WriteLn + ELSE + f(n) + END +END Buzz; + +PROCEDURE WriteInt(n : INTEGER); +VAR buf : ARRAY[0..9] OF CHAR; +BEGIN + FormatString("%i\n", buf, n); + WriteString(buf) +END WriteInt; + +PROCEDURE Newline(n : INTEGER); +BEGIN + WriteLn +END Newline; + +VAR i : INTEGER; +BEGIN + FOR i:=1 TO 30 DO + Fizz(i) + END; + + ReadChar +END Fizzbuzz. diff --git a/Task/FizzBuzz/PicoLisp/fizzbuzz-1.l b/Task/FizzBuzz/PicoLisp/fizzbuzz-1.l index a2981ec674..4844314528 100644 --- a/Task/FizzBuzz/PicoLisp/fizzbuzz-1.l +++ b/Task/FizzBuzz/PicoLisp/fizzbuzz-1.l @@ -1,3 +1,6 @@ (for N 100 (prinl (or (pack (at (0 . 3) "Fizz") (at (0 . 5) "Buzz")) N) ) ) + +# Above, we simply count till 100 'prin'-ting number 'at' 3rd ('Fizz'), 5th ('Buzz') and 'pack'-ing 15th number ('FizzBuzz'). +# Rest of the times 'N' is printed as it loops in 'for'. diff --git a/Task/FizzBuzz/REBOL/fizzbuzz-1.rebol b/Task/FizzBuzz/REBOL/fizzbuzz-1.rebol index 5a8b6235be..1f70b346de 100644 --- a/Task/FizzBuzz/REBOL/fizzbuzz-1.rebol +++ b/Task/FizzBuzz/REBOL/fizzbuzz-1.rebol @@ -1 +1,20 @@ -repeat i 100 [case/all [i // 3 = 0 [print"fizz"] i // 5 = 0 [print "buzz"] 1 [print i]]] +REBOL [ + Title: "FizzBuzz" + Author: oofoe + Date: 2009-12-10 + URL: http://rosettacode.org/wiki/FizzBuzz +] + +; Concatenative. Note use of 'case/all' construct to evaluate all +; conditions. I use 'copy' to allocate a new string each time through +; the loop -- otherwise 'x' would get very long... + +repeat i 100 [ + x: copy "" + case/all [ + 0 = mod i 3 [append x "Fizz"] + 0 = mod i 5 [append x "Buzz"] + "" = x [x: mold i] + ] + print x +] diff --git a/Task/FizzBuzz/REBOL/fizzbuzz-2.rebol b/Task/FizzBuzz/REBOL/fizzbuzz-2.rebol index 1f70b346de..155aa902ed 100644 --- a/Task/FizzBuzz/REBOL/fizzbuzz-2.rebol +++ b/Task/FizzBuzz/REBOL/fizzbuzz-2.rebol @@ -1,20 +1,7 @@ -REBOL [ - Title: "FizzBuzz" - Author: oofoe - Date: 2009-12-10 - URL: http://rosettacode.org/wiki/FizzBuzz -] - -; Concatenative. Note use of 'case/all' construct to evaluate all -; conditions. I use 'copy' to allocate a new string each time through -; the loop -- otherwise 'x' would get very long... - repeat i 100 [ - x: copy "" - case/all [ - 0 = mod i 3 [append x "Fizz"] - 0 = mod i 5 [append x "Buzz"] - "" = x [x: mold i] - ] - print x + print switch/default 0 compose [ + (mod i 15) ["fizzbuzz"] + (mod i 3) ["fizz"] + (mod i 5) ["buzz"] + ][i] ] diff --git a/Task/FizzBuzz/REBOL/fizzbuzz-3.rebol b/Task/FizzBuzz/REBOL/fizzbuzz-3.rebol index 7890dd076f..79db820be0 100644 --- a/Task/FizzBuzz/REBOL/fizzbuzz-3.rebol +++ b/Task/FizzBuzz/REBOL/fizzbuzz-3.rebol @@ -1,11 +1 @@ -repeat i 100 [ - print switch/default 0 compose [ - (mod i 15) ["fizzbuzz"] - (mod i 3) ["fizz"] - (mod i 5) ["buzz"] - ][i] -] - -; And minimized version: - -repeat i 100[j:""if 0 = mod i 3[j:"fizz"]if 0 = mod i 5[j: join j"buzz"]if j =""[j: i]print j] +repeat i 100[j:""if i // 3 = 0[j:"fizz"]if i // 5 = 0[j: join j"buzz"]if""= j[j: i]print j] diff --git a/Task/FizzBuzz/Rust/fizzbuzz-1.rust b/Task/FizzBuzz/Rust/fizzbuzz-1.rust index d18e3ce843..9ca580cbb3 100644 --- a/Task/FizzBuzz/Rust/fizzbuzz-1.rust +++ b/Task/FizzBuzz/Rust/fizzbuzz-1.rust @@ -1,11 +1,9 @@ +use std::borrow::Cow; // Allows us to avoid unnecessary allocations fn main() { - let result = (1..101).map(|n| match (n % 3, n % 5) { - (0, 0) => "FizzBuzz".to_owned(), - (0, _) => "Fizz".to_owned(), - (_, 0) => "Buzz".to_owned(), - _ => n.to_string() - }); - for r in result { - println!("{}", r); - } + (1..101).map(|n| match (n % 3, n % 5) { + (0, 0) => "FizzBuzz".into(), + (0, _) => "Fizz".into(), + (_, 0) => "Buzz".into(), + _ => Cow::from(n.to_string()) + }).for_each(|n| println!("{}", n)); } diff --git a/Task/FizzBuzz/Rust/fizzbuzz-2.rust b/Task/FizzBuzz/Rust/fizzbuzz-2.rust index a217d3f240..e7dc292de3 100644 --- a/Task/FizzBuzz/Rust/fizzbuzz-2.rust +++ b/Task/FizzBuzz/Rust/fizzbuzz-2.rust @@ -1,11 +1,11 @@ +use std::borrow::Cow; fn main() { for i in 1..101 { - let word = match (i % 3, i % 5) { - (0, 0) => "FizzBuzz".to_owned(), - (0, _) => "Fizz".to_owned(), - (_, 0) => "Buzz".to_owned(), - _ => i.to_string().to_owned(), - }; - println!("{}", word); + println!("{}", match (i % 3, i % 5) { + (0, 0) => "FizzBuzz".into(), + (0, _) => "Fizz".into(), + (_, 0) => "Buzz".into(), + _ => Cow::from(i.to_string()), + }); } } diff --git a/Task/FizzBuzz/Simula/fizzbuzz.simula b/Task/FizzBuzz/Simula/fizzbuzz.simula index a267d5c16f..ce12bd0871 100644 --- a/Task/FizzBuzz/Simula/fizzbuzz.simula +++ b/Task/FizzBuzz/Simula/fizzbuzz.simula @@ -2,14 +2,14 @@ begin integer i; for i := 1 step 1 until 100 do begin - if mod( i, 15 ) = 0 then - outtext( "FizzBuzz" ) - else if mod( i, 3 ) = 0 then - outtext( "Fizz" ) - else if mod( i, 5 ) = 0 then - outtext( "Buzz" ) - else - outint( i, 3 ); + boolean fizzed; + fizzed := 0 = mod(i, 3); + if fizzed then + outtext("Fizz"); + if mod(i, 5) = 0 then + outtext("Buzz") + else if not fizzed then + outint(i, 3); outimage end; end diff --git a/Task/FizzBuzz/Stata/fizzbuzz.stata b/Task/FizzBuzz/Stata/fizzbuzz.stata new file mode 100644 index 0000000000..4d0d8894b3 --- /dev/null +++ b/Task/FizzBuzz/Stata/fizzbuzz.stata @@ -0,0 +1,17 @@ +program define fizzbuzz + args n + forvalues i = 1/`n' { + if mod(`i',15) == 0 { + display "FizzBuzz" + } + else if mod(`i',5) == 0 { + display "Buzz" + } + else if mod(`i',3) == 0 { + display "Fizz" + } + else { + display `i' + } + } +end diff --git a/Task/FizzBuzz/Swift/fizzbuzz.swift b/Task/FizzBuzz/Swift/fizzbuzz-1.swift similarity index 100% rename from Task/FizzBuzz/Swift/fizzbuzz.swift rename to Task/FizzBuzz/Swift/fizzbuzz-1.swift diff --git a/Task/FizzBuzz/Swift/fizzbuzz-2.swift b/Task/FizzBuzz/Swift/fizzbuzz-2.swift new file mode 100644 index 0000000000..932946ab12 --- /dev/null +++ b/Task/FizzBuzz/Swift/fizzbuzz-2.swift @@ -0,0 +1,6 @@ +for i in 1...100{ + var s:String? + if i%3==0{s="Fizz"} + if i%5==0{s=(s ?? "")+"Buzz"} + print(s ?? i) +} diff --git a/Task/FizzBuzz/VBA/fizzbuzz.vba b/Task/FizzBuzz/VBA/fizzbuzz.vba new file mode 100644 index 0000000000..dad7bc163d --- /dev/null +++ b/Task/FizzBuzz/VBA/fizzbuzz.vba @@ -0,0 +1,17 @@ +Option Explicit + +Sub FizzBuzz() +Dim Tb(1 To 100) As Variant +Dim i As Integer + For i = 1 To 100 + Tb(i) = i + If i Mod 15 = 0 Then + Tb(i) = "FizzBuzz" + ElseIf i Mod 3 = 0 Then + Tb(i) = "Fizz" + ElseIf i Mod 5 = 0 Then + Tb(i) = "Buzz" + End If + Next + Debug.Print Join(Tb, vbCrLf) +End Sub diff --git a/Task/Flatten-a-list/Aime/flatten-a-list.aime b/Task/Flatten-a-list/Aime/flatten-a-list.aime index 4e26cc92c3..8c1ff2887a 100644 --- a/Task/Flatten-a-list/Aime/flatten-a-list.aime +++ b/Task/Flatten-a-list/Aime/flatten-a-list.aime @@ -1,52 +1,34 @@ void show_list(list l) { - integer i; - text s; + integer i, k; o_text("["); - s = ""; - i = 0; - while (i < l_length(l)) { - o_text(s); - if (l_s_integer(l, i)) { - o_integer(l[i]); + while (i < ~l) { + o_text(i ? ", " : ""); + if (l_j_integer(k, l, i)) { + o_integer(k); } else { show_list(l[i]); } - s = ", "; i += 1; } o_text("]"); } -void -flat(list c, object o) +list +flatten(list c, object o) { if (__id(o) == INTEGER_ID) { - l_append(c, o); + c.append(o); } else { - l_ucall(o, flat, 1, c); + l_ucall(o, flatten, 1, c); } -} -list -flatten(list l) -{ - list c; - - l_ucall(l, flat, 1, c); - - return c; -} - -list -nl(...) -{ - return xcall(l_assemble); + c; } integer @@ -54,12 +36,13 @@ main(void) { list l; - l = nl(nl(1), 2, nl(nl(3, 4), 5), nl(nl(nl())), nl(nl(nl(6))), 7, 8, nl()); + l = list(list(1), 2, list(list(3, 4), 5), + list(list(list())), list(list(list(6))), 7, 8, list()); show_list(l); o_byte('\n'); - show_list(flatten(l)); + show_list(flatten(list(), l)); o_byte('\n'); return 0; diff --git a/Task/Flatten-a-list/JavaScript/flatten-a-list-5.js b/Task/Flatten-a-list/JavaScript/flatten-a-list-5.js index 5fdb352af1..10ef5307a8 100644 --- a/Task/Flatten-a-list/JavaScript/flatten-a-list-5.js +++ b/Task/Flatten-a-list/JavaScript/flatten-a-list-5.js @@ -1,3 +1,2 @@ -let flatten = list => list.reduce( - (a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), [] -); +// flatten :: Tree a -> [a] +const flatten = t => Array.isArray(t) ? [].concat(...t.map(flatten)) : 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 b5ada8a348..40d4af3b02 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 @@ -flat(A) = mapreduce(x->isa(x,Array)? flat(x): x, vcat, [], A) +flat(arr::Array) = mapreduce(x -> isa(x, Array) ? flat(x) : x, append!, [], arr) 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 3fce66af5a..19e66022ef 100644 --- a/Task/Flatten-a-list/Julia/flatten-a-list-2.julia +++ b/Task/Flatten-a-list/Julia/flatten-a-list-2.julia @@ -1,8 +1,11 @@ -function flat(A) - result = Any[] - grep(a) = for x in a - isa(x,Array) ? grep(x) : push!(result,x) - end - grep(A) - result - end +function flat2(arr) + rst = Any[] + grep(v) = for x in v + if isa(x, Array) grep(x) else push!(rst, x) end + end + grep(arr) + rst +end + +arr = [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] +@show flat(arr) diff --git a/Task/Flatten-a-list/Perl-6/flatten-a-list.pl6 b/Task/Flatten-a-list/Perl-6/flatten-a-list.pl6 new file mode 100644 index 0000000000..c4fb4c1362 --- /dev/null +++ b/Task/Flatten-a-list/Perl-6/flatten-a-list.pl6 @@ -0,0 +1,7 @@ +my @l = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []]; + +say .perl given gather @l.deepmap(*.take); # lazy recursive version + +# Another way to do it is with a recursive function (here actually a Block calling itself with the &?BLOCK dynamic variable): + +say { |(@$_ > 1 ?? map(&?BLOCK, @$_) !! $_) }(@l) diff --git a/Task/Flatten-a-list/Red/flatten-a-list.red b/Task/Flatten-a-list/Red/flatten-a-list.red index 387d7f868f..ad22d64a76 100644 --- a/Task/Flatten-a-list/Red/flatten-a-list.red +++ b/Task/Flatten-a-list/Red/flatten-a-list.red @@ -4,3 +4,11 @@ flatten: function [ ][ load form block ] + +red>> flatten [[1] 2 [[3 4] 5] [[[]]] [[[6]]] 7 8 []] +== [1 2 3 4 5 6 7 8] + +;flatten a list to a string +>> blk: [1 2 ["test"] "a" [["bb"]] 3 4 [[[99]]]] +>> form blk +== "1 2 test a bb 3 4 99" diff --git a/Task/Flatten-a-list/Ring/flatten-a-list.ring b/Task/Flatten-a-list/Ring/flatten-a-list.ring index 98fe69eed7..e686fb90d7 100644 --- a/Task/Flatten-a-list/Ring/flatten-a-list.ring +++ b/Task/Flatten-a-list/Ring/flatten-a-list.ring @@ -1,10 +1,11 @@ -aList = "[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]" -bList = "" -cList = "" -for n=1 to len(aList) - if ascii(aList[n]) >= 48 and ascii(aList[n]) <= 57 - bList = bList + ", " + aList[n] ok +aString = "[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]" +bString = "" +cString = "" +for n=1 to len(aString) + if ascii(aString[n]) >= 48 and ascii(aString[n]) <= 57 + bString = bString + ", " + aString[n] + ok next -cList = substr(bList,3,Len(bList)-2) -dList = "[" + cList + "]" -see dList + nl +cString = substr(bString,3,Len(bString)-2) +cString = '"' + cString + '"' +see cString + nl diff --git a/Task/Flipping-bits-game/Julia/flipping-bits-game.julia b/Task/Flipping-bits-game/Julia/flipping-bits-game.julia new file mode 100644 index 0000000000..bf923da648 --- /dev/null +++ b/Task/Flipping-bits-game/Julia/flipping-bits-game.julia @@ -0,0 +1,97 @@ +module FlippingBitsGame + +using Compat +using Compat.Printf +using Compat.Random + +struct Configuration + M::BitMatrix +end + +Base.size(c::Configuration) = size(c.M) +function Base.show(io::IO, conf::Configuration) + M = conf.M + nrow, ncol = size(M) + print(io, " " ^ 3) + for c in 1:ncol + @printf(io, "%3i", c) + end + println(io, "\n", " " ^ 4, "-" ^ 3ncol) + for r in 1:nrow + @printf(io, "%2i |", r) + for c in 1:ncol + @printf(io, "%2c ", ifelse(M[r, c], 'T', 'F')) + end + println(io) + end + return nothing +end +Base.:(==)(a::Configuration, b::Configuration) = a.M == b.M + +struct Index{D} + i::Int +end +const ColIndex = Index{:C} +const RowIndex = Index{:R} + +function Base.flipbits!(conf::Configuration, c::ColIndex) + col = @view conf.M[:, c.i] + @. col = !col + return conf +end +function Base.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) + if rand() < 0.5 + flipbits!(conf, ColIndex(rand(1:ncol))) + else + flipbits!(conf, RowIndex(rand(1:nrow))) + end + end + return conf +end + +function play() + nrow::Int, ncol::Int = 0, 0 + while nrow < 2 || ncol < 2 + print("Insert the size of the matrix (nrow [> 1] *space* ncol [> 1]):") + nrow, ncol = parse.(Int, split(readline())) + end + mat = randomconfig(nrow, ncol) + obj = deepcopy(mat) + randommoves!(obj, 100) + nflips = 0 + while mat != obj + println("\n", nflips, " flips until now.") + println("Current configuration:") + println(mat) + println("Objective configuration:") + println(obj) + print("Insert R[ind] to flip row, C[ind] to flip a column, Q to quit: ") + line = readline() + input = match(r"([qrc])(\d+)"i, line) + if input ≢ nothing && all(input.captures .≢ nothing) + dim = Symbol(uppercase(input.captures[1])) + ind = Index{dim}(parse(Int, input.captures[2])) + flipbits!(mat, ind) + nflips += 1 + elseif occursin("q", line) + println("\nSEE YOU SOON!") + return + else + println("\nINPUT NOT VALID, RETRY!\n") + end + end + println("\nSUCCED! In ", nflips, " flips.") + println(mat) + return +end + +end # module FlippingBitsGame diff --git a/Task/Flipping-bits-game/OCaml/flipping-bits-game.ocaml b/Task/Flipping-bits-game/OCaml/flipping-bits-game.ocaml new file mode 100644 index 0000000000..458a7e6892 --- /dev/null +++ b/Task/Flipping-bits-game/OCaml/flipping-bits-game.ocaml @@ -0,0 +1,72 @@ +module FlipGame = +struct + type t = bool array array + + let make side = Array.make_matrix side side false + + let flipcol b n = + for i = 0 to (Array.length b - 1) do + b.(n).(i) <- not b.(n).(i) + done + + let fliprow b n = + for i = 0 to (Array.length b - 1) do + b.(i).(n) <- not b.(i).(n) + done + + let randflip b = + let n = Random.int (Array.length b - 1) in + match Random.bool () with + | true -> fliprow b n + | false -> flipcol b n + + let rec game side steps = + let start, target = make side, make side in + for i = 1 to steps do + randflip start; + randflip target + done; + if start = target then game side steps (* try again *) else + (start, target) + + let print b = + for i = 0 to Array.length b - 1 do + for j = 0 to Array.length b - 1 do + Printf.printf " %d " (if b.(j).(i) then 1 else 0) + done; + print_newline () + done; + print_newline () + + let draw_game board target = + print_endline "TARGET"; print target; + print_endline "BOARD"; print board +end + +let play () = + let module G = FlipGame in + let board, target = G.game 3 10 in + let steps = ref 0 in + while board <> target do + G.draw_game board target; + print_string "> "; + flush stdout; + incr steps; + match String.split_on_char ' ' (read_line ()) with + | ["row"; row] -> + (match int_of_string_opt row with + | Some n -> G.fliprow board n + | None -> print_endline "(nothing happens)") + | ["col"; col] -> + (match int_of_string_opt col with + | Some n -> G.flipcol board n + | None -> print_endline "(nothing happens)") + | _ -> () + done; + G.draw_game board target; + Printf.printf "\n\nGame solved in %d steps\n" !steps + +let () = + if not !Sys.interactive then + (Random.self_init (); + play ()) diff --git a/Task/Flipping-bits-game/REXX/flipping-bits-game.rexx b/Task/Flipping-bits-game/REXX/flipping-bits-game.rexx index e6db114432..8a33a9f23b 100644 --- a/Task/Flipping-bits-game/REXX/flipping-bits-game.rexx +++ b/Task/Flipping-bits-game/REXX/flipping-bits-game.rexx @@ -1,82 +1,69 @@ /*REXX program presents a "flipping bit" puzzle. The user can solve via it via C.L. */ -parse arg N u . /*get optional arguments from the C.L. */ -if N=='' | N=="," then N =3 /*Size given? Then use default of 3.*/ -if u=='' | u=="," then u =N /*the number of bits initialized to ON.*/ -col@= 'a b c d e f g h i j k l m n o p q r s t u v w x y z' /*for the column id.*/ -cols=space(col@, 0); upper cols /*letters to be used for the columns. */ +parse arg N u seed . /*get optional arguments from the C.L. */ +if N=='' | N=="," then N=3 /*Size given? Then use default of 3.*/ +if u=='' | u=="," then u=N /*the number of bits initialized to ON.*/ +if datatype(seed, 'W') then call random ,,seed /*is there a seed (for repeatability?) */ +col@= 'a b c d e f g h i j k l m n o p q r s t u v w x y z' /*literal for column id.*/ +cols=space(col@, 0); upper cols /*letters to be used for the columns. */ @.=0; !.=0 /*set both arrays to "off" characters.*/ tries=0 /*number of player's attempts (so far).*/ do while show(0) < u /* [↓] turn "on" U number of bits.*/ - r=random(1, N); c=random(1, N) /*get a random row and column. */ - @.r.c=1 ; !.r.c=1 /*set (both) row and column to ON. */ + r=random(1, N); c=random(1, N) /*get a random row and column. */ + @.r.c=1 ; !.r.c=1 /*set (both) row and column to ON. */ end /*while*/ /* [↑] keep going 'til U bits set.*/ -oz=z /*keep the original array string. */ -call show 1, ' ◄───target' /*show target for user to attain. */ - - do random(1,2); call flip 'R',random(1,N) /*flip a row of bits. */ - call flip 'C',random(1,N) /* " " column " " */ - end /*random···*/ /* [↑] just perform 1 or 2 times. */ - +oz=z /*save the original array string. */ +call show 1, ' ◄═══target═══╣', , 1 /*display the target for user to attain*/ + do random(1,2); call flip 'R',random(1,N) /*flip a row of bits. */ + call flip 'C',random(1,N) /* " " column " " */ + end /*random*/ /* [↑] just perform 1 or 2 times. */ if z==oz then call flip 'R', random(1, N) /*ensure it's not target we're flipping*/ - - do until z==oz /*prompt until they get it right. */ - call prompt /*get a row or column number from C.L. */ - call flip left(?, 1), substr(?, 2) /*flip a user selected row or column. */ + do until z==oz; call prompt /*prompt until they get it right. */ + call flip left(?, 1), substr(?, 2) /*flip a user selected row or column. */ call show 0 /*get image (Z) of the updated array. */ - end /*until···*/ - + end /*until*/ call show 1, ' ◄───your array' /*display the array to the terminal. */ say '─────────Congrats! You did it in' tries "tries." exit tries /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -halt: say 'program was halted!'; exit /*the REXX program was halted by user. */ -isInt: return datatype(arg(1), 'W') /*returns 1 if arg is an integer.*/ -isLet: return datatype(arg(1), 'M') /*returns 1 if arg is a letter. */ -terr: if ok then say '***error!***: illegal' arg(1); ok=0; return +halt: say 'program was halted by user.'; exit /*the REXX program was halted by user. */ +hdr: aaa=arg(1); if oo==1 then aaa=translate(aaa, "╔═║", '┌─│'); say aaa; return +isInt: return datatype( arg(1), 'W') /*returns 1 if arg is an integer.*/ +isLet: return datatype( arg(1), 'M') /*returns 1 if arg is a letter. */ +terr: if ok then say '───────── ***error***: illegal' arg(1); ok=0; return /*──────────────────────────────────────────────────────────────────────────────────────*/ -flip: parse arg x,# /*X is R or C; #: is which one.*/ - do c=1 for N while x=='R'; @.#.c=\@.#.c; end /*c*/ - do r=1 for N while x=='C'; @.r.#=\@.r.#; end /*r*/ - return /* [↑] the bits can be ON or OFF. */ +flip: arg x,#; do c=1 for N while x=='R'; @.#.c = \@.#.c; end /*c*/ + do r=1 for N while x=='C'; @.r.# = \@.r.#; end /*r*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ prompt: if tries\==0 then say '─────────bit array after play: ' tries signal on halt /*another method for the player to quit*/ - !='─────────Please enter a row number or column letter, or Quit:' + !='─────────Please enter a row number or a column letter, or Quit:' call show 1, ' ◄───your array' /*display the array to the terminal. */ - - do forever; ok=1; say; say !; pull ? _ . 1 all /*prompt & get ans*/ - if abbrev('QUIT', ?, 1) then do; say 'quitting···'; exit 0; end - if ?=='' then do; call show 1," ◄───target",.; ok=0 - call show 1," ◄───your array" - end /* [↑] reshow targ*/ - if _\=='' then call terr 'too many args entered:' all - if \isInt(?) & \isLet(?) then call terr 'row/column: ' ? - if isLet(?) then a=pos(?,cols) - if isLet(?) & (a<1 | a>N) then call terr 'column: ' ? - if isLet(?) & length(?)>1 then call terr 'column: ' ? - if isLet(?) then ?='C'pos(?, cols) - if isInt(?) & (?<1 | ?>N) then call terr 'row: ' ? - if isInt(?) then ?=?/1 /*normalize number*/ - if isInt(?) then ?='R'? - if ok then leave /*No errors? Leave*/ + do forever until ok; ok=1; say; say !; pull ? _ . 1 aa + if abbrev('QUIT', ?, 1) then do; say '─────────quitting···'; exit 0; end + if ?=='' then do; call show 1," ◄═══target═══╣",.,1; ok=0 + call show 1," ◄───your array" + end /* [↑] reshow targ*/ + if _ \== '' then call terr 'too many args entered:' aa + if \isInt(?) & \isLet(?) then call terr 'row/column: ' ? + if isLet(?) then a=pos(?, cols) + if isLet(?) & (a<1 | a>N | length(?)>1) then call terr 'column: ' ? + if isLet(?) then ?='C'pos(?, cols) + if isInt(?) & (?<1 | ?>N) then call terr 'row: ' ? + if isInt(?) then ?='R' || (?/1) /*normalize number*/ end /*forever*/ /*end of da checks*/ - - tries=tries+1 /*bump da counter.*/ + tries= tries + 1 /*bump da counter.*/ return ? /*return response.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ -show: $=0; _=; parse arg tell,tx,o /*$≡num of ON bits*/ - if tell then do; say /*are we telling? */ - say ' ' subword(col@,1,N) " column letter" - say 'row ╔'copies('═',N+N+1) /*prepend col hdrs*/ +show: $=0; _=; parse arg tell,tx,o,oo /*$≡num of ON bits*/ + if tell then do; say; say ' ' subword(col@, 1, N) " column letter" + call hdr 'row ┌'copies('─', N+N+1) /*prepend col hdrs*/ end /* [↑] grid hdrs.*/ z= /* [↓] build grid.*/ do r=1 for N /*show grid rows.*/ - do c=1 for N; if o==. then do; z=z || !.r.c; _=_ !.r.c; $=$+!.r.c; end - else do; z=z || @.r.c; _=_ @.r.c; $=$+@.r.c; end + do c=1 for N; if o==. then do; z=z || !.r.c; _=_ !.r.c; $=$ + !.r.c; end + else do; z=z || @.r.c; _=_ @.r.c; $=$ + @.r.c; end end /*c*/ /*··· and sum ONs.*/ if tx\=='' then tar.r=_ tx /*build da target?*/ - if tell then say right(r, 2) ' ║'_ tx; _= /*show the grid? */ + if tell then call hdr right(r, 2) ' │'_ tx; _= /*show the grid? */ end /*r*/ /*show a grid row.*/ - - if tell then say /*show blank line.*/ - return $ /*num of on bits. */ + if tell then say; return $ /*show blank line?*/ diff --git a/Task/Flow-control-structures/360-Assembly/flow-control-structures-1.360 b/Task/Flow-control-structures/360-Assembly/flow-control-structures-1.360 new file mode 100644 index 0000000000..0d8227970c --- /dev/null +++ b/Task/Flow-control-structures/360-Assembly/flow-control-structures-1.360 @@ -0,0 +1,2 @@ + B TESTPX goto label TESTPX + BR 14 goto to the address found in register 14 diff --git a/Task/Flow-control-structures/360-Assembly/flow-control-structures-2.360 b/Task/Flow-control-structures/360-Assembly/flow-control-structures-2.360 new file mode 100644 index 0000000000..fd3ebf0e2c --- /dev/null +++ b/Task/Flow-control-structures/360-Assembly/flow-control-structures-2.360 @@ -0,0 +1,7 @@ + LA 15,SINUSX load in reg15 address of function SINUSX + BALR 14,15 call the subroutine SINUX and place address RETPNT in reg14 +RETPNT EQU * + +SINUSX EQU * subroutine SINUSX + ... + BR 14 return to caller diff --git a/Task/Flow-control-structures/360-Assembly/flow-control-structures-3.360 b/Task/Flow-control-structures/360-Assembly/flow-control-structures-3.360 new file mode 100644 index 0000000000..bf655ba0b4 --- /dev/null +++ b/Task/Flow-control-structures/360-Assembly/flow-control-structures-3.360 @@ -0,0 +1,8 @@ + L 4,A Load A in register 4 + C 4,B Compare A with B + BH TESTGT Branch on High if A>B then goto TESTGT + BL TESTLT Branch on Low if A=B then goto TESTGE + BNE TESTNE Branch on Not Equal if A<>B then goto TESTNE diff --git a/Task/Flow-control-structures/360-Assembly/flow-control-structures-4.360 b/Task/Flow-control-structures/360-Assembly/flow-control-structures-4.360 new file mode 100644 index 0000000000..cd746353b1 --- /dev/null +++ b/Task/Flow-control-structures/360-Assembly/flow-control-structures-4.360 @@ -0,0 +1,4 @@ + LA 3,8 r3 loop counter +LOOP EQU * + ... loop 8 times (r3=8,7,...,2,1) + BCT 3,LOOP r3=r3-1 ; if r3<>0 then loop diff --git a/Task/Flow-control-structures/360-Assembly/flow-control-structures-5.360 b/Task/Flow-control-structures/360-Assembly/flow-control-structures-5.360 new file mode 100644 index 0000000000..b5104bde80 --- /dev/null +++ b/Task/Flow-control-structures/360-Assembly/flow-control-structures-5.360 @@ -0,0 +1,7 @@ +* do i=1 to 8 by 2 + L 3,1 r3 index and start value 1 + LA 4,2 r4 step 2 + L 5,8 r5 to value 8 +LOOPI EQU * + ... loop 4 times (r3=1,3,5,7) + BXLE 3,4,LOOPI r3=r3+r4; if r3<=r5 then loop diff --git a/Task/Flow-control-structures/360-Assembly/flow-control-structures-6.360 b/Task/Flow-control-structures/360-Assembly/flow-control-structures-6.360 new file mode 100644 index 0000000000..be07861e2e --- /dev/null +++ b/Task/Flow-control-structures/360-Assembly/flow-control-structures-6.360 @@ -0,0 +1,7 @@ +* do i=8 to 1 by -2 + L 3,1 r3 index and start value 8 + LH 4,=H'-2' r4 step -2 + L 5,8 r5 to value 1 +LOOPI EQU * + ... loop 4 times (r3=8,6,4,2) + BXH 3,4,LOOPI r3=r3+r4; if r3>r5 then loop diff --git a/Task/Flow-control-structures/Julia/flow-control-structures.julia b/Task/Flow-control-structures/Julia/flow-control-structures.julia new file mode 100644 index 0000000000..f5bb260662 --- /dev/null +++ b/Task/Flow-control-structures/Julia/flow-control-structures.julia @@ -0,0 +1,7 @@ +function example() + println("Hello ") + @goto world + println("Never printed") + @label world + println("world") +end diff --git a/Task/Floyds-triangle/360-Assembly/floyds-triangle.360 b/Task/Floyds-triangle/360-Assembly/floyds-triangle.360 new file mode 100644 index 0000000000..bb2fcf3c04 --- /dev/null +++ b/Task/Floyds-triangle/360-Assembly/floyds-triangle.360 @@ -0,0 +1,39 @@ +* Floyd's triangle 21/06/2018 +FLOYDTRI PROLOG + L R5,NN nn + BCTR R5,0 -1 + M R4,NN nn*(nn-1) + SRA R5,1 /2 + A R5,NN m=(nn*(nn-1))/2+nn; max_value + CVD R5,XDEC binary to packed decimal (PL8) + EDMK ZN,XDEC+4 packed dec (PL4) to char (CL8) + S R1,=A(ZN) r1=number of spaces + L R9,=A(L'ZN+1) length(zn08)+1 + SR R9,R1 s=length(m)+1 + SR R8,R8 k=0 + LA R6,1 i=1 + DO WHILE=(C,R6,LE,NN) do i=1 to nn + LA R10,PG pgi=0 + LA R7,1 j=1 + DO WHILE=(CR,R7,LE,R6) do j=1 to i + LA R8,1(R8) k=k+1 + XDECO R8,XDEC k + LA R11,XDEC+12 +12 + SR R11,R9 -s + LR R2,R9 s + BCTR R2,0 -1 + EX R2,MVCX mvc @PG+pgi,@XDEC+12-s,LEN=s + AR R10,R9 pgi+=s + LA R7,1(R7) j++ + ENDDO , enddo j + XPRNT PG,L'PG print buffer + LA R6,1(R6) i++ + ENDDO , enddo i + EPILOG +MVCX MVC 0(0,R10),0(R11) mvc PG,XDEC +NN DC F'14' number of rows +PG DC CL80' ' buffer +XDEC DS CL12 temp +ZN DC X'4020202020202020' mask CL8 7num + YREGS + END FLOYDTRI diff --git a/Task/Floyds-triangle/BASIC/floyds-triangle-1.basic b/Task/Floyds-triangle/BASIC/floyds-triangle-1.basic new file mode 100644 index 0000000000..c47ed9bf99 --- /dev/null +++ b/Task/Floyds-triangle/BASIC/floyds-triangle-1.basic @@ -0,0 +1,11 @@ + 100 : + 110 REM FLOYD'S TRIANGLE + 120 : + 130 DEF FN Q(A) = INT ( LOG (A) / LOG (10)) + 1 + 140 N = 14 + 150 DIM P(N): P(0) = - 1: FOR J = 1 TO N: I = (N * N - N) / 2 + J + 160 P(J) = P(J - 1) + FN Q(I) + 1: NEXT J + 200 FOR R = 1 TO N: FOR C = 1 TO R + 210 NR = NR + 1:COL = P(C) - ( FN Q(NR) - 1) + 220 HTAB COL: PRINT NR;: NEXT C + 230 PRINT : NEXT R diff --git a/Task/Floyds-triangle/BASIC/floyds-triangle-2.basic b/Task/Floyds-triangle/BASIC/floyds-triangle-2.basic new file mode 100644 index 0000000000..2663014a3b --- /dev/null +++ b/Task/Floyds-triangle/BASIC/floyds-triangle-2.basic @@ -0,0 +1,12 @@ + n = 14 + num = 1 + last = (n^2 - n + 2) DIV 2 + FOR row = 1 TO n + col = last + FOR num = num TO num + row - 1 + @% = LEN(STR$(col)) + 1 : REM set column width + PRINT num ; + col += 1 + NEXT + PRINT + NEXT row diff --git a/Task/Floyds-triangle/Befunge/floyds-triangle.bf b/Task/Floyds-triangle/Befunge/floyds-triangle.bf index 1d83373b3a..3c200578c8 100644 --- a/Task/Floyds-triangle/Befunge/floyds-triangle.bf +++ b/Task/Floyds-triangle/Befunge/floyds-triangle.bf @@ -1,3 +1,5 @@ -0" :swor fo rebmuN">:#,_&>55v ->1+\1-:#v_$$1+\1- 55+,:v>$$@+ -^,*84.:\<+1\+1/2*+1:::\_^#:,< +0" :seniL">:#,_&>:!#@_55+,:00p::1+*2/1v +vv+1:\-1p01g5-\g00>\:::9`\"c"`+\9v:>>+00g1-:00p5p1-00g^ +:#\1#,-#:\_$$.\:#^_$$>>1+\1-55+,:!#@_ diff --git a/Task/Floyds-triangle/Julia/floyds-triangle.julia b/Task/Floyds-triangle/Julia/floyds-triangle.julia new file mode 100644 index 0000000000..e69de29bb2 diff --git a/Task/Floyds-triangle/Modula-2/floyds-triangle.mod2 b/Task/Floyds-triangle/Modula-2/floyds-triangle.mod2 new file mode 100644 index 0000000000..0cd11e9884 --- /dev/null +++ b/Task/Floyds-triangle/Modula-2/floyds-triangle.mod2 @@ -0,0 +1,37 @@ +MODULE FloydTriangle; +FROM FormatString IMPORT FormatString; +FROM Terminal IMPORT WriteString,WriteLn,ReadChar; + +PROCEDURE WriteInt(n : INTEGER); +VAR buf : ARRAY[0..9] OF CHAR; +BEGIN + FormatString("%4i", buf, n); + WriteString(buf) +END WriteInt; + +PROCEDURE Print(r : INTEGER); +VAR n,i,limit : INTEGER; +BEGIN + IF r<0 THEN RETURN END; + + n := 1; + limit := 1; + WHILE r#0 DO + FOR i:=1 TO limit DO + WriteInt(n); + INC(n) + END; + WriteLn; + + DEC(r); + INC(limit) + END +END Print; + +BEGIN + Print(5); + WriteLn; + Print(14); + + ReadChar +END FloydTriangle. diff --git a/Task/Floyds-triangle/Perl-6/floyds-triangle-2.pl6 b/Task/Floyds-triangle/Perl-6/floyds-triangle-2.pl6 index ac9ffc8abb..71f0664797 100644 --- a/Task/Floyds-triangle/Perl-6/floyds-triangle-2.pl6 +++ b/Task/Floyds-triangle/Perl-6/floyds-triangle-2.pl6 @@ -1 +1,14 @@ constant @floyd = gather for 1..* -> $s { take [++$ xx $s] } + +# Printing: + +sub say-floyd($n) { + my @formats = @floyd[$n-1].map: {"%{.chars}s"} + + for @floyd[^$n] -> @i { + say ~(@i Z @formats).map: -> ($i, $f) { $i.fmt($f) } + } +} + +say-floyd 5; +say-floyd 14; diff --git a/Task/Floyds-triangle/REXX/floyds-triangle-2.rexx b/Task/Floyds-triangle/REXX/floyds-triangle-2.rexx index ec3513edff..4400bea2fe 100644 --- a/Task/Floyds-triangle/REXX/floyds-triangle-2.rexx +++ b/Task/Floyds-triangle/REXX/floyds-triangle-2.rexx @@ -3,9 +3,9 @@ parse arg N .; if N=='' | N=="," then N=5 /*Not specified? Then use the mx=N * (N+1) % 2 - N /*calculate maximum value of any value.*/ say 'displaying a ' N " row Floyd's triangle:" /*show the header for Floyd's triangle.*/ say -#=1; do r=1 for N; i=0; _= /*construct Floyd's triangle row by row*/ - do #=# for r; i=i+1 /*start to construct a row of triangle.*/ - _=_ right(#, length( mx+i ) ) /*build a row of the Floyd's triangle. */ +#=1; do r=1 for N; i=0; _= /*construct Floyd's triangle row by row*/ + do #=# for r; i=i+1 /*start to construct a row of triangle.*/ + _=_ right(#, length( mx+i ) ) /*build a row of the Floyd's triangle. */ end /*#*/ say substr(_, 2) /*remove 1st leading blank in the line.*/ end /*r*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Floyds-triangle/REXX/floyds-triangle-3.rexx b/Task/Floyds-triangle/REXX/floyds-triangle-3.rexx index 7f2db79961..9d8dfa0377 100644 --- a/Task/Floyds-triangle/REXX/floyds-triangle-3.rexx +++ b/Task/Floyds-triangle/REXX/floyds-triangle-3.rexx @@ -3,8 +3,8 @@ parse arg N .; if N=='' | N=="," then N=6 /*Not specified? Then use the mx=N * (N+1) % 2 - N /*calculate maximum value of any value.*/ say 'displaying a ' N " row Floyd's triangle in base 16:" /*show triangle header.*/ say -#=1; do r=1 for N; i=0; _= /*construct Floyd's triangle row by row*/ - do #=# for r; i=i+1 /*start to construct a row of triangle.*/ +#=1; do r=1 for N; i=0; _= /*construct Floyd's triangle row by row*/ + do #=# for r; i=i+1 /*start to construct a row of triangle.*/ _=_ right( d2x(#), length( d2x(mx+i))) /*build a row of the Floyd's triangle. */ end /*#*/ say substr(_, 2) /*remove 1st leading blank in the line.*/ diff --git a/Task/Floyds-triangle/REXX/floyds-triangle-4.rexx b/Task/Floyds-triangle/REXX/floyds-triangle-4.rexx index 4419bfb799..cb09bd4ecf 100644 --- a/Task/Floyds-triangle/REXX/floyds-triangle-4.rexx +++ b/Task/Floyds-triangle/REXX/floyds-triangle-4.rexx @@ -5,12 +5,12 @@ if radx=='' | radx=="," then radx=10 /* " " " " " mx=N * (N+1) % 2 - N /*calculate maximum value of any value.*/ say 'displaying a ' N " row Floyd's triangle in base" radx':' /*display the header.*/ say -#=1; do r=1 for N; i=0; _= /*construct Floyd's triangle row by row*/ - do #=# for r; i=i+1 /*start to construct a row of triangle.*/ +#=1; do r=1 for N; i=0; _= /*construct Floyd's triangle row by row*/ + do #=# for r; i=i+1 /*start to construct a row of triangle.*/ _=_ right(base(#, radx), length( base(mx+i, radx) ) ) /*build triangle row.*/ end /*#*/ - say substr(_, 2) /*remove 1st leading blank in the line,*/ - end /*r*/ /* [↑] introduced by first abutment. */ + say substr(_, 2) /*remove 1st leading blank in the line,*/ + end /*r*/ /* [↑] introduced by first abutment. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ base: procedure; parse arg x 1 ox,toB,inB /*obtain number, toBase, inBase. */ diff --git a/Task/Forest-fire/BASIC/forest-fire-10.basic b/Task/Forest-fire/BASIC/forest-fire-10.basic index a78a164bdf..c6dab6da3f 100644 --- a/Task/Forest-fire/BASIC/forest-fire-10.basic +++ b/Task/Forest-fire/BASIC/forest-fire-10.basic @@ -1,56 +1,104 @@ - 10 PAPER 6: CLS - 20 DIM n$(20,30) - 30 LET init=.5 - 40 LET f=.02 - 50 LET p=.05 - 60 PAPER 0 - 70 FOR i=0 TO 31 - 80 PRINT AT 0,i;" " - 90 PRINT AT 21,i;" " -100 NEXT i -110 FOR i=0 TO 21 -120 PRINT AT i,0;" " -130 PRINT AT i,31;" " -140 NEXT i -150 INK 7 -160 PRINT AT 0,1;"FOREST FIRE for Rosetta Code" -170 LET generation=0 -180 PRINT AT 21,1;"Generation 0" -190 LET trees=0 -200 PRINT AT 21,22;"Cover" -210 FOR i=1 TO 20 -220 FOR j=1 TO 30 -230 IF RND ForestState.Burning Then + forestCache(j, i) = IIf(rnd.NextDouble <= _f, ForestState.Burning, ForestState.Tree) + End If + + Case ForestState.Burning + For i2 As Integer = i - 1 To i + 1 + If i2 = -1 OrElse i2 >= _winHeight Then Continue For + For j2 As Integer = j - 1 To j + 1 + If j2 = -1 OrElse i2 >= _winWidth Then Continue For + If _forest(j2, i2) = ForestState.Tree Then forestCache(j2, i2) = ForestState.Burning + Next + Next + forestCache(j, i) = ForestState.Empty + + Case Else + forestCache(j, i) = IIf(rnd.NextDouble <= _p, ForestState.Tree, ForestState.Empty) + End Select + Next + Next + + _forest = forestCache + _gen += 1 + End Sub + + Private Sub DrawForest() + Dim bmCache As New Bitmap(_winWidth, _winHeight) + + For i As Integer = 0 To _winHeight - 1 + For j As Integer = 0 To _winWidth - 1 + Select Case _forest(j, i) + Case ForestState.Tree + bmCache.SetPixel(j, i, Color.Green) + + Case ForestState.Burning + bmCache.SetPixel(j, i, Color.Red) + End Select + Next + Next + + _bm = bmCache + Me.Refresh() + End Sub + + Private Sub ForestFire_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint + e.Graphics.DrawImage(_bm, 0, 0) + + Me.Text = "Gen " & _gen.ToString() & " @ " & (_gen / (_sw.ElapsedMilliseconds / 1000)).ToString("F02") & " FPS: Forest Fire" + End Sub +End Class diff --git a/Task/Forest-fire/BASIC/forest-fire-11.basic b/Task/Forest-fire/BASIC/forest-fire-11.basic new file mode 100644 index 0000000000..a78a164bdf --- /dev/null +++ b/Task/Forest-fire/BASIC/forest-fire-11.basic @@ -0,0 +1,56 @@ + 10 PAPER 6: CLS + 20 DIM n$(20,30) + 30 LET init=.5 + 40 LET f=.02 + 50 LET p=.05 + 60 PAPER 0 + 70 FOR i=0 TO 31 + 80 PRINT AT 0,i;" " + 90 PRINT AT 21,i;" " +100 NEXT i +110 FOR i=0 TO 21 +120 PRINT AT i,0;" " +130 PRINT AT i,31;" " +140 NEXT i +150 INK 7 +160 PRINT AT 0,1;"FOREST FIRE for Rosetta Code" +170 LET generation=0 +180 PRINT AT 21,1;"Generation 0" +190 LET trees=0 +200 PRINT AT 21,22;"Cover" +210 FOR i=1 TO 20 +220 FOR j=1 TO 30 +230 IF RND ForestState.Burning Then - forestCache(j, i) = IIf(rnd.NextDouble <= _f, ForestState.Burning, ForestState.Tree) - End If - - Case ForestState.Burning - For i2 As Integer = i - 1 To i + 1 - If i2 = -1 OrElse i2 >= _winHeight Then Continue For - For j2 As Integer = j - 1 To j + 1 - If j2 = -1 OrElse i2 >= _winWidth Then Continue For - If _forest(j2, i2) = ForestState.Tree Then forestCache(j2, i2) = ForestState.Burning - Next - Next - forestCache(j, i) = ForestState.Empty - - Case Else - forestCache(j, i) = IIf(rnd.NextDouble <= _p, ForestState.Tree, ForestState.Empty) - End Select - Next - Next - - _forest = forestCache - _gen += 1 - End Sub - - Private Sub DrawForest() - Dim bmCache As New Bitmap(_winWidth, _winHeight) - - For i As Integer = 0 To _winHeight - 1 - For j As Integer = 0 To _winWidth - 1 - Select Case _forest(j, i) - Case ForestState.Tree - bmCache.SetPixel(j, i, Color.Green) - - Case ForestState.Burning - bmCache.SetPixel(j, i, Color.Red) - End Select - Next - Next - - _bm = bmCache - Me.Refresh() - End Sub - - Private Sub ForestFire_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles MyBase.Paint - e.Graphics.DrawImage(_bm, 0, 0) - - Me.Text = "Gen " & _gen.ToString() & " @ " & (_gen / (_sw.ElapsedMilliseconds / 1000)).ToString("F02") & " FPS: Forest Fire" - End Sub -End Class + 10 DIM F$(20,30) + 20 DIM N$(20,30) + 30 LET INIT=.5 + 40 LET F=.02 + 50 LET P=.05 + 60 PRINT AT 0,1;"[FOREST FIRE FOR ROSETTA CODE]" + 70 FOR I=0 TO 21 + 80 PRINT AT I,0;"[ ]" + 90 PRINT AT I,31;"[ ]" + 100 NEXT I + 110 FOR I=1 TO 30 + 120 PRINT AT 21,I;"[ ]" + 130 NEXT I + 140 LET G=0 + 150 LET T=0 + 160 PRINT AT 21,1;"[GENERATION 0]" + 170 PRINT AT 21,20;"[COVER]" + 180 FOR I=1 TO 20 + 190 FOR J=1 TO 30 + 200 IF RND>=INIT THEN GOTO 240 + 210 PRINT AT I,J;"0" + 220 LET F$(I,J)="0" + 230 LET T=T+1 + 240 NEXT J + 250 NEXT I + 300 PRINT AT 21,26;"[ ]" + 310 LET N=INT (.5+T/6) + 320 GOSUB 1000 + 330 PRINT AT 21,26;I$;"[ PC]" + 340 FOR I=1 TO 20 + 350 PRINT AT I,0;"[>]" + 360 FOR J=1 TO 30 + 380 IF F$(I,J)<>"[a]" THEN GOTO 410 + 390 LET N$(I,J)=" " + 400 GOTO 530 + 410 IF F$(I,J)<>" " THEN GOTO 433 + 420 IF RND<=P THEN LET N$(I,J)="0" + 430 GOTO 530 + 433 LET N$(I,J)=CHR$ (1+CODE F$(I,J)) + 437 IF N$(I,J)>"Z" THEN LET N$(I,J)="£" + 440 FOR K=I-1 TO I+1 + 450 FOR L=J-1 TO J+1 + 460 IF K=0 OR L=0 OR K=21 OR L=21 THEN GOTO 480 + 470 IF F$(K,L)="[a]" THEN GOTO 510 + 480 NEXT L + 490 NEXT K + 500 GOTO 520 + 510 LET N$(I,J)="[a]" + 520 IF RND<=F THEN LET N$(I,J)="[a]" + 530 NEXT J + 540 PRINT AT I,0;"[ ]" + 550 NEXT I + 552 LET G=G+1 + 554 LET N=G + 556 GOSUB 1000 + 558 PRINT AT 21,12;I$ + 560 LET T=0 + 570 FOR I=1 TO 20 + 575 PRINT AT I,31;"[<]" + 580 FOR J=1 TO 30 + 590 IF N$(I,J)<>"[a]" AND N$(I,J)<>" " THEN LET T=T+1 + 600 NEXT J + 610 LET F$(I)=N$(I) + 620 PRINT AT I,1;F$(I) + 625 PRINT AT I,31;"[ ]" + 630 GOTO 300 +1000 LET S$=STR$ N +1010 LET I$="" +1020 FOR K=1 TO LEN S$ +1030 LET I$=I$+CHR$ (128+CODE S$(K)) +1040 NEXT K +1050 RETURN diff --git a/Task/Forest-fire/Forth/forest-fire.fth b/Task/Forest-fire/Forth/forest-fire.fth new file mode 100644 index 0000000000..d346f1ee89 --- /dev/null +++ b/Task/Forest-fire/Forth/forest-fire.fth @@ -0,0 +1,64 @@ +30 CONSTANT WIDTH +30 CONSTANT HEIGHT +WIDTH HEIGHT * CONSTANT SIZE + +1 VALUE SEED +: (RAND) ( -- u) \ xorshift generator + SEED DUP 13 LSHIFT XOR + DUP 17 RSHIFT XOR + DUP 5 LSHIFT XOR + DUP TO SEED ; +10000 CONSTANT RANGE +100 CONSTANT GROW +1 CONSTANT BURN +: RAND ( -- u) (RAND) RANGE MOD ; + +\ Create buffers for world state +CREATE A SIZE ALLOT A SIZE ERASE +CREATE B SIZE ALLOT B SIZE ERASE + +0 CONSTANT NONE 1 CONSTANT TREE 2 CONSTANT FIRE +: NEARBY-FIRE? ( addr u -- t|f) + 2 -1 DO + 2 -1 DO + J WIDTH * I + OVER + \ calculate an offset + DUP 0> OVER SIZE < AND IF + >R OVER R> + C@ \ fetch state of the offset cell + FIRE = IF UNLOOP UNLOOP DROP DROP TRUE EXIT THEN + ELSE DROP THEN + LOOP + LOOP DROP DROP FALSE ; +: GROW? RAND GROW <= ; \ spontaneously sprout? +: BURN? RAND BURN <= ; \ spontaneously combust? +: STEP ( prev next --) \ Given state in PREV, put next in NEXT + >R 0 BEGIN DUP SIZE < + WHILE + 2DUP + C@ CASE + FIRE OF NONE ENDOF + TREE OF 2DUP NEARBY-FIRE? BURN? OR IF FIRE ELSE TREE THEN ENDOF + NONE OF GROW? IF TREE ELSE NONE THEN ENDOF + ENDCASE + ( i next-cell-state) OVER R@ + C! \ commit to next + 1+ REPEAT R> DROP DROP DROP ; + +: (ESCAPE) 27 EMIT [CHAR] [ EMIT ; +: ESCAPE" POSTPONE (ESCAPE) POSTPONE S" POSTPONE TYPE ; IMMEDIATE +: CLEAR ESCAPE" H" ; +: RETURN ESCAPE" E" ; +: RESET ESCAPE" m" ; +: .FOREST ( addr --) CLEAR + HEIGHT 0 DO + WIDTH 0 DO + DUP C@ CASE + NONE OF SPACE ENDOF + TREE OF ESCAPE" 32m" [CHAR] T EMIT RESET ENDOF + FIRE OF ESCAPE" 31m" [CHAR] # EMIT RESET ENDOF + ENDCASE 1+ + LOOP RETURN + LOOP RESET DROP ; + +: (GO) ( buffer buffer' -- buffer' buffer) + 2DUP STEP \ step the simulation + DUP .FOREST \ print the current state + SWAP ; \ prepare for next iteration +: GO A B BEGIN (GO) AGAIN ; diff --git a/Task/Forest-fire/Ring/forest-fire.ring b/Task/Forest-fire/Ring/forest-fire.ring new file mode 100644 index 0000000000..bf5dd971a1 --- /dev/null +++ b/Task/Forest-fire/Ring/forest-fire.ring @@ -0,0 +1,88 @@ +# Project : Forest fire +# Date : 2018/01/13 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + + +load "guilib.ring" +load "stdlib.ring" + +paint = null + +new qapp + { + win1 = new qwidget() { + setwindowtitle("Forest fire") + setgeometry(100,100,500,600) + label1 = new qlabel(win1) { + setgeometry(10,10,400,400) + settext("") + } + new qpushbutton(win1) { + setgeometry(150,500,100,30) + settext("draw") + setclickevent("draw()") + } + show() + } + exec() + } + +func draw + p1 = new qpicture() + color = new qcolor() { + setrgb(0,0,255,255) + } + pen = new qpen() { + setcolor(color) + setwidth(1) + } + paint = new qpainter() { + begin(p1) + setpen(pen) + +pregen = newlist(200,200) +newgen = newlist(200,200) + + for gen = 1 to 20 + see "gen = " + gen + nl + for x = 1 to 199 + for y = 1 to 199 + switch pregen[x][y] + on 0 + if random(9)/10 > 0.099 + newgen[x][y] = 1 + color = new qcolor() + color.setrgb(0,128,0,255) + pen.setcolor(color) + setpen(pen) + drawpoint(x,y) + ok + on 2 + newgen[x][y] = 0 + color = new qcolor() + color.setrgb(165,42,42,255) + pen.setcolor(color) + setpen(pen) + drawpoint(x,y) + on 1 + if pregen[x][y] = 2 or pregen[x][y] = 2 or pregen[x][y+1] = 2 or + pregen[x][y] = 2 or pregen[x][y+1] = 2 or pregen[x+1][y] = 2 or + pregen[x+1][y] = 2 or pregen[x+1][y+1] = 2 or random(9)/10 > 0.0999 + color = new qcolor() + color.setrgb(255,0,0,255) + pen.setcolor(color) + setpen(pen) + drawpoint(x,y) + newgen[x][y] = 2 + ok + off + pregen[x][y] = newgen[x][y] + next + next +next + + endpaint() + } + label1 { setpicture(p1) show() } + return diff --git a/Task/Fork/D/fork.d b/Task/Fork/D/fork.d new file mode 100644 index 0000000000..aaf4cb44f6 --- /dev/null +++ b/Task/Fork/D/fork.d @@ -0,0 +1,9 @@ +import core.thread; +import std.stdio; + +void main() { + new Thread({ + writeln("Spawned thread."); + }).start; + writeln("Main thread."); +} diff --git a/Task/Fork/Kotlin/fork.kotlin b/Task/Fork/Kotlin/fork.kotlin new file mode 100644 index 0000000000..241248215b --- /dev/null +++ b/Task/Fork/Kotlin/fork.kotlin @@ -0,0 +1,26 @@ +// version 1.1.51 + +import java.io.InputStreamReader +import java.io.BufferedReader +import java.io.IOException + +fun main(args: Array) { + try { + val pb = ProcessBuilder() + val currentUser = pb.environment().get("USER") + val command = listOf("ps", "-f", "U", currentUser) + pb.command(command) + val proc = pb.start() + val isr = InputStreamReader(proc.inputStream) + val br = BufferedReader(isr) + var line: String? = "Output of running $command is:" + while(true) { + println(line) + line = br.readLine() + if (line == null) break + } + } + catch (iox: IOException) { + iox.printStackTrace() + } +} diff --git a/Task/Formal-power-series/Julia/formal-power-series-1.julia b/Task/Formal-power-series/Julia/formal-power-series-1.julia new file mode 100644 index 0000000000..54056544d0 --- /dev/null +++ b/Task/Formal-power-series/Julia/formal-power-series-1.julia @@ -0,0 +1,166 @@ +module FormalPowerSeries + +_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.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) + print(io, a) + a, s = next(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) + @printf(io, " %s %s⋅x^%i", + ifelse(sign(a) ≥ 0, '+', '-'), abs(a), i) + i += 1 + end + print(io, "...") +end + +struct MinusFPS{T,A<:AbstractFPS{T}} <: AbstractFPS{T} + a::A +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) + return -v, s +end + +struct SumFPS{T,A<:AbstractFPS,B<:AbstractFPS} <: AbstractFPS{T} + a::A + b::B +end +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} + stateA, stateB = st + valueA, stateA = next(fps.a, stateA) + valueB, stateB = next(fps.b, stateB) + return T(valueA + valueB), (stateA, stateB) +end + +struct ProductFPS{T,A<:AbstractFPS,B<:AbstractFPS} <: AbstractFPS{T} + a::A + b::B +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} + stateA, stateB, listA, listB = st + valueA, stateA = next(fps.a, stateA) + valueB, stateB = next(fps.b, stateB) + push!(listA, valueA) + unshift!(listB, valueB) + return T(sum(listA .* listB)), (stateA, stateB, listA, listB) +end + +struct DifferentiatedFPS{T,A<:AbstractFPS} <: AbstractFPS{T} + a::A +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 +end +function Base.next(fps::DifferentiatedFPS{T,A}, st) where {T,A} + n, s = st + n += one(n) + v, s = next(fps.a, s) + return n * v, (n, s) +end + +struct IntegratedFPS{T,A<:AbstractFPS} <: AbstractFPS{T} + a::A + k::T +end +integrate(fps::AbstractFPS{T}, k::T=zero(T)) where T = IntegratedFPS{T,typeof(fps)}(fps, k) +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} + n, s = st + iszero(n) && return fps.k, (one(n), s) + v, s = next(fps.a, s) + r::T = _div(v, n) + n += one(n) + return r, (n, s) +end + +# Examples of FPS: constant + +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.convert(::Type{FiniteFPS}, x::Real) = FiniteFPS{typeof(x)}((x,)) +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)) +end + +struct ConstantFPS{T} <: AbstractFPS{T} + k::T +end +Base.start(::ConstantFPS) = nothing +Base.next(c::ConstantFPS, ::Any) = 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 + n, fac, s = st + local r::T + if iseven(n) + r = zero(T) + else + r = _div(one(T), (s * fac)) + s = -s + end + n += 1 + fac *= n + return r, (n, fac, s) +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 + n, fac, s = st + local r::T + if iseven(n) + r = _div(one(T), (s * fac)) + else + r = zero(T) + s = -s + end + n += 1 + fac *= n + return r, (n, fac, s) +end + +end # module FormalPowerSeries diff --git a/Task/Formal-power-series/Julia/formal-power-series-2.julia b/Task/Formal-power-series/Julia/formal-power-series-2.julia new file mode 100644 index 0000000000..847b66f25b --- /dev/null +++ b/Task/Formal-power-series/Julia/formal-power-series-2.julia @@ -0,0 +1,15 @@ +@show cosine = FormalPowerSeries.CosineFPS() +@show sine = FormalPowerSeries.SineFPS() + +intcosine = FormalPowerSeries.integrate(cosine) +uminintsine = 1 - FormalPowerSeries.integrate(sine) + +# Check coefficients up to the 20th term +coefsine = collect(Iterators.take(sine, 20)) +coefintcosine = collect(Iterators.take(intcosine, 20)) + +coefcosine = collect(Iterators.take(cosine, 20)) +coefuminintsine = collect(Iterators.take(uminintsine, 20)) + +@assert coefsine == coefintcosine "The integral of cos should be sin" +@assert coefcosine == coefuminintsine "1 minus the integral of sin should be cos" diff --git a/Task/Formal-power-series/Kotlin/formal-power-series.kotlin b/Task/Formal-power-series/Kotlin/formal-power-series.kotlin new file mode 100644 index 0000000000..fafa7d62a0 --- /dev/null +++ b/Task/Formal-power-series/Kotlin/formal-power-series.kotlin @@ -0,0 +1,208 @@ +// version 1.2.10 + +fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b) + +class Frac : Comparable { + val num: Long + val denom: Long + + companion object { + val ZERO = Frac(0, 1) + val ONE = Frac(1, 1) + } + + constructor(n: Long, d: Long) { + require(d != 0L) + var nn = n + var dd = d + if (nn == 0L) { + dd = 1 + } + else if (dd < 0) { + nn = -nn + dd = -dd + } + val g = Math.abs(gcd(nn, dd)) + if (g > 1) { + nn /= g + dd /= g + } + num = nn + denom = dd + } + + constructor(n: Int, d: Int) : this(n.toLong(), d.toLong()) + + operator fun plus(other: Frac) = + Frac(num * other.denom + denom * other.num, other.denom * denom) + + operator fun unaryPlus() = this + + operator fun unaryMinus() = Frac(-num, denom) + + operator fun minus(other: Frac) = this + (-other) + + operator fun times(other: Frac) = + Frac(this.num * other.num, this.denom * other.denom) + + operator fun rem(other: Frac) = this - Frac((this / other).toLong(), 1) * other + + operator fun inc() = this + ONE + operator fun dec() = this - ONE + + fun inverse(): Frac { + require(num != 0L) + return Frac(denom, num) + } + + operator fun div(other: Frac) = this * other.inverse() + + fun abs() = if (num >= 0) this else -this + + override fun compareTo(other: Frac): Int { + val diff = this.toDouble() - other.toDouble() + return when { + diff < 0.0 -> -1 + diff > 0.0 -> +1 + else -> 0 + } + } + + override fun equals(other: Any?): Boolean { + if (other == null || other !is Frac) return false + return this.compareTo(other) == 0 + } + + override fun hashCode() = num.hashCode() xor denom.hashCode() + + override fun toString() = if (denom == 1L) "$num" else "$num/$denom" + + fun toDouble() = num.toDouble() / denom + + fun toLong() = num / denom +} + +interface Gene { + fun coef(n: Int): Frac +} + +class Term(private val gene: Gene) { + private val cache = mutableListOf() + + operator fun get(n: Int): Frac { + if (n < 0) return Frac.ZERO + if (n >= cache.size) { + for (i in cache.size..n) cache.add(gene.coef(i)) + } + return cache[n] + } +} + +class FormalPS { + private lateinit var term: Term + + private companion object { + const val DISP_TERM = 12 + const val X_VAR = "x" + } + + constructor() {} + + constructor(term: Term) { + this.term = term + } + + constructor(polynomial: List) : + this(Term(object : Gene { + override fun coef(n: Int) = + if (n < 0 || n >= polynomial.size) + Frac.ZERO + else + polynomial[n] + })) + + fun copyFrom(other: FormalPS) { + term = other.term + } + + fun inverseCoef(n: Int): Frac { + val res = Array(n + 1) { Frac.ZERO } + res[0] = term[0].inverse() + for (i in 1..n) { + for (j in 0 until i) res[i] += term[i - j] * res[j] + res[i] *= -res[0] + } + return res[n] + } + + operator fun plus(other: FormalPS) = + FormalPS(Term(object : Gene { + override fun coef(n: Int) = term[n] + other.term[n] + })) + + operator fun minus(other: FormalPS) = + FormalPS(Term(object : Gene { + override fun coef(n: Int) = term[n] - other.term[n] + })) + + operator fun times(other: FormalPS) = + FormalPS(Term(object : Gene { + override fun coef(n: Int): Frac { + var res = Frac.ZERO + for (i in 0..n) res += term[i] * other.term[n - i] + return res + } + })) + + operator fun div(other: FormalPS) = + FormalPS(Term(object : Gene { + override fun coef(n: Int): Frac { + var res = Frac.ZERO + for (i in 0..n) res += term[i] * other.inverseCoef(n - i) + return res + } + })) + + fun diff() = + FormalPS(Term(object : Gene { + override fun coef(n: Int) = term[n + 1] * Frac(n + 1, 1) + })) + + fun intg() = + FormalPS(Term(object : Gene { + override fun coef(n: Int) = + if (n == 0) Frac.ZERO else term[n - 1] * Frac(1, n) + })) + + override fun toString() = toString(DISP_TERM) + + private fun toString(dpTerm: Int): String { + val sb = StringBuilder() + var c = term[0] + if (c != Frac.ZERO) sb.append(c.toString()) + for (i in 1 until dpTerm) { + c = term[i] + if (c != Frac.ZERO) { + if (c > Frac.ZERO && sb.length > 0) sb.append(" + ") + sb.append (when { + c == Frac.ONE -> X_VAR + c == -Frac.ONE -> " - $X_VAR" + c.num < 0 -> " - ${-c}$X_VAR" + else -> "$c$X_VAR" + }) + if (i > 1) sb.append("^$i") + } + } + if (sb.length == 0) sb.append("0") + sb.append(" + ...") + return sb.toString() + } +} + +fun main(args: Array) { + var cos = FormalPS() + val sin = cos.intg() + cos.copyFrom(FormalPS(listOf(Frac.ONE)) - sin.intg()) + println("SIN(x) = $sin") + println("COS(x) = $cos") +} diff --git a/Task/Formal-power-series/Mathematica/formal-power-series.math b/Task/Formal-power-series/Mathematica/formal-power-series.math new file mode 100644 index 0000000000..8ba54e5658 --- /dev/null +++ b/Task/Formal-power-series/Mathematica/formal-power-series.math @@ -0,0 +1,3 @@ +cos = Series[Cos[x], {x, 0, 10}]; +sin = Series[Sin[x], {x, 0, 8}]; +sin - Integrate[cos, x] diff --git a/Task/Formatted-numeric-output/Factor/formatted-numeric-output.factor b/Task/Formatted-numeric-output/Factor/formatted-numeric-output.factor new file mode 100644 index 0000000000..a4e99de057 --- /dev/null +++ b/Task/Formatted-numeric-output/Factor/formatted-numeric-output.factor @@ -0,0 +1,2 @@ +USE: formatting +7.125 "%09.3f\n" printf diff --git a/Task/Formatted-numeric-output/Visual-Basic/formatted-numeric-output-1.vb b/Task/Formatted-numeric-output/Visual-Basic/formatted-numeric-output-1.vb new file mode 100644 index 0000000000..7aa59a46aa --- /dev/null +++ b/Task/Formatted-numeric-output/Visual-Basic/formatted-numeric-output-1.vb @@ -0,0 +1 @@ +Debug.Print Format$(7.125, "00000.000") diff --git a/Task/Formatted-numeric-output/Visual-Basic/formatted-numeric-output-2.vb b/Task/Formatted-numeric-output/Visual-Basic/formatted-numeric-output-2.vb new file mode 100644 index 0000000000..ae24056a2c --- /dev/null +++ b/Task/Formatted-numeric-output/Visual-Basic/formatted-numeric-output-2.vb @@ -0,0 +1 @@ +00007.125 diff --git a/Task/Forward-difference/Julia/forward-difference.julia b/Task/Forward-difference/Julia/forward-difference.julia index 18d19000f9..dffb61e1cb 100644 --- a/Task/Forward-difference/Julia/forward-difference.julia +++ b/Task/Forward-difference/Julia/forward-difference.julia @@ -1 +1,4 @@ -ndiff(A, n::Integer) = n < 1 ? A : diff(ndiff(A, n-1)) +ndiff(A::Array, n::Integer) = n < 1 ? A : diff(ndiff(A, n-1)) + +s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] +println.(collect(ndiff(s, i) for i in 0:9)) diff --git a/Task/Forward-difference/Ring/forward-difference.ring b/Task/Forward-difference/Ring/forward-difference.ring new file mode 100644 index 0000000000..eebb363e9b --- /dev/null +++ b/Task/Forward-difference/Ring/forward-difference.ring @@ -0,0 +1,28 @@ +# Project : Forward difference +# Date : 2018/01/19 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : + +s = [90, 47, 58, 29, 22, 32, 55, 5, 55, 73] +for p = 1 to 9 + s = fwddiff(s) + showarray(s) +next + +func fwddiff(s) + for j=1 to len(s)-1 + s[j] = s[j+1]-s[j] + next + n = len(s) + del(s, n) + return s + +func showarray(vect) + see "{" + svect = "" + for n = 1 to len(vect) + svect = svect + vect[n] + ", " + next + svect = left(svect, len(svect) - 2) + see svect + see "}" + nl diff --git a/Task/Four-bit-adder/Kotlin/four-bit-adder.kotlin b/Task/Four-bit-adder/Kotlin/four-bit-adder.kotlin new file mode 100644 index 0000000000..fa0cd202f0 --- /dev/null +++ b/Task/Four-bit-adder/Kotlin/four-bit-adder.kotlin @@ -0,0 +1,52 @@ +// version 1.1.51 + +val Boolean.I get() = if (this) 1 else 0 + +val Int.B get() = this != 0 + +class Nybble(val n3: Boolean, val n2: Boolean, val n1: Boolean, val n0: Boolean) { + fun toInt() = n0.I + n1.I * 2 + n2.I * 4 + n3.I * 8 + + override fun toString() = "${n3.I}${n2.I}${n1.I}${n0.I}" +} + +fun Int.toNybble(): Nybble { + val n = BooleanArray(4) + for (k in 0..3) n[k] = ((this shr k) and 1).B + return Nybble(n[3], n[2], n[1], n[0]) +} + +fun xorGate(a: Boolean, b: Boolean) = (a && !b) || (!a && b) + +fun halfAdder(a: Boolean, b: Boolean) = Pair(xorGate(a, b), a && b) + +fun fullAdder(a: Boolean, b: Boolean, c: Boolean): Pair { + val (s1, c1) = halfAdder(c, a) + val (s2, c2) = halfAdder(s1, b) + return s2 to (c1 || c2) +} + +fun fourBitAdder(a: Nybble, b: Nybble): Pair { + val (s0, c0) = fullAdder(a.n0, b.n0, false) + val (s1, c1) = fullAdder(a.n1, b.n1, c0) + val (s2, c2) = fullAdder(a.n2, b.n2, c1) + val (s3, c3) = fullAdder(a.n3, b.n3, c2) + return Nybble(s3, s2, s1, s0) to c3.I +} + +const val f = "%s + %s = %d %s (%2d + %2d = %2d)" + +fun test(i: Int, j: Int) { + val a = i.toNybble() + val b = j.toNybble() + val (r, c) = fourBitAdder(a, b) + val s = c * 16 + r.toInt() + println(f.format(a, b, c, r, i, j, s)) +} + +fun main(args: Array) { + println(" A B C R I J S") + for (i in 0..15) { + for (j in i..minOf(i + 1, 15)) test(i, j) + } +} diff --git a/Task/Four-bit-adder/Ring/four-bit-adder.ring b/Task/Four-bit-adder/Ring/four-bit-adder.ring new file mode 100644 index 0000000000..ee252a5ba2 --- /dev/null +++ b/Task/Four-bit-adder/Ring/four-bit-adder.ring @@ -0,0 +1,69 @@ +###--------------------------- +# Program: 4 Bit Adder - Ring +# Author: Bert Mariani +# Date: 2018-02-28 +# +# Bit Adder: Input A B Cin +# Output S Cout +# +# A ^ B => axb XOR gate +# axb ^ C => Sout XOR gate +# axb & C => d AND gate +# +# A & B => anb AND gate +# anb | d => Cout OR gate +# +# Call Adder for number of bit in input fields +###------------------------------------------- +### 4 Bits + +Cout = "0" +OutputS = "0000" +InputA = "0101" +InputB = "1101" + + See "InputA:.. "+ InputA +nl + See "InputB:.. "+ InputB +nl +BitsAdd(InputA, InputB) + See "Sum...: "+ Cout +" "+ OutputS +nl+nl + +###------------------------------------------- +### 32 Bits + +Cout = "0" +OutputS = "00000000000000000000000000000000" +InputA = "01010101010101010101010101010101" +InputB = "11011101110111011101110111011101" + + See "InputA:.. "+ InputA +nl + See "InputB:.. "+ InputB +nl +BitsAdd(InputA, InputB) + See "Sum...: "+ Cout +" "+ OutputS +nl+nl + +###------------------------------- + +Func BitsAdd(InputA, InputB) + nbrBits = len(InputA) + + for i = nbrBits to 1 step -1 + A = InputA[i] + B = InputB[i] + C = Cout + + S = Adder(A,B,C) + OutputS[i] = "" + S + next +return + +###------------------------ +Func Adder(A,B,C) + + axb = A ^ B + Sout = axb ^ C + d = axb & C + + anb = A & B + Cout = anb | d ### Cout is global + +return(Sout) +###------------------------ diff --git a/Task/Fractal-tree/BASIC/fractal-tree-1.basic b/Task/Fractal-tree/BASIC/fractal-tree-1.basic new file mode 100644 index 0000000000..5e10ba50e8 --- /dev/null +++ b/Task/Fractal-tree/BASIC/fractal-tree-1.basic @@ -0,0 +1,45 @@ +graphsize 300,300 + +level = 12 : len =63 # initial values +x = 230: y = 285 +rotation = pi/2 + +A1 = pi/27 : A2 = pi/8 # constants which determine shape +C1 = 0.7 : C2 = 0.85 + +dim xs(level+1) : dim ys(level+1) # stacks + +fastgraphics +color black +rect 0,0,graphwidth,graphheight +refresh +color green +gosub tree +refresh +imgsave "Fractal_tree_BASIC-256.png", "PNG" +end + +tree: + xs[level] = x : ys[level] = y + gosub putline + if level>0 then + level = level - 1 + len = len*C1 + rotation = rotation - A1 + gosub tree + len = len/C1*C2 + rotation = rotation + A1 + A2 + gosub tree + rotation = rotation - A2 + len = len/C2 + level = level + 1 + end if + x = xs[level] : y = ys[level] + return + +putline: + yn = -sin(rotation)*len + y + xn = cos(rotation)*len + x + line x,y,xn,yn + x = xn : y = yn + return diff --git a/Task/Fractal-tree/BASIC/fractal-tree-2.basic b/Task/Fractal-tree/BASIC/fractal-tree-2.basic new file mode 100644 index 0000000000..999ec71311 --- /dev/null +++ b/Task/Fractal-tree/BASIC/fractal-tree-2.basic @@ -0,0 +1,60 @@ + 'Fractal Tree - for Run Basic - 29 Apr 2018 + 'from BASIC256 - http://rosettacode.org/wiki/Fractal_tree#BASIC256 + 'copy this text and go to http://www.runbasic.com + +WindowWidth = 500 'Run Basic max size 800 x 600 +WindowHeight = 350 +c = 255 '255 for white '0 for black + + graphic #w, WindowWidth, WindowHeight + #w cls("black") 'black background color + #w color(c,c,c) 'changes color to white + +level = 10 ' initial values +leng = 50 +x = 230: y = 325 ' initial values x = 230: y = 285 +pi = 3.1415 +rotation = 3.1415/2 + +'A1 = pi/27 : A2 = pi/8 ' constants which determine shape +'C1 = 0.7 : C2 = 0.85 ' tree is drifted left + +A1 = pi/9 : A2 = pi/9 ' constants which determine shape +C1 = 0.85 : C2 = 0.85 ' Symmetrical Tree + +dim xs(level+1) : dim ys(level+1) ' stacks + +print : print "Welcome to the Run BASIC Fractal Tree Program" +#w color("green") 'color green +gosub [tree] + render #w +' imgsave "Fractal_tree_BASIC-256.png", "PNG" +Print "Thank you and goodbye" +end + +[tree] + xs(level) = x : ys(level) = y + gosub [putline] + if level>0 then + level = level - 1 + leng = leng*C1 + rotation = rotation - A1 + gosub [tree] + leng = leng/C1*C2 + rotation = rotation + A1 + A2 + gosub [tree] + rotation = rotation - A2 + leng = leng/C2 + level = level + 1 + end if + x = xs(level) : y = ys(level) + return + +[putline] + yn = -1*sin(rotation)*leng + y + xn = cos(rotation)*leng + x + #w line(x,y,xn,yn) + x = xn : y = yn + return +'end of code +End diff --git a/Task/Fractal-tree/BASIC/fractal-tree-3.basic b/Task/Fractal-tree/BASIC/fractal-tree-3.basic new file mode 100644 index 0000000000..1bac770a1b --- /dev/null +++ b/Task/Fractal-tree/BASIC/fractal-tree-3.basic @@ -0,0 +1,5 @@ + Spread = 25 + Scale = 0.76 + SizeX% = 400 + SizeY% = 300 + Depth% = 10 diff --git a/Task/Fractal-tree/BASIC/fractal-tree-4.basic b/Task/Fractal-tree/BASIC/fractal-tree-4.basic new file mode 100644 index 0000000000..18cd91ed62 --- /dev/null +++ b/Task/Fractal-tree/BASIC/fractal-tree-4.basic @@ -0,0 +1,16 @@ + VDU 23,22,SizeX%;SizeY%;8,16,16,128 + + PROCbranch(SizeX%, 0, SizeY%/2, 90, Depth%) + END + + DEF PROCbranch(x1, y1, size, angle, depth%) + LOCAL x2, y2 + x2 = x1 + size * COSRAD(angle) + y2 = y1 + size * SINRAD(angle) + VDU 23,23,depth%;0;0;0; + LINE x1, y1, x2, y2 + IF depth% > 0 THEN + PROCbranch(x2, y2, size * Scale, angle - Spread, depth% - 1) + PROCbranch(x2, y2, size * Scale, angle + Spread, depth% - 1) + ENDIF + ENDPROC diff --git a/Task/Fractal-tree/Rust/fractal-tree.rust b/Task/Fractal-tree/Rust/fractal-tree.rust new file mode 100644 index 0000000000..bac0a67a7d --- /dev/null +++ b/Task/Fractal-tree/Rust/fractal-tree.rust @@ -0,0 +1,57 @@ +//Cargo deps : +// piston = "0.35.0" +// piston2d-graphics = "0.23.0" +// piston2d-opengl_graphics = "0.49.0" +// pistoncore-glutin_window = "0.42.0" + +extern crate piston; +extern crate graphics; +extern crate opengl_graphics; +extern crate glutin_window; + +use piston::window::WindowSettings; +use piston::event_loop::{Events, EventSettings}; +use piston::input::RenderEvent; +use glutin_window::GlutinWindow as Window; +use opengl_graphics::{GlGraphics, OpenGL}; +use graphics::{clear, line, Context}; + +const ANG: f64 = 20.0; +const COLOR: [f32; 4] = [1.0, 0.0, 0.5, 1.0]; +const LINE_THICKNESS: f64 = 5.0; +const DEPTH: u32 = 11; + +fn main() { + let mut window: Window = WindowSettings::new("Fractal Tree", [1024, 768]) + .opengl(OpenGL::V3_2) + .exit_on_esc(true) + .build() + .unwrap(); + let mut gl = GlGraphics::new(OpenGL::V3_2); + + let mut events = Events::new(EventSettings::new()); + while let Some(e) = events.next(&mut window) { + if let Some(args) = e.render_args() { + gl.draw(args.viewport(), |c, g| { + clear([1.0, 1.0, 1.0, 1.0], g); + draw_fractal_tree(512.0, 700.0, 0.0, DEPTH, c, g); + }); + } + } +} + +fn draw_fractal_tree(x1: f64, y1: f64, angle: f64, depth: u32, c: Context, g: &mut GlGraphics) { + let x2 = x1 + angle.to_radians().sin() * depth as f64 * 10.0; + let y2 = y1 - angle.to_radians().cos() * depth as f64 * 10.0; + line( + COLOR, + LINE_THICKNESS * depth as f64 * 0.2, + [x1, y1, x2, y2], + c.transform, + g, + ); + if depth > 0 { + draw_fractal_tree(x2, y2, angle - ANG, depth - 1, c, g); + draw_fractal_tree(x2, y2, angle + ANG, depth - 1, c, g); + } +} diff --git a/Task/Fractran/Fortran/fractran-4.f b/Task/Fractran/Fortran/fractran-4.f index 6c05bac73a..367c6d7833 100644 --- a/Task/Fractran/Fortran/fractran-4.f +++ b/Task/Fractran/Fortran/fractran-4.f @@ -30,7 +30,7 @@ N = IT !A copy I can damage. NF = 0 !No factors found. P = 0 !Because no primes have been tried. - PP:DO WHILE (IT.GT.1) !Step through the possibilities. + PP:DO WHILE (N.GT.1) !Step through the possibilities. P = P + 1 !Another prime impends. F = PRIME(P) !Grab a possible factor. POW = 0 !It has no power yet. @@ -48,11 +48,10 @@ STOP "Not enough storage!" !Quite. END IF !But normally, NF = NF + 1 !Admit another factor. - FACTOR.PNUM(NF) = P !Identify the prime. + FACTOR.PNUM(NF) = P !Identify the prime. NOT the prime itself. FACTOR.PPOW(NF) = POW !Place its power. END IF !So much for that factor. - IF (N.LE.1) EXIT PP !Perhaps nothing remains? - END DO PP !Try another prime. + END DO PP !Try another prime, if N > 1 still. FACTOR.PNUM(0) = NF !Place the count. END FUNCTION FACTOR !Thus, a list of primes and their powers. diff --git a/Task/Fractran/Julia/fractran.julia b/Task/Fractran/Julia/fractran.julia new file mode 100644 index 0000000000..d3e38efc38 --- /dev/null +++ b/Task/Fractran/Julia/fractran.julia @@ -0,0 +1,32 @@ +function fractran(n::Integer, ratios::Vector{<:Rational}, steplim::Integer) + rst = zeros(BigInt, steplim) + for i in 1:steplim + rst[i] = n + if (pos = findfirst(x -> isinteger(n * x), ratios)) > 0 + n *= ratios[pos] + else + break + end + end + return rst +end + +using IterTools +macro ratio_str(s) + a = split(s, r"[\s,/]+") + return collect(parse(BigInt, n) // parse(BigInt, d) for (n, d) in partition(a, 2)) +end + +fracs = ratio"""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""" +println("The first 20 in the series are ", fractran(2, fracs, 20)) + +prmfound = 0 +n = big(2) +while prmfound < 20 + if isinteger(log2(n)) + prmfound += 1 + println("Prime $prmfound found: $n is 2 ^ $(Int(log2(n)))") + end + n = fractran(n, fracs, 2)[2] +end diff --git a/Task/Fractran/Perl-6/fractran-2.pl6 b/Task/Fractran/Perl-6/fractran-2.pl6 index 4165244c9f..143eef8917 100644 --- a/Task/Fractran/Perl-6/fractran-2.pl6 +++ b/Task/Fractran/Perl-6/fractran-2.pl6 @@ -1,3 +1,6 @@ +sub fractran(@program) { + 2, { first Int, map (* * $_).narrow, @program } ... 0 +} for fractran <17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1> { say $++, "\t", .msb, "\t", $_ if 1 +< .msb == $_; diff --git a/Task/Fractran/Ruby/fractran.rb b/Task/Fractran/Ruby/fractran.rb index 6ee7d3dbad..8e6ab847dc 100644 --- a/Task/Fractran/Ruby/fractran.rb +++ b/Task/Fractran/Ruby/fractran.rb @@ -1,5 +1,5 @@ -str = %w[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] -FractalProgram = str.map(&:to_r) #=> array of rationals +ar = %w[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] +FractalProgram = ar.map(&:to_r) #=> array of rationals Runner = Enumerator.new do |y| num = 2 diff --git a/Task/Function-composition/Elena/function-composition.elena b/Task/Function-composition/Elena/function-composition.elena index 2a001ea0fa..50c792852f 100644 --- a/Task/Function-composition/Elena/function-composition.elena +++ b/Task/Function-composition/Elena/function-composition.elena @@ -3,12 +3,12 @@ import extensions. func1 extension op { compose(BaseFunction1 f) - = (:x)(self eval(f eval:x)). + = (:x)(self(f(x))). } program = [ var fg := (:x)(x + 1) compose(:x)(x * x). - console printLine(fg eval(3)). + console printLine(fg(3)). ]. diff --git a/Task/Function-composition/Fortress/function-composition-1.fortress b/Task/Function-composition/Fortress/function-composition-1.fortress new file mode 100644 index 0000000000..0d5036a845 --- /dev/null +++ b/Task/Function-composition/Fortress/function-composition-1.fortress @@ -0,0 +1,5 @@ + compose[\A, B, C\](f:A->B, g:B->C, i:Any): A->C = do + f(g(i)) + end + + composed(i:RR64): RR64 = compose(sin, cos, i) diff --git a/Task/Function-composition/Fortress/function-composition-2.fortress b/Task/Function-composition/Fortress/function-composition-2.fortress new file mode 100644 index 0000000000..3811bd289c --- /dev/null +++ b/Task/Function-composition/Fortress/function-composition-2.fortress @@ -0,0 +1,5 @@ + alt_compose(f:Number->RR64, g:Number->RR64, i:RR64): ()->RR64 = do + f(g(i)) + end + + alt_composed(i:RR64): RR64 = compose(sin, cos, i) diff --git a/Task/Function-composition/Fortress/function-composition-3.fortress b/Task/Function-composition/Fortress/function-composition-3.fortress new file mode 100644 index 0000000000..dcec8b7aab --- /dev/null +++ b/Task/Function-composition/Fortress/function-composition-3.fortress @@ -0,0 +1 @@ + opr_composed(i:Number): Number->RR64 = (sin COMPOSE cos)(i) diff --git a/Task/Function-composition/Julia/function-composition-1.julia b/Task/Function-composition/Julia/function-composition-1.julia new file mode 100644 index 0000000000..ba1574c46a --- /dev/null +++ b/Task/Function-composition/Julia/function-composition-1.julia @@ -0,0 +1 @@ +@show (asin ∘ sin)(0.5) diff --git a/Task/Function-composition/Julia/function-composition-2.julia b/Task/Function-composition/Julia/function-composition-2.julia new file mode 100644 index 0000000000..70d40773dd --- /dev/null +++ b/Task/Function-composition/Julia/function-composition-2.julia @@ -0,0 +1,2 @@ +compose(f::Function, g::Function) = (x) -> g(f(x)) +@show compose(sin, asin)(0.5) diff --git a/Task/Function-composition/Julia/function-composition.julia b/Task/Function-composition/Julia/function-composition.julia deleted file mode 100644 index 56de333938..0000000000 --- a/Task/Function-composition/Julia/function-composition.julia +++ /dev/null @@ -1 +0,0 @@ -compose(f::Function, g::Function) = x->f(g(x)) diff --git a/Task/Function-composition/Perl-6/function-composition.pl6 b/Task/Function-composition/Perl-6/function-composition.pl6 index e08d28875c..cf3fba3810 100644 --- a/Task/Function-composition/Perl-6/function-composition.pl6 +++ b/Task/Function-composition/Perl-6/function-composition.pl6 @@ -1,3 +1,3 @@ sub triple($n) { 3 * $n } -my &f = &triple ∘ &[-] ∘ { $^n + 2 }; -say &f(5); # Prints "-21". +my &f = &triple ∘ &prefix:<-> ∘ { $^n + 2 }; +say &f(5); # prints "-21". diff --git a/Task/Function-definition/BASIC/function-definition.basic b/Task/Function-definition/BASIC/function-definition-1.basic similarity index 100% rename from Task/Function-definition/BASIC/function-definition.basic rename to Task/Function-definition/BASIC/function-definition-1.basic diff --git a/Task/Function-definition/BASIC/function-definition-2.basic b/Task/Function-definition/BASIC/function-definition-2.basic new file mode 100644 index 0000000000..57a410038c --- /dev/null +++ b/Task/Function-definition/BASIC/function-definition-2.basic @@ -0,0 +1,3 @@ +10 DEF FN MULT(X) = X*Y +20 Y = 4 : REM VALUE OF SECOND ARGUMENT MUST BE ASSIGNED SEPARATELY +30 PRINT FN MULT(3) diff --git a/Task/Function-definition/HolyC/function-definition.holyc b/Task/Function-definition/HolyC/function-definition.holyc new file mode 100644 index 0000000000..57c42043cb --- /dev/null +++ b/Task/Function-definition/HolyC/function-definition.holyc @@ -0,0 +1,7 @@ +F64 Multiply(F64 a, F64 b) { + return a * b; +} + +F64 x; +x = Multiply(42, 13.37); +Print("%5.2f\n", x); diff --git a/Task/Function-definition/Julia/function-definition-1.julia b/Task/Function-definition/Julia/function-definition-1.julia index 21a2c8f154..146f2f0873 100644 --- a/Task/Function-definition/Julia/function-definition-1.julia +++ b/Task/Function-definition/Julia/function-definition-1.julia @@ -1,3 +1,3 @@ -function multiply(a::Number,b::Number) - return a*b +function multiply(a::Number, b::Number) + return a * b end diff --git a/Task/Function-definition/Julia/function-definition-2.julia b/Task/Function-definition/Julia/function-definition-2.julia index 961b43b07f..bff8e0b849 100644 --- a/Task/Function-definition/Julia/function-definition-2.julia +++ b/Task/Function-definition/Julia/function-definition-2.julia @@ -1 +1 @@ -multiply(a,b) = a*b +multiply(a, b) = a * b diff --git a/Task/Function-definition/Julia/function-definition-3.julia b/Task/Function-definition/Julia/function-definition-3.julia index 01d199afcc..f66becf9fd 100644 --- a/Task/Function-definition/Julia/function-definition-3.julia +++ b/Task/Function-definition/Julia/function-definition-3.julia @@ -1 +1 @@ -(a,b) -> a*b +multiply = (a, b) -> a * b diff --git a/Task/Function-definition/Perl-6/function-definition-4.pl6 b/Task/Function-definition/Perl-6/function-definition-4.pl6 index c20b482f51..19e76d16fd 100644 --- a/Task/Function-definition/Perl-6/function-definition-4.pl6 +++ b/Task/Function-definition/Perl-6/function-definition-4.pl6 @@ -1,2 +1 @@ -sub multiply (Rat $a, Rat $b) returns Rat { $a * $b } my Rat sub multiply (Rat $a, Rat $b) { $a * $b } diff --git a/Task/Function-definition/Stata/function-definition-1.stata b/Task/Function-definition/Stata/function-definition-1.stata new file mode 100644 index 0000000000..9797e3f17f --- /dev/null +++ b/Task/Function-definition/Stata/function-definition-1.stata @@ -0,0 +1,7 @@ +prog def multiply, return + args a b + return sca product=`a'*`b' +end + +multiply 77 13 +di r(product) diff --git a/Task/Function-definition/Stata/function-definition-2.stata b/Task/Function-definition/Stata/function-definition-2.stata new file mode 100644 index 0000000000..917a2e6d9b --- /dev/null +++ b/Task/Function-definition/Stata/function-definition-2.stata @@ -0,0 +1,7 @@ +mata +scalar multiply(scalar x, scalar y) { + return(x*y) +} + +multiply(77,13) +end diff --git a/Task/Function-definition/VBA/function-definition-1.vba b/Task/Function-definition/VBA/function-definition-1.vba new file mode 100644 index 0000000000..357acc6a10 --- /dev/null +++ b/Task/Function-definition/VBA/function-definition-1.vba @@ -0,0 +1,3 @@ +Function Multiply(lngMcand As Long, lngMplier As Long) As Long + Multiply = lngMcand * lngMplier +End Function diff --git a/Task/Function-definition/VBA/function-definition-2.vba b/Task/Function-definition/VBA/function-definition-2.vba new file mode 100644 index 0000000000..7bf1b4f5c0 --- /dev/null +++ b/Task/Function-definition/VBA/function-definition-2.vba @@ -0,0 +1,4 @@ +Sub Main() +Dim Result As Long + Result = Multiply(564231, 897) +End Sub diff --git a/Task/Function-frequency/Julia/function-frequency.julia b/Task/Function-frequency/Julia/function-frequency.julia new file mode 100644 index 0000000000..c8de1499a4 --- /dev/null +++ b/Task/Function-frequency/Julia/function-frequency.julia @@ -0,0 +1,33 @@ +using DataStructures + +function funcfreqs(expr::Expr) + cnt = counter(Symbol) + expr.head == :call && + push!(cnt, expr.args[1]) + for e in expr.args + e isa Expr && merge!(cnt, funcfreqs(e)) + end + return cnt +end + +function parseall(str::AbstractString) + exs = Any[] + pos = start(str) + while !done(str, pos) + ex, pos = parse(str, pos) # returns next starting point as well as expr + ex.head == :toplevel ? append!(exs, ex.args) : push!(exs, ex) + end + if isempty(exs) + throw(ParseError("end of input")) + elseif length(exs) == 1 + return exs[1] + else + return Expr(:block, exs...) + end +end + +freqs = readstring("src/Function_frequency.jl") |> parseall |> funcfreqs + +for (v, f) in freqs + @printf("%10s → %i\n", v, f) +end diff --git a/Task/GUI-Maximum-window-dimensions/C/gui-maximum-window-dimensions.c b/Task/GUI-Maximum-window-dimensions/C/gui-maximum-window-dimensions.c new file mode 100644 index 0000000000..26d35b7d61 --- /dev/null +++ b/Task/GUI-Maximum-window-dimensions/C/gui-maximum-window-dimensions.c @@ -0,0 +1,10 @@ +/*Abhishek Ghosh, 3rd October 2017*/ + +#include +#include + +int main() +{ + printf("Dimensions of the screen are (w x h) : %d x %d pixels",GetSystemMetrics(SM_CXSCREEN),GetSystemMetrics(SM_CYSCREEN)); + return 0; +} diff --git a/Task/GUI-Maximum-window-dimensions/Scala/gui-maximum-window-dimensions.scala b/Task/GUI-Maximum-window-dimensions/Scala/gui-maximum-window-dimensions.scala new file mode 100644 index 0000000000..afbab28b30 --- /dev/null +++ b/Task/GUI-Maximum-window-dimensions/Scala/gui-maximum-window-dimensions.scala @@ -0,0 +1,20 @@ +import java.awt.{Dimension, Insets, Toolkit} + +import javax.swing.JFrame + +class MaxWindowDims() extends JFrame { + val toolkit: Toolkit = Toolkit.getDefaultToolkit + val (insets0, screenSize) = (toolkit.getScreenInsets(getGraphicsConfiguration), toolkit.getScreenSize) + + println("Physical screen size: " + screenSize) + System.out.println("Insets: " + insets0) + screenSize.width -= (insets0.left + insets0.right) + screenSize.height -= (insets0.top + insets0.bottom) + System.out.println("Max available: " + screenSize) +} + +object MaxWindowDims { + def main(args: Array[String]): Unit = { + new MaxWindowDims + } +} diff --git a/Task/GUI-component-interaction/00DESCRIPTION b/Task/GUI-component-interaction/00DESCRIPTION index 9738abd180..af74f87b3f 100644 --- a/Task/GUI-component-interaction/00DESCRIPTION +++ b/Task/GUI-component-interaction/00DESCRIPTION @@ -1,10 +1,10 @@ {{omit from|ACL2}} {{omit from|Applesoft BASIC|no concept of a GUI}} -{{omit from|Commodore BASIC}} {{omit from|AWK|no concept of a GUI}} {{omit from|Batch File}} {{omit from|Blast}} {{omit from|Brainf***}} +{{omit from|Commodore BASIC}} {{omit from|GUISS|Only makes use of installed applications}} {{omit from|Integer BASIC|no concept of a GUI}} {{omit from|Lilypond}} @@ -14,6 +14,8 @@ {{omit from|PARI/GP}} {{omit from|PostScript}} {{omit from|Retro}} +{{omit from|SQL PL|It does not handle GUI}} + Almost every application needs to communicate with the user in some way. Therefore, a substantial part of the code deals with the interaction diff --git a/Task/GUI-component-interaction/Maple/gui-component-interaction-1.maple b/Task/GUI-component-interaction/Maple/gui-component-interaction-1.maple new file mode 100644 index 0000000000..7b6053d20a --- /dev/null +++ b/Task/GUI-component-interaction/Maple/gui-component-interaction-1.maple @@ -0,0 +1 @@ +Increase(); diff --git a/Task/GUI-component-interaction/Maple/gui-component-interaction-2.maple b/Task/GUI-component-interaction/Maple/gui-component-interaction-2.maple new file mode 100644 index 0000000000..706266626d --- /dev/null +++ b/Task/GUI-component-interaction/Maple/gui-component-interaction-2.maple @@ -0,0 +1 @@ +Random(); diff --git a/Task/GUI-component-interaction/Maple/gui-component-interaction-3.maple b/Task/GUI-component-interaction/Maple/gui-component-interaction-3.maple new file mode 100644 index 0000000000..e136a37568 --- /dev/null +++ b/Task/GUI-component-interaction/Maple/gui-component-interaction-3.maple @@ -0,0 +1,14 @@ +macro(SP=DocumentTools:-SetProperty, GP=DocumentTools:-GetProperty); +with(Maplets[Elements]): +SP("Text",value,0); +Increase:=proc() + SP("Text",value,parse(GP("Text",value))+1); +end proc; +Random:=proc() + maplet := Maplet(["Are you sure?", [Button("OK", Shutdown("true")), Button("Cancel", Shutdown())]]); + result := Maplets[Display](maplet); + if result = "true" then + j:=rand(1..1000); + SP("Text",value,j()); + end if; +end proc; diff --git a/Task/GUI-component-interaction/Perl-6/gui-component-interaction.pl6 b/Task/GUI-component-interaction/Perl-6/gui-component-interaction.pl6 index 0f4d1daaf8..c14f3630f2 100644 --- a/Task/GUI-component-interaction/Perl-6/gui-component-interaction.pl6 +++ b/Task/GUI-component-interaction/Perl-6/gui-component-interaction.pl6 @@ -1,8 +1,9 @@ use GTK::Simple; +use GTK::Simple::App; my GTK::Simple::App $app .= new(title => 'GUI component interaction'); -$app.set_content( +$app.set-content( my $box = GTK::Simple::VBox.new( my $value = GTK::Simple::Entry.new(text => '0'), my $increment = GTK::Simple::Button.new(label => 'Increment'), @@ -10,8 +11,8 @@ $app.set_content( ) ); -$app.size_request(400, 100); -$app.border_width = 20; +$app.size-request(400, 100); +$app.border-width = 20; $box.spacing = 10; $value.changed.tap: { @@ -19,14 +20,14 @@ $value.changed.tap: { } $increment.clicked.tap: { - $value.text += 1; + my $val = $value.text; $val += 1; $value.text = $val.Str } $random.clicked.tap: { # Dirty hack to work around the fact that GTK::Simple doesn't provide # access to GTK message dialogs yet :P if run «zenity --question --text "Reset to random value?"» { - $value.text = (^100).pick; + $value.text = (^100).pick.Str } } diff --git a/Task/GUI-enabling-disabling-of-controls/00DESCRIPTION b/Task/GUI-enabling-disabling-of-controls/00DESCRIPTION index da9da1798a..8855526f54 100644 --- a/Task/GUI-enabling-disabling-of-controls/00DESCRIPTION +++ b/Task/GUI-enabling-disabling-of-controls/00DESCRIPTION @@ -1,10 +1,10 @@ {{omit from|ACL2}} {{omit from|Applesoft BASIC|no concept of a GUI}} -{{omit from|Commodore BASIC}} {{omit from|AWK|no concept of a GUI}} {{omit from|Batch File}} {{omit from|Blast}} {{omit from|Brainf***}} +{{omit from|Commodore BASIC}} {{omit from|GUISS|Can only do what the installed applications can do}} {{omit from|Integer BASIC|no concept of a GUI}} {{omit from|Lilypond}} @@ -14,6 +14,7 @@ {{omit from|PARI/GP}} {{omit from|PostScript}} {{omit from|Retro}} +{{omit from|SQL PL|It does not handle GUI}} In addition to fundamental [[GUI component interaction]], an application should dynamically enable and disable GUI components, to give some guidance to the diff --git a/Task/GUI-enabling-disabling-of-controls/Java/gui-enabling-disabling-of-controls-2.java b/Task/GUI-enabling-disabling-of-controls/Java/gui-enabling-disabling-of-controls-2.java index b2697d13df..b421ac62b4 100644 --- a/Task/GUI-enabling-disabling-of-controls/Java/gui-enabling-disabling-of-controls-2.java +++ b/Task/GUI-enabling-disabling-of-controls/Java/gui-enabling-disabling-of-controls-2.java @@ -53,7 +53,7 @@ public class InteractFX extends Application { Button increment = new Button("Increment"); increment.setOnAction(event-> inputValue.set(inputValue.get() + 1)); - // incr-button is disabled when input is >= 0 + // incr-button is disabled when input is >= 10 increment.disableProperty().bind(inputValue.greaterThanOrEqualTo(10)); diff --git a/Task/GUI-enabling-disabling-of-controls/Kotlin/gui-enabling-disabling-of-controls.kotlin b/Task/GUI-enabling-disabling-of-controls/Kotlin/gui-enabling-disabling-of-controls.kotlin new file mode 100644 index 0000000000..d72e77f7c3 --- /dev/null +++ b/Task/GUI-enabling-disabling-of-controls/Kotlin/gui-enabling-disabling-of-controls.kotlin @@ -0,0 +1,70 @@ +// version 1.2.21 + +import javafx.application.Application +import javafx.beans.property.SimpleLongProperty +import javafx.scene.Scene +import javafx.scene.control.Button +import javafx.scene.control.TextField +import javafx.scene.layout.HBox +import javafx.scene.layout.VBox +import javafx.stage.Stage +import javafx.util.converter.NumberStringConverter +import javafx.event.ActionEvent + +val digits = Regex("[0-9]*") + +class InteractFX : Application() { + + override fun start(stage: Stage) { + val input = object : TextField("0") { + // only accept numbers as input + override fun replaceText(start: Int, end: Int, text: String) { + if (text.matches(digits)) super.replaceText(start, end, text) + } + + // only accept numbers on copy + paste + override fun replaceSelection(text: String) { + if (text.matches(digits)) super.replaceSelection(text) + } + } + + // when the textfield is empty, replace text with "0" + input.textProperty().addListener { _, _, newValue -> + if (newValue == null || newValue.trim().isEmpty()) input.text = "0" + } + + // get a bi-directional bound long-property of the input value + val inputValue = SimpleLongProperty() + input.textProperty().bindBidirectional(inputValue, NumberStringConverter()) + + // textfield is disabled when the current value is other than "0" + input.disableProperty().bind(inputValue.isNotEqualTo(0)) + + val increment = Button("Increment") + increment.addEventHandler(ActionEvent.ACTION) { inputValue.set(inputValue.get() + 1) } + + // increment button is disabled when input is >= 10 + increment.disableProperty().bind(inputValue.greaterThanOrEqualTo(10)) + + val decrement = Button("Decrement") + decrement.addEventHandler(ActionEvent.ACTION) { inputValue.set(inputValue.get() - 1) } + + // decrement button is disabled when input is <= 0 + decrement.disableProperty().bind(inputValue.lessThanOrEqualTo(0)) + + // layout + val root = VBox() + root.children.add(input) + val buttons = HBox() + buttons.children.addAll(increment, decrement) + root.children.add(buttons) + + stage.scene = Scene(root) + stage.sizeToScene() + stage.show() + } +} + +fun main(args: Array) { + Application.launch(InteractFX::class.java, *args) +} diff --git a/Task/GUI-enabling-disabling-of-controls/Maple/gui-enabling-disabling-of-controls-1.maple b/Task/GUI-enabling-disabling-of-controls/Maple/gui-enabling-disabling-of-controls-1.maple new file mode 100644 index 0000000000..7b6053d20a --- /dev/null +++ b/Task/GUI-enabling-disabling-of-controls/Maple/gui-enabling-disabling-of-controls-1.maple @@ -0,0 +1 @@ +Increase(); diff --git a/Task/GUI-enabling-disabling-of-controls/Maple/gui-enabling-disabling-of-controls-2.maple b/Task/GUI-enabling-disabling-of-controls/Maple/gui-enabling-disabling-of-controls-2.maple new file mode 100644 index 0000000000..72d3216325 --- /dev/null +++ b/Task/GUI-enabling-disabling-of-controls/Maple/gui-enabling-disabling-of-controls-2.maple @@ -0,0 +1 @@ +Decrease(); diff --git a/Task/GUI-enabling-disabling-of-controls/Maple/gui-enabling-disabling-of-controls-3.maple b/Task/GUI-enabling-disabling-of-controls/Maple/gui-enabling-disabling-of-controls-3.maple new file mode 100644 index 0000000000..877b69c26f --- /dev/null +++ b/Task/GUI-enabling-disabling-of-controls/Maple/gui-enabling-disabling-of-controls-3.maple @@ -0,0 +1,29 @@ +macro(SP=DocumentTools:-SetProperty, GP=DocumentTools:-GetProperty); +with(Maplets[Elements]): +SP("Text",value,0); +Increase:=proc() + SP("Text",value,parse(GP("Text",value))+1); + if parse(GP("Text",value))>=10 then + SP("Button0", enabled, false); + else + SP("Button0", enabled, true); + end if; + if parse(GP("Text",value))<=0 then + SP("Button1", enabled, false); + else + SP("Button1", enabled, true); + end if; +end proc; +Decrease:=proc() + SP("Text",value,parse(GP("Text",value))-1); + if parse(GP("Text",value))<=0 then + SP("Button1", enabled, false); + else + SP("Button1", enabled, true); + end if; + if parse(GP("Text",value))>=10 then + SP("Button0", enabled, false); + else + SP("Button0", enabled, true); + end if; +end proc; diff --git a/Task/GUI-enabling-disabling-of-controls/Perl-6/gui-enabling-disabling-of-controls.pl6 b/Task/GUI-enabling-disabling-of-controls/Perl-6/gui-enabling-disabling-of-controls.pl6 index 2396296933..e9c464bc88 100644 --- a/Task/GUI-enabling-disabling-of-controls/Perl-6/gui-enabling-disabling-of-controls.pl6 +++ b/Task/GUI-enabling-disabling-of-controls/Perl-6/gui-enabling-disabling-of-controls.pl6 @@ -1,8 +1,9 @@ use GTK::Simple; +use GTK::Simple::App; my GTK::Simple::App $app .= new( title => 'Controls Enable / Disable' ); -$app.set_content( +$app.set-content( my $box = GTK::Simple::HBox.new( my $inc = GTK::Simple::Button.new( label => ' + ' ), my $value = GTK::Simple::Entry.new, @@ -10,7 +11,7 @@ $app.set_content( ) ); -$app.border_width = 10; +$app.border-width = 10; $box.spacing = 10; $value.changed.tap: { @@ -19,9 +20,9 @@ $value.changed.tap: { $dec.sensitive = $value.text > 0; } -$value.text = 0; +$value.text = '0'; -$inc.clicked.tap: { $value.text += 1 } -$dec.clicked.tap: { $value.text -= 1 } +$inc.clicked.tap: { my $val = $value.text; $val += 1; $value.text = $val.Str } +$dec.clicked.tap: { my $val = $value.text; $val -= 1; $value.text = $val.Str } $app.run; diff --git a/Task/Galton-box-animation/Kotlin/galton-box-animation.kotlin b/Task/Galton-box-animation/Kotlin/galton-box-animation.kotlin new file mode 100644 index 0000000000..499a1578f5 --- /dev/null +++ b/Task/Galton-box-animation/Kotlin/galton-box-animation.kotlin @@ -0,0 +1,102 @@ +// version 1.2.10 + +import java.util.Random + +val boxW = 41 // Galton box width. +val boxH = 37 // Galton box height. +val pinsBaseW = 19 // Pins triangle base. +val nMaxBalls = 55 // Number of balls. + +val centerH = pinsBaseW + (boxW - pinsBaseW * 2 + 1) / 2 - 1 +val rand = Random() + +enum class Cell(val c: Char) { + EMPTY(' '), + BALL('o'), + WALL('|'), + CORNER('+'), + FLOOR('-'), + PIN('.') +} + +/* Galton box. Will be printed upside down. */ +val box = List(boxH) { Array(boxW) { Cell.EMPTY } } + +class Ball(var x: Int, var y: Int) { + + init { + require(box[y][x] == Cell.EMPTY) + box[y][x] = Cell.BALL + } + + fun doStep() { + if (y <= 0) return // Reached the bottom of the box. + val cell = box[y - 1][x] + when (cell) { + Cell.EMPTY -> { + box[y][x] = Cell.EMPTY + y-- + box[y][x] = Cell.BALL + } + + Cell.PIN -> { + box[y][x] = Cell.EMPTY + y-- + if (box[y][x - 1] == Cell.EMPTY && box[y][x + 1] == Cell.EMPTY) { + x += rand.nextInt(2) * 2 - 1 + box[y][x] = Cell.BALL + return + } + else if (box[y][x - 1] == Cell.EMPTY) x++ + else x-- + box[y][x] = Cell.BALL + } + + else -> { + // It's frozen - it always piles on other balls. + } + } + } +} + +fun initializeBox() { + // Set ceiling and floor: + box[0][0] = Cell.CORNER + box[0][boxW - 1] = Cell.CORNER + for (i in 1 until boxW - 1) box[0][i] = Cell.FLOOR + for (i in 0 until boxW) box[boxH - 1][i] = box[0][i] + + // Set walls: + for (r in 1 until boxH - 1) { + box[r][0] = Cell.WALL + box[r][boxW - 1] = Cell.WALL + } + + // Set pins: + for (nPins in 1..pinsBaseW) { + for (pin in 0 until nPins) { + box[boxH - 2 - nPins][centerH + 1 - nPins + pin * 2] = Cell.PIN + } + } +} + +fun drawBox() { + for (row in box.reversed()) { + for (i in row.indices) print(row[i].c) + println() + } +} + +fun main(args: Array) { + initializeBox() + val balls = mutableListOf() + for (i in 0 until nMaxBalls + boxH) { + println("\nStep $i:") + if (i < nMaxBalls) balls.add(Ball(centerH, boxH - 2)) // Add ball. + drawBox() + + // Next step for the simulation. + // Frozen balls are kept in balls list for simplicity + for (b in balls) b.doStep() + } +} diff --git a/Task/Gamma-function/Julia/gamma-function-1.julia b/Task/Gamma-function/Julia/gamma-function-1.julia index c4129dc643..eaa8425447 100644 --- a/Task/Gamma-function/Julia/gamma-function-1.julia +++ b/Task/Gamma-function/Julia/gamma-function-1.julia @@ -1 +1 @@ -gamma(x) +@show gamma(1) diff --git a/Task/Gamma-function/Julia/gamma-function-2.julia b/Task/Gamma-function/Julia/gamma-function-2.julia index 079c39c211..69e8772932 100644 --- a/Task/Gamma-function/Julia/gamma-function-2.julia +++ b/Task/Gamma-function/Julia/gamma-function-2.julia @@ -1,4 +1,3 @@ -gamma_quad(t) = quadgk(x -> x^(t-1)*exp(-x), zero(t), inf(t), reltol=100*eps(t))[1] - -# generalize to handle arrays of inputs: -@vectorize_1arg Real gamma_quad +using QuadGK +gammaquad(t::Float64) = first(quadgk(x -> x ^ (t - 1) * exp(-x), zero(t), Inf, reltol = 100eps(t))) +@show gammaquad(1.0) diff --git a/Task/Gamma-function/Maple/gamma-function.maple b/Task/Gamma-function/Maple/gamma-function.maple new file mode 100644 index 0000000000..5cbbfe2bcd --- /dev/null +++ b/Task/Gamma-function/Maple/gamma-function.maple @@ -0,0 +1,4 @@ +GAMMA(17/2); +GAMMA(7*I); +M := Matrix(2, 3, 'fill' = -3.6); +MTM:-gamma(M); diff --git a/Task/Gamma-function/Stata/gamma-function.stata b/Task/Gamma-function/Stata/gamma-function.stata new file mode 100644 index 0000000000..e7b0914f22 --- /dev/null +++ b/Task/Gamma-function/Stata/gamma-function.stata @@ -0,0 +1,42 @@ +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/00DESCRIPTION b/Task/Gaussian-elimination/00DESCRIPTION index 09cd5dfd4d..bd40bc1a1f 100644 --- a/Task/Gaussian-elimination/00DESCRIPTION +++ b/Task/Gaussian-elimination/00DESCRIPTION @@ -1 +1,9 @@ -Problem: Solve Ax=b using Gaussian elimination then backwards substitution. A being an n by n matrix. Also, x and b are n by 1 vectors. To improve accuracy, please use partial pivoting and scaling. +;Task: +Solve   '''Ax=b'''   using Gaussian elimination then backwards substitution. + +'''A'''   being an   '''n''' by '''n'''   matrix. + +Also,   '''x''' and '''b'''   are   '''n''' by '''1'''   vectors. + +To improve accuracy, please use partial pivoting and scaling. +

diff --git a/Task/Gaussian-elimination/FreeBASIC/gaussian-elimination.freebasic b/Task/Gaussian-elimination/FreeBASIC/gaussian-elimination.freebasic new file mode 100644 index 0000000000..d25f1ca496 --- /dev/null +++ b/Task/Gaussian-elimination/FreeBASIC/gaussian-elimination.freebasic @@ -0,0 +1,61 @@ +Sub GaussJordan(matrix() As Double,rhs() As Double,ans() As Double) + Dim As Long n=Ubound(matrix,1) + Redim ans(0):Redim ans(1 To n) + Dim As Double b(1 To n,1 To n),r(1 To n) + For c As Long=1 To n 'take copies + r(c)=rhs(c) + For d As Long=1 To n + b(c,d)=matrix(c,d) + Next d + Next c + #macro pivot(num) + For p1 As Long = num To n - 1 + For p2 As Long = p1 + 1 To n + If Abs(b(p1,num)) ε { + log.Println("out of tolerance") + log.Fatal("expected", tc.x) + } + } +} + +func GaussPartial(a0 [][]float64, b0 []float64) ([]float64, error) { + m := len(b0) + a := make([][]float64, m) + for i, ai := range a0 { + row := make([]float64, m+1) + copy(row, ai) + row[m] = b0[i] + a[i] = row + } + for k := range a { + iMax := 0 + max := -1. + for i := k; i < m; i++ { + row := a[i] + // compute scale factor s = max abs in row + s := -1. + for j := k; j < m; j++ { + x := math.Abs(row[j]) + if x > s { + s = x + } + } + // scale the abs used to pick the pivot. + if abs := math.Abs(row[k]) / s; abs > max { + iMax = i + max = abs + } + } + if a[iMax][k] == 0 { + return nil, errors.New("singular") + } + a[k], a[iMax] = a[iMax], a[k] + for i := k + 1; i < m; i++ { + for j := k + 1; j <= m; j++ { + a[i][j] -= a[k][j] * (a[i][k] / a[k][k]) + } + a[i][k] = 0 + } + } + x := make([]float64, m) + for i := m - 1; i >= 0; i-- { + x[i] = a[i][m] + for j := i + 1; j < m; j++ { + x[i] -= a[i][j] * x[j] + } + x[i] /= a[i][i] + } + return x, nil +} diff --git a/Task/Gaussian-elimination/Klong/gaussian-elimination-1.klong b/Task/Gaussian-elimination/Klong/gaussian-elimination-1.klong new file mode 100644 index 0000000000..af648d963d --- /dev/null +++ b/Task/Gaussian-elimination/Klong/gaussian-elimination-1.klong @@ -0,0 +1,5 @@ +elim::{[h m];h::*m::x@>*'x; + :[2>#x;x;(,h),0,:\.f({1_x}'{x-h**x%*h}'1_m)]} +subst::{[v];v::[]; + {v::v,((*x)-/:[[]~v;[];v*x@1+!#v])%x@1+#v}'||'x;|v} +gauss::{subst(elim(x))} diff --git a/Task/Gaussian-elimination/Klong/gaussian-elimination-2.klong b/Task/Gaussian-elimination/Klong/gaussian-elimination-2.klong new file mode 100644 index 0000000000..073ddd61f1 --- /dev/null +++ b/Task/Gaussian-elimination/Klong/gaussian-elimination-2.klong @@ -0,0 +1,12 @@ + gauss([[1.00 0.00 0.00 0.00 0.00 0.00 -0.01] + [1.00 0.63 0.39 0.25 0.16 0.10 0.61] + [1.00 1.26 1.58 1.98 2.49 3.13 0.91] + [1.00 1.88 3.55 6.70 12.62 23.80 0.99] + [1.00 2.51 6.32 15.88 39.90 100.28 0.60] + [1.00 3.14 9.87 31.01 97.41 306.02 0.02]] +[-0.00999999999999981 + 1.60279039450211414 + -1.6132030599055625 + 1.24549412137143782 + -0.490989719584658025 + 0.0657606961752320591] diff --git a/Task/Gaussian-elimination/Kotlin/gaussian-elimination.kotlin b/Task/Gaussian-elimination/Kotlin/gaussian-elimination.kotlin new file mode 100644 index 0000000000..339c8327ff --- /dev/null +++ b/Task/Gaussian-elimination/Kotlin/gaussian-elimination.kotlin @@ -0,0 +1,81 @@ +// version 1.1.51 + +val ta = arrayOf( + doubleArrayOf(1.00, 0.00, 0.00, 0.00, 0.00, 0.00), + doubleArrayOf(1.00, 0.63, 0.39, 0.25, 0.16, 0.10), + doubleArrayOf(1.00, 1.26, 1.58, 1.98, 2.49, 3.13), + doubleArrayOf(1.00, 1.88, 3.55, 6.70, 12.62, 23.80), + doubleArrayOf(1.00, 2.51, 6.32, 15.88, 39.90, 100.28), + doubleArrayOf(1.00, 3.14, 9.87, 31.01, 97.41, 306.02) +) + +val tb = doubleArrayOf(-0.01, 0.61, 0.91, 0.99, 0.60, 0.02) + +val tx = doubleArrayOf( + -0.01, 1.602790394502114, -1.6132030599055613, + 1.2454941213714368, -0.4909897195846576, 0.065760696175232 +) + +const val EPSILON = 1e-14 // tolerance required + +fun gaussPartial(a0: Array, b0: DoubleArray): DoubleArray { + val m = b0.size + val a = Array(m) { DoubleArray(m) } + for ((i, ai) in a0.withIndex()) { + val row = ai.copyOf(m + 1) + row[m] = b0[i] + a[i] = row + } + for (k in 0 until a.size) { + var iMax = 0 + var max = -1.0 + for (i in k until m) { + val row = a[i] + // compute scale factor s = max abs in row + var s = -1.0 + for (j in k until m) { + val e = Math.abs(row[j]) + if (e > s) s = e + } + // scale the abs used to pick the pivot + val abs = Math.abs(row[k]) / s + if (abs > max) { + iMax = i + max = abs + } + } + if (a[iMax][k] == 0.0) { + throw RuntimeException("Matrix is singular.") + } + val tmp = a[k] + a[k] = a[iMax] + a[iMax] = tmp + for (i in k + 1 until m) { + for (j in k + 1..m) { + a[i][j] -= a[k][j] * a[i][k] / a[k][k] + } + a[i][k] = 0.0 + } + } + val x = DoubleArray(m) + for (i in m - 1 downTo 0) { + x[i] = a[i][m] + for (j in i + 1 until m) { + x[i] -= a[i][j] * x[j] + } + x[i] /= a[i][i] + } + return x +} + +fun main(args: Array) { + val x = gaussPartial(ta, tb) + println(x.asList()) + for ((i, xi) in x.withIndex()) { + if (Math.abs(tx[i] - xi) > EPSILON) { + println("Out of tolerance.") + println("Expected values are ${tx.asList()}") + return + } + } +} diff --git a/Task/Gaussian-elimination/Perl-6/gaussian-elimination.pl6 b/Task/Gaussian-elimination/Perl-6/gaussian-elimination.pl6 index f3bc86d02d..4585810e3b 100644 --- a/Task/Gaussian-elimination/Perl-6/gaussian-elimination.pl6 +++ b/Task/Gaussian-elimination/Perl-6/gaussian-elimination.pl6 @@ -1,54 +1,57 @@ -sub mat_elem(@a, $y, $x, $n) is rw { @a[ $y * $n + $x ] } -sub swap_row(@a, @b, $r1, $r2, $n) { - return if $r1 == $r2; - for ^$n -> $i { - ( - mat_elem(@a, $r1, $i, $n), - mat_elem(@a, $r2, $i, $n) - ).=reverse; - } - @b[$r1, $r2].=reverse; +sub gauss-jordan-solve (@a, @b) { + @b.kv.map: { @a[$^k].append: $^v }; + @a.&rref[*]»[*-1]; } -sub gauss_eliminate(@a, @b, $n) { - sub A($y, $x) is rw { mat_elem(@a, $y, $x, $n) } - my ($i, $j, $col, $row, $max_row, $dia); - my ($max, $tmp); - for ^$n -> $dia { - for $dia ^..^ $n -> $row { - swap_row @a, @b, $dia, - max(:by({ abs(A($_, $dia)) }), $dia ^..^ $n), - $n; - $tmp = A($row, $dia) / A($dia, $dia); - for $dia ^..^ $n -> $col { - A($row, $col) -= $tmp * A($dia, $col); - } - A($row, $dia) = 0; - @b[$row] -= $tmp * @b[$dia]; - } +# reduced row echelon form (Gauss-Jordan elimination) +sub rref (@m) { + return unless @m; + my ($lead, $rows, $cols) = 0, +@m, +@m[0]; + + for ^$rows -> $r { + $lead < $cols or return @m; + my $i = $r; + until @m[$i;$lead] { + ++$i == $rows or next; + $i = $r; + ++$lead == $cols and return @m; + } + @m[$i, $r] = @m[$r, $i] if $r != $i; + my $lv = @m[$r;$lead]; + @m[$r] »/=» $lv; + for ^$rows -> $n { + next if $n == $r; + @m[$n] »-=» @m[$r] »*» (@m[$n;$lead] // 0); + } + ++$lead; } - my @x; - for $n - 1, $n - 2 ... 0 -> $row { - $tmp = @b[$row]; - for $n - 1, $n - 2 ...^ $row -> $j { - $tmp -= @x[$j] * A($row, $j); - } - @x[$row] = $tmp / A($row, $row); - } - return @x; + @m } -sub MAIN { - my @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 - >; - my @b = < - -0.01 0.61 0.91 0.99 0.60 0.02 - >; - .say for gauss_eliminate(@a, @b, 6); +sub rat-or-int ($num) { + return $num unless $num ~~ Rat; + return $num.narrow if $num.narrow.WHAT ~~ Int; + $num.nude.join: '/'; } + +sub say-it ($message, @array, $fmt = " %8s") { + say "\n$message"; + $_».&rat-or-int.fmt($fmt).put for @array; +} + +my @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 ], +); +my @b = ( -0.01, 0.61, 0.91, 0.99, 0.60, 0.02 ); + +say-it 'A matrix:', @a, "%6.2f"; +say-it 'or, A in exact rationals:', @a; +say-it 'B matrix:', @b, "%6.2f"; +say-it 'or, B in exact rationals:', @b; +say-it 'x matrix:', (my @gj = gauss-jordan-solve @a, @b), "%16.12f"; +say-it 'or, x in exact rationals:', @gj, "%28s"; diff --git a/Task/Gaussian-elimination/REXX/gaussian-elimination-2.rexx b/Task/Gaussian-elimination/REXX/gaussian-elimination-2.rexx index 81d2ccef92..1f05d31cef 100644 --- a/Task/Gaussian-elimination/REXX/gaussian-elimination-2.rexx +++ b/Task/Gaussian-elimination/REXX/gaussian-elimination-2.rexx @@ -1,33 +1,40 @@ -/*REXX program solves Ax=b with Gaussian elimination & backwards substitution.*/ -parse arg iFID .; if iFID=='' then iFID='GAUSS_E.DAT' /*¬given? Use default.*/ -numeric digits 200 /*use hefty precision.*/ - do rec=1 while lines(iFID)\==0 /*read equation sets. */ - #=0 - do $=1 while lines(iFID)\==0 /*process the equation*/ - z=linein(iFID); if z='' then leave /*Blank line? e─o─data*/ - if $==1 then do; say; say center(' equations ',75,'▒'); say; end - say z /*show an equation. */ - if left(space(z),1)=='*' then iterate /*ignore any comments.*/ - #=#+1; n=words(z)-1 /*assign equation #s. */ - do e=1 for n; a.#.e=word(z,e); end /*e*/ /*process the A #s. */ - b.#=word(z,n+1) /* " " B #s. */ - end /*$*/ - if #\==0 then call Gauss_elimination /*compute,show results*/ - end /*rec*/ -exit /*stick a fork in it, we're all done. */ -/*────────────────────────────────────────────────────────────────────────────*/ -Gauss_elimination: 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 - 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; end /*i*/ - x.j=(b.j-_)/a.j.j - end /*j*/ /* [↑] uses backwards substitution. */ -numeric digits 8 /*for the display, only use 8 digits.*/ -say; 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*/ -return +/*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. */ +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 $=1 while lines(iFID) \== 0 /*process the equation. */ + 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.*/ + do e=1 for n; a.#.e= word(z, e) + end /*e*/ /* [↑] process A numbers. */ + 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 + end /*k*/ + 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 + end /*i*/ + x.j=(b.j - _) / a.j.j + end /*j*/ /* [↑] uses backwards substitution. */ + say + numeric digits 8 /*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*/ + return diff --git a/Task/Gaussian-elimination/REXX/gaussian-elimination-3.rexx b/Task/Gaussian-elimination/REXX/gaussian-elimination-3.rexx new file mode 100644 index 0000000000..62b0ddf25e --- /dev/null +++ b/Task/Gaussian-elimination/REXX/gaussian-elimination-3.rexx @@ -0,0 +1,48 @@ +/*REXX program solves Ax=b with Gaussian elimination and backwards substitution. */ +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. */ + 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.*/ + 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.*/ + 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 " " " */ + 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*/ + 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 + end /*k*/ + 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 + end /*i*/ + x.j=(b.j - _) / a.j.j + end /*j*/ /* [↑] uses backwards substitution. */ + say + numeric digits 8 /*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*/ + return diff --git a/Task/Gaussian-elimination/Sidef/gaussian-elimination.sidef b/Task/Gaussian-elimination/Sidef/gaussian-elimination.sidef index cd39875188..1c5f1299dd 100644 --- a/Task/Gaussian-elimination/Sidef/gaussian-elimination.sidef +++ b/Task/Gaussian-elimination/Sidef/gaussian-elimination.sidef @@ -1,11 +1,22 @@ -var Matrix = require('Math::Matrix'); +func gauss_jordan_solve (a, b) { -var a = Matrix.new([0,1,0], - [0,0,1], - [2,0,1]); + var A = gather { + ^b -> each {|i| take(a[i] + b[i]) } + } -var b = Matrix.new([1], - [2], - [4]); + rref(A).map{ .last } +} -a.concat(b).solve.print; +var 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 ], +] + +var b = [ -0.01, 0.61, 0.91, 0.99, 0.60, 0.02 ] + +var G = gauss_jordan_solve(a, b) +say G.map { "%27s" % .as_rat }.join("\n") diff --git a/Task/Gaussian-elimination/Stata/gaussian-elimination-1.stata b/Task/Gaussian-elimination/Stata/gaussian-elimination-1.stata new file mode 100644 index 0000000000..ceafe7e35a --- /dev/null +++ b/Task/Gaussian-elimination/Stata/gaussian-elimination-1.stata @@ -0,0 +1,29 @@ +void gauss(real matrix a, real matrix b, real scalar det) { + real scalar i,j,n,s + real vector js + + det = 1 + n = rows(a) + for (i=1; i=1; i--) { + for (j=i+1; j<=n; j++) { + b[i,.] = b[i,.]-a[i,j]*b[j,.] + } + b[i,.] = b[i,.]/a[i,i] + det = det*a[i,i] + } +} diff --git a/Task/Gaussian-elimination/Stata/gaussian-elimination-2.stata b/Task/Gaussian-elimination/Stata/gaussian-elimination-2.stata new file mode 100644 index 0000000000..44fc2dec68 --- /dev/null +++ b/Task/Gaussian-elimination/Stata/gaussian-elimination-2.stata @@ -0,0 +1,43 @@ +void ludec(real matrix a, real matrix l, real matrix u, real vector p) { + real scalar i,j,n,s + real vector js + + l = a + n = rows(a) + p = 1::n + for (i=1; i=1; i--) { + for (j=i+1; j<=n; j++) { + y[i,.] = y[i,.]-u[i,j]*y[j,.] + } + y[i,.] = y[i,.]/u[i,i] + } +} diff --git a/Task/Gaussian-elimination/Stata/gaussian-elimination-3.stata b/Task/Gaussian-elimination/Stata/gaussian-elimination-3.stata new file mode 100644 index 0000000000..6d93d6d98c --- /dev/null +++ b/Task/Gaussian-elimination/Stata/gaussian-elimination-3.stata @@ -0,0 +1,21 @@ +: gauss(a=(2,9,4\7,5,3\6,1,8),b=I(3),det=.) + +: b + 1 2 3 + +----------------------------------------------+ + 1 | -.1027777778 .1888888889 -.0194444444 | + 2 | .1055555556 .0222222222 -.0611111111 | + 3 | .0638888889 -.1444444444 .1472222222 | + +----------------------------------------------+ + +: ludec(a=(2,9,4\7,5,3\6,1,8),l=.,u=.,p=.) + +: luback(l,u,p,y=I(3)) + +: y + 1 2 3 + +----------------------------------------------+ + 1 | -.1027777778 .1888888889 -.0194444444 | + 2 | .1055555556 .0222222222 -.0611111111 | + 3 | .0638888889 -.1444444444 .1472222222 | + +----------------------------------------------+ diff --git a/Task/Generate-Chess960-starting-position/00DESCRIPTION b/Task/Generate-Chess960-starting-position/00DESCRIPTION index dd0b053203..2e9ce1bf18 100644 --- a/Task/Generate-Chess960-starting-position/00DESCRIPTION +++ b/Task/Generate-Chess960-starting-position/00DESCRIPTION @@ -1,4 +1,4 @@ -'''[[wp:Chess960|Chess960]]'''   is a variant of chess created by world champion [[wp:Bobby Fischer|Bobby Fischer]]. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: +'''[[wp:Chess960|Chess960]]''' is a variant of chess created by world champion [[wp:Bobby Fischer|Bobby Fischer]]. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: * as in the standard chess game, all eight white pawns must be placed on the second rank. * White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints: @@ -11,5 +11,5 @@ With those constraints there are '''960''' possible starting positions, thus the ;Task: -The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions.   You will show the result as the first rank displayed with   [[wp:Chess symbols in Unicode|Chess symbols in Unicode: ♔♕♖♗♘]]   or with the letters   '''K'''ing   '''Q'''ueen   '''R'''ook   '''B'''ishop   k'''N'''ight. +The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with [[wp:Chess symbols in Unicode|Chess symbols in Unicode: ♔♕♖♗♘]] or with the letters '''K'''ing '''Q'''ueen '''R'''ook '''B'''ishop k'''N'''ight.

diff --git a/Task/Generate-Chess960-starting-position/C/generate-chess960-starting-position.c b/Task/Generate-Chess960-starting-position/C/generate-chess960-starting-position.c new file mode 100644 index 0000000000..bcaff01ed8 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/C/generate-chess960-starting-position.c @@ -0,0 +1,104 @@ +/*Abhishek Ghosh, 10th October 2017*/ + +#include +#include +#include +#include +#include + +char rank[9]; + +int pos[8]; + +void swap(int i,int j){ + int temp = pos[i]; + pos[i] = pos[j]; + pos[j] = temp; +} + +void generateFirstRank(){ + int kPos,qPos,bPos1,bPos2,rPos1,rPos2,nPos1,nPos2,i; + + for(i=0;i<8;i++){ + rank[i] = 'e'; + pos[i] = i; + } + + do{ + kPos = rand()%8; + rPos1 = rand()%8; + rPos2 = rand()%8; + }while((rPos1-kPos<=0 && rPos2-kPos<=0)||(rPos1-kPos>=0 && rPos2-kPos>=0)||(rPos1==rPos2 || kPos==rPos1 || kPos==rPos2)); + + rank[pos[rPos1]] = 'R'; + rank[pos[kPos]] = 'K'; + rank[pos[rPos2]] = 'R'; + + swap(rPos1,7); + swap(rPos2,6); + swap(kPos,5); + + do{ + bPos1 = rand()%5; + bPos2 = rand()%5; + }while(((pos[bPos1]-pos[bPos2])%2==0)||(bPos1==bPos2)); + + rank[pos[bPos1]] = 'B'; + rank[pos[bPos2]] = 'B'; + + swap(bPos1,4); + swap(bPos2,3); + + do{ + qPos = rand()%3; + nPos1 = rand()%3; + }while(qPos==nPos1); + + rank[pos[qPos]] = 'Q'; + rank[pos[nPos1]] = 'N'; + + for(i=0;i<8;i++) + if(rank[i]=='e'){ + rank[i] = 'N'; + break; + } +} + +void printRank(){ + int i; + + #ifdef _WIN32 + printf("%s\n",rank); + #else + { + setlocale(LC_ALL,""); + printf("\n"); + for(i=0;i<8;i++){ + if(rank[i]=='K') + printf("%lc",(wint_t)9812); + else if(rank[i]=='Q') + printf("%lc",(wint_t)9813); + else if(rank[i]=='R') + printf("%lc",(wint_t)9814); + else if(rank[i]=='B') + printf("%lc",(wint_t)9815); + if(rank[i]=='N') + printf("%lc",(wint_t)9816); + } + } + #endif +} + +int main() +{ + int i; + + srand((unsigned)time(NULL)); + + for(i=0;i<9;i++){ + generateFirstRank(); + printRank(); + } + + return 0; +} diff --git a/Task/Generate-Chess960-starting-position/Julia/generate-chess960-starting-position.julia b/Task/Generate-Chess960-starting-position/Julia/generate-chess960-starting-position.julia index 10e6467e3f..86b3dd225b 100644 --- a/Task/Generate-Chess960-starting-position/Julia/generate-chess960-starting-position.julia +++ b/Task/Generate-Chess960-starting-position/Julia/generate-chess960-starting-position.julia @@ -1,30 +1,30 @@ -# placeholder knights -rank1 = ['♘', '♘', '♘', '♘', '♘', '♘', '♘', '♘'] +function generateposition() + # Placeholder knights + rank = ['♘', '♘', '♘', '♘', '♘', '♘', '♘', '♘'] + lrank = length(rank) -# function to check if a space is available -isfree(x::Int) = rank1[x] == '♘' + # Check if a space is available + isfree(x::Int) = rank[x] == '♘' -# place king -king = rand(2:7) -rank1[king] = '♔' + # Place the King + rank[indking = rand(2:lrank-1)] = '♔' -# place rooks -rook1 = rand(filter(isfree, 1:8)) -rank1[rook1] = '♖' + # Place rooks + rank[indrook = rand(filter(isfree, 1:lrank))] = '♖' + if indrook > indking + rank[rand(filter(isfree, 1:indking-1))] = '♖' + else + rank[rand(filter(isfree, indking+1:lrank))] = '♖' + end -if rook1 > king - rank1[rand(filter(x -> isfree(x) && x < king, 1:8))] = '♖' -else - rank1[rand(filter(x -> isfree(x) && x > king, 1:8))] = '♖' + # Place bishops + rank[indbish = rand(filter(isfree, 1:8))] = '♗' + pbish = filter(iseven(indbish) ? isodd : iseven, 1:lrank) + rank[rand(filter(isfree, pbish))] = '♗' + + # Place queen + rank[rand(filter(isfree, 1:lrank))] = '♕' + return rank end -# place bishops -bishop1 = rand(filter(isfree, 1:8)) -rank1[bishop1] = '♗' -rank1[rand(filter(x -> isfree(x) && iseven(x) != iseven(bishop1), 1:8))] = '♗' - -# place queen -rank1[rand(filter(isfree, 1:8))] = '♕' - -# print first rank -println(join(rank1)) +@show generateposition() diff --git a/Task/Generate-Chess960-starting-position/Perl-6/generate-chess960-starting-position-3.pl6 b/Task/Generate-Chess960-starting-position/Perl-6/generate-chess960-starting-position-3.pl6 index a4fa7a4b9e..a2b36a62c8 100644 --- a/Task/Generate-Chess960-starting-position/Perl-6/generate-chess960-starting-position-3.pl6 +++ b/Task/Generate-Chess960-starting-position/Perl-6/generate-chess960-starting-position-3.pl6 @@ -1,6 +1,4 @@ -constant chess960 = eager - .subst(:nth(2), /'♜'/, '♚') - if / '♝' [..]* '♝' / - for < ♛ ♜ ♜ ♜ ♝ ♝ ♞ ♞ >.permutations».join.uniq; +constant chess960 = + < ♛ ♜ ♜ ♜ ♝ ♝ ♞ ♞ >.permutations».join.unique.grep( / '♝' [..]* '♝' / )».subst(:nth(2), /'♜'/, '♚'); .say for chess960; diff --git a/Task/Generate-Chess960-starting-position/Perl-6/generate-chess960-starting-position-4.pl6 b/Task/Generate-Chess960-starting-position/Perl-6/generate-chess960-starting-position-4.pl6 index aa8c4fe5d7..d24ff283f9 100644 --- a/Task/Generate-Chess960-starting-position/Perl-6/generate-chess960-starting-position-4.pl6 +++ b/Task/Generate-Chess960-starting-position/Perl-6/generate-chess960-starting-position-4.pl6 @@ -1,4 +1,4 @@ -constant chess960 = eager gather for 0..3 -> $q { +constant chess960 = gather for 0..3 -> $q { (my @q = <♜ ♚ ♜>).splice($q, 0, '♛'); for 0 .. @q -> $n1 { (my @n1 = @q).splice($n1, 0, '♞'); diff --git a/Task/Generate-Chess960-starting-position/Rust/generate-chess960-starting-position.rust b/Task/Generate-Chess960-starting-position/Rust/generate-chess960-starting-position.rust index 48184d756f..16e63913de 100644 --- a/Task/Generate-Chess960-starting-position/Rust/generate-chess960-starting-position.rust +++ b/Task/Generate-Chess960-starting-position/Rust/generate-chess960-starting-position.rust @@ -29,9 +29,7 @@ fn main() { let mut chess960 = Chess960(BTreeSet::new()); chess960.invoke("", "KQRRNNBB"); - let mut i = 0; - for p in chess960.0 { + for (i, p) in chess960.0.iter().enumerate() { println!("{}: {}", i, p); - i += 1; } } diff --git a/Task/Generate-Chess960-starting-position/Scala/generate-chess960-starting-position-1.scala b/Task/Generate-Chess960-starting-position/Scala/generate-chess960-starting-position-1.scala new file mode 100644 index 0000000000..9aab47dd44 --- /dev/null +++ b/Task/Generate-Chess960-starting-position/Scala/generate-chess960-starting-position-1.scala @@ -0,0 +1,25 @@ +import scala.annotation.tailrec + +object Chess960 extends App { + + private val pieces = List('♖', '♗', '♘', '♕', '♔', '♘', '♗', '♖') + + @tailrec + private def generateFirstRank(pieces: List[Char]): List[Char] = { + def check(rank: String) = + rank.matches(".*♖.*♔.*♖.*") && rank.matches(".*♗(..|....|......|)♗.*") + + val p = scala.util.Random.shuffle(pieces) + if (check(p.toString.replaceAll("[^\\p{Upper}]", ""))) + generateFirstRank(pieces) + else p + } + + loop(10) + + @tailrec + private def loop(n: Int): Unit = { + println(generateFirstRank(pieces)) + if (n <= 0) () else loop(n - 1) + } +} diff --git a/Task/Generate-Chess960-starting-position/Scala/generate-chess960-starting-position.scala b/Task/Generate-Chess960-starting-position/Scala/generate-chess960-starting-position-2.scala similarity index 100% rename from Task/Generate-Chess960-starting-position/Scala/generate-chess960-starting-position.scala rename to Task/Generate-Chess960-starting-position/Scala/generate-chess960-starting-position-2.scala diff --git a/Task/Generate-lower-case-ASCII-alphabet/ABAP/generate-lower-case-ascii-alphabet-1.abap b/Task/Generate-lower-case-ASCII-alphabet/ABAP/generate-lower-case-ascii-alphabet-1.abap new file mode 100644 index 0000000000..1e629e0fd5 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/ABAP/generate-lower-case-ascii-alphabet-1.abap @@ -0,0 +1,3 @@ +REPORT lower_case_ascii. + +WRITE: / to_lower( sy-abcde ). diff --git a/Task/Generate-lower-case-ASCII-alphabet/ABAP/generate-lower-case-ascii-alphabet-2.abap b/Task/Generate-lower-case-ASCII-alphabet/ABAP/generate-lower-case-ascii-alphabet-2.abap new file mode 100644 index 0000000000..6d6e2c46dd --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/ABAP/generate-lower-case-ascii-alphabet-2.abap @@ -0,0 +1,10 @@ +REPORT lower_case_ascii. + +cl_demo_output=>new( + )->begin_section( |Generate lower case ASCII alphabet| + )->write( REDUCE string( INIT out TYPE string + FOR char = 1 UNTIL char > strlen( sy-abcde ) + NEXT out = COND #( WHEN out IS INITIAL THEN sy-abcde(1) + ELSE |{ out } { COND string( WHEN char <> strlen( sy-abcde ) THEN sy-abcde+char(1) ) }| ) ) + )->write( |Or use the system field: { sy-abcde }| + )->display( ). diff --git a/Task/Generate-lower-case-ASCII-alphabet/ABAP/generate-lower-case-ascii-alphabet.abap b/Task/Generate-lower-case-ASCII-alphabet/ABAP/generate-lower-case-ascii-alphabet.abap deleted file mode 100644 index f6c07fa24a..0000000000 --- a/Task/Generate-lower-case-ASCII-alphabet/ABAP/generate-lower-case-ascii-alphabet.abap +++ /dev/null @@ -1 +0,0 @@ -DATA(alpha) = to_lower( sy-abcde ). diff --git a/Task/Generate-lower-case-ASCII-alphabet/AppleScript/generate-lower-case-ascii-alphabet-1.applescript b/Task/Generate-lower-case-ASCII-alphabet/AppleScript/generate-lower-case-ascii-alphabet-1.applescript index c9d3f1bdf5..dde4b341b5 100644 --- a/Task/Generate-lower-case-ASCII-alphabet/AppleScript/generate-lower-case-ascii-alphabet-1.applescript +++ b/Task/Generate-lower-case-ASCII-alphabet/AppleScript/generate-lower-case-ascii-alphabet-1.applescript @@ -5,56 +5,34 @@ on run end run --- GENERIC FUNCTIONS ---------------------------------------------------------- - --- chr :: Int -> Char -on chr(n) - character id n -end chr - --- ord :: Char -> Int -on ord(c) - id of c -end ord +-- GENERIC FUNCTIONS --------------------------------------------------------- -- enumFromTo :: Enum a => a -> a -> [a] on enumFromTo(m, n) - set {intM, intN} to {fromEnum(m), fromEnum(n)} - - if intM > intN then - set d to -1 + if class of m is integer then + enumFromToInt(m, n) else - set d to 1 + enumFromToChar(m, n) end if - set lst to {} - if class of m is text then - repeat with i from intM to intN by d - set end of lst to chr(i) - end repeat - else - repeat with i from intM to intN by d - set end of lst to i - end repeat - end if - return lst end enumFromTo --- fromEnum :: Enum a => a -> Int -on fromEnum(x) - set c to class of x - if c is boolean then - if x then - 1 - else - 0 - end if - else if c is text then - if x ≠ "" then - id of x - else - missing value - end if +-- enumFromToChar :: Char -> Char -> [Char] +on enumFromToChar(m, n) + set {intM, intN} to {id of m, id of n} + set xs to {} + repeat with i from intM to intN by signum(intN - intM) + set end of xs to character id i + end repeat + return xs +end enumFromToChar + +-- signum :: Num -> Num +on signum(x) + if x < 0 then + -1 + else if x = 0 then + 0 else - x as integer + 1 end if -end fromEnum +end signum diff --git a/Task/Generate-lower-case-ASCII-alphabet/Brainf---/generate-lower-case-ascii-alphabet-1.bf b/Task/Generate-lower-case-ASCII-alphabet/Brainf---/generate-lower-case-ascii-alphabet-1.bf new file mode 100644 index 0000000000..4328cbe07a --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Brainf---/generate-lower-case-ascii-alphabet-1.bf @@ -0,0 +1,26 @@ +Make room for 26 characters +>>>>>>>>>>>>> +>>>>>>>>>>>>> +Set counter to 26 +>> ++++++++++++++ ++++++++++++++ +Generate the numbers 1 to 26 +[-<< Decrement counter + [+<] Add one to each nonzero cell moving right to left + + Add one to first zero cell encountered + [>]> Return head to counter +] +<< +Add 96 to each cell +[ +++++++++++++++++ +++++++++++++++++ +++++++++++++++++ +++++++++++++++++ +++++++++++++++++ +++++++++++++++++ +<] +Print each cell +>[.>] +++++++++++. \n diff --git a/Task/Generate-lower-case-ASCII-alphabet/Brainf---/generate-lower-case-ascii-alphabet-2.bf b/Task/Generate-lower-case-ASCII-alphabet/Brainf---/generate-lower-case-ascii-alphabet-2.bf new file mode 100644 index 0000000000..602111cdf4 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Brainf---/generate-lower-case-ascii-alphabet-2.bf @@ -0,0 +1,3 @@ +>>>>>>>>>>>>>>>>>>>>>>>>>>>>++++++++++++++++++++++++++[-<<[+<] ++[>]>]<<[+++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++<]>[.>]++++++++++. diff --git a/Task/Generate-lower-case-ASCII-alphabet/C-sharp/generate-lower-case-ascii-alphabet-1.cs b/Task/Generate-lower-case-ASCII-alphabet/C-sharp/generate-lower-case-ascii-alphabet-1.cs new file mode 100644 index 0000000000..52f790b014 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/C-sharp/generate-lower-case-ascii-alphabet-1.cs @@ -0,0 +1,10 @@ +using System; +using System.Linq; + +internal class Program +{ + private static void Main() + { + Console.WriteLine(String.Concat(Enumerable.Range('a', 26).Select(c => (char)c))); + } +} diff --git a/Task/Generate-lower-case-ASCII-alphabet/C-sharp/generate-lower-case-ascii-alphabet.cs b/Task/Generate-lower-case-ASCII-alphabet/C-sharp/generate-lower-case-ascii-alphabet-2.cs similarity index 100% rename from Task/Generate-lower-case-ASCII-alphabet/C-sharp/generate-lower-case-ascii-alphabet.cs rename to Task/Generate-lower-case-ASCII-alphabet/C-sharp/generate-lower-case-ascii-alphabet-2.cs diff --git a/Task/Generate-lower-case-ASCII-alphabet/DUP/generate-lower-case-ascii-alphabet.dup b/Task/Generate-lower-case-ASCII-alphabet/DUP/generate-lower-case-ascii-alphabet.dup new file mode 100644 index 0000000000..babde28ef1 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/DUP/generate-lower-case-ascii-alphabet.dup @@ -0,0 +1,2 @@ +0"abcdefghijklmnopqrstuvwxyz" {store character values of string in cells 0..length of string-1} +26[$][^^-;,1-]# {Loop from 26-26 to 26-0, print the respective cell contents to STDOUT} 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 new file mode 100644 index 0000000000..5bc36627c0 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/Elena/generate-lower-case-ascii-alphabet.elena @@ -0,0 +1,34 @@ +import extensions. +import system'collections. + +singleton Alphabet :: BaseEnumerable +{ + enumerator = Enumerator:: + { + char current. + + get = current. + + bool next + [ + if ($nil==current) + [ + current := $97. + ]; + if (current != $122) + [ + current := (current toInt + 1) toChar. + ]; + [ + ^ false + ]. + + ^ true + ] + }. +} + +program = +[ + console printLine(Alphabet). +]. diff --git a/Task/Generate-lower-case-ASCII-alphabet/Julia/generate-lower-case-ascii-alphabet.julia b/Task/Generate-lower-case-ASCII-alphabet/Julia/generate-lower-case-ascii-alphabet.julia index 3afcfb3430..9ee8deb910 100644 --- a/Task/Generate-lower-case-ASCII-alphabet/Julia/generate-lower-case-ascii-alphabet.julia +++ b/Task/Generate-lower-case-ASCII-alphabet/Julia/generate-lower-case-ascii-alphabet.julia @@ -1,5 +1,2 @@ -['a':'z'] - -[c for c = 'a':'z'] - -string('a':'z'...) +@show collect('a':'z') +@show join('a':'z') diff --git a/Task/Generate-lower-case-ASCII-alphabet/OCaml/generate-lower-case-ascii-alphabet.ocaml b/Task/Generate-lower-case-ASCII-alphabet/OCaml/generate-lower-case-ascii-alphabet.ocaml new file mode 100644 index 0000000000..629ec2a2fc --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/OCaml/generate-lower-case-ascii-alphabet.ocaml @@ -0,0 +1,4 @@ +# Array.make 26 'a' |> Array.mapi (fun i c -> int_of_char c + i |> char_of_int);; +- : char array = +[|'a'; 'b'; 'c'; 'd'; 'e'; 'f'; 'g'; 'h'; 'i'; 'j'; 'k'; 'l'; 'm'; 'n'; 'o'; + 'p'; 'q'; 'r'; 's'; 't'; 'u'; 'v'; 'w'; 'x'; 'y'; 'z'|] diff --git a/Task/Generate-lower-case-ASCII-alphabet/Perl-6/generate-lower-case-ascii-alphabet.pl6 b/Task/Generate-lower-case-ASCII-alphabet/Perl-6/generate-lower-case-ascii-alphabet.pl6 index 8c3f2874c3..b22cc80db9 100644 --- a/Task/Generate-lower-case-ASCII-alphabet/Perl-6/generate-lower-case-ascii-alphabet.pl6 +++ b/Task/Generate-lower-case-ASCII-alphabet/Perl-6/generate-lower-case-ascii-alphabet.pl6 @@ -1 +1 @@ -my @letters = 'a'..'z'; +say my @letters = 'a'..'z'; diff --git a/Task/Generate-lower-case-ASCII-alphabet/VBA/generate-lower-case-ascii-alphabet.vba b/Task/Generate-lower-case-ASCII-alphabet/VBA/generate-lower-case-ascii-alphabet.vba new file mode 100644 index 0000000000..a81d991bb2 --- /dev/null +++ b/Task/Generate-lower-case-ASCII-alphabet/VBA/generate-lower-case-ascii-alphabet.vba @@ -0,0 +1,19 @@ +Option Explicit + +Sub Main_Lower_Case_Ascii_Alphabet() +Dim Alpha() As String + + Alpha = Alphabet(97, 122) + Debug.Print Join(Alpha, ", ") +End Sub + +Function Alphabet(FirstAscii As Byte, LastAscii As Byte) As String() +Dim strarrTemp() As String, i& + + ReDim strarrTemp(0 To LastAscii - FirstAscii) + For i = FirstAscii To LastAscii + strarrTemp(i - FirstAscii) = Chr(i) + Next + Alphabet = strarrTemp + Erase strarrTemp +End Function diff --git a/Task/Generator-Exponential/00DESCRIPTION b/Task/Generator-Exponential/00DESCRIPTION index 73f09b0d92..cfe2dae77a 100644 --- a/Task/Generator-Exponential/00DESCRIPTION +++ b/Task/Generator-Exponential/00DESCRIPTION @@ -1,19 +1,26 @@ {{omit from|Lilypond}} [[Category:Non parametric generators]] [[Category:Stateful transactions]] + A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. + Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”. + Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state. -'''Task description''' -# Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size). -# Use it to create a generator of: -:# Squares. -:# Cubes. -# Create a new generator that filters all cubes from the generator of squares. -# Drop the first 20 values from this last generator of filtered results then show the next 10 values +;Task: +* Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size). +* Use it to create a generator of: +:::*   Squares. +:::*   Cubes. +* Create a new generator that filters all cubes from the generator of squares. +* Drop the first 20 values from this last generator of filtered results, and then show the next 10 values. + + Note that this task ''requires'' the use of generators in the calculation of the result. -'''See also''' + +;Also see: * [[wp:Generator (computer_science)|Generator]] +

diff --git a/Task/Generator-Exponential/Julia/generator-exponential.julia b/Task/Generator-Exponential/Julia/generator-exponential.julia index d713569aa5..8f9c1f8c80 100644 --- a/Task/Generator-Exponential/Julia/generator-exponential.julia +++ b/Task/Generator-Exponential/Julia/generator-exponential.julia @@ -1,16 +1,20 @@ -drop(n, gen) = (for i=1:n gen() end ; gen) +drop(gen::Function, n::Integer) = (for _ in 1:n gen() end; gen) +take(gen::Function, n::Integer) = collect(gen() for _ in 1:n) -take(n, gen) = [gen() for i=1:n] - -pgen(n) = let x=0; () -> (x+=1)^n; end - -function genfilter(gen1, gen2) - let r1 = -Inf, r2 = gen2() - () -> begin - r1 = gen1() - while r2 < r1 r2 = gen2() end - while r1 == r2 r1 = gen1() end - r1 - end - end +function pgen(n::Number) + x = 0 + return () -> (x += 1) ^ n end + +function genfilter(g1::Function, g2::Function) + local r1 + local r2 = g2() + return () -> begin + r1 = g1() + while r2 < r1 r2 = g2() end + while r1 == r2 r1 = g1() end + return r1 + end +end + +@show take(drop(genfilter(pgen(2), pgen(3)), 20), 10) diff --git a/Task/Generator-Exponential/Lingo/generator-exponential-1.lingo b/Task/Generator-Exponential/Lingo/generator-exponential-1.lingo new file mode 100644 index 0000000000..328313f434 --- /dev/null +++ b/Task/Generator-Exponential/Lingo/generator-exponential-1.lingo @@ -0,0 +1,11 @@ +squares = script("generator.power").new(2) +cubes = script("generator.power").new(3) +filter = script("generator.filter").new(squares, cubes) +filter.skip(20) +res = [] +i = 0 +repeat while filter.exec(res) + i = i + 1 + if i>10 then exit repeat + put res[1] +end repeat diff --git a/Task/Generator-Exponential/Lingo/generator-exponential-2.lingo b/Task/Generator-Exponential/Lingo/generator-exponential-2.lingo new file mode 100644 index 0000000000..1a86458433 --- /dev/null +++ b/Task/Generator-Exponential/Lingo/generator-exponential-2.lingo @@ -0,0 +1,23 @@ +property _exp +property _index + +-- @constructor +on new (me, e) + me._exp = e + me._index = 0 + return me +end + +on exec (me, input) + me._index = me._index+1 + input[1] = integer(power(me._index, me._exp)) + return TRUE +end + +on skip (me, steps) + me._index = me._index + steps +end + +on reset (me) + me._index = 0 +end diff --git a/Task/Generator-Exponential/Lingo/generator-exponential-3.lingo b/Task/Generator-Exponential/Lingo/generator-exponential-3.lingo new file mode 100644 index 0000000000..4edeea7e2a --- /dev/null +++ b/Task/Generator-Exponential/Lingo/generator-exponential-3.lingo @@ -0,0 +1,43 @@ +property _genv +property _genf + +-- @constructor +on new (me, genv, genf) + me._genv = genv + me._genf = genf + return me +end + +on exec (me, input) + repeat while TRUE + me._genv.exec(input) + v = input[1] + ok = TRUE + me._genf.reset() -- reset filter generator + repeat while TRUE + me._genf.exec(input) + f = input[1] + if f>v then exit repeat + if f=v then + ok=FALSE + exit repeat + end if + end repeat + if ok then + input[1] = v + exit repeat + end if + end repeat + return TRUE +end + +on skip (me, steps) + repeat with i = 1 to steps + me.exec([]) + end repeat +end + +on reset (me) + me._genv.reset() + me._genf.reset() +end diff --git a/Task/Generic-swap/Crystal/generic-swap.crystal b/Task/Generic-swap/Crystal/generic-swap.crystal new file mode 100644 index 0000000000..053b49fb51 --- /dev/null +++ b/Task/Generic-swap/Crystal/generic-swap.crystal @@ -0,0 +1 @@ +a, b = b, a diff --git a/Task/Generic-swap/Haskell/generic-swap.hs b/Task/Generic-swap/Haskell/generic-swap-1.hs similarity index 100% rename from Task/Generic-swap/Haskell/generic-swap.hs rename to Task/Generic-swap/Haskell/generic-swap-1.hs diff --git a/Task/Generic-swap/Haskell/generic-swap-2.hs b/Task/Generic-swap/Haskell/generic-swap-2.hs new file mode 100644 index 0000000000..8ea2c31119 --- /dev/null +++ b/Task/Generic-swap/Haskell/generic-swap-2.hs @@ -0,0 +1,7 @@ +import Control.Monad.Ref +swap :: MonadRef r m => r a -> r a -> m () +swap xRef yRef = do + x<-readRef xRef + y<-readRef yRef + writeRef xRef y + writeRef yRef x diff --git a/Task/Globally-replace-text-in-several-files/Kotlin/globally-replace-text-in-several-files.kotlin b/Task/Globally-replace-text-in-several-files/Kotlin/globally-replace-text-in-several-files.kotlin new file mode 100644 index 0000000000..3fbc8491a5 --- /dev/null +++ b/Task/Globally-replace-text-in-several-files/Kotlin/globally-replace-text-in-several-files.kotlin @@ -0,0 +1,15 @@ +// version 1.2.0 + +import java.io.File + +fun main(args: Array) { + val files = arrayOf("file1.txt", "file2.txt") + for (file in files) { + val f = File(file) + var text = f.readText() + println(text) + text = text.replace("Goodbye London!", "Hello New York!") + f.writeText(text) + println(f.readText()) + } +} diff --git a/Task/Globally-replace-text-in-several-files/REXX/globally-replace-text-in-several-files-2.rexx b/Task/Globally-replace-text-in-several-files/REXX/globally-replace-text-in-several-files-2.rexx index 87cbb1dbe6..9911cc3bc6 100644 --- a/Task/Globally-replace-text-in-several-files/REXX/globally-replace-text-in-several-files-2.rexx +++ b/Task/Globally-replace-text-in-several-files/REXX/globally-replace-text-in-several-files-2.rexx @@ -1,7 +1,7 @@ /* REXX *************************************************************** * Copy all files *.txt to *.rpl * replacing all occurrences of old by new -* Execute in the directory containing the files to ne processed +* Execute in the directory containing the files to be processed * 16.01.2013 Walter Pachl * ...if file names contain blanks **********************************************************************/ diff --git a/Task/Globally-replace-text-in-several-files/Red/globally-replace-text-in-several-files.red b/Task/Globally-replace-text-in-several-files/Red/globally-replace-text-in-several-files.red new file mode 100644 index 0000000000..6dca2c1b4d --- /dev/null +++ b/Task/Globally-replace-text-in-several-files/Red/globally-replace-text-in-several-files.red @@ -0,0 +1,4 @@ +>> f: request-file +>> str: read f +>> replace/all str "Goodbye London!" "Hello New York!" +>> write f str diff --git a/Task/Globally-replace-text-in-several-files/Scala/globally-replace-text-in-several-files.scala b/Task/Globally-replace-text-in-several-files/Scala/globally-replace-text-in-several-files.scala new file mode 100644 index 0000000000..6623416b67 --- /dev/null +++ b/Task/Globally-replace-text-in-several-files/Scala/globally-replace-text-in-several-files.scala @@ -0,0 +1,13 @@ +import java.io.{File, PrintWriter} + +object GloballyReplaceText extends App { + + val (charsetName, fileNames) = ("UTF8", Seq("file1.txt", "file2.txt")) + for (fileHandle <- fileNames.map(new File(_))) + new PrintWriter(fileHandle, charsetName) { + print(scala.io.Source.fromFile(fileHandle, charsetName).mkString + .replace("Goodbye London!", "Hello New York!")) + close() + } + +} diff --git a/Task/Gray-code/Aime/gray-code-1.aime b/Task/Gray-code/Aime/gray-code-1.aime index 0875c61135..3c7b798fb9 100644 --- a/Task/Gray-code/Aime/gray-code-1.aime +++ b/Task/Gray-code/Aime/gray-code-1.aime @@ -1,7 +1,7 @@ integer gray_encode(integer n) { - return n ^ (n >> 1); + n ^ (n >> 1); } integer @@ -14,5 +14,5 @@ gray_decode(integer n) p ^= n; } - return p; + p; } diff --git a/Task/Gray-code/Julia/gray-code.julia b/Task/Gray-code/Julia/gray-code.julia index 5cb734a2a2..5a5c585e3d 100644 --- a/Task/Gray-code/Julia/gray-code.julia +++ b/Task/Gray-code/Julia/gray-code.julia @@ -1,9 +1,8 @@ -gray_encode(n) = n $ (n >> 1) - -function gray_decode(n) - p = n +grayencode(n::Integer) = n ⊻ (n >> 1) +function graydecode(n::Integer) + r = n while (n >>= 1) != 0 - p $= n + r ⊻= n end - return p + return r end diff --git a/Task/Gray-code/Perl-6/gray-code.pl6 b/Task/Gray-code/Perl-6/gray-code.pl6 new file mode 100644 index 0000000000..9d820d0fc4 --- /dev/null +++ b/Task/Gray-code/Perl-6/gray-code.pl6 @@ -0,0 +1,16 @@ +sub gray_encode ( Int $n --> Int ) { + return $n +^ ( $n +> 1 ); +} + +sub gray_decode ( Int $n is copy --> Int ) { + my $mask = 1 +< (32-2); + $n +^= $mask +> 1 if $n +& $mask while $mask +>= 1; + return $n; +} + +for ^32 -> $n { + my $g = gray_encode($n); + my $d = gray_decode($g); + printf "%2d: %5b => %5b => %5b: %2d\n", $n, $n, $g, $d, $d; + die if $d != $n; +} diff --git a/Task/Gray-code/Ring/gray-code.ring b/Task/Gray-code/Ring/gray-code.ring new file mode 100644 index 0000000000..89a6712666 --- /dev/null +++ b/Task/Gray-code/Ring/gray-code.ring @@ -0,0 +1,39 @@ +# Project : Gray code +# Date : 2018/01/12 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +pos = 5 +see "0 : 00000 => 00000 => 00000" + nl +for n = 1 to 31 + res1 = tobase(n, 2, pos) + res2 = tobase(grayencode(n), 2, pos) + res3 = tobase(graydecode(n), 2, pos) + see "" + n + " : " + res1 + " => " + res2 + " => " + res3 + nl +next + +func grayencode(n) + return n ^ (n >> 1) + +func graydecode(n) + p = n + while (n = n >> 1) + p = p ^ n + end + return p + +func tobase(nr, base, pos) + binary = 0 + i = 1 + while(nr != 0) + remainder = nr % base + nr = floor(nr/base) + binary= binary + (remainder*i) + i = i*10 + end + result = "" + for nr = 1 to pos - len(string(binary)) + result = result + "0" + next + result = result + string(binary) + return result diff --git a/Task/Grayscale-image/JavaScript/grayscale-image.js b/Task/Grayscale-image/JavaScript/grayscale-image.js index c5c4d9df66..0ebc9d9d76 100644 --- a/Task/Grayscale-image/JavaScript/grayscale-image.js +++ b/Task/Grayscale-image/JavaScript/grayscale-image.js @@ -1,38 +1,23 @@ - - + ctx.drawImage(img, 0, 0); + let pixels = ctx.getImageData(0, 0, imgW, imgH); + for (let y = 0; y < pixels.height; y ++) { + for (let x = 0; x < pixels.width; x ++) { + let i = (y * 4) * pixels.width + x * 4; + let avg = (pixels.data[i] + pixels.data[i + 1] + pixels.data[i + 2]) / 3; + + pixels.data[i] = avg; + pixels.data[i + 1] = avg; + pixels.data[i + 2] = avg; + } + } + ctx.putImageData(pixels, 0, 0, 0, 0, pixels.width, pixels.height); + return cnv.toDataURL(); +} diff --git a/Task/Grayscale-image/Kotlin/grayscale-image.kotlin b/Task/Grayscale-image/Kotlin/grayscale-image.kotlin new file mode 100644 index 0000000000..25a3ee8704 --- /dev/null +++ b/Task/Grayscale-image/Kotlin/grayscale-image.kotlin @@ -0,0 +1,27 @@ +// version 1.2.10 + +import java.io.File +import java.awt.image.BufferedImage +import javax.imageio.ImageIO + +fun BufferedImage.toGrayScale() { + for (x in 0 until width) { + for (y in 0 until height) { + var argb = getRGB(x, y) + val alpha = (argb shr 24) and 0xFF + val red = (argb shr 16) and 0xFF + val green = (argb shr 8) and 0xFF + val blue = argb and 0xFF + val lumin = (0.2126 * red + 0.7152 * green + 0.0722 * blue).toInt() + argb = (alpha shl 24) or (lumin shl 16) or (lumin shl 8) or lumin + setRGB(x, y, argb) + } + } +} + +fun main(args: Array) { + val image = ImageIO.read(File("bbc.jpg")) // using BBC BASIC image + image.toGrayScale() + val grayFile = File("bbc_gray.jpg") + ImageIO.write(image, "jpg", grayFile) +} diff --git a/Task/Grayscale-image/Maple/grayscale-image.maple b/Task/Grayscale-image/Maple/grayscale-image.maple new file mode 100644 index 0000000000..2f3e3d421d --- /dev/null +++ b/Task/Grayscale-image/Maple/grayscale-image.maple @@ -0,0 +1,16 @@ +with(ImageTools): +#conversion forward +dimensions:=[upperbound(img)]; +gray := Matrix(dimensions[1], dimensions[2]); +for i from 1 to dimensions[1] do + for j from 1 to dimensions[2] do + gray[i,j] := 0.2126 * img[i,j,1] + 0.7152*img[i,j,2] + 0.0722*img[i,j,3]: + end do: +end do: +#display the result +Embed(Create(gray)): +#conversion backward +x:=Create(gray); +ToRGB(x); +#display the result +Embed(x); diff --git a/Task/Grayscale-image/REXX/grayscale-image-1.rexx b/Task/Grayscale-image/REXX/grayscale-image-1.rexx index 9da1802395..00f37c9a48 100644 --- a/Task/Grayscale-image/REXX/grayscale-image-1.rexx +++ b/Task/Grayscale-image/REXX/grayscale-image-1.rexx @@ -1,4 +1,4 @@ -/*REXX program converts a RGB (red─green─blue) image to a grayscale image. */ +/*REXX program converts a RGB (red─green─blue) image into a grayscale/greyscale image. */ blue= '00 00 ff'x /*define the blue color (hexadecimal).*/ @.= blue /*set the entire image to blue color.*/ width= 60 /* width of the image (in pixels). */ @@ -9,7 +9,8 @@ height= 100 /*height " " " " r= left(@.col.row, 1) ; r=c2d(r) /*extract the component red & convert.*/ g=substr(@.col.row, 2, 1) ; g=c2d(g) /* " " " green " " */ b= right(@.col.row, 1) ; b=c2d(b) /* " " " blue " " */ - @.col.row=d2c((.2126*r+.7152*g +.0722*b)%1) /*convert RGB number ───► grayscale. */ - end /*row*/ /* [↑] D2C convert decimal ───> char*/ + _= d2c( (.2126*r + .7152*g + .0722*b) % 1) /*convert RGB number ───► grayscale. */ + @.col.row=copies(_, 3) /*redefine old RGB ───► grayscale. */ + end /*row*/ /* [↑] D2C convert decimal ───► char*/ end /*col*/ /* [↑] x%1 is the same as TRUNC(x) */ /*stick a fork in it, we're all done. */ diff --git a/Task/Grayscale-image/REXX/grayscale-image-2.rexx b/Task/Grayscale-image/REXX/grayscale-image-2.rexx index e52429a3c3..b2de793a98 100644 --- a/Task/Grayscale-image/REXX/grayscale-image-2.rexx +++ b/Task/Grayscale-image/REXX/grayscale-image-2.rexx @@ -1,5 +1,5 @@ blue= "00 00 ff"x /*define the blue color (hexadecimal).*/ - blue= '00 00 ff'x /*define the blue color (hexadecimal).*/ + blue= '00 00 FF'x /*define the blue color (hexadecimal).*/ blue= '0000ff'x /*define the blue color (hexadecimal).*/ blue= '00000000 00000000 11111111'b /*define the blue color (binary). */ diff --git a/Task/Greatest-common-divisor/AWK/greatest-common-divisor.awk b/Task/Greatest-common-divisor/AWK/greatest-common-divisor.awk index d85099e87c..b6129c1d08 100644 --- a/Task/Greatest-common-divisor/AWK/greatest-common-divisor.awk +++ b/Task/Greatest-common-divisor/AWK/greatest-common-divisor.awk @@ -1,4 +1,4 @@ -$ awk 'func gcd(p,q){return(q?gcd(q,(p%q)):p)}{print gcd($1,$2)}' +$ awk 'function gcd(p,q){return(q?gcd(q,(p%q)):p)}{print gcd($1,$2)}' 12 16 4 22 33 diff --git a/Task/Greatest-common-divisor/Elena/greatest-common-divisor.elena b/Task/Greatest-common-divisor/Elena/greatest-common-divisor.elena new file mode 100644 index 0000000000..9a46ac6331 --- /dev/null +++ b/Task/Greatest-common-divisor/Elena/greatest-common-divisor.elena @@ -0,0 +1,34 @@ +import system'math. +import extensions. + +gcd = (:a:b) +[ + var $a := a. + var $b := b. + while($b != 0) + [ + var tmp := $a. + $a := $b. + $b := tmp mod($b). + ]. + + ^ $a. +]. + +printGCD = (:a:b) +[ + console printLineFormatted("GCD of {0} and {1} is {2}", a, b, gcd(a,b)). +]. + +program = +[ + printGCD(1,1). + printGCD(1,10). + printGCD(10,100). + printGCD(5,50). + printGCD(8,24). + printGCD(36,17). + printGCD(36,18). + printGCD(36,19). + printGCD(36,33). +]. diff --git a/Task/Greatest-common-divisor/Klong/greatest-common-divisor.klong b/Task/Greatest-common-divisor/Klong/greatest-common-divisor.klong new file mode 100644 index 0000000000..b785c1948c --- /dev/null +++ b/Task/Greatest-common-divisor/Klong/greatest-common-divisor.klong @@ -0,0 +1 @@ +gcd::{:[~x;y:|~y;x:|x>y;.f(y;x!y);.f(x;y!x)]} diff --git a/Task/Greatest-common-divisor/Ruby/greatest-common-divisor-1.rb b/Task/Greatest-common-divisor/Ruby/greatest-common-divisor-1.rb index 47ad20a77b..7d169c178e 100644 --- a/Task/Greatest-common-divisor/Ruby/greatest-common-divisor-1.rb +++ b/Task/Greatest-common-divisor/Ruby/greatest-common-divisor-1.rb @@ -1,2 +1 @@ -irb(main):001:0> 40902.gcd(24140) -=> 34 +40902.gcd(24140) # => 34 diff --git a/Task/Greatest-common-divisor/Simula/greatest-common-divisor.simula b/Task/Greatest-common-divisor/Simula/greatest-common-divisor.simula new file mode 100644 index 0000000000..5ca2f4a6b7 --- /dev/null +++ b/Task/Greatest-common-divisor/Simula/greatest-common-divisor.simula @@ -0,0 +1,23 @@ +BEGIN + INTEGER PROCEDURE GCD(a, b); INTEGER a, b; + BEGIN + IF a = 0 THEN a := b + ELSE + WHILE 0 < b DO BEGIN INTEGER i; + i := MOD(a, b); a := b; b := i; + END; + GCD := a + END; + + INTEGER a, b; + !outint(SYSOUT.IMAGE.MAIN.LENGTH, 0);!OUTIMAGE;!OUTIMAGE; + !SYSOUT.IMAGE :- BLANKS(132); ! this may or may not work; + FOR b := 1 STEP 5 UNTIL 37 DO BEGIN + FOR a := 0 STEP 2 UNTIL 21 DO BEGIN + OUTTEXT(" ("); OUTINT(a, 0); + OUTCHAR(','); OUTINT(b, 2); + OUTCHAR(')'); OUTINT(GCD(a, b), 3); + END; + OUTIMAGE + END +END diff --git a/Task/Greatest-common-divisor/Stata/greatest-common-divisor.stata b/Task/Greatest-common-divisor/Stata/greatest-common-divisor.stata new file mode 100644 index 0000000000..3672d9440d --- /dev/null +++ b/Task/Greatest-common-divisor/Stata/greatest-common-divisor.stata @@ -0,0 +1,9 @@ +function gcd(a_,b_) { + a = abs(a_) + b = abs(b_) + while (b>0) { + a = mod(a,b) + swap(a,b) + } + return(a) +} diff --git a/Task/Greatest-common-divisor/XLISP/greatest-common-divisor.xlisp b/Task/Greatest-common-divisor/XLISP/greatest-common-divisor.xlisp new file mode 100644 index 0000000000..f57d6ac5ba --- /dev/null +++ b/Task/Greatest-common-divisor/XLISP/greatest-common-divisor.xlisp @@ -0,0 +1,4 @@ +(defun greatest-common-divisor (x y) + (if (= y 0) + x + (greatest-common-divisor y (mod x y)) ) ) diff --git a/Task/Greatest-element-of-a-list/Aime/greatest-element-of-a-list-1.aime b/Task/Greatest-element-of-a-list/Aime/greatest-element-of-a-list-1.aime new file mode 100644 index 0000000000..ba2cb69b40 --- /dev/null +++ b/Task/Greatest-element-of-a-list/Aime/greatest-element-of-a-list-1.aime @@ -0,0 +1,15 @@ +integer +lmax(list l) +{ + integer max, x; + + max = l[0]; + + for (, x in l) { + if (max < x) { + max = x; + } + } + + max; +} diff --git a/Task/Greatest-element-of-a-list/Aime/greatest-element-of-a-list-2.aime b/Task/Greatest-element-of-a-list/Aime/greatest-element-of-a-list-2.aime new file mode 100644 index 0000000000..4f3e9322dc --- /dev/null +++ b/Task/Greatest-element-of-a-list/Aime/greatest-element-of-a-list-2.aime @@ -0,0 +1,10 @@ +integer +lmax(list l) +{ + integer max; + + max = l[0]; + l.ucall(max_i, 1, max); + + max; +} diff --git a/Task/Greatest-element-of-a-list/Aime/greatest-element-of-a-list.aime b/Task/Greatest-element-of-a-list/Aime/greatest-element-of-a-list.aime deleted file mode 100644 index 29d9a7af9f..0000000000 --- a/Task/Greatest-element-of-a-list/Aime/greatest-element-of-a-list.aime +++ /dev/null @@ -1,19 +0,0 @@ -integer -lmax(list l) -{ - integer i, max, x; - - max = l[0]; - - i = 1; - while (i < l_length(l)) { - x = l[i]; - if (max < x) { - max = x; - } - - i += 1; - } - - return max; -} diff --git a/Task/Greatest-element-of-a-list/AppleScript/greatest-element-of-a-list-2.applescript b/Task/Greatest-element-of-a-list/AppleScript/greatest-element-of-a-list-2.applescript index 4e845788ff..14b324466c 100644 --- a/Task/Greatest-element-of-a-list/AppleScript/greatest-element-of-a-list-2.applescript +++ b/Task/Greatest-element-of-a-list/AppleScript/greatest-element-of-a-list-2.applescript @@ -1,9 +1,9 @@ --- maximumBy :: (a -> a -> Ordering) -> [a] -> a -on maximumBy(f, xs) +-- maximumByMay :: (a -> a -> Ordering) -> [a] -> Maybe a +on maximumByMay(f, xs) set cmp to mReturn(f) script max on |λ|(a, b) - if a is missing value or cmp's |λ|(a, b) < 0 then + if cmp's |λ|(a, b) < 0 then b else a @@ -11,8 +11,8 @@ on maximumBy(f, xs) end |λ| end script - foldl(max, missing value, xs) -end maximumBy + foldl1May(max, xs) +end maximumByMay -- TEST ----------------------------------------------------------------------- on run @@ -34,16 +34,33 @@ on run end |λ| end script - return {¬ - maximumBy(comparing(|length|), lstWords), ¬ - maximumBy(comparing(population), lstCities)} + + return catMaybes({¬ + maximumByMay(comparing(|length|), lstWords), ¬ + maximumByMay(comparing(|length|), {}), ¬ + maximumByMay(comparing(population), lstCities)}) --> {"epsilon", {name:"Shanghai", population:24.15}} + end run -- GENERIC FUNCTIONS ---------------------------------------------------------- +-- catMaybes :: [Maybe a] -> [a] +on catMaybes(mbs) + script emptyOrListed + on |λ|(m) + if nothing of m then + {} + else + {just of m} + end if + end |λ| + end script + concatMap(emptyOrListed, mbs) +end catMaybes + -- comparing :: (a -> b) -> (a -> a -> Ordering) on comparing(f) set mf to mReturn(f) @@ -64,23 +81,62 @@ on comparing(f) end script end comparing --- foldl :: (a -> b -> a) -> a -> [b] -> a -on foldl(f, startValue, xs) +-- concatMap :: (a -> [b]) -> [a] -> [b] +on concatMap(f, xs) + set acc to {} tell mReturn(f) - set v to startValue - set lng to length of xs - repeat with i from 1 to lng - set v to |λ|(v, item i of xs, i, xs) + repeat with x in xs + set acc to acc & |λ|(contents of x) end repeat - return v end tell -end foldl + return acc +end concatMap + +-- foldl1May :: (a -> a -> a) -> [a] -> Maybe a +on foldl1May(f, xs) + set lng to length of xs + if lng > 0 then + if lng > 1 then + tell mReturn(f) + set v to item 1 of xs + set lng to length of xs + repeat with i from 2 to lng + set v to |λ|(v, item i of xs, i, xs) + end repeat + return just(v) + end tell + else + just(item 1 of xs) + end if + else + nothing("Empty list") + end if +end foldl1May + +-- just :: a -> Just a +on just(x) + {nothing:false, just:x} +end just -- length :: [a] -> Int on |length|(xs) length of xs end |length| +-- max :: Ord a => a -> a -> a +on max(x, y) + if x > y then + x + else + y + end if +end max + +-- nothing :: () -> Nothing +on nothing(msg) + {nothing:true, msg:msg} +end nothing + -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) diff --git a/Task/Greatest-element-of-a-list/Befunge/greatest-element-of-a-list.bf b/Task/Greatest-element-of-a-list/Befunge/greatest-element-of-a-list.bf index 2d86c135ae..cc233cbe8f 100644 --- a/Task/Greatest-element-of-a-list/Befunge/greatest-element-of-a-list.bf +++ b/Task/Greatest-element-of-a-list/Befunge/greatest-element-of-a-list.bf @@ -1,3 +1,3 @@ -v$9 < ->~:20g`#v_1+#^_20g,@ -^p02 < +001pv < + >&:01g`#v_1+#^_01g.@ + ^p10 < diff --git a/Task/Greatest-element-of-a-list/Dart/greatest-element-of-a-list.dart b/Task/Greatest-element-of-a-list/Dart/greatest-element-of-a-list.dart index 433b000642..ae465afe20 100644 --- a/Task/Greatest-element-of-a-list/Dart/greatest-element-of-a-list.dart +++ b/Task/Greatest-element-of-a-list/Dart/greatest-element-of-a-list.dart @@ -8,3 +8,8 @@ num findGreatestElement(List list){ } return greatestElement; } +/* and this is a shorter version */ +import 'dart:math'; +num findGreatestElement(List list){ + return list.reduce(max); +} diff --git a/Task/Greatest-element-of-a-list/Emacs-Lisp/greatest-element-of-a-list-3.l b/Task/Greatest-element-of-a-list/Emacs-Lisp/greatest-element-of-a-list-3.l new file mode 100644 index 0000000000..2f05dd07c2 --- /dev/null +++ b/Task/Greatest-element-of-a-list/Emacs-Lisp/greatest-element-of-a-list-3.l @@ -0,0 +1 @@ +(cl-loop for el in '(2 7 5) maximize el) diff --git a/Task/Greatest-element-of-a-list/Futhark/greatest-element-of-a-list.futhark b/Task/Greatest-element-of-a-list/Futhark/greatest-element-of-a-list.futhark new file mode 100644 index 0000000000..9453a15f35 --- /dev/null +++ b/Task/Greatest-element-of-a-list/Futhark/greatest-element-of-a-list.futhark @@ -0,0 +1 @@ +let main (xs: []f64) = reduce f64.max (-f64.inf) xs diff --git a/Task/Greatest-element-of-a-list/JavaScript/greatest-element-of-a-list-5.js b/Task/Greatest-element-of-a-list/JavaScript/greatest-element-of-a-list-5.js index 1853dc5313..bdb7b54254 100644 --- a/Task/Greatest-element-of-a-list/JavaScript/greatest-element-of-a-list-5.js +++ b/Task/Greatest-element-of-a-list/JavaScript/greatest-element-of-a-list-5.js @@ -3,11 +3,19 @@ // MAXIMUM BY ... -------------------------------------------------------- - // maximumBy :: (a -> a -> Ordering) -> [a] -> a - const maximumBy = (f, xs) => - xs.reduce((a, x) => a === undefined ? x : ( - f(x, a) > 0 ? x : a - ), undefined); + // Ordering: (LT|EQ|GT): + // GT: 1 (or other positive n) + // EQ: 0 + // LT: -1 (or other negative n) + // maximumByMay :: (a -> a -> Ordering) -> [a] -> Maybe a + const maximumByMay = (f, xs) => + xs.length > 0 ? ( + just(xs.slice(1) + .reduce((a, x) => f(x, a) > 0 ? x : a, xs[0])) + ) : nothing('Empty list'); + + + // GENERIC FUNCTIONS ----------------------------------------------------- // comparing :: (a -> b) -> (a -> a -> Ordering) const comparing = f => @@ -18,6 +26,32 @@ return a < b ? -1 : a > b ? 1 : 0 }; + // catMaybes :: [Maybe a] -> [a] + const catMaybes = mbs => + concatMap(m => m.nothing ? [] : [m.just], mbs); + + // concatMap :: (a -> [b]) -> [a] -> [b] + const concatMap = (f, xs) => + xs.length > 0 ? [].concat.apply([], xs.map(f)) : []; + + // just :: a -> Just a + const just = x => ({ + nothing: false, + just: x + }); + + // nothing :: () -> Nothing + const nothing = (optionalMsg) => ({ + nothing: true, + msg: optionalMsg + }); + + // show :: Int -> a -> Indented String + // show :: a -> String + const show = (...x) => + JSON.stringify.apply( + null, x.length > 1 ? [x[1], null, x[0]] : x + ); // TEST ------------------------------------------------------------------ const words = ["alpha", "beta", "gamma", "delta", "epsilon", "zeta", "eta"]; @@ -36,6 +70,9 @@ }, { k: 'Shanghai', n: 24.3 + }, { + k: 'Tokyo', + n: 13.2 }]; // length :: [a] -> Int @@ -44,12 +81,14 @@ // population :: {k: String, n: Float} const population = dct => dct.n; - // show :: a -> String - const show = x => JSON.stringify(x, null, 2); - // OUTPUT ---------------------------------------------------------------- - return show({ - byWordLength: maximumBy(comparing(length), words), - byCityPopulation: maximumBy(comparing(population), cities) - }); + const maxima = ([ + maximumByMay(comparing(length), words), + maximumByMay(comparing(length), []), + maximumByMay(comparing(population), cities) + ]); + + return show(2, + catMaybes(maxima) + ); })(); diff --git a/Task/Greatest-element-of-a-list/NewLISP/greatest-element-of-a-list.newlisp b/Task/Greatest-element-of-a-list/NewLISP/greatest-element-of-a-list-1.newlisp similarity index 100% rename from Task/Greatest-element-of-a-list/NewLISP/greatest-element-of-a-list.newlisp rename to Task/Greatest-element-of-a-list/NewLISP/greatest-element-of-a-list-1.newlisp diff --git a/Task/Greatest-element-of-a-list/NewLISP/greatest-element-of-a-list-2.newlisp b/Task/Greatest-element-of-a-list/NewLISP/greatest-element-of-a-list-2.newlisp new file mode 100644 index 0000000000..6663fea7ee --- /dev/null +++ b/Task/Greatest-element-of-a-list/NewLISP/greatest-element-of-a-list-2.newlisp @@ -0,0 +1,2 @@ +(apply max '(1 2 3 5 2 3 4)) ; apply to list +; Added by Nehal-Singhal 2018-05-29 diff --git a/Task/Greatest-element-of-a-list/Red/greatest-element-of-a-list.red b/Task/Greatest-element-of-a-list/Red/greatest-element-of-a-list.red new file mode 100644 index 0000000000..e5b0332e88 --- /dev/null +++ b/Task/Greatest-element-of-a-list/Red/greatest-element-of-a-list.red @@ -0,0 +1,3 @@ +Red [] +list: [1 2 3 5 4] +print last sort list diff --git a/Task/Greatest-element-of-a-list/Stata/greatest-element-of-a-list-1.stata b/Task/Greatest-element-of-a-list/Stata/greatest-element-of-a-list-1.stata new file mode 100644 index 0000000000..f0ac5880f4 --- /dev/null +++ b/Task/Greatest-element-of-a-list/Stata/greatest-element-of-a-list-1.stata @@ -0,0 +1,2 @@ +qui sum x +di r(max) diff --git a/Task/Greatest-element-of-a-list/Stata/greatest-element-of-a-list-2.stata b/Task/Greatest-element-of-a-list/Stata/greatest-element-of-a-list-2.stata new file mode 100644 index 0000000000..1cb24a4d66 --- /dev/null +++ b/Task/Greatest-element-of-a-list/Stata/greatest-element-of-a-list-2.stata @@ -0,0 +1,2 @@ +a = 1,5,3,4,2,7,9,8 +max(a) diff --git a/Task/Greatest-subsequential-sum/Julia/greatest-subsequential-sum.julia b/Task/Greatest-subsequential-sum/Julia/greatest-subsequential-sum.julia index ce97aac472..54be7166f1 100644 --- a/Task/Greatest-subsequential-sum/Julia/greatest-subsequential-sum.julia +++ b/Task/Greatest-subsequential-sum/Julia/greatest-subsequential-sum.julia @@ -1,14 +1,17 @@ -const A = [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1] -maxval = 0 -maxseq = Int[] - -for head=1:length(A), tail=head:length(A) - val = sum(A[head:tail]) - if val > maxval - maxval = val - maxseq = A[head:tail] +function gss(arr::Vector{<:Number}) + smax = hmax = tmax = 0 + for head in eachindex(arr), tail in head:length(arr) + s = sum(arr[head:tail]) + if s > smax + smax = s + hmax, tmax = head, tail + end end + return arr[hmax:tmax] end -println(maxseq) -println(maxval) +arr = [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1] +subseq = gss(arr) +s = sum(subseq) + +println("Greatest subsequential sum of $arr:\n → $subseq with sum $s") diff --git a/Task/Greatest-subsequential-sum/Ring/greatest-subsequential-sum.ring b/Task/Greatest-subsequential-sum/Ring/greatest-subsequential-sum.ring new file mode 100644 index 0000000000..d3395678b3 --- /dev/null +++ b/Task/Greatest-subsequential-sum/Ring/greatest-subsequential-sum.ring @@ -0,0 +1,51 @@ +# Project : Greatest subsequential sum +# Date : 2017/09/26 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +aList1 = [0, 1, 2, -3, 3, -1, 0, -4, 0, -1, -4, 2] +see "[0, 1, 2, -3, 3, -1, 0, -4, 0, -1, -4, 2] -> " + sum(aList1) + nl +aList2 = [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1] +see "[-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1] -> " + sum(aList2) + nl +aList3 = [-1, -2, -3, -4, -5] +see "[-1, -2, -3, -4, -5] -> " + sum(aList3) + nl +aList4 = [] +see "[] - > " + sum(aList4) + nl + +func sum aList + sumold = [] + sumnew = [] + snew = 0 + flag = 0 + if len(aList) = 0 + return 0 + ok + for s=1 to len(aList) + if aList[s] > -1 + flag = 1 + ok + next + if flag = 0 + return "[]" + ok + for n=1 to len(aList) + sumold = [] + sold = 0 + for m=n to len(aList) + add(sumold, aList[m]) + sold = sold + aList[m] + if sold > snew + snew = sold + sumnew = sumold + ok + next + next + return showarray(sumnew) + +func showarray(a) + conv = "[" + for i = 1 to len(a) + conv = conv + string(a[i]) + ", " + next + conv = left(conv, len(conv) - 2) + "]" + return conv diff --git a/Task/Greyscale-bars-Display/Perl-6/greyscale-bars-display.pl6 b/Task/Greyscale-bars-Display/Perl-6/greyscale-bars-display.pl6 index 7cbcf11161..11a35ea7e7 100644 --- a/Task/Greyscale-bars-Display/Perl-6/greyscale-bars-display.pl6 +++ b/Task/Greyscale-bars-Display/Perl-6/greyscale-bars-display.pl6 @@ -2,11 +2,11 @@ my $wininfo = qx[xwininfo -root]; my ($width,$height) = ($wininfo ~~ /'Width: ' (\d+) .*? 'Height: ' (\d+)/).list; ($width,$height) = 1280,768 unless $width; -my $PGM = open "greybars.pgm", :w or die "Can't create greybars.pgm: $!"; +my $PGM = open "Greyscale-bars-perl6.pgm", :w or die "Can't create Greyscale-bars-perl6.pgm: $!"; $PGM.print: qq:to/EOH/; P2 - # greybars.pgm + # Greyscale-bars-perl6.pgm $width $height 65535 EOH @@ -31,8 +31,6 @@ $PGM.say: $line for ^$h4; $PGM.close; -shell "eog -f greybars.pgm"; - sub divvy($all, $div) { my @marks = ((1/$div,2/$div ... 1) X* $all)».round; @marks Z- 0,|@marks; diff --git a/Task/Greyscale-bars-Display/Ring/greyscale-bars-display.ring b/Task/Greyscale-bars-Display/Ring/greyscale-bars-display.ring new file mode 100644 index 0000000000..425bd2b9a7 --- /dev/null +++ b/Task/Greyscale-bars-Display/Ring/greyscale-bars-display.ring @@ -0,0 +1,61 @@ +# Project : Greyscale bars/Display +# Date : 2018/01/09 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +load "guilib.ring" + +paint = null + +new qapp + { + win1 = new qwidget() { + setwindowtitle("Greyscale bars/Display") + setgeometry(100,100,500,600) + label1 = new qlabel(win1) { + setgeometry(10,10,400,400) + settext("") + } + new qpushbutton(win1) { + setgeometry(150,500,100,30) + settext("draw") + setclickevent("draw()") + } + show() + } + exec() + } + +func draw + p1 = new qpicture() + color = new qcolor() { + setrgb(0,0,255,255) + } + pen = new qpen() { + setcolor(color) + setwidth(1) + } + paint = new qpainter() { + begin(p1) + setpen(pen) + + for row=1 to 4 + n=pow(2,(row+2)) + w=1280/n + py=256*(4-row) + for b=0 to n-1 + g=floor(255*b/(n-1)) + if n=16 or n=64 + g=255-g + ok + color2 = new qcolor() + color2.setrgb(g,g,g,255) + mybrush = new qbrush() {setstyle(1) setcolor(color2)} + paint.setbrush(mybrush) + paint.drawrect(w*b,py,w,256) + next + next + + endpaint() + } + label1 { setpicture(p1) show() } diff --git a/Task/Guess-the-number-With-feedback--player-/00DESCRIPTION b/Task/Guess-the-number-With-feedback--player-/00DESCRIPTION index ef99f7f245..fd9e6364c2 100644 --- a/Task/Guess-the-number-With-feedback--player-/00DESCRIPTION +++ b/Task/Guess-the-number-With-feedback--player-/00DESCRIPTION @@ -7,5 +7,5 @@ The computer should guess intelligently based on the accumulated scores given. O ;Related tasks: *   [[Guess the number/With Feedback]] -* *nbsp; [[Bulls and cows/Player]] +*   [[Bulls and cows/Player]]

diff --git a/Task/Guess-the-number-With-feedback/Elena/guess-the-number-with-feedback.elena b/Task/Guess-the-number-With-feedback/Elena/guess-the-number-with-feedback.elena new file mode 100644 index 0000000000..6d95107d4c --- /dev/null +++ b/Task/Guess-the-number-With-feedback/Elena/guess-the-number-with-feedback.elena @@ -0,0 +1,25 @@ +import extensions. + +program = +[ + int randomNumber := randomGenerator eval(1,10). + console printLine("I'm thinking of a number between 1 and 10. Can you guess it?"). + bool numberCorrect := false. + until(numberCorrect) + [ + console print("Guess: "). + int userGuess := console readLine; toInt. + if (randomNumber == userGuess) + [ + numberCorrect := true. + console printLine("Congrats!! You guessed right!") + ]; + if (randomNumber < userGuess) + [ + console printLine("Your guess was too high"). + ]; + [ + console printLine("Your guess was too low"). + ] + ]. +]. diff --git a/Task/Guess-the-number-With-feedback/HolyC/guess-the-number-with-feedback.holyc b/Task/Guess-the-number-With-feedback/HolyC/guess-the-number-with-feedback.holyc new file mode 100644 index 0000000000..b60fd98e33 --- /dev/null +++ b/Task/Guess-the-number-With-feedback/HolyC/guess-the-number-with-feedback.holyc @@ -0,0 +1,20 @@ +U8 n, *g; +U8 min = 1, max = 100; + +n = min + RandU16 % max; + +Print("Guess the number between %d and %d: ", min, max); + +while(1) { + g = GetStr; + + if (Str2I64(g) == n) { + Print("You guessed correctly!\n"); + break; + } + + if (Str2I64(g) < n) + Print("Your guess was too low.\nTry again: "); + if (Str2I64(g) > n) + Print("Your guess was too high.\nTry again: "); +} diff --git a/Task/Guess-the-number-With-feedback/Julia/guess-the-number-with-feedback.julia b/Task/Guess-the-number-With-feedback/Julia/guess-the-number-with-feedback.julia index 72c8743104..d3780dc32e 100644 --- a/Task/Guess-the-number-With-feedback/Julia/guess-the-number-with-feedback.julia +++ b/Task/Guess-the-number-With-feedback/Julia/guess-the-number-with-feedback.julia @@ -1,11 +1,15 @@ -function guess_feedback(n) - number = rand(1:n) - print("I choose a number between 1 and $n\nYour guess? ") - while((guess = readline(STDIN)) != string(number)) - isdigit(guess) ? - print("Too $(parse(Int,guess) < number ? "small" : "big")") : - print("Enter an integer please") - print("\nNew guess? ") - end - print("you guessed right!") +function guesswithfeedback(n::Integer) + number = rand(1:n) + print("I choose a number between 1 and $n\nYour guess? ") + while (guess = readline()) != dec(number) + if all(isdigit, guess) + print("Too ", parse(Int, guess) < number ? "small" : "big") + else + print("Enter an integer please") + end + print(", new guess? ") + end + println("You guessed right!") end + +guesswithfeedback(10) diff --git a/Task/Guess-the-number-With-feedback/Scala/guess-the-number-with-feedback.scala b/Task/Guess-the-number-With-feedback/Scala/guess-the-number-with-feedback.scala new file mode 100644 index 0000000000..52f8e28259 --- /dev/null +++ b/Task/Guess-the-number-With-feedback/Scala/guess-the-number-with-feedback.scala @@ -0,0 +1,17 @@ +import java.util.Random +import java.util.Scanner + +val scan = new Scanner(System.in) +val random = new Random +val (from , to) = (1, 100) +val randomNumber = random.nextInt(to - from + 1) + from +var guessedNumber = 0 +printf("The number is between %d and %d.\n", from, to) + +do { + print("Guess what the number is: ") + guessedNumber = scan.nextInt + if (guessedNumber > randomNumber) println("Your guess is too high!") + else if (guessedNumber < randomNumber) println("Your guess is too low!") + else println("You got it!") +} while (guessedNumber != randomNumber) diff --git a/Task/Guess-the-number-With-feedback/VBScript/guess-the-number-with-feedback.vb b/Task/Guess-the-number-With-feedback/VBScript/guess-the-number-with-feedback.vb new file mode 100644 index 0000000000..8a7bba10cc --- /dev/null +++ b/Task/Guess-the-number-With-feedback/VBScript/guess-the-number-with-feedback.vb @@ -0,0 +1,26 @@ +Dim max,min,secretnum,numtries,usernum +max=100 +min=1 +numtries=0 +Randomize +secretnum = Int((max-min+1)*Rnd+min) + +Do While usernum <> secretnum + usernum = Inputbox("Guess the secret number beween 1-100","Guessing Game") + If IsEmpty(usernum) Then + WScript.Quit + End If + If IsNumeric(usernum) Then + numtries = numtries + 1 + usernum = Cint(usernum) + If usernum < secretnum Then + Msgbox("The secret number is higher than " + CStr(usernum)) + ElseIf usernum > secretnum Then + Msgbox("The secret number is lower than " + CStr(usernum)) + Else + Msgbox("Congratulations, you found the secret number in " + CStr(numtries) + " guesses!") + End If + Else + Msgbox("Please enter a valid number.") + End If +Loop diff --git a/Task/Guess-the-number/Aime/guess-the-number.aime b/Task/Guess-the-number/Aime/guess-the-number.aime index 019fbe72ce..061c130d45 100644 --- a/Task/Guess-the-number/Aime/guess-the-number.aime +++ b/Task/Guess-the-number/Aime/guess-the-number.aime @@ -2,7 +2,7 @@ file f; integer n; text s; -f_affix(f, "/dev/stdin"); +f.stdin; n = irand(1, 10); o_text("I'm thinking of a number between 1 and 10.\n"); diff --git a/Task/Guess-the-number/Batch-File/guess-the-number.bat b/Task/Guess-the-number/Batch-File/guess-the-number.bat index f20ee0e6f8..a1b4e8f168 100644 --- a/Task/Guess-the-number/Batch-File/guess-the-number.bat +++ b/Task/Guess-the-number/Batch-File/guess-the-number.bat @@ -1,18 +1,7 @@ @echo off -setlocal EnableDelayedExpansion -:begin - SET /A rand=%random% %% (10 - 1 + 1)+ 1 - SET guess= - SET /P guess=Pick a number between 1 and 10: +set /a answer=%random%%%(10-1+1)+1 +set /p guess=Pick a number between 1 and 10: :loop - IF "!guess!" == "" ( - EXIT - ) - SET /A guess=!guess! - IF !guess! equ !rand! ( - ECHO Well guessed^^! - EXIT - ) - SET guess= - SET /P guess=Nope, guess again: - GOTO loop +if %guess%==%answer% (echo Well guessed! +pause) else (set /p guess=Nope, guess again: +goto loop) diff --git a/Task/Guess-the-number/Elena/guess-the-number.elena b/Task/Guess-the-number/Elena/guess-the-number.elena new file mode 100644 index 0000000000..a5d57861a6 --- /dev/null +++ b/Task/Guess-the-number/Elena/guess-the-number.elena @@ -0,0 +1,21 @@ +import extensions. + +program = +[ + int randomNumber := randomGenerator eval(1,10). + console printLine("I'm thinking of a number between 1 and 10. Can you guess it?"). + bool numberCorrect := false. + until(numberCorrect) + [ + console print("Guess: "). + int userGuess := console readLine; toInt. + if (randomNumber == userGuess) + [ + numberCorrect := true. + console printLine("Congrats!! You guessed right!") + ]; + [ + console printLine("That's not it. Guess again."). + ] + ]. +]. diff --git a/Task/Guess-the-number/HolyC/guess-the-number.holyc b/Task/Guess-the-number/HolyC/guess-the-number.holyc new file mode 100644 index 0000000000..6030c63658 --- /dev/null +++ b/Task/Guess-the-number/HolyC/guess-the-number.holyc @@ -0,0 +1,17 @@ +U8 n, *g; + +n = 1 + RandU16 % 10; + +Print("I'm thinking of a number between 1 and 10.\n"); +Print("Try to guess it:\n"); + +while(1) { + g = GetStr; + + if (Str2I64(g) == n) { + Print("Correct!\n"); + break; + } + + Print("That's not my number. Try another guess:\n"); +} diff --git a/Task/Guess-the-number/Julia/guess-the-number.julia b/Task/Guess-the-number/Julia/guess-the-number.julia index 8206a296ac..7846e4f627 100644 --- a/Task/Guess-the-number/Julia/guess-the-number.julia +++ b/Task/Guess-the-number/Julia/guess-the-number.julia @@ -1,8 +1,10 @@ function guess() - number = rand(1:10) - print("Guess my number! ") - while(readline(STDIN) != string(number)) - print("Nope, try again! ") - end - println("Well guessed!") + number = dec(rand(1:10)) + print("Guess my number! ") + while readline() != number + print("Nope, try again... ") + end + println("Well guessed!") end + +guess() diff --git a/Task/Guess-the-number/Python/guess-the-number.py b/Task/Guess-the-number/Python/guess-the-number.py index b785c41d0e..543f8654dd 100644 --- a/Task/Guess-the-number/Python/guess-the-number.py +++ b/Task/Guess-the-number/Python/guess-the-number.py @@ -1,6 +1,5 @@ import random -target, guess = random.randint(1, 10), 0 -guess = int(input("Guess a number that's between 1 and 10: ")) -while target != guess: - guess = int(input("Guess again! ")) +t,g=random.randint(1,10),0 +g=int(input("Guess a number that's between 1 and 10: ")) +while t!=g:g=int(input("Guess again! ")) print("That's right!") diff --git a/Task/Guess-the-number/Ring/guess-the-number.ring b/Task/Guess-the-number/Ring/guess-the-number.ring index 755c0d5cd1..d3ddc9817c 100644 --- a/Task/Guess-the-number/Ring/guess-the-number.ring +++ b/Task/Guess-the-number/Ring/guess-the-number.ring @@ -1,17 +1,23 @@ -while true -see "Hey There, -======================== -I'm thinking of a number between 0 and 10, Can you guess it?? -Guess :> " -give x -n = random(10) -if x = n see " -********************************************** - ** Thats right You Are Genius :D ** -********************************************** -" -exit -else -see "Oops its not true, Try again please :)" + copy(nl,3) -ok +### Bert Mariani +### 2018-03-01 +### Guess_My_Number + +myNumber = random(10) +answer = 0 + +See "Guess my number between 1 and 10"+ nl + +while answer != myNumber + See "Your guess: " + Give answer + + if answer = myNumber + See "Well done! You guessed it! "+ myNumber +nl + else + See "Try again"+ nl + ok + + if answer = 0 + See "Give up. My number is: "+ myNumber +nl + ok end diff --git a/Task/Guess-the-number/VBA/guess-the-number.vba b/Task/Guess-the-number/VBA/guess-the-number.vba new file mode 100644 index 0000000000..5493ea5601 --- /dev/null +++ b/Task/Guess-the-number/VBA/guess-the-number.vba @@ -0,0 +1,9 @@ +Sub GuessTheNumber() +Dim NbComputer As Integer, NbPlayer As Integer + Randomize Timer + NbComputer = Int((Rnd * 10) + 1) + Do + NbPlayer = Application.InputBox("Choose a number between 1 and 10 : ", "Enter your guess", Type:=1) + Loop While NbComputer <> NbPlayer + MsgBox "Well guessed!" +End Sub diff --git a/Task/HTTP/Haskell/http-1.hs b/Task/HTTP/Haskell/http-1.hs index 5feca277fd..dbb5c76642 100644 --- a/Task/HTTP/Haskell/http-1.hs +++ b/Task/HTTP/Haskell/http-1.hs @@ -2,10 +2,9 @@ import Network.Browser import Network.HTTP import Network.URI -httpreq = do - rsp <- Network.Browser.browse $ do - setAllowRedirects True - setOutHandler $ const (return ()) - request $ getRequest "http://www.rosettacode.org/" - - putStrLn $ rspBody $ snd rsp +main = do + rsp <- Network.Browser.browse $ do + setAllowRedirects True + setOutHandler $ const (return ()) + request $ getRequest "http://www.rosettacode.org/" + putStrLn $ rspBody $ snd rsp diff --git a/Task/HTTP/JavaScript/http-2.js b/Task/HTTP/JavaScript/http-2.js index 1dc4829fb1..f9e59fcce1 100644 --- a/Task/HTTP/JavaScript/http-2.js +++ b/Task/HTTP/JavaScript/http-2.js @@ -1,3 +1,5 @@ -$.get('http://rosettacode.org', function(data) { - console.log(data); -}; +fetch('http://rosettacode.org').then(function(response) { + return response.text(); +}).then(function(myText) { + console.log(myText); +}); diff --git a/Task/HTTP/JavaScript/http-3.js b/Task/HTTP/JavaScript/http-3.js new file mode 100644 index 0000000000..c6af7e95d1 --- /dev/null +++ b/Task/HTTP/JavaScript/http-3.js @@ -0,0 +1,65 @@ +/** + * @name _http + * @description Generic API Client using XMLHttpRequest + * @param {string} url The URI/URL to connect to + * @param {string} method The HTTP method to invoke- GET, POST, etc + * @param {function} callback Once the HTTP request has completed, responseText is passed into this function for execution + * @param {object} params Query Parameters in a JavaScript Object (Optional) + * + */ +function _http(url, method, callback, params) { + var xhr, + reqUrl; + + xhr = new XMLHttpRequest(); + xhr.onreadystatechange = function xhrProc() { + if (xhr.readyState == 4 && xhr.status == 200) { + callback(xhr.responseText); + } + }; + + + /** If Query Parameters are present, handle them... */ + if (typeof params === 'undefined') { + reqUrl = url; + } else { + switch (method) { + case 'GET': + reqUrl = url + procQueryParams(params); + break; + case 'POST': + reqUrl = url; + break; + default: + } + } + + + /** Send the HTTP Request */ + if (reqUrl) { + xhr.open(method, reqUrl, true); + xhr.setRequestHeader("Accept", "application/json"); + + if (method === 'POST') { + xhr.send(params); + } else { + xhr.send(); + } + } + + + /** + * @name procQueryParams + * @description Return function that converts Query Parameters from a JavaScript Object to a proper URL encoded string + * @param {object} params Query Parameters in a JavaScript Object + * + */ + function procQueryParams(params) { + return "?" + Object + .keys(params) + .map(function (key) { + return key + "=" + encodeURIComponent(params[key]) + }) + .join("&") + } +} diff --git a/Task/HTTP/JavaScript/http-4.js b/Task/HTTP/JavaScript/http-4.js new file mode 100644 index 0000000000..1dc4829fb1 --- /dev/null +++ b/Task/HTTP/JavaScript/http-4.js @@ -0,0 +1,3 @@ +$.get('http://rosettacode.org', function(data) { + console.log(data); +}; diff --git a/Task/HTTP/JavaScript/http-5.js b/Task/HTTP/JavaScript/http-5.js new file mode 100644 index 0000000000..b200a700c9 --- /dev/null +++ b/Task/HTTP/JavaScript/http-5.js @@ -0,0 +1,19 @@ +const http = require('http'); + +http.get('http://rosettacode.org', (resp) => { + + let data = ''; + + // A chunk of data has been recieved. + resp.on('data', (chunk) => { + data += chunk; + }); + + // The whole response has been received. Print out the result. + resp.on('end', () => { + console.log("Data:", data); + }); + +}).on("error", (err) => { + console.log("Error: " + err.message); +}); diff --git a/Task/HTTP/Nim/http.nim b/Task/HTTP/Nim/http.nim index 0e4fa4ce54..f730285218 100644 --- a/Task/HTTP/Nim/http.nim +++ b/Task/HTTP/Nim/http.nim @@ -1,3 +1,4 @@ import httpclient -echo getContent "http://rosettacode.org" +var client = newHttpClient() +echo client.getContent "http://rosettacode.org" diff --git a/Task/HTTP/Pascal/http-1.pascal b/Task/HTTP/Pascal/http-1.pascal new file mode 100644 index 0000000000..1869481201 --- /dev/null +++ b/Task/HTTP/Pascal/http-1.pascal @@ -0,0 +1,16 @@ +{$mode objfpc}{$H+} +uses fphttpclient; + +var + s: string; + hc: tfphttpclient; + +begin + hc := tfphttpclient.create(nil); + try + s := hc.get('http://www.example.com') + finally + hc.free + end; + writeln(s) +end. diff --git a/Task/HTTP/Pascal/http.pascal b/Task/HTTP/Pascal/http-2.pascal similarity index 100% rename from Task/HTTP/Pascal/http.pascal rename to Task/HTTP/Pascal/http-2.pascal diff --git a/Task/HTTPS-Authenticated/Haskell/https-authenticated.hs b/Task/HTTPS-Authenticated/Haskell/https-authenticated.hs new file mode 100644 index 0000000000..808ed03bec --- /dev/null +++ b/Task/HTTPS-Authenticated/Haskell/https-authenticated.hs @@ -0,0 +1,27 @@ +{-# LANGUAGE OverloadedStrings #-} + +module Main (main) where + +import Data.Aeson (Value) +import Data.Default.Class (def) +import Network.HTTP.Req + ( (/:) + , GET(..) + , NoReqBody(..) + , basicAuth + , https + , jsonResponse + , req + , responseBody + , runReq + ) + +main :: IO () +main = do + response <- runReq def $ req + GET + (https "httpbin.org" /: "basic-auth" /: "someuser" /: "somepassword") + NoReqBody + jsonResponse + (basicAuth "someuser" "somepassword") + print (responseBody response :: Value) diff --git a/Task/HTTPS-Authenticated/Kotlin/https-authenticated.kotlin b/Task/HTTPS-Authenticated/Kotlin/https-authenticated.kotlin new file mode 100644 index 0000000000..c64791e85a --- /dev/null +++ b/Task/HTTPS-Authenticated/Kotlin/https-authenticated.kotlin @@ -0,0 +1,28 @@ +// version 1.2.0 + +import java.net.Authenticator +import java.net.PasswordAuthentication +import javax.net.ssl.HttpsURLConnection +import java.net.URL +import java.io.InputStreamReader +import java.io.BufferedReader + +object PasswordAuthenticator : Authenticator() { + override fun getPasswordAuthentication() = + PasswordAuthentication ("username", "password".toCharArray()) +} + +fun main(args: Array) { + val url = URL("https://somehost.com") + val con = url.openConnection() as HttpsURLConnection + Authenticator.setDefault(PasswordAuthenticator) + con.allowUserInteraction = true + con.connect() + val isr = InputStreamReader(con.inputStream) + val br = BufferedReader(isr) + while (true) { + val line = br.readLine() + if (line == null) break + println(line) + } +} diff --git a/Task/HTTPS-Authenticated/Perl-6/https-authenticated.pl6 b/Task/HTTPS-Authenticated/Perl-6/https-authenticated.pl6 new file mode 100644 index 0000000000..0b6313e5db --- /dev/null +++ b/Task/HTTPS-Authenticated/Perl-6/https-authenticated.pl6 @@ -0,0 +1,10 @@ +use HTTP::UserAgent; + +my $username = 'username'; # my username +my $password = 'password'; # my password +my $address = 'http://192.168.1.1/Status_Router.asp'; # my local wireless router + +my $ua = HTTP::UserAgent.new; +$ua.auth( $username, $password ); +my $response = $ua.get: $address; +say $response.is-success ?? $response.content !! $response.status-line; diff --git a/Task/HTTPS-Authenticated/Scala/https-authenticated.scala b/Task/HTTPS-Authenticated/Scala/https-authenticated.scala new file mode 100644 index 0000000000..a5403a1ac0 --- /dev/null +++ b/Task/HTTPS-Authenticated/Scala/https-authenticated.scala @@ -0,0 +1,24 @@ +import java.net.{Authenticator, PasswordAuthentication, URL} + +import javax.net.ssl.HttpsURLConnection + +import scala.io.BufferedSource + + +object Authenticated extends App { + + val con: HttpsURLConnection = + new URL("https://somehost.com").openConnection().asInstanceOf[HttpsURLConnection] + + object PasswordAuthenticator extends Authenticator { + override def getPasswordAuthentication = + new PasswordAuthentication("username", "password".toCharArray) + } + + Authenticator.setDefault(PasswordAuthenticator) + con.setAllowUserInteraction(true) + con.connect() + + new BufferedSource(con.getInputStream).getLines.foreach(println(_)) + +} diff --git a/Task/HTTPS-Client-authenticated/Go/https-client-authenticated.go b/Task/HTTPS-Client-authenticated/Go/https-client-authenticated.go new file mode 100644 index 0000000000..7ccaf5a34b --- /dev/null +++ b/Task/HTTPS-Client-authenticated/Go/https-client-authenticated.go @@ -0,0 +1,38 @@ +package main + +import ( + "crypto/tls" + "io/ioutil" + "log" + "net/http" +) + +func main() { + + // load key pair + cert, err := tls.LoadX509KeyPair( + "./client.local.tld/client.local.tld.crt", + "./client.local.tld/client.local.tld.key", + ) + + if err != nil { + log.Fatal("Error while loading x509 key pair", err) + } + + // Create TLS Config in order to had client certificate + tlsConfig := &tls.Config{Certificates: []tls.Certificate{cert}} + + tlsConfig.BuildNameToCertificate() + transport := &http.Transport{TLSClientConfig: tlsConfig} + + // create http client with our custom transport with TLS config + client := &http.Client{Transport: transport} + + res, err := client.Get("https://www.example.com/") + if err != nil { + log.Fatal(err) + } + contents, err := ioutil.ReadAll(res.Body) + log.Print(string(contents)) + +} diff --git a/Task/HTTPS-Client-authenticated/Kotlin/https-client-authenticated.kotlin b/Task/HTTPS-Client-authenticated/Kotlin/https-client-authenticated.kotlin new file mode 100644 index 0000000000..f74a2a9902 --- /dev/null +++ b/Task/HTTPS-Client-authenticated/Kotlin/https-client-authenticated.kotlin @@ -0,0 +1,37 @@ +// version 1.2.0 + +import java.security.KeyStore +import javax.net.ssl.KeyManagerFactory +import javax.net.ssl.SSLContext +import javax.net.ssl.HttpsURLConnection +import java.net.URL +import java.io.FileInputStream +import java.io.InputStreamReader +import java.io.BufferedReader + +fun getSSLContext(p12Path: String, password: String): SSLContext { + val ks = KeyStore.getInstance("pkcs12") + val fis = FileInputStream(p12Path) + val pwd = password.toCharArray() + ks.load(fis, pwd) + val kmf = KeyManagerFactory.getInstance("PKIX") + kmf.init(ks, pwd) + val sc = SSLContext.getInstance("TLS") + sc.init(kmf.keyManagers, null, null) + return sc +} + +fun main(args: Array) { + // The .p12 file contains the client certificate and private key + val sc = getSSLContext("whatever.p12", "password") + val url = URL("https://somehost.com") + val con = url.openConnection() as HttpsURLConnection + con.sslSocketFactory = sc.socketFactory + val isr = InputStreamReader(con.inputStream) + val br = BufferedReader(isr) + while (true) { + val line = br.readLine() + if (line == null) break + println(line) + } +} diff --git a/Task/HTTPS-Client-authenticated/Scala/https-client-authenticated.scala b/Task/HTTPS-Client-authenticated/Scala/https-client-authenticated.scala new file mode 100644 index 0000000000..c03dec67e1 --- /dev/null +++ b/Task/HTTPS-Client-authenticated/Scala/https-client-authenticated.scala @@ -0,0 +1,29 @@ +import java.io.FileInputStream +import java.net.URL +import java.security.KeyStore + +import javax.net.ssl.{HttpsURLConnection, KeyManagerFactory, SSLContext} + +import scala.io.BufferedSource + +object ClientAuthenticated extends App { + + val con: HttpsURLConnection = + new URL("https://somehost.com").openConnection().asInstanceOf[HttpsURLConnection] + + def getSSLContext(p12Path: String, password: String): SSLContext = { + val ks = KeyStore.getInstance("pkcs12") + val pwd = password.toCharArray + ks.load(new FileInputStream(p12Path), pwd) + val kmf = KeyManagerFactory.getInstance("PKIX") + kmf.init(ks, pwd) + val sc = SSLContext.getInstance("TLS") + sc.init(kmf.getKeyManagers, null, null) + sc + } + + // The .p12 file contains the client certificate and private key + HttpsURLConnection.setDefaultSSLSocketFactory(getSSLContext("whatever.p12", "password").getSocketFactory) + new BufferedSource(con.getInputStream).getLines.foreach(println(_)) + +} diff --git a/Task/HTTPS/Haskell/https-1.hs b/Task/HTTPS/Haskell/https-1.hs index 1a08bd8ca2..99bb582060 100644 --- a/Task/HTTPS/Haskell/https-1.hs +++ b/Task/HTTPS/Haskell/https-1.hs @@ -5,4 +5,4 @@ import qualified Data.ByteString.Lazy as L import Network (withSocketsDo) main = withSocketsDo - $ simpleHttp "https://sourceforge.net/" >>= L.putStr + $ simpleHttp "https://sourceforge.net/" >>= L.putStr diff --git a/Task/HTTPS/NewLISP/https.newlisp b/Task/HTTPS/NewLISP/https.newlisp new file mode 100644 index 0000000000..6d4b09ad69 --- /dev/null +++ b/Task/HTTPS/NewLISP/https.newlisp @@ -0,0 +1 @@ +(! "curl https://sourceforge.net") diff --git a/Task/HTTPS/Nim/https.nim b/Task/HTTPS/Nim/https.nim index 703744b70e..b841f152c8 100644 --- a/Task/HTTPS/Nim/https.nim +++ b/Task/HTTPS/Nim/https.nim @@ -1,3 +1,4 @@ import httpclient -echo getContent "https://sourceforge.net" +var client = newHttpClient() +echo client.getContent("https://sourceforge.net") diff --git a/Task/HTTPS/Pascal/https.pascal b/Task/HTTPS/Pascal/https.pascal new file mode 100644 index 0000000000..4695110808 --- /dev/null +++ b/Task/HTTPS/Pascal/https.pascal @@ -0,0 +1,16 @@ +{$mode objfpc}{$H+} +uses fphttpclient; + +var + s: string; + hc: tfphttpclient; + +begin + hc := tfphttpclient.create(nil); + try + s := hc.get('https://www.example.com') + finally + hc.free + end; + writeln(s) +end. diff --git a/Task/HTTPS/Perl-6/https-1.pl6 b/Task/HTTPS/Perl-6/https-1.pl6 new file mode 100644 index 0000000000..f3574851bd --- /dev/null +++ b/Task/HTTPS/Perl-6/https-1.pl6 @@ -0,0 +1,2 @@ +use WWW; +say get 'https://sourceforge.net/'; diff --git a/Task/HTTPS/Perl-6/https-2.pl6 b/Task/HTTPS/Perl-6/https-2.pl6 new file mode 100644 index 0000000000..17f9272b24 --- /dev/null +++ b/Task/HTTPS/Perl-6/https-2.pl6 @@ -0,0 +1,2 @@ +use HTTP::UserAgent; +say HTTP::UserAgent.new.get('https://sourceforge.net/').content; diff --git a/Task/Hailstone-sequence/Aime/hailstone-sequence.aime b/Task/Hailstone-sequence/Aime/hailstone-sequence.aime index 5819a7a6ec..bec404b3fb 100644 --- a/Task/Hailstone-sequence/Aime/hailstone-sequence.aime +++ b/Task/Hailstone-sequence/Aime/hailstone-sequence.aime @@ -5,18 +5,18 @@ print_hailstone(integer h) while (h ^ 1) { lb_p_integer(l, h); - h = __hold(h & 1, 3 * h + 1, h / 2); + h = h & 1 ? 3 * h + 1 : h / 2; } o_form("hailstone sequence for ~ is ~1 ~ ~ ~ .. ~ ~ ~ ~, it is ~ long\n", - l[0], l[1], l[2], l[3], l[-3], l[-2], l[-1], 1, l_length(l) + 1); + l[0], l[1], l[2], l[3], l[-3], l[-2], l[-1], 1, ~l + 1); } void max_hailstone(integer x) { integer e, i, m; - record r; + index r; m = 0; i = 1; @@ -26,16 +26,16 @@ max_hailstone(integer x) h = i; l = 1; while (h ^ 1) { - if (r_j_integer(k, r, itoa(h))) { + if (i_j_integer(k, r, h)) { l += k; break; } else { l += 1; - h = __hold(h & 1, 3 * h + 1, h / 2); + h = h & 1 ? 3 * h + 1 : h / 2; } } - r_f_integer(r, itoa(i), l - 1); + r[i] = l - 1; if (m < l) { m = l; @@ -45,7 +45,7 @@ max_hailstone(integer x) i += 1; } - o_form("hailstone sequence length for ~ is ~ long\n", e, m); + o_form("hailstone sequence length for ~ is ~\n", e, m); } integer diff --git a/Task/Hailstone-sequence/Elena/hailstone-sequence.elena b/Task/Hailstone-sequence/Elena/hailstone-sequence.elena new file mode 100644 index 0000000000..ee1f190ce9 --- /dev/null +++ b/Task/Hailstone-sequence/Elena/hailstone-sequence.elena @@ -0,0 +1,48 @@ +import system'collections. +import extensions. + +int const maxNumber = 100000. + +Hailstone = (:n:lengths) +[ + if (n == 1) + [ + ^ 1 + ]. + + while (true) + [ + if (lengths containsKey(n)) + [ + ^ lengths[n] + ]; + [ + if (n int; isEven) + [ + lengths[n] := 1 + Hailstone(n/2, lengths) + ]; + [ + lengths[n] := 1 + Hailstone((3*n) + 1, lengths) + ] + ] + ] +]. + +program = +[ + int longestChain := 0. + int longestNumber := 0. + var recursiveLengths := Dictionary new. + + 1 till(maxNumber) do(:i) + [ + var chainLength := Hailstone(i, recursiveLengths). + if (longestChain < chainLength) + [ + longestChain := chainLength. + longestNumber := i. + ] + ]. + + console printFormatted("max below {0}: {1} ({2} steps)", maxNumber, longestNumber, longestChain). +]. diff --git a/Task/Hailstone-sequence/Haskell/hailstone-sequence-1.hs b/Task/Hailstone-sequence/Haskell/hailstone-sequence-1.hs index 66db1b763a..82df1a9b43 100644 --- a/Task/Hailstone-sequence/Haskell/hailstone-sequence-1.hs +++ b/Task/Hailstone-sequence/Haskell/hailstone-sequence-1.hs @@ -1,20 +1,21 @@ import Data.List (maximumBy) import Data.Ord (comparing) +collatz :: Int -> Int +collatz n + | even n = n `div` 2 + | otherwise = 3 * n + 1 + hailstone :: Int -> [Int] hailstone = takeWhile (/= 1) . iterate collatz - where - collatz n = - if even n - then n `div` 2 - else 3 * n + 1 longestChain :: Int longestChain = - fst - (maximumBy (comparing snd) (((,) <*> length . hailstone) <$> [1 .. 100000])) + fst $ + maximumBy (comparing snd) $ (,) <*> (length . hailstone) <$> [1 .. 100000] --TEST ------------------------------------------------------------------------- +main :: IO () main = mapM_ putStrLn diff --git a/Task/Hailstone-sequence/JavaScript/hailstone-sequence-9.js b/Task/Hailstone-sequence/JavaScript/hailstone-sequence-9.js index 47afdc8726..884d74f299 100644 --- a/Task/Hailstone-sequence/JavaScript/hailstone-sequence-9.js +++ b/Task/Hailstone-sequence/JavaScript/hailstone-sequence-9.js @@ -1,58 +1,104 @@ (() => { - const dctMemo = {}; - // Length only of hailstone sequence + // hailstones :: Int -> [Int] + const hailstones = x => { + const collatz = memoized(n => + even(n) ? div(n, 2) : (3 * n) + 1); + return reverse(until( + xs => xs[0] === 1, + xs => cons(collatz(xs[0]), xs), [x] + )); + }; + // collatzLength :: Int -> Int - const collatzLength = n => { - let i = 1; - let a = n; - let lng; + const collatzLength = n => + until( + xi => xi[0] === 1, + ([x, i]) => [(x % 2 ? 3 * x + 1 : x / 2), i + 1], // + [n, 1] + )[1]; - while (a !== 1) { - lng = dctMemo[a]; - if ('u' === (typeof lng)[0]) { - a = (a % 2 ? 3 * a + 1 : a / 2); - i++; - } else return lng + i - 1; - } - return i; + // GENERIC FUNCTIONS ----------------------------------------------------- + + // comparing :: (a -> b) -> (a -> a -> Ordering) + const comparing = f => + (x, y) => { + const + a = f(x), + b = f(y); + return a < b ? -1 : (a > b ? 1 : 0); + }; + + // cons :: a -> [a] -> [a] + const cons = (x, xs) => [x].concat(xs); + + // div :: Int -> Int -> Int + const div = (x, y) => Math.floor(x / y); + + // enumFromTo :: Int -> Int -> [Int] + const enumFromTo = (m, n) => + Array.from({ + length: Math.floor(n - m) + 1 + }, (_, i) => m + i); + + // even :: Int -> Bool + const even = n => n % 2 === 0; + + // fst :: (a, b) -> a + const fst = pair => pair.length === 2 ? pair[0] : undefined; + + // map :: (a -> b) -> [a] -> [b] + const map = (f, xs) => xs.map(f); + + // maximumBy :: (a -> a -> Ordering) -> [a] -> a + const maximumBy = (f, xs) => + xs.length > 0 ? ( + xs.slice(1) + .reduce((a, x) => f(x, a) > 0 ? x : a, xs[0]) + ) : undefined; + + // memoized :: (a -> b) -> (a -> b) + const memoized = f => { + const dctMemo = {}; + return x => { + const v = dctMemo[x]; + return v !== undefined ? v : (dctMemo[x] = f(x)); + }; }; - // range :: Int -> Int -> Maybe Int -> [Int] - const range = (m, n, delta) => { - const blnUp = n > m, - d = blnUp ? (delta || 1) : -(delta || 1), - lng = Math.abs(Math.floor((blnUp ? n - m : m - n) / d) + 1), - a = Array(lng); - let i = lng; + // reverse :: [a] -> [a] + const reverse = xs => + xs.slice(0) + .reverse(); - while (i--) a[i] = (d * i) + m; - return a; + // unlines :: [String] -> String + const unlines = xs => xs.join('\n'); + + // until :: (a -> Bool) -> (a -> a) -> a -> a + const until = (p, f, x) => { + let v = x; + while (!p(v)) v = f(v); + return v; }; - // longestBelow :: Int -> {Number::Int, Length:Int} - const longestBelow = n => - range(1, n) - .reduce( - (a, x) => { - const lng = dctMemo[x] || (dctMemo[x] = collatzLength(x)); + // MAIN ------------------------------------------------------------------ + const + // ceiling :: Int + ceiling = 100000, - return lng > a.l ? { - n: x, - l: lng - } : a - - }, { - n: 0, - l: 0 - } + // (maxLen, maxNum) :: (Int, Int) + [maxLen, maxNum] = + maximumBy( + comparing(fst), + map(i => [collatzLength(i), i], enumFromTo(1, ceiling)) ); - - // TEST - // show :: a -> String - const show = x => JSON.stringify(x, null, 2); - - return show( - [100000, 1000000, 10000000].map(longestBelow) - ); + return unlines([ + 'Collatz sequence for 27: ', + `${hailstones(27)}`, + '', + `The number ${maxNum} has the longest hailstone sequence`, + `for any starting number under ${ceiling}.`, + '', + `The length of that sequence is ${maxLen}.` + ]); })(); diff --git a/Task/Hailstone-sequence/Julia/hailstone-sequence-1.julia b/Task/Hailstone-sequence/Julia/hailstone-sequence-1.julia new file mode 100644 index 0000000000..762abe3e82 --- /dev/null +++ b/Task/Hailstone-sequence/Julia/hailstone-sequence-1.julia @@ -0,0 +1,11 @@ +function hailstonelength(n::Integer) + len = 1 + while n > 1 + n = ifelse(iseven(n), n ÷ 2, 3n + 1) + len += 1 + end + return len +end + +@show hailstonelength(27) +@show findmax(hailstonelength(i) for i in 1:100_000) diff --git a/Task/Hailstone-sequence/Julia/hailstone-sequence-2.julia b/Task/Hailstone-sequence/Julia/hailstone-sequence-2.julia new file mode 100644 index 0000000000..5da9b9d91c --- /dev/null +++ b/Task/Hailstone-sequence/Julia/hailstone-sequence-2.julia @@ -0,0 +1,40 @@ +struct HailstoneSeq{T<:Integer} + start::T +end + +Base.eltype(::HailstoneSeq{T}) where T = T + +Base.start(hs::HailstoneSeq) = (-1, hs.start) +Base.done(::HailstoneSeq, state) = state == (1, 4) +function Base.next(::HailstoneSeq, state) + _, s2 = state + s1 = s2 + if iseven(s2) + s2 = s2 ÷ 2 + else + s2 = 3s2 + 1 + end + return s1, (s1, s2) +end + +function Base.length(hs::HailstoneSeq) + r = 0 + for _ in hs + r += 1 + end + return r +end + +function Base.show(io::IO, hs::HailstoneSeq) + f5 = collect(Iterators.take(hs, 5)) + print(io, "HailstoneSeq(", join(f5, ", "), "...)") +end + +hs = HailstoneSeq(27) +println("Collection of the Hailstone sequence from 27: $hs") +cl = collect(hs) +println("First 5 elements: ", join(cl[1:5], ", ")) +println("Last 5 elements: ", join(cl[end-4:end], ", ")) + +Base.isless(h::HailstoneSeq, s::HailstoneSeq) = length(h) < length(s) +println("The number with the longest sequence under 100,000 is: ", maximum(HailstoneSeq.(1:100_000))) diff --git a/Task/Hailstone-sequence/Julia/hailstone-sequence-3.julia b/Task/Hailstone-sequence/Julia/hailstone-sequence-3.julia new file mode 100644 index 0000000000..5da9b9d91c --- /dev/null +++ b/Task/Hailstone-sequence/Julia/hailstone-sequence-3.julia @@ -0,0 +1,40 @@ +struct HailstoneSeq{T<:Integer} + start::T +end + +Base.eltype(::HailstoneSeq{T}) where T = T + +Base.start(hs::HailstoneSeq) = (-1, hs.start) +Base.done(::HailstoneSeq, state) = state == (1, 4) +function Base.next(::HailstoneSeq, state) + _, s2 = state + s1 = s2 + if iseven(s2) + s2 = s2 ÷ 2 + else + s2 = 3s2 + 1 + end + return s1, (s1, s2) +end + +function Base.length(hs::HailstoneSeq) + r = 0 + for _ in hs + r += 1 + end + return r +end + +function Base.show(io::IO, hs::HailstoneSeq) + f5 = collect(Iterators.take(hs, 5)) + print(io, "HailstoneSeq(", join(f5, ", "), "...)") +end + +hs = HailstoneSeq(27) +println("Collection of the Hailstone sequence from 27: $hs") +cl = collect(hs) +println("First 5 elements: ", join(cl[1:5], ", ")) +println("Last 5 elements: ", join(cl[end-4:end], ", ")) + +Base.isless(h::HailstoneSeq, s::HailstoneSeq) = length(h) < length(s) +println("The number with the longest sequence under 100,000 is: ", maximum(HailstoneSeq.(1:100_000))) diff --git a/Task/Hailstone-sequence/Julia/hailstone-sequence.julia b/Task/Hailstone-sequence/Julia/hailstone-sequence.julia deleted file mode 100644 index e3027b0d71..0000000000 --- a/Task/Hailstone-sequence/Julia/hailstone-sequence.julia +++ /dev/null @@ -1,8 +0,0 @@ -function hailstone(n) - seq = [n] - while n>1 - n = n % 2 == 0 ? n >> 1 : 3n + 1 - push!(seq,n) - end - return seq -end diff --git a/Task/Hamming-numbers/AWK/hamming-numbers.awk b/Task/Hamming-numbers/AWK/hamming-numbers.awk index 050dc120d8..7738707b1c 100644 --- a/Task/Hamming-numbers/AWK/hamming-numbers.awk +++ b/Task/Hamming-numbers/AWK/hamming-numbers.awk @@ -1,9 +1,10 @@ -# syntax: GAWK -f HAMMING_NUMBERS.AWK +# syntax: gawk -M -f hamming_numbers.awk BEGIN { for (i=1; i<=20; i++) { printf("%d ",hamming(i)) } printf("\n1691: %d\n",hamming(1691)) + printf("\n1000000: %d\n",hamming(1000000)) exit(0) } function hamming(limit, h,i,j,k,n,x2,x3,x5) { diff --git a/Task/Hamming-numbers/Ada/hamming-numbers.ada b/Task/Hamming-numbers/Ada/hamming-numbers.ada new file mode 100644 index 0000000000..8b9c9a2465 --- /dev/null +++ b/Task/Hamming-numbers/Ada/hamming-numbers.ada @@ -0,0 +1,113 @@ +with Ada.Numerics.Generic_Elementary_Functions; +with Ada.Text_IO; use Ada.Text_IO; +with GNATCOLL.GMP.Integers; +with GNATCOLL.GMP.Lib; + +procedure Hamming is + + type Log_Type is new Long_Long_Float; + package Funcs is new Ada.Numerics.Generic_Elementary_Functions (Log_Type); + + type Factors_Array is array (Positive range <>) of Positive; + + generic + Factors : Factors_Array := (2, 3, 5); + -- The factors for smooth numbers. Hamming numbers are 5-smooth. + package Smooth_Numbers is + type Number is private; + function Compute (Nth : Positive) return Number; + function Image (N : Number) return String; + + private + type Exponent_Type is new Natural; + type Exponents_Array is array (Factors'Range) of Exponent_Type; + -- Numbers are stored as the exponents of the prime factors. + + type Number is record + Exponents : Exponents_Array; + Log : Log_Type; + -- The log of the value, used to ease sorting. + end record; + + function "=" (N1, N2 : Number) return Boolean + is (for all F in Factors'Range => N1.Exponents (F) = N2.Exponents (F)); + end Smooth_Numbers; + + package body Smooth_Numbers is + One : constant Number := (Exponents => (others => 0), Log => 0.0); + Factors_Log : array (Factors'Range) of Log_Type; + + function Image (N : Number) return String is + use GNATCOLL.GMP.Integers, GNATCOLL.GMP.Lib; + R, Tmp : Big_Integer; + begin + Set (R, "1"); + for F in Factors'Range loop + Set (Tmp, Factors (F)'Image); + Raise_To_N (Tmp, GNATCOLL.GMP.Unsigned_Long (N.Exponents (F))); + Multiply (R, Tmp); + end loop; + return Image (R); + end Image; + + function Compute (Nth : Positive) return Number is + Candidates : array (Factors'Range) of Number; + + Values : array (1 .. Nth) of Number; + -- Will result in Storage_Error for very large values of Nth + + Indices : array (Factors'Range) of Natural := + (others => Values'First); + Current : Number; + Tmp : Number; + begin + for F in Factors'Range loop + Factors_Log (F) := Funcs.Log (Log_Type (Factors (F))); + Candidates (F) := One; + Candidates (F).Exponents (F) := 1; + Candidates (F).Log := Factors_Log (F); + end loop; + + Values (1) := One; + + for Count in 2 .. Nth loop + -- Find next value (the lowest of the candidates) + Current := Candidates (Factors'First); + for F in Factors'First + 1 .. Factors'Last loop + if Candidates (F).Log < Current.Log then + Current := Candidates (F); + end if; + end loop; + + Values (Count) := Current; + + -- Update the candidates. There might be several candidates with + -- the same value + for F in Factors'Range loop + if Candidates (F) = Current then + Indices (F) := Indices (F) + 1; + + Tmp := Values (Indices (F)); + Tmp.Exponents (F) := Tmp.Exponents (F) + 1; + Tmp.Log := Tmp.Log + Factors_Log (F); + + Candidates (F) := Tmp; + end if; + end loop; + end loop; + + return Values (Nth); + end Compute; + end Smooth_Numbers; + + package Hamming is new Smooth_Numbers ((2, 3, 5)); + +begin + for N in 1 .. 20 loop + Put (" " & Hamming.Image (Hamming.Compute (N))); + end loop; + New_Line; + + Put_Line (Hamming.Image (Hamming.Compute (1691))); + Put_Line (Hamming.Image (Hamming.Compute (1_000_000))); +end Hamming; diff --git a/Task/Hamming-numbers/Julia/hamming-numbers.julia b/Task/Hamming-numbers/Julia/hamming-numbers.julia index 0c9f5ba23e..391f6acc6c 100644 --- a/Task/Hamming-numbers/Julia/hamming-numbers.julia +++ b/Task/Hamming-numbers/Julia/hamming-numbers.julia @@ -1,19 +1,19 @@ -n = 40 +function hamming(n::Integer) + seq = collect(0:n) + pwrs2 = 2 .^ seq + pwrs3 = 3 .^ seq + pwrs5 = 5 .^ seq -powers_2 = 2.^[0:n-1] -powers_3 = 3.^[0:n-1] -powers_5 = 5.^[0:n-1] + matrix = pwrs2 * pwrs3' + pwrs23 = sort(reshape(matrix, length(matrix))) -matrix = powers_2 * powers_3' -powers_23 = sort(reshape(matrix,length(matrix),1),1) + matrix = pwrs23 * pwrs5' + if any(x -> x < 0, matrix) warn("overflow values in result, try to use big($n) instead") end + return sort(reshape(matrix, length(matrix))) +end -matrix = powers_23 * powers_5' -powers_235 = sort(reshape(matrix,length(matrix),1),1) +x = hamming(big(100)) -# -# Remove the integer overflow values. -# -powers_235 = powers_235[powers_235 .> 0] - -println(powers_235[1:20]) -println(powers_235[1691]) +println("First 20 hamming numbers: ", join(x[1:20], ", ")) +println("1691-th hamming number: ", x[1691]) +println("Million-th hamming number: ", x[1000000]) diff --git a/Task/Hamming-numbers/PicoLisp/hamming-numbers.l b/Task/Hamming-numbers/PicoLisp/hamming-numbers.l index 7c6b4be2b4..6cd8676991 100644 --- a/Task/Hamming-numbers/PicoLisp/hamming-numbers.l +++ b/Task/Hamming-numbers/PicoLisp/hamming-numbers.l @@ -9,5 +9,5 @@ H ) ) (println (make (for N 20 (link (hamming N))))) -(println (hamming 1691)) -(println (hamming 1000000)) +(println (hamming 1691)) # very fast +(println (hamming 1000000)) # runtime about 13 minutes on i5-3570S diff --git a/Task/Hamming-numbers/Python/hamming-numbers-3.py b/Task/Hamming-numbers/Python/hamming-numbers-3.py index 1c572fc067..5f269400e5 100644 --- a/Task/Hamming-numbers/Python/hamming-numbers-3.py +++ b/Task/Hamming-numbers/Python/hamming-numbers-3.py @@ -1,25 +1,16 @@ -from itertools import tee, chain, groupby, islice -from heapq import merge +from heapq import heappush, heappop +from itertools import islice -def raymonds_hamming(): - # Generate "5-smooth" numbers, also called "Hamming numbers" - # or "Regular numbers". See: http://en.wikipedia.org/wiki/Regular_number - # Finds solutions to 2**i * 3**j * 5**k for some integers i, j, and k. +def h(): + heap = [1] + while True: + h = heappop(heap) + while heap and h==heap[0]: + heappop(heap) + for m in [2,3,5]: + heappush(heap, m*h) + yield h - def deferred_output(): - for i in output: - yield i - - result, p2, p3, p5 = tee(deferred_output(), 4) - m2 = (2*x for x in p2) # multiples of 2 - m3 = (3*x for x in p3) # multiples of 3 - m5 = (5*x for x in p5) # multiples of 5 - merged = merge(m2, m3, m5) - combined = chain([1], merged) # prepend a starting point - output = (k for k,g in groupby(combined)) # eliminate duplicates - - return result - -print list(islice(raymonds_hamming(), 20)) -print islice(raymonds_hamming(), 1689, 1690).next() -print islice(raymonds_hamming(), 999999, 1000000).next() +print list(islice(h(), 20)) +print list(islice(h(), 1690, 1691)) +print list(islice(h(), 999999, 1000000)) # runtime 9.5 sec on i5-3570S diff --git a/Task/Hamming-numbers/Python/hamming-numbers-4.py b/Task/Hamming-numbers/Python/hamming-numbers-4.py index a8ec26ee3a..1c572fc067 100644 --- a/Task/Hamming-numbers/Python/hamming-numbers-4.py +++ b/Task/Hamming-numbers/Python/hamming-numbers-4.py @@ -1,13 +1,25 @@ +from itertools import tee, chain, groupby, islice from heapq import merge -from itertools import tee -def hamming_numbers(): - last = 1 - yield last +def raymonds_hamming(): + # Generate "5-smooth" numbers, also called "Hamming numbers" + # or "Regular numbers". See: http://en.wikipedia.org/wiki/Regular_number + # Finds solutions to 2**i * 3**j * 5**k for some integers i, j, and k. - a,b,c = tee(hamming_numbers(), 3) + def deferred_output(): + for i in output: + yield i - for n in merge((2*i for i in a), (3*i for i in b), (5*i for i in c)): - if n != last: - yield n - last = n + result, p2, p3, p5 = tee(deferred_output(), 4) + m2 = (2*x for x in p2) # multiples of 2 + m3 = (3*x for x in p3) # multiples of 3 + m5 = (5*x for x in p5) # multiples of 5 + merged = merge(m2, m3, m5) + combined = chain([1], merged) # prepend a starting point + output = (k for k,g in groupby(combined)) # eliminate duplicates + + return result + +print list(islice(raymonds_hamming(), 20)) +print islice(raymonds_hamming(), 1689, 1690).next() +print islice(raymonds_hamming(), 999999, 1000000).next() diff --git a/Task/Hamming-numbers/Python/hamming-numbers-5.py b/Task/Hamming-numbers/Python/hamming-numbers-5.py index 5c8e8f4a87..a8ec26ee3a 100644 --- a/Task/Hamming-numbers/Python/hamming-numbers-5.py +++ b/Task/Hamming-numbers/Python/hamming-numbers-5.py @@ -1,38 +1,13 @@ -from itertools import islice, chain, tee +from heapq import merge +from itertools import tee -def merge(r, s): - # This is faster than heapq.merge. - rr = r.next() - ss = s.next() - while True: - if rr < ss: - yield rr - rr = r.next() - else: - yield ss - ss = s.next() +def hamming_numbers(): + last = 1 + yield last -def p(n): - def gen(): - x = n - while True: - yield x - x *= n - return gen() + a,b,c = tee(hamming_numbers(), 3) -def pp(n, s): - def gen(): - for x in (merge(s, chain([n], (n * y for y in fb)))): - yield x - r, fb = tee(gen()) - return r - -def hamming(a, b = None): - if not b: - b = a + 1 - seq = (chain([1], pp(5, pp(3, p(2))))) - return list(islice(seq, a - 1, b - 1)) - -print hamming(1, 21) -print hamming(1691)[0] -print hamming(1000000)[0] + for n in merge((2*i for i in a), (3*i for i in b), (5*i for i in c)): + if n != last: + yield n + last = n diff --git a/Task/Hamming-numbers/Python/hamming-numbers-6.py b/Task/Hamming-numbers/Python/hamming-numbers-6.py new file mode 100644 index 0000000000..5c8e8f4a87 --- /dev/null +++ b/Task/Hamming-numbers/Python/hamming-numbers-6.py @@ -0,0 +1,38 @@ +from itertools import islice, chain, tee + +def merge(r, s): + # This is faster than heapq.merge. + rr = r.next() + ss = s.next() + while True: + if rr < ss: + yield rr + rr = r.next() + else: + yield ss + ss = s.next() + +def p(n): + def gen(): + x = n + while True: + yield x + x *= n + return gen() + +def pp(n, s): + def gen(): + for x in (merge(s, chain([n], (n * y for y in fb)))): + yield x + r, fb = tee(gen()) + return r + +def hamming(a, b = None): + if not b: + b = a + 1 + seq = (chain([1], pp(5, pp(3, p(2))))) + return list(islice(seq, a - 1, b - 1)) + +print hamming(1, 21) +print hamming(1691)[0] +print hamming(1000000)[0] diff --git a/Task/Hamming-numbers/R/hamming-numbers.r b/Task/Hamming-numbers/R/hamming-numbers-1.r similarity index 100% rename from Task/Hamming-numbers/R/hamming-numbers.r rename to Task/Hamming-numbers/R/hamming-numbers-1.r diff --git a/Task/Hamming-numbers/R/hamming-numbers-2.r b/Task/Hamming-numbers/R/hamming-numbers-2.r new file mode 100644 index 0000000000..4902bc4b32 --- /dev/null +++ b/Task/Hamming-numbers/R/hamming-numbers-2.r @@ -0,0 +1,8 @@ +hamming <- function(n) { + a <- numeric(n) + a[1] <- 1 + for (i in 2:n) { + a[i] <- nextn(a[i-1]+1) + } + a +} diff --git a/Task/Handle-a-signal/D/handle-a-signal.d b/Task/Handle-a-signal/D/handle-a-signal.d new file mode 100644 index 0000000000..de9578c746 --- /dev/null +++ b/Task/Handle-a-signal/D/handle-a-signal.d @@ -0,0 +1,29 @@ +import core.stdc.signal; +import core.thread; +import std.concurrency; +import std.datetime.stopwatch; +import std.stdio; + +__gshared int gotint = 0; +extern(C) void handleSigint(int sig) nothrow @nogc @system { + /* + * Signal safety: It is not safe to call clock(), printf(), + * or exit() inside a signal handler. Instead, we set a flag. + */ + gotint = 1; +} + +void main() { + auto sw = StopWatch(AutoStart.yes); + signal(SIGINT, &handleSigint); + for (int i=0; !gotint;) { + Thread.sleep(500_000.usecs); + if (gotint) { + break; + } + writeln(++i); + } + sw.stop(); + auto td = sw.peek(); + writeln("Program has run for ", td); +} diff --git a/Task/Happy-numbers/Elena/happy-numbers.elena b/Task/Happy-numbers/Elena/happy-numbers.elena new file mode 100644 index 0000000000..4cf260c9db --- /dev/null +++ b/Task/Happy-numbers/Elena/happy-numbers.elena @@ -0,0 +1,44 @@ +import extensions. +import system'collections. +import system'routines. + +isHappy = (:n) +[ + list cache := list(5). + int sum := 0. + int num := n. + while (num != 1) + [ + if (cache indexOfElement:num != -1) + [ + ^ false + ]. + cache append(num). + while (num != 0) + [ + int digit := num mod:10. + sum += (digit*digit). + num /= 10 + ]. + num := sum. + sum := 0 + ]. + + ^ true +]. + +program = +[ + list happynums := list(8). + int num := 1. + while (happynums length < 8) + [ + if (isHappy eval(num)) + [ + happynums append(num) + ]. + + num += 1 + ]. + console printLine("First 8 happy numbers: ", happynums). +]. diff --git a/Task/Happy-numbers/VBA/happy-numbers.vba b/Task/Happy-numbers/VBA/happy-numbers.vba new file mode 100644 index 0000000000..bfb3c44269 --- /dev/null +++ b/Task/Happy-numbers/VBA/happy-numbers.vba @@ -0,0 +1,29 @@ +Option Explicit + +Sub Test_Happy() +Dim i&, Cpt& + + For i = 1 To 100 + If Is_Happy_Number(i) Then + Debug.Print "Is Happy : " & i + Cpt = Cpt + 1 + If Cpt = 8 Then Exit For + End If + Next +End Sub + +Public Function Is_Happy_Number(ByVal N As Long) As Boolean +Dim i&, Number$, Cpt& + Is_Happy_Number = False 'default value + Do + Cpt = Cpt + 1 'Count Loops + Number = CStr(N) 'conversion Long To String to be able to use Len() function + N = 0 + For i = 1 To Len(Number) + N = N + CInt(Mid(Number, i, 1)) ^ 2 + Next i + 'If Not N = 1 after 50 Loop ==> Number Is Not Happy + If Cpt = 50 Then Exit Function + Loop Until N = 1 + Is_Happy_Number = True +End Function diff --git a/Task/Harshad-or-Niven-series/Factor/harshad-or-niven-series.factor b/Task/Harshad-or-Niven-series/Factor/harshad-or-niven-series.factor new file mode 100644 index 0000000000..95915ae0d9 --- /dev/null +++ b/Task/Harshad-or-Niven-series/Factor/harshad-or-niven-series.factor @@ -0,0 +1,9 @@ +USING: math.text.utils lists lists.lazy ; + +: niven? ( n -- ? ) dup 1 digit-groups sum mod 0 = ; +: first-n-niven ( n -- seq ) + 1 lfrom [ niven? ] lfilter ltake list>array ; +: next-niven ( n -- m ) 1 + [ dup niven? ] [ 1 + ] until ; + +20 first-n-niven . +1000 next-niven . diff --git a/Task/Harshad-or-Niven-series/Julia/harshad-or-niven-series.julia b/Task/Harshad-or-Niven-series/Julia/harshad-or-niven-series.julia index a05cdd0b41..1f11c7b30f 100644 --- a/Task/Harshad-or-Niven-series/Julia/harshad-or-niven-series.julia +++ b/Task/Harshad-or-Niven-series/Julia/harshad-or-niven-series.julia @@ -1,10 +1,14 @@ -isharshad(x) = x % sum(digits(x)) == 0 -function harshads(n) - h = Int[] - i = 1 - while length(h) < n - isharshad(i) && push!(h,i) - i+=1 +isharshad(x) = x % sum(digits(x)) == 0 +nextharshad(x) = begin while !isharshad(x+1) x += 1 end; return x + 1 end + +function harshads(n::Integer) + h = Vector{typeof(n)}(n) + h[1] = 1 + for j in 2:n + h[j] = nextharshad(h[j-1]) end return h end + +println("First 20 harshad numbers: ", join(harshads(20), ", ")) +println("First harshad number after 1001: ", nextharshad(1000)) diff --git a/Task/Harshad-or-Niven-series/PicoLisp/harshad-or-niven-series.l b/Task/Harshad-or-Niven-series/PicoLisp/harshad-or-niven-series.l new file mode 100644 index 0000000000..18f0ca0f20 --- /dev/null +++ b/Task/Harshad-or-Niven-series/PicoLisp/harshad-or-niven-series.l @@ -0,0 +1,23 @@ +#if niven number, return it. +(de niven (N) + (if (=0 (% N (apply+ (getN N)))) N) ) + +#function which creates a list of numbers from input +(de getN (N) + (mapcar any (chop N)) ) + +#function to apply '+' func to list of numbers +(de apply+ (Ln) + (apply + Ln) ) + +#function to delete NIL from the entire list +(de delNIL (L) + (delete NIL L T) ) + +#This function generates niven number list +(de nivGen (R N) + (delNIL (mapcar niven (range R N))) ) + +#print 1st 20 niven numbers and 1st niven number greater than 1000 +(printsp ~(list ~(head 20 + (nivGen 1 1000) ) ~(head 1 (nivGen 1001 1010)) ) ) diff --git a/Task/Harshad-or-Niven-series/Rust/harshad-or-niven-series.rust b/Task/Harshad-or-Niven-series/Rust/harshad-or-niven-series.rust new file mode 100644 index 0000000000..d8b0cc1268 --- /dev/null +++ b/Task/Harshad-or-Niven-series/Rust/harshad-or-niven-series.rust @@ -0,0 +1,16 @@ +fn is_hashard (n : u32) -> bool { + let sum_digits = n.to_string() + .chars() + .map(|c| c.to_digit(10).unwrap()) + .fold(0, |a, b| a+b); + n % sum_digits == 0 +} + +fn main() { + for i in (1u32..).filter(|num| is_hashard(*num)).take(20) { + println!("Hashard : {}", i); + } + for i in (1_001u32..).filter(|num| is_hashard(*num)).take(1) { + println!("First Hashard bigger than 1_000 : {}", i); + } +} diff --git a/Task/Hash-from-two-arrays/C++/hash-from-two-arrays-1.cpp b/Task/Hash-from-two-arrays/C++/hash-from-two-arrays-1.cpp index 407cfdaa8b..7f131edd01 100644 --- a/Task/Hash-from-two-arrays/C++/hash-from-two-arrays-1.cpp +++ b/Task/Hash-from-two-arrays/C++/hash-from-two-arrays-1.cpp @@ -1,16 +1,12 @@ -#include +#include #include -int -main( int argc, char* argv[] ) +int main() { - std::string keys[] = { "1", "2", "3" } ; - std::string vals[] = { "a", "b", "c" } ; + std::string keys[] = { "1", "2", "3" }; + std::string vals[] = { "a", "b", "c" }; - std::map< std::string, std::string > hash ; - - for( int i = 0 ; i < 3 ; i++ ) - { - hash[ keys[i] ] = vals[i] ; - } + std::unordered_map hash; + for( int i = 0 ; i < 3 ; i++ ) + hash[ keys[i] ] = vals[i] ; } diff --git a/Task/Hash-from-two-arrays/C++/hash-from-two-arrays-2.cpp b/Task/Hash-from-two-arrays/C++/hash-from-two-arrays-2.cpp index 2a0f0d0d04..0ecadbd204 100644 --- a/Task/Hash-from-two-arrays/C++/hash-from-two-arrays-2.cpp +++ b/Task/Hash-from-two-arrays/C++/hash-from-two-arrays-2.cpp @@ -1,17 +1,11 @@ -#include // for std::map -#include // for std::transform -#include // for std::string -#include // for std::make_pair +#include +#include +#include int main() { - std::string keys[] = { "one", "two", "three" }; + std::string keys[] = { "1", "2", "3" }; std::string vals[] = { "foo", "bar", "baz" }; - std::map hash; - - std::transform(keys, keys+3, - vals, - std::inserter(hash, hash.end()), - std::make_pair); + std::unordered_map hash(ranges::view::zip(keys, vals)); } diff --git a/Task/Hash-from-two-arrays/Julia/hash-from-two-arrays-1.julia b/Task/Hash-from-two-arrays/Julia/hash-from-two-arrays-1.julia index 733230ee9b..3cdf529862 100644 --- a/Task/Hash-from-two-arrays/Julia/hash-from-two-arrays-1.julia +++ b/Task/Hash-from-two-arrays/Julia/hash-from-two-arrays-1.julia @@ -1,4 +1,4 @@ -julia> K = ["a", "b", "c"] -julia> V = [1, 2, 3] -julia> H = [key => value for (key, value) in zip(K,V)] -{"b"=>2,"c"=>3,"a"=>1} +k = ["a", "b", "c"] +v = [1, 2, 3] + +Dict(ki => vi for (ki, vi) in zip(k, v)) diff --git a/Task/Hash-from-two-arrays/Julia/hash-from-two-arrays-2.julia b/Task/Hash-from-two-arrays/Julia/hash-from-two-arrays-2.julia index 44dac07a46..9217ed85aa 100644 --- a/Task/Hash-from-two-arrays/Julia/hash-from-two-arrays-2.julia +++ b/Task/Hash-from-two-arrays/Julia/hash-from-two-arrays-2.julia @@ -1,2 +1 @@ -julia> H = (String=>Int)[key => value for (key, value) in zip(K,V)] -["b"=>2,"c"=>3,"a"=>1] +Dict(zip(keys, values)) diff --git a/Task/Hash-from-two-arrays/Julia/hash-from-two-arrays-3.julia b/Task/Hash-from-two-arrays/Julia/hash-from-two-arrays-3.julia index a9e3040ab4..b3d6eda868 100644 --- a/Task/Hash-from-two-arrays/Julia/hash-from-two-arrays-3.julia +++ b/Task/Hash-from-two-arrays/Julia/hash-from-two-arrays-3.julia @@ -1,2 +1 @@ -julia> H = Dict(K, V) -["b"=>2,"c"=>3,"a"=>1] +Dict{String,Int32}(zip(keys, values)) diff --git a/Task/Hash-from-two-arrays/Perl-6/hash-from-two-arrays.pl6 b/Task/Hash-from-two-arrays/Perl-6/hash-from-two-arrays.pl6 new file mode 100644 index 0000000000..a114b5fe7d --- /dev/null +++ b/Task/Hash-from-two-arrays/Perl-6/hash-from-two-arrays.pl6 @@ -0,0 +1,19 @@ +my @keys = ; +my @values = ^5; + +my %hash = @keys Z=> @values; + + +#Alternatively, by assigning to a hash slice: +%hash{@keys} = @values; + + +# Or to create an anonymous hash: +%( @keys Z=> @values ); + + +# All of these zip forms trim the result to the length of the shorter of their two input lists. +# If you wish to enforce equal lengths, you can use a strict hyperoperator instead: + +quietly # suppress warnings about unused hash +{ @keys »=>« @values }; # Will fail if the lists differ in length diff --git a/Task/Hash-from-two-arrays/Ring/hash-from-two-arrays.ring b/Task/Hash-from-two-arrays/Ring/hash-from-two-arrays.ring new file mode 100644 index 0000000000..df3a9ba3f4 --- /dev/null +++ b/Task/Hash-from-two-arrays/Ring/hash-from-two-arrays.ring @@ -0,0 +1,17 @@ +# Project : Hash from two arrays +# Date : 2018/03/18 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : + +list1="one two three" +list2="1 2 3" +a = str2list(substr(list1," ",nl)) +b = str2list(substr(list2," ",nl)) +c = list(len(a)) +for i=1 to len(b) + temp = number(b[i]) + c[temp] = a[i] +next +for i = 1 to len(c) + see c[i] + " " + i + nl +next diff --git a/Task/Hash-from-two-arrays/Ruby/hash-from-two-arrays-2.rb b/Task/Hash-from-two-arrays/Ruby/hash-from-two-arrays-2.rb index 8ad34e5c16..aa17e72cfe 100644 --- a/Task/Hash-from-two-arrays/Ruby/hash-from-two-arrays-2.rb +++ b/Task/Hash-from-two-arrays/Ruby/hash-from-two-arrays-2.rb @@ -1,8 +1,4 @@ -class Array - def zip_hash(other) - Hash[self.zip(other)] - end -end +keys = ['hal', 666, [1,2,3]] +vals = ['ibm', 'devil', 123] -hash = %w{ a b c }.zip_hash( %w{ 1 2 3 } ) -p hash # => {"a"=>"1", "b"=>"2", "c"=>"3"} +keys.zip(vals).to_h diff --git a/Task/Hash-join/C++/hash-join.cpp b/Task/Hash-join/C++/hash-join.cpp new file mode 100644 index 0000000000..8606ba5d70 --- /dev/null +++ b/Task/Hash-join/C++/hash-join.cpp @@ -0,0 +1,64 @@ +#include +#include +#include +#include + +using tab_t = std::vector>; +tab_t tab1 { +// Age Name + {"27", "Jonah"} +, {"18", "Alan"} +, {"28", "Glory"} +, {"18", "Popeye"} +, {"28", "Alan"} +}; + +tab_t tab2 { +// Character Nemesis + {"Jonah", "Whales"} +, {"Jonah", "Spiders"} +, {"Alan", "Ghosts"} +, {"Alan", "Zombies"} +, {"Glory", "Buffy"} +}; + +std::ostream& operator<<(std::ostream& o, const tab_t& t) { + for(size_t i = 0; i < t.size(); ++i) { + o << i << ":"; + for(const auto& e : t[i]) + o << '\t' << e; + o << std::endl; + } + return o; +} + +tab_t Join(const tab_t& a, size_t columna, const tab_t& b, size_t columnb) { + std::unordered_multimap hashmap; + // hash + for(size_t i = 0; i < a.size(); ++i) { + hashmap.insert(std::make_pair(a[i][columna], i)); + } + // map + tab_t result; + for(size_t i = 0; i < b.size(); ++i) { + auto range = hashmap.equal_range(b[i][columnb]); + for(auto it = range.first; it != range.second; ++it) { + tab_t::value_type row; + row.insert(row.end() , a[it->second].begin() , a[it->second].end()); + row.insert(row.end() , b[i].begin() , b[i].end()); + result.push_back(std::move(row)); + } + } + return result; +} + +int main(int argc, char const *argv[]) +{ + using namespace std; + int ret = 0; + cout << "Table A: " << endl << tab1 << endl; + cout << "Table B: " << endl << tab2 << endl; + auto tab3 = Join(tab1, 1, tab2, 0); + cout << "Joined tables: " << endl << tab3 << endl; + return ret; +} diff --git a/Task/Hash-join/Perl-6/hash-join.pl6 b/Task/Hash-join/Perl-6/hash-join.pl6 new file mode 100644 index 0000000000..c4c685ca9f --- /dev/null +++ b/Task/Hash-join/Perl-6/hash-join.pl6 @@ -0,0 +1,27 @@ +sub hash-join(@a, &a, @b, &b) { + my %hash := @b.classify(&b); + + @a.map: -> $a { + |(%hash{a $a} // next).map: -> $b { [$a, $b] } + } +} + +# Testing: + +my @A = + [27, "Jonah"], + [18, "Alan"], + [28, "Glory"], + [18, "Popeye"], + [28, "Alan"], +; + +my @B = + ["Jonah", "Whales"], + ["Jonah", "Spiders"], + ["Alan", "Ghosts"], + ["Alan", "Zombies"], + ["Glory", "Buffy"], +; + +.say for hash-join @A, *[1], @B, *[0]; diff --git a/Task/Hash-join/Rust/hash-join.rust b/Task/Hash-join/Rust/hash-join.rust index c53ca9b06f..30f5046e91 100644 --- a/Task/Hash-join/Rust/hash-join.rust +++ b/Task/Hash-join/Rust/hash-join.rust @@ -1,26 +1,43 @@ use std::collections::HashMap; +use std::hash::Hash; + +// If you know one of the tables is smaller, it is best to make it the second parameter. +fn hash_join(first: &[(K, A)], second: &[(K, B)]) -> Vec<(A, K, B)> +where + K: Hash + Eq + Copy, + A: Copy, + B: Copy, +{ + let mut hash_map = HashMap::new(); + + // hash phase + for &(key, val_a) in second { + // collect all values by their keys, appending new ones to each existing entry + hash_map.entry(key).or_insert_with(Vec::new).push(val_a); + } + + let mut result = Vec::new(); + // join phase + for &(key, val_b) in first { + if let Some(vals) = hash_map.get(&key) { + let tuples = vals.iter().map(|&val_a| (val_b, key, val_a)); + result.extend(tuples); + } + } + + result +} fn main() { - let table_a = vec![ - (27, "Jonah"), (18, "Alan"), (28, "Glory"), - (18, "Popeye"), (28, "Alan") - ]; - let table_b = vec![ + let table1 = [("Jonah", 27), ("Alan", 18), ("Glory", 28), ("Popeye", 18), ("Alan", 28)]; + let table2 = [ ("Jonah", "Whales"), ("Jonah", "Spiders"), ("Alan", "Ghosts"), ("Alan", "Zombies"), ("Glory", "Buffy") ]; - // hash phase - let mut h = HashMap::new(); - for (i, a) in table_a.iter().enumerate() { - h.entry(a.1).or_insert_with(Vec::new).push(i); - } - // join phase - for b in table_b { - if let Some(vals) = h.get(b.0) { - for &val in vals { - let a = table_a.get(val).unwrap(); - println!("{:?} {:?}", a, b); - } - } + let result = hash_join(&table1, &table2); + println!("Age | Character Name | Nemesis"); + println!("----|----------------|--------"); + for (age, name, nemesis) in result { + println!("{:<3} | {:^14} | {}", age, name, nemesis); } } diff --git a/Task/Haversine-formula/C++/haversine-formula.cpp b/Task/Haversine-formula/C++/haversine-formula.cpp new file mode 100644 index 0000000000..bd1bdb6b51 --- /dev/null +++ b/Task/Haversine-formula/C++/haversine-formula.cpp @@ -0,0 +1,56 @@ +#define _USE_MATH_DEFINES + +#include +#include + +const static double EarthRadiusKm = 6372.8; + +inline double DegreeToRadian(double angle) +{ + return M_PI * angle / 180.0; +} + +class Coordinate +{ +public: + Coordinate(double latitude ,double longitude):myLatitude(latitude), myLongitude(longitude) + {} + + double Latitude() const + { + return myLatitude; + } + + double Longitude() const + { + return myLongitude; + } + +private: + + double myLatitude; + double myLongitude; +}; + +double HaversineDistance(const Coordinate& p1, const Coordinate& p2) +{ + double latRad1 = DegreeToRadian(p1.Latitude()); + double latRad2 = DegreeToRadian(p2.Latitude()); + double lonRad1 = DegreeToRadian(p1.Longitude()); + double lonRad2 = DegreeToRadian(p2.Longitude()); + + double diffLa = latRad2 - latRad1; + double doffLo = lonRad2 - lonRad1; + + double computation = asin(sqrt(sin(diffLa / 2) * sin(diffLa / 2) + cos(latRad1) * cos(latRad2) * sin(doffLo / 2) * sin(doffLo / 2))); + return 2 * EarthRadiusKm * computation; +} + +int main() +{ + Coordinate c1(36.12, -86.67); + Coordinate c2(33.94, -118.4); + + std::cout << "Distance = " << HaversineDistance(c1, c2) << std::endl; + return 0; +} diff --git a/Task/Haversine-formula/Elena/haversine-formula.elena b/Task/Haversine-formula/Elena/haversine-formula.elena new file mode 100644 index 0000000000..5aa81337ca --- /dev/null +++ b/Task/Haversine-formula/Elena/haversine-formula.elena @@ -0,0 +1,23 @@ +import extensions. +import system'math. + +Haversine = (:lat1:lon1:lat2:lon2) +[ + var R := 6372.8r. + var dLat := (lat2 - lat1) radian. + var dLon := (lon2 - lon1) radian. + + var dLat1 := lat1 radian. + var dLat2 := lat2 radian. + + var a := (dLat / 2) sin * (dLat / 2) sin + (dLon / 2) sin * (dLon / 2) sin * dLat1 cos * dLat2 cos. + + //var c := 2 * a sqrt; arcsin. + ^ R * 2 * a sqrt; arcsin. +]. + +program = +[ + console printLineFormatted("The distance between coordinates {0},{1} and {2},{3} is: {4}", 36.12r, -86.67r, 33.94r, -118.40r, + Haversine(36.12r, -86.67r, 33.94r, -118.40r)). +]. diff --git a/Task/Haversine-formula/JavaScript/haversine-formula-2.js b/Task/Haversine-formula/JavaScript/haversine-formula-2.js index 6722b76ec3..f1eccdda2f 100644 --- a/Task/Haversine-formula/JavaScript/haversine-formula-2.js +++ b/Task/Haversine-formula/JavaScript/haversine-formula-2.js @@ -2,11 +2,12 @@ 'use strict'; // haversine :: (Num, Num) -> (Num, Num) -> Num - let haversine = ([lat1, lon1], [lat2, lon2]) => { + const haversine = ([lat1, lon1], [lat2, lon2]) => { // Math lib function names - let [pi, asin, sin, cos, sqrt, pow, round] = - ['PI', 'asin', 'sin', 'cos', 'sqrt', 'pow', 'round'] - .map(k => Math[k]), + const [pi, asin, sin, cos, sqrt, pow, round] = [ + 'PI', 'asin', 'sin', 'cos', 'sqrt', 'pow', 'round' + ] + .map(k => Math[k]), // degrees as radians [rlat1, rlat2, rlon1, rlon2] = [lat1, lat2, lon1, lon2] diff --git a/Task/Haversine-formula/Julia/haversine-formula.julia b/Task/Haversine-formula/Julia/haversine-formula.julia index 8f1c78fbed..2331c2b906 100644 --- a/Task/Haversine-formula/Julia/haversine-formula.julia +++ b/Task/Haversine-formula/Julia/haversine-formula.julia @@ -1,5 +1,5 @@ -julia> haversine(lat1,lon1,lat2,lon2) = 2 * 6372.8 * asin(sqrt(sind((lat2-lat1)/2)^2 + cosd(lat1) * cosd(lat2) * sind((lon2 - lon1)/2)^2)) -# method added to generic function haversine +haversine(lat1, lon1, lat2, lon2) = + 2 * 6372.8 * asin(sqrt(sind((lat2 - lat1) / 2) ^ 2 + + cosd(lat1) * cosd(lat2) * sind((lon2 - lon1) / 2) ^ 2)) -julia> haversine(36.12,-86.67,33.94,-118.4) -2887.2599506071106 +@show haversine(36.12, -86.67, 33.94, -118.4) diff --git a/Task/Haversine-formula/REXX/haversine-formula.rexx b/Task/Haversine-formula/REXX/haversine-formula.rexx index 90b05203b7..c53b7dcc33 100644 --- a/Task/Haversine-formula/REXX/haversine-formula.rexx +++ b/Task/Haversine-formula/REXX/haversine-formula.rexx @@ -5,21 +5,21 @@ say " Los Angles: north 33º 56.4', west 118º 24.0' = 33.94º, -118.4 @using_radius= 'using the mean radius of the earth as ' /*a literal for SAY.*/ radii.=.; radii.1=6372.8; radii.2=6371 /*mean radii of the earth in kilometers*/ say; m=1/0.621371192237 /*M: one statute mile in " */ - do radius=1 while radii.radius\==. /*calc. distance using specific radius.*/ + do radius=1 while radii.radius\==. /*calc. distance using specific radii. */ d=surfaceDistance( 36.12, -86.67, 33.94, -118.4, radii.radius); say say center(@using_radius radii.radius ' kilometers', 75, '─') say ' Distance between: ' format(d/1 ,,2) " kilometers," say ' or ' format(d/m ,,2) " statute miles," say ' or ' format(d/m*5280/6076.1,,2) " nautical (or air miles)." - end /*radius*/ /*these └───◄ displays 2 decimal digs.*/ + end /*radius*/ /*show──┘ 2 dec. digs past dec. point*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -Acos: return .5*pi() - aSin( arg(1) ) -d2d: return arg(1) // 360 /*normalize degrees to a unit circle. */ -d2r: return r2r(arg(1)*pi() / 180) /*normalize and convert deg ──► radians*/ -r2d: return d2d((arg(1)*180 / pi())) /*normalize and convert rad ──► degrees*/ -r2r: return arg(1) // (pi()*2) /*normalize radians to a unit circle. */ -p: return word(arg(1),1) /*pick the first of two words (numbers)*/ +Acos: return pi() * .5 - aSin( arg(1) ) /*calculate the ArcCos of an argument. */ +d2d: return arg(1) // 360 /*normalize degrees to a unit circle. */ +d2r: return r2r( arg(1) * pi() / 180) /*normalize and convert deg ──► radians*/ +r2d: return d2d( (arg(1) * 180 / pi())) /*normalize and convert rad ──► degrees*/ +r2r: return arg(1) // (pi() * 2) /*normalize radians to a unit circle. */ +p: return word( arg(1), 1) /*pick the first of two words (numbers)*/ pi: pi=3.141592653589793238462643383279502884197169399375105820975; return pi /*──────────────────────────────────────────────────────────────────────────────────────*/ surfaceDistance: parse arg th1,ph1,th2,ph2,r /*use haversine formula for distance.*/ @@ -31,23 +31,23 @@ surfaceDistance: parse arg th1,ph1,th2,ph2,r /*use haversine formula for d z= sin(th1) - sin(th2) return Asin( sqrt( x**2 + y**2 + z**2) / 2 ) * r * 2 /*──────────────────────────────────────────────────────────────────────────────────────*/ -Asin: procedure; parse arg x 1 z 1 o 1 p; a=abs(x); aa=a*a - if a>=sqrt(2) * .5 then return sign(x) * Acos(sqrt(1-aa)) - do j=2 by 2 until p=z; p=z; o=o*aa*(j-1)/j; z=z+o/(j+1); end /*j*/ - return z /* [↑] compute until no more noise. */ +Asin: procedure; parse arg x 1 z 1 o 1 p; a=abs(x); aa=a * a + if a>=sqrt(2) * .5 then return sign(x) * Acos( sqrt(1 - aa) ) + do j=2 by 2 until p=z; p=z; o=o*aa* (j-1) /j; z=z + o/(j+1); end /*j*/ + return z /* [↑] compute until no more noise. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -cos: procedure; parse arg x; x=r2r(x); a=abs(x); Hpi=pi*.5 - numeric fuzz min(6,digits()-3); if a=pi() then return -1 - if a=Hpi | a=Hpi*3 then return 0; if a=pi()/3 then return .5 - if a=pi()*2/3 then return -.5; return .sinCos(1,1,-1) +cos: procedure; parse arg x; x=r2r(x); a=abs(x); Hpi=pi * .5 + numeric fuzz min(6, digits() - 3) ; if a=pi then return -1 + if a=Hpi | a=Hpi*3 then return 0 ; if a=pi/3 then return .5 + if a=pi * 2 / 3 then return -.5; return .sinCos(1, 1, -1) /*──────────────────────────────────────────────────────────────────────────────────────*/ -sin: procedure; parse arg x; x=r2r(x); numeric fuzz min(5, digits()-3) - if abs(x)=pi() then return 0; return .sinCos(x,x,1) +sin: procedure; parse arg x; x=r2r(x); numeric fuzz min(5, digits() - 3) + if abs(x)=pi then return 0; return .sinCos(x, x, +1) /*──────────────────────────────────────────────────────────────────────────────────────*/ .sinCos: parse arg z 1 p,_,i; q=x*x do k=2 by 2; _=-_*q/(k*(k+i)); z=z+_; if z=p then leave; p=z; end; return z /*──────────────────────────────────────────────────────────────────────────────────────*/ sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); m.=9; numeric form; h=d+6 numeric digits; parse value format(x,2,1,,0) 'E0' with g "E" _ .; g=g * .5'e'_ % 2 - do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ - do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ + 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/Hello-world-Graphical/Elena/hello-world-graphical.elena b/Task/Hello-world-Graphical/Elena/hello-world-graphical.elena index f1981c1bc2..dacacdd117 100644 --- a/Task/Hello-world-Graphical/Elena/hello-world-graphical.elena +++ b/Task/Hello-world-Graphical/Elena/hello-world-graphical.elena @@ -1,6 +1,6 @@ import forms. -class Window :: SDIDialog +class MainWindow:: SDIDialog { object goodByeWorldLabel. object closeButton. diff --git a/Task/Hello-world-Graphical/FreeBASIC/hello-world-graphical-1.freebasic b/Task/Hello-world-Graphical/FreeBASIC/hello-world-graphical-1.freebasic new file mode 100644 index 0000000000..bd692cd286 --- /dev/null +++ b/Task/Hello-world-Graphical/FreeBASIC/hello-world-graphical-1.freebasic @@ -0,0 +1,4 @@ +screen 1 'Mode 320x200 +locate 12,15 +? "Goodbye, World!" +sleep diff --git a/Task/Hello-world-Graphical/FreeBASIC/hello-world-graphical-2.freebasic b/Task/Hello-world-Graphical/FreeBASIC/hello-world-graphical-2.freebasic new file mode 100644 index 0000000000..8d8928073d --- /dev/null +++ b/Task/Hello-world-Graphical/FreeBASIC/hello-world-graphical-2.freebasic @@ -0,0 +1,2 @@ +#INCLUDE "windows.bi" +MessageBox(0, "Goodbye, World!", "Message",0) diff --git a/Task/Hello-world-Graphical/FreeBASIC/hello-world-graphical.freebasic b/Task/Hello-world-Graphical/FreeBASIC/hello-world-graphical.freebasic deleted file mode 100644 index e059003621..0000000000 --- a/Task/Hello-world-Graphical/FreeBASIC/hello-world-graphical.freebasic +++ /dev/null @@ -1,16 +0,0 @@ -'FreeBASIC Hello-fb0.bas May 2015 - -Screen 0 'open text window -Print "Hello world" - -Print "Enter any key to go the graphics screen" -sleep - -screen 18 'Screen 18 Resolution 640x480 with at least 256 colors -locate 10,10 -Print "Hello world!" - -locate 20,10 -Print "Enter any key to exit" -sleep -End diff --git a/Task/Hello-world-Graphical/HolyC/hello-world-graphical-1.holyc b/Task/Hello-world-Graphical/HolyC/hello-world-graphical-1.holyc new file mode 100644 index 0000000000..96f55b793d --- /dev/null +++ b/Task/Hello-world-Graphical/HolyC/hello-world-graphical-1.holyc @@ -0,0 +1 @@ +PopUpOk("Goodbye, World!"); diff --git a/Task/Hello-world-Graphical/HolyC/hello-world-graphical-2.holyc b/Task/Hello-world-Graphical/HolyC/hello-world-graphical-2.holyc new file mode 100644 index 0000000000..6343cb20aa --- /dev/null +++ b/Task/Hello-world-Graphical/HolyC/hello-world-graphical-2.holyc @@ -0,0 +1,6 @@ +link graphics +procedure main() + WOpen("size=100,20") | stop("No window") + WWrites("Goodbye, World!") + WDone() +end diff --git a/Task/Hello-world-Graphical/HolyC/hello-world-graphical-3.holyc b/Task/Hello-world-Graphical/HolyC/hello-world-graphical-3.holyc new file mode 100644 index 0000000000..fce8c59d05 --- /dev/null +++ b/Task/Hello-world-Graphical/HolyC/hello-world-graphical-3.holyc @@ -0,0 +1,21 @@ +import gui +$include "guih.icn" + +class WindowApp : Dialog () + + # -- automatically called when the dialog is created + method component_setup () + # add 'hello world' label + label := Label("label=Hello world","pos=0,0") + add (label) + + # make sure we respond to close event + connect(self, "dispose", CLOSE_BUTTON_EVENT) + end +end + +# create and show the window +procedure main () + w := WindowApp () + w.show_modal () +end diff --git a/Task/Hello-world-Graphical/N-t-roff/hello-world-graphical.n b/Task/Hello-world-Graphical/N-t-roff/hello-world-graphical.n new file mode 100644 index 0000000000..f06c489626 --- /dev/null +++ b/Task/Hello-world-Graphical/N-t-roff/hello-world-graphical.n @@ -0,0 +1 @@ +Goodbye, World! diff --git a/Task/Hello-world-Graphical/PARI-GP/hello-world-graphical.pari b/Task/Hello-world-Graphical/PARI-GP/hello-world-graphical.pari new file mode 100644 index 0000000000..5f856f0cd0 --- /dev/null +++ b/Task/Hello-world-Graphical/PARI-GP/hello-world-graphical.pari @@ -0,0 +1,3 @@ +plotinit(1, 1, 1, 1); +plotstring(1, "Goodbye, World!"); +plotdraw([1, 0, 15]); diff --git a/Task/Hello-world-Graphical/Perl-6/hello-world-graphical.pl6 b/Task/Hello-world-Graphical/Perl-6/hello-world-graphical.pl6 new file mode 100644 index 0000000000..aecee70079 --- /dev/null +++ b/Task/Hello-world-Graphical/Perl-6/hello-world-graphical.pl6 @@ -0,0 +1,7 @@ +use GTK::Simple; +use GTK::Simple::App; + +my GTK::Simple::App $app .= new; +$app.border-width = 20; +$app.set-content( GTK::Simple::Label.new(text => "Goodbye, World!") ); +$app.run; diff --git a/Task/Hello-world-Graphical/Python/hello-world-graphical-7.py b/Task/Hello-world-Graphical/Python/hello-world-graphical-7.py new file mode 100644 index 0000000000..79ee1db36a --- /dev/null +++ b/Task/Hello-world-Graphical/Python/hello-world-graphical-7.py @@ -0,0 +1,20 @@ +from kivy.app import App +from kivy.uix.floatlayout import FloatLayout +from kivy.uix.button import Button +from kivy.uix.popup import Popup +from kivy.uix.label import Label + + +class GoodByeApp(App): + def build(self, *args, **kwargs): + layout = FloatLayout() + ppp = Popup(title='Goodbye, World!', + size_hint=(0.75, 0.75), opacity=0.8, + content=Label(font_size='50sp', text='Goodbye, World!')) + btn = Button(text='Goodbye', size_hint=(0.3, 0.3), + pos_hint={'center': (0.5, 0.5)}, on_press=ppp.open) + layout.add_widget(btn) + return layout + + +GoodByeApp().run() diff --git a/Task/Hello-world-Graphical/Python/hello-world-graphical-8.py b/Task/Hello-world-Graphical/Python/hello-world-graphical-8.py new file mode 100644 index 0000000000..e3e337829e --- /dev/null +++ b/Task/Hello-world-Graphical/Python/hello-world-graphical-8.py @@ -0,0 +1,29 @@ +from kivy.app import App +from kivy.lang.builder import Builder + +kv = ''' +#:import Factory kivy.factory.Factory + +FloatLayout: + Button: + text: 'Goodbye' + size_hint: (0.3, 0.3) + pos_hint: {'center': (0.5, 0.5)} + on_press: Factory.ThePopUp().open() + +: + title: 'Goodbye, World!' + size_hint: (0.75, 0.75) + opacity: 0.8 + Label: + text: 'Goodbye, World!' + font_size: '50sp' +''' + + +class GoodByeApp(App): + def build(self, *args, **kwargs): + return Builder.load_string(kv) + + +GoodByeApp().run() diff --git a/Task/Hello-world-Graphical/Red/hello-world-graphical.red b/Task/Hello-world-Graphical/Red/hello-world-graphical.red new file mode 100644 index 0000000000..0632ec2887 --- /dev/null +++ b/Task/Hello-world-Graphical/Red/hello-world-graphical.red @@ -0,0 +1 @@ +>> view [ text "Hello World !"] diff --git a/Task/Hello-world-Graphical/Visual-Basic-.NET/hello-world-graphical.visual b/Task/Hello-world-Graphical/Visual-Basic-.NET/hello-world-graphical.visual index 50ea284203..8e14f2c32d 100644 --- a/Task/Hello-world-Graphical/Visual-Basic-.NET/hello-world-graphical.visual +++ b/Task/Hello-world-Graphical/Visual-Basic-.NET/hello-world-graphical.visual @@ -1,3 +1,5 @@ +Imports System.Windows.Forms + Module GoodbyeWorld Sub Main() Messagebox.Show("Goodbye, World!") diff --git a/Task/Hello-world-Line-printer/00DESCRIPTION b/Task/Hello-world-Line-printer/00DESCRIPTION index 54563b8b5d..6e0f5fca2a 100644 --- a/Task/Hello-world-Line-printer/00DESCRIPTION +++ b/Task/Hello-world-Line-printer/00DESCRIPTION @@ -1,5 +1,6 @@ {{omit from|PARI/GP}} {{omit from|ML/I|Does not have printer-related functions}} +{{omit from|SQL PL|It does not handle attached devices}} ;Task: Cause a line printer attached to the computer to print a line containing the message:   Hello World! diff --git a/Task/Hello-world-Line-printer/Clojure/hello-world-line-printer.clj b/Task/Hello-world-Line-printer/Clojure/hello-world-line-printer.clj new file mode 100644 index 0000000000..3357467cc5 --- /dev/null +++ b/Task/Hello-world-Line-printer/Clojure/hello-world-line-printer.clj @@ -0,0 +1,6 @@ +(ns rosetta-code.line-printer + (:import java.io.FileWriter)) + +(defn -main [& args] + (with-open [wr (new FileWriter "/dev/lp0")] + (.write wr "Hello, World!"))) diff --git a/Task/Hello-world-Line-printer/N-t-roff/hello-world-line-printer.n b/Task/Hello-world-Line-printer/N-t-roff/hello-world-line-printer.n new file mode 100644 index 0000000000..980a0d5f19 --- /dev/null +++ b/Task/Hello-world-Line-printer/N-t-roff/hello-world-line-printer.n @@ -0,0 +1 @@ +Hello 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 new file mode 100644 index 0000000000..2a8aa89acd --- /dev/null +++ b/Task/Hello-world-Newbie/ARM-Assembly/hello-world-newbie.arm @@ -0,0 +1,19 @@ +/* ARM assembly Raspberry PI */ +/* program helloword.s */ +.data +szMessage: .asciz "Hello world. \n" +.equ LGMESSAGE, . - szMessage @ compute length of message +.text +.global main +main: + 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 + swi 0 +iAdrMessage: .int szMessage +} diff --git a/Task/Hello-world-Newline-omission/Ada/hello-world-newline-omission.ada b/Task/Hello-world-Newline-omission/Ada/hello-world-newline-omission-1.ada similarity index 74% rename from Task/Hello-world-Newline-omission/Ada/hello-world-newline-omission.ada rename to Task/Hello-world-Newline-omission/Ada/hello-world-newline-omission-1.ada index f9221fb6de..e54094a437 100644 --- a/Task/Hello-world-Newline-omission/Ada/hello-world-newline-omission.ada +++ b/Task/Hello-world-Newline-omission/Ada/hello-world-newline-omission-1.ada @@ -1,6 +1,6 @@ with Ada.Text_IO; -procedure Goodbye_World is +procedure Goodbye_World is begin Ada.Text_IO.Put("Goodbye, World!"); end Goodbye_World; diff --git a/Task/Hello-world-Newline-omission/Ada/hello-world-newline-omission-2.ada b/Task/Hello-world-Newline-omission/Ada/hello-world-newline-omission-2.ada new file mode 100644 index 0000000000..d2edd2918d --- /dev/null +++ b/Task/Hello-world-Newline-omission/Ada/hello-world-newline-omission-2.ada @@ -0,0 +1,8 @@ +with Ada.Text_IO; +with Ada.Text_IO.Text_Streams; + +procedure Goodbye_World is + stdout: Ada.Text_IO.File_Type := Ada.Text_IO.Standard_Output; +begin + String'Write(Ada.Text_IO.Text_Streams.Stream(stdout), "Goodbye World"); +end Goodbye_World; diff --git a/Task/Hello-world-Newline-omission/Befunge/hello-world-newline-omission.bf b/Task/Hello-world-Newline-omission/Befunge/hello-world-newline-omission.bf new file mode 100644 index 0000000000..a15672be39 --- /dev/null +++ b/Task/Hello-world-Newline-omission/Befunge/hello-world-newline-omission.bf @@ -0,0 +1 @@ +"!dlroW ,eybdooG">:#,_@ diff --git a/Task/Hello-world-Newline-omission/Elena/hello-world-newline-omission.elena b/Task/Hello-world-Newline-omission/Elena/hello-world-newline-omission.elena new file mode 100644 index 0000000000..ae3f6ad1d4 --- /dev/null +++ b/Task/Hello-world-Newline-omission/Elena/hello-world-newline-omission.elena @@ -0,0 +1,7 @@ +import extensions. + +program = +[ + //print will not append a newline + console print("Goodbye, World!"). +]. diff --git a/Task/Hello-world-Newline-omission/Gambas/hello-world-newline-omission.gambas b/Task/Hello-world-Newline-omission/Gambas/hello-world-newline-omission.gambas new file mode 100644 index 0000000000..9ee7a9b097 --- /dev/null +++ b/Task/Hello-world-Newline-omission/Gambas/hello-world-newline-omission.gambas @@ -0,0 +1,6 @@ +Public Sub Main() + +Print "Goodbye, "; 'The semicolon stops the newline being added +Print "World!" + +End diff --git a/Task/Hello-world-Newline-omission/HolyC/hello-world-newline-omission-1.holyc b/Task/Hello-world-Newline-omission/HolyC/hello-world-newline-omission-1.holyc new file mode 100644 index 0000000000..31bd04972f --- /dev/null +++ b/Task/Hello-world-Newline-omission/HolyC/hello-world-newline-omission-1.holyc @@ -0,0 +1 @@ +"Goodbye, World!"; diff --git a/Task/Hello-world-Newline-omission/HolyC/hello-world-newline-omission-2.holyc b/Task/Hello-world-Newline-omission/HolyC/hello-world-newline-omission-2.holyc new file mode 100644 index 0000000000..95aa6865d2 --- /dev/null +++ b/Task/Hello-world-Newline-omission/HolyC/hello-world-newline-omission-2.holyc @@ -0,0 +1 @@ +write("Goodbye, World!") diff --git a/Task/Hello-world-Newline-omission/Icon/hello-world-newline-omission.icon b/Task/Hello-world-Newline-omission/Icon/hello-world-newline-omission.icon new file mode 100644 index 0000000000..550278b160 --- /dev/null +++ b/Task/Hello-world-Newline-omission/Icon/hello-world-newline-omission.icon @@ -0,0 +1,3 @@ +procedure main() + writes("Goodbye, World!") +end diff --git a/Task/Hello-world-Newline-omission/Modula-2/hello-world-newline-omission.mod2 b/Task/Hello-world-Newline-omission/Modula-2/hello-world-newline-omission.mod2 new file mode 100644 index 0000000000..c6c93f9df3 --- /dev/null +++ b/Task/Hello-world-Newline-omission/Modula-2/hello-world-newline-omission.mod2 @@ -0,0 +1,7 @@ +MODULE HelloWorld; +FROM Terminal IMPORT WriteString,ReadChar; + +BEGIN + WriteString("Goodbye, World!"); + ReadChar +END HelloWorld. diff --git a/Task/Hello-world-Newline-omission/N-t-roff/hello-world-newline-omission.n b/Task/Hello-world-Newline-omission/N-t-roff/hello-world-newline-omission.n new file mode 100644 index 0000000000..f06c489626 --- /dev/null +++ b/Task/Hello-world-Newline-omission/N-t-roff/hello-world-newline-omission.n @@ -0,0 +1 @@ +Goodbye, World! diff --git a/Task/Hello-world-Standard-error/00DESCRIPTION b/Task/Hello-world-Standard-error/00DESCRIPTION index 7586809f79..c26183a00f 100644 --- a/Task/Hello-world-Standard-error/00DESCRIPTION +++ b/Task/Hello-world-Standard-error/00DESCRIPTION @@ -7,6 +7,7 @@ {{omit from|GUISS|Cannot customize error messages}} {{omit from|Integer BASIC}} {{omit from|Jack|No other output stream available.}} +{{omit from|SQL PL|It only prints in standard output. There is no way to print in standard error. Not even with "BEGIN SIGNAL SQLSTATE 'ABCDE' SET MESSAGE_TEXT = 'Hello World!'; END"}} {{omit from|TI-83 BASIC|Same reason as TI-89.}} {{omit from|TI-89 BASIC|no analogue to stderr, unless you count graph display vs. program IO}} {{omit from|Unlambda|No concept of standard error (or alternate output streams in general).}} diff --git a/Task/Hello-world-Standard-error/ARM-Assembly/hello-world-standard-error.arm b/Task/Hello-world-Standard-error/ARM-Assembly/hello-world-standard-error.arm new file mode 100644 index 0000000000..0f817f7232 --- /dev/null +++ b/Task/Hello-world-Standard-error/ARM-Assembly/hello-world-standard-error.arm @@ -0,0 +1,19 @@ +/* ARM assembly Raspberry PI */ +/* program hellowordLP.s */ +.data +szMessage: .asciz "Goodbye world. \n " @ error message +.equ LGMESSAGE, . - szMessage @ compute length of message + +.text +.global main +main: + mov r0, #2 @ output error 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 + swi #0 @ perform the system call +iAdrMessage: .int szMessage diff --git a/Task/Hello-world-Standard-error/N-t-roff/hello-world-standard-error.n b/Task/Hello-world-Standard-error/N-t-roff/hello-world-standard-error.n new file mode 100644 index 0000000000..fc76c1a96e --- /dev/null +++ b/Task/Hello-world-Standard-error/N-t-roff/hello-world-standard-error.n @@ -0,0 +1 @@ +.tm Goodbye, World! diff --git a/Task/Hello-world-Text/6502-Assembly/hello-world-text.6502 b/Task/Hello-world-Text/6502-Assembly/hello-world-text.6502 index 8acfce74bc..b03ae4cf45 100644 --- a/Task/Hello-world-Text/6502-Assembly/hello-world-text.6502 +++ b/Task/Hello-world-Text/6502-Assembly/hello-world-text.6502 @@ -2,8 +2,8 @@ ; String printing limited to strings of 256 characters or less. a_cr = $0d ; Carriage return. -bsout = $ffd2 ; KERNAL ROM, output a character to current device. - +bsout = $ffd2 ; C64 KERNAL ROM, output a character to current device. + ; use $fded for Apple 2 .code ldx #0 ; Starting index 0 in X register. diff --git a/Task/Hello-world-Text/C/hello-world-text-4.c b/Task/Hello-world-Text/C/hello-world-text-4.c new file mode 100644 index 0000000000..1ad413c047 --- /dev/null +++ b/Task/Hello-world-Text/C/hello-world-text-4.c @@ -0,0 +1,6 @@ +#include + +int main() +{ + return printf("\nHello World!"); +} diff --git a/Task/Hello-world-Text/Common-Lisp/hello-world-text-3.lisp b/Task/Hello-world-Text/Common-Lisp/hello-world-text-3.lisp new file mode 100644 index 0000000000..36973866b1 --- /dev/null +++ b/Task/Hello-world-Text/Common-Lisp/hello-world-text-3.lisp @@ -0,0 +1,6 @@ +;; Project : Hello world/Text +;; Date : 2018/03/05 +;; Author : Gal Zsolt [~ CalmoSoft ~] +;; Email : + +(format t "~a" "Hello world!") diff --git a/Task/Hello-world-Text/FreeBASIC/hello-world-text.freebasic b/Task/Hello-world-Text/FreeBASIC/hello-world-text.freebasic index 5c68c94fb3..b0f7782487 100644 --- a/Task/Hello-world-Text/FreeBASIC/hello-world-text.freebasic +++ b/Task/Hello-world-Text/FreeBASIC/hello-world-text.freebasic @@ -1,16 +1,2 @@ -'FreeBASIC Hello-fb0.bas May 2015 -' -Screen 0 'open text window -Print "Hello world" - -Print "Enter any key to go the graphics screen" +? "Hello world!" sleep - -screen 18 'Screen 18 Resolution 640x480 with at least 256 colors -locate 10,10 -Print "Hello world!" - -locate 20,10 -Print "Enter any key to exit" -sleep -End diff --git a/Task/Hello-world-Text/Haskell/hello-world-text.hs b/Task/Hello-world-Text/Haskell/hello-world-text.hs index 1136b1e880..bc88e41bcf 100644 --- a/Task/Hello-world-Text/Haskell/hello-world-text.hs +++ b/Task/Hello-world-Text/Haskell/hello-world-text.hs @@ -1,3 +1 @@ -message :: String -message = "Hello world!" -main = putStrLn message +main = putStrLn "Hello world!" diff --git a/Task/Hello-world-Text/HolyC/hello-world-text.holyc b/Task/Hello-world-Text/HolyC/hello-world-text.holyc new file mode 100644 index 0000000000..8ca2fa083e --- /dev/null +++ b/Task/Hello-world-Text/HolyC/hello-world-text.holyc @@ -0,0 +1 @@ +"Hello world!\n"; diff --git a/Task/Hello-world-Text/N-t-roff/hello-world-text.n b/Task/Hello-world-Text/N-t-roff/hello-world-text.n new file mode 100644 index 0000000000..cd0875583a --- /dev/null +++ b/Task/Hello-world-Text/N-t-roff/hello-world-text.n @@ -0,0 +1 @@ +Hello world! diff --git a/Task/Hello-world-Text/PL-M/hello-world-text.plm b/Task/Hello-world-Text/PL-M/hello-world-text.plm new file mode 100644 index 0000000000..f77a771285 --- /dev/null +++ b/Task/Hello-world-Text/PL-M/hello-world-text.plm @@ -0,0 +1,8 @@ +HELLO_WORLD: DO; + /* external I/O routines */ + WRITE$STRING: PROCEDURE( S ) EXTERNAL; DECLARE S POINTER; END WRITE$STRING; + /* end external routines */ + MAIN: PROCEDURE; + CALL WRITE$STRING( @( 'Hello world!', 0AH, 0 ) ); + END MAIN; +END HELLO_WORLD; diff --git a/Task/Hello-world-Text/Rust/hello-world-text-1.rust b/Task/Hello-world-Text/Rust/hello-world-text-1.rust new file mode 100644 index 0000000000..3b2b467160 --- /dev/null +++ b/Task/Hello-world-Text/Rust/hello-world-text-1.rust @@ -0,0 +1,3 @@ +fn main () { + print!("Hello world!"); +} diff --git a/Task/Hello-world-Text/Rust/hello-world-text.rust b/Task/Hello-world-Text/Rust/hello-world-text-2.rust similarity index 100% rename from Task/Hello-world-Text/Rust/hello-world-text.rust rename to Task/Hello-world-Text/Rust/hello-world-text-2.rust diff --git a/Task/Hello-world-Text/VBScript/hello-world-text.vb b/Task/Hello-world-Text/VBScript/hello-world-text.vb index 9410f92818..8c450e4021 100644 --- a/Task/Hello-world-Text/VBScript/hello-world-text.vb +++ b/Task/Hello-world-Text/VBScript/hello-world-text.vb @@ -1 +1 @@ -WScript.Echo("Hello world!") +WScript.Echo "Hello world!" diff --git a/Task/Hello-world-Text/Visual-Basic-.NET/hello-world-text.visual b/Task/Hello-world-Text/Visual-Basic-.NET/hello-world-text.visual new file mode 100644 index 0000000000..84db28d661 --- /dev/null +++ b/Task/Hello-world-Text/Visual-Basic-.NET/hello-world-text.visual @@ -0,0 +1,7 @@ +Imports System + +Module HelloWorld + Sub Main() + Console.WriteLine("Hello world!") + End Sub +End Module diff --git a/Task/Hello-world-Web-server/00DESCRIPTION b/Task/Hello-world-Web-server/00DESCRIPTION index d905dcdd75..dc4ebf8ad3 100644 --- a/Task/Hello-world-Web-server/00DESCRIPTION +++ b/Task/Hello-world-Web-server/00DESCRIPTION @@ -4,6 +4,7 @@ {{omit from|Maxima}} {{omit from|ML/I|No sockets}} {{omit from|Retro}} +{{omit from|SQL PL|It does not listen any port different to the database server and it does not has daemons - No sockets}} {{omit from|TI-83 BASIC}} {{omit from|ZX Spectrum Basic|No sockets}} diff --git a/Task/Hello-world-Web-server/Aime/hello-world-web-server-1.aime b/Task/Hello-world-Web-server/Aime/hello-world-web-server-1.aime index 0c08ef0519..eaac8720d7 100644 --- a/Task/Hello-world-Web-server/Aime/hello-world-web-server-1.aime +++ b/Task/Hello-world-Web-server/Aime/hello-world-web-server-1.aime @@ -14,8 +14,8 @@ serve(dispatch w, file s, list colors) "

Goodbye, world!

\n"); # chrome won't show the page if we close right away. we'll close in 2s. - d_now(d); - d_offset(d, 2, 0); + d.now; + d.offset(2, 0); w_schedule(w, d, f_close, i); } @@ -27,7 +27,7 @@ main(void) file s; tcpip_listen(s, 8080, 0); - w_watch(w, s, serve, w, s, l_effect("blue", "green", "red", "yellow")); + w_watch(w, s, serve, w, s, list("blue", "green", "red", "yellow")); w_press(w); return 0; diff --git a/Task/Hello-world-Web-server/Crystal/hello-world-web-server.crystal b/Task/Hello-world-Web-server/Crystal/hello-world-web-server.crystal new file mode 100644 index 0000000000..1fe6432eff --- /dev/null +++ b/Task/Hello-world-Web-server/Crystal/hello-world-web-server.crystal @@ -0,0 +1,7 @@ +require "http/server" + +server = HTTP::Server.new(8080) do |context| +context.response.print "Goodbye World" +end + +server.listen diff --git a/Task/Hello-world-Web-server/Perl-6/hello-world-web-server-1.pl6 b/Task/Hello-world-Web-server/Perl-6/hello-world-web-server-1.pl6 new file mode 100644 index 0000000000..3978e76158 --- /dev/null +++ b/Task/Hello-world-Web-server/Perl-6/hello-world-web-server-1.pl6 @@ -0,0 +1,7 @@ +my $listen = IO::Socket::INET.new(:listen, :localhost, :localport(8080)); +loop { + my $conn = $listen.accept; + my $req = $conn.get ; + $conn.print: "HTTP/1.0 200 OK\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\nGoodbye, World!\r\n"; + $conn.close; +} diff --git a/Task/Hello-world-Web-server/Perl-6/hello-world-web-server-2.pl6 b/Task/Hello-world-Web-server/Perl-6/hello-world-web-server-2.pl6 new file mode 100644 index 0000000000..1f6a964c31 --- /dev/null +++ b/Task/Hello-world-Web-server/Perl-6/hello-world-web-server-2.pl6 @@ -0,0 +1,8 @@ +react { + whenever IO::Socket::Async.listen('0.0.0.0', 8080) -> $conn { + whenever $conn.Supply.lines -> $line { + $conn.print: "HTTP/1.0 200 OK\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\nGoodbye, World!\r\n"; + $conn.close; + } + } +} diff --git a/Task/Hello-world-Web-server/Perl-6/hello-world-web-server.pl6 b/Task/Hello-world-Web-server/Perl-6/hello-world-web-server.pl6 deleted file mode 100644 index db4e4993cd..0000000000 --- a/Task/Hello-world-Web-server/Perl-6/hello-world-web-server.pl6 +++ /dev/null @@ -1,6 +0,0 @@ -my $sock = IO::Socket::INET.new(:localhost('0.0.0.0'), :localport(8080), :listen); -say "Goodbye Web Server listening on $sock.localhost():$sock.localport()"; -while $sock.accept -> $client { - $client.send: "HTTP/1.0 200 OK\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\nGoodbye, World!\r\n"; - $client.close; -} diff --git a/Task/Here-document/C/here-document.c b/Task/Here-document/C/here-document.c new file mode 100644 index 0000000000..5f7f2b8837 --- /dev/null +++ b/Task/Here-document/C/here-document.c @@ -0,0 +1,16 @@ +/*Abhishek Ghosh, 7th October 2017*/ + +#include + +int main() +{ + printf("\nThe Heredoc task was marked not implementable in C.\ + \nFrankly the person who did so seems to have little idea of what C\ + is capable of.\n\ + After all, what would one call this multiline printf statement ?\ + I may be old, but do not forget that it all started with me.\ + \n\nEver enigmatic...\n\ + C "); + + return 0; +} diff --git a/Task/Here-document/JavaScript/here-document.js b/Task/Here-document/JavaScript/here-document.js new file mode 100644 index 0000000000..adf1d439ca --- /dev/null +++ b/Task/Here-document/JavaScript/here-document.js @@ -0,0 +1,6 @@ +const myVar = 123; +const tempLit = `Here is some +multi-line string. And here is +the value of "myVar": ${myVar} +That's all.`; +console.log(tempLit) diff --git a/Task/Here-document/Perl-6/here-document-1.pl6 b/Task/Here-document/Perl-6/here-document-1.pl6 index 512fe629d1..d52e1c8826 100644 --- a/Task/Here-document/Perl-6/here-document-1.pl6 +++ b/Task/Here-document/Perl-6/here-document-1.pl6 @@ -1,6 +1,5 @@ my $color = 'green'; - -my $text = qq :to 'END'; +say qq :to 'END'; some line color: $color another line diff --git a/Task/Here-document/Perl-6/here-document-3.pl6 b/Task/Here-document/Perl-6/here-document-3.pl6 index 13b22f4002..c93092450a 100644 --- a/Task/Here-document/Perl-6/here-document-3.pl6 +++ b/Task/Here-document/Perl-6/here-document-3.pl6 @@ -1,7 +1,6 @@ -my $s = Q :array :to 'EOH'; +my @a = <1 2 3 4>; +say Q :array :to 'EOH'; 123 \n '"` @a$bc @a[] EOH - -dd $s; # OUTPUT«Str $var = "123 \\n '\"`\n \@a\$bc\n 1 2 3 4\n"» diff --git a/Task/Here-document/UNIX-Shell/here-document-5.sh b/Task/Here-document/UNIX-Shell/here-document-5.sh index f472e4640a..4346dbe6e0 100644 --- a/Task/Here-document/UNIX-Shell/here-document-5.sh +++ b/Task/Here-document/UNIX-Shell/here-document-5.sh @@ -1,9 +1,8 @@ -#!/bin/csh -f -cat << ANARBITRARYTOKEN - * Your HOME is $HOME - * 2 + 2 is `@ n = 2 + 2; echo \$n` -ANARBITRARYTOKEN - -cat << 'ANARBITRARYTOKEN' -$PATH \$PATH `shutdown now` -'ANARBITRARYTOKEN' +echo ' +In any unix shell, you specify a text block and can use all whitespace like + (spaces) & (tab) in it, by using single quotes. +As mentioned above, a Unix "here document" is a type of redirection. +In a literal Bash here document, the starting token must be +quoted, but the end token must not, so they are not the same, which does not +conform to the task definition. +' diff --git a/Task/Here-document/UNIX-Shell/here-document-6.sh b/Task/Here-document/UNIX-Shell/here-document-6.sh new file mode 100644 index 0000000000..f472e4640a --- /dev/null +++ b/Task/Here-document/UNIX-Shell/here-document-6.sh @@ -0,0 +1,9 @@ +#!/bin/csh -f +cat << ANARBITRARYTOKEN + * Your HOME is $HOME + * 2 + 2 is `@ n = 2 + 2; echo \$n` +ANARBITRARYTOKEN + +cat << 'ANARBITRARYTOKEN' +$PATH \$PATH `shutdown now` +'ANARBITRARYTOKEN' diff --git a/Task/Heronian-triangles/AppleScript/heronian-triangles.applescript b/Task/Heronian-triangles/AppleScript/heronian-triangles.applescript index 20b8803890..822aac3fe2 100644 --- a/Task/Heronian-triangles/AppleScript/heronian-triangles.applescript +++ b/Task/Heronian-triangles/AppleScript/heronian-triangles.applescript @@ -1,13 +1,13 @@ use framework "Foundation" -property ca : current application +-- HERONIAN TRIANGLES -------------------------------------------------------- -- heroniansOfSideUpTo :: Int -> [(Int, Int, Int)] on heroniansOfSideUpTo(n) script sideA - on lambda(a) + on |λ|(a) script sideB - on lambda(b) + on |λ|(b) script sideC -- primitiveHeronian :: Int -> Int -> Int -> Bool on primitiveHeronian(x, y, z) @@ -16,55 +16,51 @@ on heroniansOfSideUpTo(n) isIntegerValue(hArea(x, y, z)) end primitiveHeronian - on lambda(c) + on |λ|(c) if primitiveHeronian(a, b, c) then - [[a, b, c]] + {{a, b, c}} else - [] + {} end if - end lambda + end |λ| end script - concatMap(sideC, range(b, n)) - end lambda + concatMap(sideC, enumFromTo(b, n)) + end |λ| end script - concatMap(sideB, range(a, n)) - end lambda + concatMap(sideB, enumFromTo(a, n)) + end |λ| end script - concatMap(sideA, range(1, n)) + concatMap(sideA, enumFromTo(1, n)) end heroniansOfSideUpTo - --- TEST - +-- TEST ---------------------------------------------------------------------- on run set n to 200 - set lstHeron to sortByKeys(map(triangleDimensions, ¬ - heroniansOfSideUpTo(n)), ¬ - {"area", "perimeter", "maxSide"}) + set lstHeron to ¬ + sortByComparing({{"area", true}, {"perimeter", true}, {"maxSide", true}}, ¬ + map(triangleDimensions, heroniansOfSideUpTo(n))) set lstCols to {"sides", "perimeter", "area"} - set lstColWidths to [20, 15, 0] + set lstColWidths to {20, 15, 0} set area to 210 script areaFilter -- Record -> [Record] - on lambda(recTriangle) + on |λ|(recTriangle) if area of recTriangle = area then - [recTriangle] + {recTriangle} else - [] + {} end if - end lambda + end |λ| end script - intercalate(" - -", {("Number of triangles found (with sides <= 200): " & ¬ + intercalate("\n \n", {("Number of triangles found (with sides <= 200): " & ¬ length of lstHeron as string), ¬ ¬ tabulation("First 10, ordered by area, perimeter, longest side", ¬ @@ -74,8 +70,6 @@ on run concatMap(areaFilter, lstHeron), lstCols, lstColWidths)}) end run - - -- triangleDimensions :: (Int, Int, Int) -> -- {sides: (Int, Int, Int), area: Int, perimeter: Int, maxSize: Int} on triangleDimensions(lstSides) @@ -105,23 +99,23 @@ on gcd(m, n) end gcd --- TABLE FORMATTING +-- TABULATION ---------------------------------------------------------------- -- tabulation :: [Record] -> [String] -> String -> [Integer] -> String on tabulation(strLegend, lstRecords, lstKeys, lstWidths) script heading - on lambda(strTitle, iCol) - set str to toCapitalized(strTitle) - str & nreps(space, (item iCol of lstWidths) - (length of str)) - end lambda + on |λ|(strTitle, iCol) + set str to toTitle(strTitle) + str & replicate((item iCol of lstWidths) - (length of str), space) + end |λ| end script script lineString - on lambda(rec) + on |λ|(rec) script fieldString -- fieldString :: String -> Int -> String - on lambda(strKey, i) - set v to keyValue(rec, strKey) + on |λ|(strKey, i) + set v to keyValue(strKey, rec) if class of v is list then set strData to ("(" & intercalate(", ", v) & ")") @@ -129,12 +123,12 @@ on tabulation(strLegend, lstRecords, lstKeys, lstWidths) set strData to v as string end if - strData & nreps(space, (item i of (lstWidths)) - (length of strData)) - end lambda + strData & replicate(space, (item i of (lstWidths)) - (length of strData)) + end |λ| end script tab & intercalate(tab, map(fieldString, lstKeys)) - end lambda + end |λ| end script strLegend & ":" & linefeed & linefeed & ¬ @@ -143,81 +137,52 @@ on tabulation(strLegend, lstRecords, lstKeys, lstWidths) intercalate(linefeed, map(lineString, lstRecords)) end tabulation --- isIntegerValue :: Num -> Bool -on isIntegerValue(n) - {real, integer} contains class of n and (n = (n as integer)) -end isIntegerValue +-- GENERIC FUNCTIONS --------------------------------------------------------- - --- sortByKeys :: [Record] -> [String] -> [Record] -on sortByKeys(lstRecords, lstKeys) - script keyDescriptor - on lambda(strKey) - ca's NSSortDescriptor's ¬ - sortDescriptorWithKey:(strKey) ascending:true - end lambda - end script - - ((ca's NSArray's arrayWithArray:lstRecords)'s ¬ - sortedArrayUsingDescriptors:(map(keyDescriptor, lstKeys))) as list -end sortByKeys - - --- keyValue :: Record -> String -> a -on keyValue(rec, strKey) - item 1 of ((ca's NSArray's ¬ - arrayWithObject:((ca's NSDictionary's dictionaryWithDictionary:rec)'s ¬ - objectForKey:strKey)) as list) -end keyValue - --- GENERIC FUNCTIONS +-- concat :: [[a]] -> [a] | [String] -> String +on concat(xs) + if length of xs > 0 and class of (item 1 of xs) is string then + set acc to "" + else + set acc to {} + end if + repeat with i from 1 to length of xs + set acc to acc & item i of xs + end repeat + acc +end concat -- concatMap :: (a -> [b]) -> [a] -> [b] on concatMap(f, xs) - script append - on lambda(a, b) - a & b - end lambda - end script - foldl(append, {}, map(f, xs)) + concat(map(f, xs)) end concatMap +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if m > n then + set d to -1 + else + set d to 1 + end if + set lst to {} + repeat with i from m to n by d + set end of lst to i + end repeat + return lst +end enumFromTo + -- foldl :: (a -> b -> a) -> a -> [b] -> a on foldl(f, startValue, xs) tell mReturn(f) set v to startValue set lng to length of xs repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) + set v to |λ|(v, item i of xs, i, xs) end repeat return v end tell end foldl --- map :: (a -> b) -> [a] -> [b] -on map(f, xs) - tell mReturn(f) - set lng to length of xs - set lst to {} - repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) - end repeat - return lst - end tell -end map - --- range :: Int -> Int -> [Int] -on range(m, n) - set d to 1 - if n < m then set d to -1 - set lst to {} - repeat with i from m to n by d - set end of lst to i - end repeat - return lst -end range - - -- intercalate :: Text -> [Text] -> Text on intercalate(strText, lstText) set {dlm, my text item delimiters} to {my text item delimiters, strText} @@ -226,24 +191,33 @@ on intercalate(strText, lstText) return strJoined end intercalate --- Text -> Text -on toCapitalized(str) - ((ca's NSString's stringWithString:(str))'s ¬ - capitalizedStringWithLocale:(ca's NSLocale's currentLocale())) as text -end toCapitalized +-- isIntegerValue :: Num -> Bool +on isIntegerValue(n) + {real, integer} contains class of n and (n = (n as integer)) +end isIntegerValue --- String -> Int -> String -on nreps(s, n) - set o to "" - if n < 1 then return o +-- keyValue :: String -> Record -> Maybe String +on keyValue(strKey, rec) + set ca to current application + set v to (ca's NSDictionary's dictionaryWithDictionary:rec)'s objectForKey:strKey + if v is not missing value then + item 1 of ((ca's NSArray's arrayWithObject:v) as list) + else + missing value + end if +end keyValue - repeat while (n > 1) - if (n mod 2) > 0 then set o to o & s - set n to (n div 2) - set s to (s & s) - end repeat - return o & s -end nreps +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script @@ -252,7 +226,52 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn + +-- replicate :: Int -> String -> String +on replicate(n, s) + set out to "" + if n < 1 then return out + set dbl to s + + repeat while (n > 1) + if (n mod 2) > 0 then set out to out & dbl + set n to (n div 2) + set dbl to (dbl & dbl) + end repeat + return out & dbl +end replicate + +-- List of {strKey, blnAscending} pairs -> list of records -> sorted list of records + +-- sortByComparing :: [(String, Bool)] -> [Records] -> [Records] +on sortByComparing(keyDirections, xs) + set ca to current application + + script recDict + on |λ|(x) + ca's NSDictionary's dictionaryWithDictionary:x + end |λ| + end script + set dcts to map(recDict, xs) + + script asDescriptor + on |λ|(kd) + set {k, d} to kd + ca's NSSortDescriptor's sortDescriptorWithKey:k ascending:d selector:dcts + end |λ| + end script + + ((ca's NSArray's arrayWithArray:dcts)'s ¬ + sortedArrayUsingDescriptors:map(asDescriptor, keyDirections)) as list +end sortByComparing + +-- toTitle :: String -> String +on toTitle(str) + set ca to current application + ((ca's NSString's stringWithString:(str))'s ¬ + capitalizedStringWithLocale:(ca's NSLocale's currentLocale())) as text +end toTitle diff --git a/Task/Heronian-triangles/C/heronian-triangles.c b/Task/Heronian-triangles/C/heronian-triangles.c new file mode 100644 index 0000000000..09f9c0cd06 --- /dev/null +++ b/Task/Heronian-triangles/C/heronian-triangles.c @@ -0,0 +1,122 @@ +/*Abhishek Ghosh, 6th October 2017*/ + +#include +#include +#include + +typedef struct{ + int a,b,c; + int perimeter; + double area; +}triangle; + +typedef struct elem{ + triangle t; + struct elem* next; +}cell; + +typedef cell* list; + +void addAndOrderList(list *a,triangle t){ + list iter,temp; + int flag = 0; + + if(*a==NULL){ + *a = (list)malloc(sizeof(cell)); + (*a)->t = t; + (*a)->next = NULL; + } + + else{ + temp = (list)malloc(sizeof(cell)); + + iter = *a; + while(iter->next!=NULL){ + if(((iter->t.areat.area==t.area && iter->t.perimetert.area==t.area && iter->t.perimeter==t.perimeter && iter->t.a<=t.a)) + && + (iter->next==NULL||(t.areanext->t.area || t.perimeternext->t.perimeter || t.anext->t.a))){ + temp->t = t; + temp->next = iter->next; + iter->next = temp; + flag = 1; + break; + } + + iter = iter->next; + } + + if(flag!=1){ + temp->t = t; + temp->next = NULL; + iter->next = temp; + } + } +} + +int gcd(int a,int b){ + if(b!=0) + return gcd(b,a%b); + return a; +} + +void calculateArea(triangle *t){ + (*t).perimeter = (*t).a + (*t).b + (*t).c; + (*t).area = sqrt(0.5*(*t).perimeter*(0.5*(*t).perimeter - (*t).a)*(0.5*(*t).perimeter - (*t).b)*(0.5*(*t).perimeter - (*t).c)); +} + +list generateTriangleList(int maxSide,int *count){ + int a,b,c; + triangle t; + list herons = NULL; + + *count = 0; + + for(a=1;a<=maxSide;a++){ + for(b=1;b<=a;b++){ + for(c=1;c<=b;c++){ + if(c+b > a && gcd(gcd(a,b),c)==1){ + t = (triangle){a,b,c}; + calculateArea(&t); + if(t.area/(int)t.area == 1){ + addAndOrderList(&herons,t); + (*count)++; + } + } + } + } + } + + return herons; +} + +void printList(list a,int limit,int area){ + list iter = a; + int count = 1; + + printf("\nDimensions\tPerimeter\tArea"); + + while(iter!=NULL && count!=limit+1){ + if(area==-1 ||(area==iter->t.area)){ + printf("\n%d x %d x %d\t%d\t\t%d",iter->t.a,iter->t.b,iter->t.c,iter->t.perimeter,(int)iter->t.area); + count++; + } + iter = iter->next; + } +} + +int main(int argC,char* argV[]) +{ + int count; + list herons = NULL; + + if(argC!=4) + printf("Usage : %s ",argV[0]); + else{ + herons = generateTriangleList(atoi(argV[1]),&count); + printf("Triangles found : %d",count); + (atoi(argV[3])==-1)?printf("\nPrinting first %s triangles.",argV[2]):printf("\nPrinting triangles with area %s square units.",argV[3]); + printList(herons,atoi(argV[2]),atoi(argV[3])); + free(herons); + } + return 0; +} diff --git a/Task/Heronian-triangles/REXX/heronian-triangles-1.rexx b/Task/Heronian-triangles/REXX/heronian-triangles-1.rexx index eb6ab32e13..f968be9cf4 100644 --- a/Task/Heronian-triangles/REXX/heronian-triangles-1.rexx +++ b/Task/Heronian-triangles/REXX/heronian-triangles-1.rexx @@ -1,8 +1,8 @@ /*REXX program generates & displays primitive Heronian triangles by side length and area*/ parse arg N first area . /*obtain optional arguments from the CL*/ -if N=='' | N==',' then N=200 /*Not specified? Then use the default.*/ -if first=='' | first==',' then first= 10 /* " " " " " " */ -if area=='' | area==',' then area=210 /* " " " " " " */ +if N=='' | N=="," then N=200 /*Not specified? Then use the default.*/ +if first=='' | first=="," then first= 10 /* " " " " " " */ +if area=='' | area=="," then area=210 /* " " " " " " */ numeric digits 99; numeric digits max(9, 1+length(N**5)) /*ensure 'nuff decimal digits.*/ call Heron; HT= 'Heronian triangles' /*invoke the Heron subroutine. */ say # ' primitive' HT "found with sides up to " N ' (inclusive).' diff --git a/Task/Heronian-triangles/REXX/heronian-triangles-2.rexx b/Task/Heronian-triangles/REXX/heronian-triangles-2.rexx index 627b0ec4bc..6a045afd0e 100644 --- a/Task/Heronian-triangles/REXX/heronian-triangles-2.rexx +++ b/Task/Heronian-triangles/REXX/heronian-triangles-2.rexx @@ -1,32 +1,32 @@ /*REXX program generates & displays primitive Heronian triangles by side length and area*/ parse arg N first area . /*obtain optional arguments from the CL*/ -if N=='' | N==',' then N=200 /*Not specified? Then use the default.*/ -if first=='' | first==',' then first= 10 /* " " " " " " */ -if area=='' | area==',' then area=210 /* " " " " " " */ +if N=='' | N=="," then N=200 /*Not specified? Then use the default.*/ +if first=='' | first=="," then first= 10 /* " " " " " " */ +if area=='' | area=="," then area=210 /* " " " " " " */ numeric digits 99; numeric digits max(9, 1+length(N**5)) /*ensure 'nuff decimal digits.*/ call Heron; HT= 'Heronian triangles' /*invoke the Heron subroutine. */ -say # ' primitive' HT "found with sides up to " N ' (inclusive).' -call show , 'Listing of the first ' first ' primitive' HT":" +say # ' primitive' HT "found with sides up to " N ' (inclusive).' +call show , 'Listing of the first ' first ' primitive' HT":" call show area, 'Listing of the (above) found primitive' HT "with an area of " area exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ Heron: @.=0; #=0; !.=.; minP=9e9; maxA=0; maxP=0; minA=9e9; Ln=length(N) /* __ */ - do i=5 to N**2%2; _=i*i; !._=i; end /*pre-calculate a fast √ */ + do i=5 to N**2%2; _=i*i; !._=i; end /*pre-calculate a fast √ */ do a=3 to N /*start at a minimum side length of 3. */ - even= a//2==0 /*if A is even, B and C must be odd.*/ - do b=a+even to N by 1+even; ab=a+b /*AB: is a shortcut sum. */ + even= (a//2==0) /*if A is even, B and C must be odd.*/ + do b=a+even to N by 1+even; ab=a + b /*AB: is a shortcut sum. */ if b//2==0 then bump=1 /*B is even? Then C is odd. */ else if even then bump=0 /*A is even? " " " " */ else bump=1 /*A & B odd, biz as usual. */ - do c=b+bump to N by 2; s=(ab+c)%2 /*calculate perimeter: S. */ + do c=b+bump to N by 2; s=(ab + c) % 2 /*calculate perimeter: S. */ _=s*(s-a)*(s-b)*(s-c); if !._==. then iterate /*Is _ not a square? Skip.*/ ar=!._; if ar*ar\==_ then iterate /*Area not an integer? Skip.*/ - if hGCD(a,b,c)\==1 then iterate /*GCD of sides not 1? Skip.*/ - #=#+1; p=ab+c /*primitive Heronian triangle*/ - minP=min( p,minP); maxP=max( p,maxP); Lp=length(maxP) - minA=min(ar,minA); maxA=max(ar,maxA); La=length(maxA); @.ar= - _=@.ar.p.0+1 /*bump the triangle counter.*/ - @.ar.p.0=_; @.ar.p._=right(a,Ln) right(b,Ln) right(c,Ln) /*unique.*/ + if hGCD(a,b,c) \== 1 then iterate /*GCD of sides not 1? Skip.*/ + #=# + 1; p=ab + c /*primitive Heronian triangle*/ + minP=min( p, minP); maxP=max( p, maxP); Lp=length(maxP) + minA=min(ar, minA); maxA=max(ar, maxA); La=length(maxA); @.ar= + _=@.ar.p.0 + 1 /*bump the triangle counter. */ + @.ar.p.0=_; @.ar.p._=right(a, Ln) right(b, Ln) right(c, Ln) /*unique.*/ end /*c*/ /* [↑] keep each unique perimeter #. */ end /*b*/ end /*a*/ @@ -43,3 +43,4 @@ show: m=0; say; say; parse arg ae; say arg(2); if ae\=='' then end /*k*/ end /*j*/ /* [↑] use the known perimeters. */ end /*i*/ /* [↑] show any found triangles. */ + return diff --git a/Task/Heronian-triangles/Ring/heronian-triangles.ring b/Task/Heronian-triangles/Ring/heronian-triangles.ring new file mode 100644 index 0000000000..5d53faa367 --- /dev/null +++ b/Task/Heronian-triangles/Ring/heronian-triangles.ring @@ -0,0 +1,43 @@ +# Project : Heronian triangles +# Date : 2017/11/04 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +see "Heronian triangles with sides up to 200" + nl +see "Sides Perimeter Area" + nl +for n = 1 to 200 + for m = n to 200 + for p = m to 200 + s = (n + m + p) / 2 + w = sqrt(s * (s - n) * (s - m) * (s - p)) + bool = (gcd(n, m) = 1 or gcd(n, m) = n) and (gcd(n, p) = 1 or gcd(n, p) = n) and (gcd(m, p) = 1 or gcd(m, p) = m) + if w = floor(w) and w > 0 and bool + see "{" + n + ", " + m + ", " + p + "}" + " " + s*2 + " " + w + nl + ok + next + next +next +see nl + +see "Heronian triangles with area 210:" + nl +see "Sides Perimeter Area" + nl +for n = 1 to 150 + for m = n to 150 + for p = m to 150 + s = (n + m + p) / 2 + w = sqrt(s * (s - n) * (s - m) * (s - p)) + bool = (gcd(n, m) = 1 or gcd(n, m) = n) and (gcd(n, p) = 1 or gcd(n, p) = n) and (gcd(m, p) = 1 or gcd(m, p) = m) + if w = 210 and bool + see "{" + n + ", " + m + ", " + p + "}" + " " + s*2 + " " + w + nl + ok + next + next +next + +func gcd(gcd, b) + while b + c = gcd + gcd = b + b = c % b + end + return gcd diff --git a/Task/Hickerson-series-of-almost-integers/Scala/hickerson-series-of-almost-integers.scala b/Task/Hickerson-series-of-almost-integers/Scala/hickerson-series-of-almost-integers.scala new file mode 100644 index 0000000000..acbf758e61 --- /dev/null +++ b/Task/Hickerson-series-of-almost-integers/Scala/hickerson-series-of-almost-integers.scala @@ -0,0 +1,26 @@ +import scala.annotation.tailrec + +object Hickerson extends App { + + def almostInteger(n: Int): Boolean = { + def ln2 = BigDecimal("0.69314718055994530941723212145818") + + def div: BigDecimal = ln2.pow(n + 1) * 2 + + def factorial(num: Int): Long = { + @tailrec + def accumulated(acc: Long, n: Long): Long = + if (n <= 0) acc else accumulated(acc * n, n - 1) + + accumulated(1, num) + } + + ((BigDecimal(factorial(n)) / div * 10).toBigInt() % 10).toString.matches("0|9") + } + + val aa = (1 to 17).map(n => n -> almostInteger(n)) + + println(s"Function h(n) gives a almost integer with a n of ${aa.filter(_._2).map(_._1).mkString(", ")}.") + println(s"While h(n) gives NOT an almost integer with a n of ${aa.filter(!_._2).map(_._1).mkString(", ")}.") + +} diff --git a/Task/Higher-order-functions/Elena/higher-order-functions.elena b/Task/Higher-order-functions/Elena/higher-order-functions.elena new file mode 100644 index 0000000000..294120b091 --- /dev/null +++ b/Task/Higher-order-functions/Elena/higher-order-functions.elena @@ -0,0 +1,8 @@ +import extensions. + +program = +[ + var first := (:f)(f()). + var second := [ ^ "second" ]. + console printLine(first(second)). +]. diff --git a/Task/Higher-order-functions/Lingo/higher-order-functions-1.lingo b/Task/Higher-order-functions/Lingo/higher-order-functions-1.lingo index 6cec99fba1..e171a10865 100644 --- a/Task/Higher-order-functions/Lingo/higher-order-functions-1.lingo +++ b/Task/Higher-order-functions/Lingo/higher-order-functions-1.lingo @@ -1,17 +1,17 @@ -- in some movie script ---------------------------------------- --- Runs provided function on all elements of the provided list, returns results as new list --- @param {list} tList +-- Runs provided function (of some object) on all elements of the provided list, returns results as new list +-- @param {list} aList -- @param {symbol} cbFunc -- @param {object} [cbObj=_movie] -- @return {list} ---------------------------------------- -on map (tList, cbFunc, cbObj) +on map (aList, cbFunc, cbObj) if voidP(cbObj) then cbObj = _movie res = [] - cnt = tList.count + cnt = aList.count repeat with i = 1 to cnt - res[i] = call(cbFunc, cbObj, tList[i]) + res[i] = call(cbFunc, cbObj, aList[i]) end repeat return res end diff --git a/Task/Higher-order-functions/Ring/higher-order-functions.ring b/Task/Higher-order-functions/Ring/higher-order-functions.ring new file mode 100644 index 0000000000..69022e5e07 --- /dev/null +++ b/Task/Higher-order-functions/Ring/higher-order-functions.ring @@ -0,0 +1,21 @@ +# Project : Higher-order functions +# Date : 2018/04/03 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +docalcs(1,10,"squares",:square) +docalcs(1,10,"cubes",:cube) + +func square(n) + return n * n + +func cube(n) + return n * n * n + +func docalcs(from2,upto,title,func2) + see title + " -> " + nl + for i = from2 to upto + x = call func2(i) + see x + nl + next + see nl diff --git a/Task/History-variables/Elena/history-variables.elena b/Task/History-variables/Elena/history-variables.elena new file mode 100644 index 0000000000..06d9fc2751 --- /dev/null +++ b/Task/History-variables/Elena/history-variables.elena @@ -0,0 +1,51 @@ +import extensions. +import system'collections. +import system'routines. +import extensions'routines. + +class HistoryVariable +{ + object prop Value :: _value. + stack _previous := Stack new. + + set Value:v + [ + if ($nil != _value) + [ + _previous push(_value) + ]. + + _value := v + ] + + undo + [ + ifnot (_previous isEmpty) + [ + _value := _previous pop + ]; + [ + _value := $nil + ] + ] + + enumerator => _previous. + + dispatch => _value. +} + +program = +[ + var o := HistoryVariable new. + o Value := 5. + o Value := "foo". + o Value := o Value + "bar". + + console printLine(o). + + o forEach:printingLn. + + o undo; undo; undo. + + console printLine(o Value). +]. diff --git a/Task/History-variables/Java/history-variables-1.java b/Task/History-variables/Java/history-variables-1.java new file mode 100644 index 0000000000..5c5769a462 --- /dev/null +++ b/Task/History-variables/Java/history-variables-1.java @@ -0,0 +1,73 @@ +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +/** + * A class for an "Integer with a history". + *

+ * Note that it is not possible to create an empty Variable (so there is no "null") with this type. This is a design + * choice, because if "empty" variables were allowed, reading of empty variables must return a value. Null is a + * bad idea, and Java 8's Optional (which is somewhat like the the official fix for the null-bad-idea) would + * make things more complicated than an example should be. + */ +public class IntegerWithHistory { + + /** + * The "storage Backend" is a list of all values that have been ever assigned to this variable. The List is + * populated front to back, so a new value is inserted at the start (position 0), and older values move toward the end. + */ + private final List history; + + /** + * Creates this variable and assigns the initial value + * + * @param value initial value + */ + public IntegerWithHistory(Integer value) { + history = new LinkedList<>(); + history.add(value); + } + + /** + * Sets a new value, pushing the older ones back in the history + * + * @param value the new value to be assigned + */ + public void set(Integer value) { + //History is populated from the front to the back, so the freshest value is stored a position 0 + history.add(0, value); + } + + /** + * Gets the current value. Since history is populuated front to back, the current value is the first element + * of the history. + * + * @return the current value + */ + public Integer get() { + return history.get(0); + } + + /** + * Gets the entire history all values that have been assigned to this variable. + * + * @return a List of all values, including the current one, ordered new to old + */ + public List getHistory() { + return Collections.unmodifiableList(this.history); + } + + /** + * Rolls back the history one step, so the current value is removed from the history and replaced by it's predecessor. + * This is a destructive operation! It is not possible to rollback() beyond the initial value! + * + * @return the value that had been the current value until history was rolled back. + */ + public Integer rollback() { + if (history.size() > 1) { + return history.remove(0); + } else { + return history.get(0); + } + } +} diff --git a/Task/History-variables/Java/history-variables-2.java b/Task/History-variables/Java/history-variables-2.java new file mode 100644 index 0000000000..e6d02d1c4b --- /dev/null +++ b/Task/History-variables/Java/history-variables-2.java @@ -0,0 +1,25 @@ +public class TestIntegerWithHistory { + + public static void main(String[] args) { + + //creating and setting three different values + IntegerWithHistory i = new IntegerWithHistory(3); + i.set(42); + i.set(7); + + //looking at current value and history + System.out.println("The current value of i is :" + i.get()); + System.out.println("The history of i is :" + i.getHistory()); + + //demonstrating rollback + System.out.println("Rolling back:"); + System.out.println("returns what was the current value: " + i.rollback()); + System.out.println("after rollback: " + i.get()); + System.out.println("returns what was the current value: " + i.rollback()); + System.out.println("after rollback: " + i.get()); + System.out.println("Rolling back only works to the original value: " + i.rollback()); + System.out.println("Rolling back only works to the original value: " + i.rollback()); + System.out.println("So there is no way to 'null' the variable: " + i.get()); + + } +} diff --git a/Task/History-variables/Java/history-variables-3.java b/Task/History-variables/Java/history-variables-3.java new file mode 100644 index 0000000000..e69de29bb2 diff --git a/Task/History-variables/Java/history-variables-4.java b/Task/History-variables/Java/history-variables-4.java new file mode 100644 index 0000000000..62bccf699d --- /dev/null +++ b/Task/History-variables/Java/history-variables-4.java @@ -0,0 +1,76 @@ +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +/** + * A Generic class for an "Anything with a history". + *

+ * Note that it is not possible to create an empty Variable (so there is no "null") with this type. This is a design + * choice, because if "empty" variables were allowed, reading of empty variables must return a value. Null is a + * bad idea, and Java 8's Optional (which is somewhat like the the official fix for the null-bad-idea) would + * make things more complicated than an example should be. + *

+ * Also note that this "really works" only with constant Ts. If somebody keeps a reference to an assigned value, + * and is able to modify the state of this value through the reference , this will not be reflected in the history! + */ +public class WithHistory { + + /** + * The "storage Backend" is a list of all values that have been ever assigned to this variable. The List is + * populated front to back, so a new value is inserted at the start (position 0), and older values move toward the end. + */ + private final List history; + + /** + * Creates this variable and assigns the initial value + * + * @param value initial value + */ + public WithHistory(T value) { + history = new LinkedList<>(); + history.add(value); + } + + /** + * Sets a new value, pushing the older ones back in the history + * + * @param value the new value to be assigned + */ + public void set(T value) { + //History is populated from the front to the back, so the freshest value is stored a position 0 + history.add(0, value); + } + + /** + * Gets the current value. Since history is populuated front to back, the current value is the first element + * of the history. + * + * @return the current value + */ + public T get() { + return history.get(0); + } + + /** + * Gets the entire history all values that have been assigned to this variable. + * + * @return a List of all values, including the current one, ordered new to old + */ + public List getHistory() { + return Collections.unmodifiableList(this.history); + } + + /** + * Rolls back the history one step, so the current value is removed from the history and replaced by it's predecessor. + * This is a destructive operation! It is not possible to rollback() beyond the initial value! + * + * @return the value that had been the cueent value until history was rolled back. + */ + public T rollback() { + if (history.size() > 1) { + return history.remove(0); + } else { + return history.get(0); + } + } +} diff --git a/Task/History-variables/Perl-6/history-variables.pl6 b/Task/History-variables/Perl-6/history-variables.pl6 index 86a52fbac5..a3b8cb67f3 100644 --- a/Task/History-variables/Perl-6/history-variables.pl6 +++ b/Task/History-variables/Perl-6/history-variables.pl6 @@ -7,12 +7,12 @@ class HistoryVar { } } -my $foo := HistoryVar.new; +my \foo = HistoryVar.new; -$foo = 1; -$foo = 2; -$foo += 3; -$foo = 42; +foo = 1; +foo = 2; +foo += 3; +foo = 42; -.say for $foo.history; -say "Current value: $foo"; +.say for foo.history; +say "Current value: {foo}"; diff --git a/Task/Hofstadter-Figure-Figure-sequences/Perl-6/hofstadter-figure-figure-sequences.pl6 b/Task/Hofstadter-Figure-Figure-sequences/Perl-6/hofstadter-figure-figure-sequences.pl6 index ae220c1ef9..76704879ad 100644 --- a/Task/Hofstadter-Figure-Figure-sequences/Perl-6/hofstadter-figure-figure-sequences.pl6 +++ b/Task/Hofstadter-Figure-Figure-sequences/Perl-6/hofstadter-figure-figure-sequences.pl6 @@ -1,9 +1,11 @@ -my @ffr; -my @ffs; +my %r = 1 => 1; +my %s = 1 => 2; -@ffr.plan: 0, 1, gather take @ffr[$_] + @ffs[$_] for 1..*; -@ffs.plan: 0, 2, 4..6, gather take @ffr[$_] ^..^ @ffr[$_+1] for 3..*; +sub ffr ($n) { %r{$n} //= ffr($n - 1) + ffs($n - 1) } +sub ffs ($n) { %s{$n} //= (grep none(map &ffr, 1..$n), max(%s.values)+1..*)[0] } -say @ffr[1..10]; +my @ffr = map &ffr, 1..*; +my @ffs = map &ffs, 1..*; -say "Rawks!" if (1...1000) eqv sort @ffr[1..40], @ffs[1..960]; +say @ffr[^10]; +say "Rawks!" if 1...1000 eqv sort |@ffr[^40], |@ffs[^960]; diff --git a/Task/Hofstadter-Figure-Figure-sequences/Ring/hofstadter-figure-figure-sequences.ring b/Task/Hofstadter-Figure-Figure-sequences/Ring/hofstadter-figure-figure-sequences.ring new file mode 100644 index 0000000000..c6ca5c6eca --- /dev/null +++ b/Task/Hofstadter-Figure-Figure-sequences/Ring/hofstadter-figure-figure-sequences.ring @@ -0,0 +1,33 @@ +# Project : Hofstadter Figure-Figure sequences +# Date : 2018/01/17 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +hofr = list(20) +hofr[1] = 1 +hofs = [] +add(hofs,2) +for n = 1 to 10 + hofr[n+1] = hofr[n] + hofs[n] + if n = 1 + add(hofs,4) + else + for p = hofr[n] + 1 to hofr[n+1] - 1 + if p != hofs[n] + add(hofs,p) + ok + next + ok +next +see "First 10 values of R:" + nl +showarray(hofr) +see "First 10 values of S:" + nl +showarray(hofs) + +func showarray(vect) + svect = "" + for n = 1 to 10 + svect = svect + vect[n] + " " + next + svect = left(svect, len(svect) - 1) + see svect + nl diff --git a/Task/Hofstadter-Q-sequence/Julia/hofstadter-q-sequence-1.julia b/Task/Hofstadter-Q-sequence/Julia/hofstadter-q-sequence-1.julia index 133f815e15..2cccdf2e00 100644 --- a/Task/Hofstadter-Q-sequence/Julia/hofstadter-q-sequence-1.julia +++ b/Task/Hofstadter-Q-sequence/Julia/hofstadter-q-sequence-1.julia @@ -1,9 +1,13 @@ -function Q(n) - N = maximum(n) - q = Array(Int, N) - q[1], q[2] = 1, 1 - for i = 3:N - q[i] = q[i - q[i-1]] + q[i - q[i-2]] - end - return q[n] +function hofstQseq(n, typerst::Type=Int) + nmax = maximum(n) + r = Vector{typerst}(nmax) + r[1] = 1 + if nmax ≥ 2 r[2] = 1 end + for i in 3:nmax + r[i] = r[i - r[i - 1]] + r[i - r[i - 2]] + end + return r[n] end + +println("First ten elements of sequence: ", join(hofstQseq(1:10), ", ")) +println("1000-th element: ", hofstQseq(1000)) diff --git a/Task/Hofstadter-Q-sequence/Julia/hofstadter-q-sequence-2.julia b/Task/Hofstadter-Q-sequence/Julia/hofstadter-q-sequence-2.julia index 6ffefe879d..42361100e1 100644 --- a/Task/Hofstadter-Q-sequence/Julia/hofstadter-q-sequence-2.julia +++ b/Task/Hofstadter-Q-sequence/Julia/hofstadter-q-sequence-2.julia @@ -1,15 +1,3 @@ -julia> Q(1:10) -10-element Array{Int64,1}: - 1 - 1 - 2 - 3 - 3 - 4 - 5 - 5 - 6 - 6 - -julia> Q(1000) -502 +seq = hofstQseq(1:100_000) +cnt = count(diff(seq) .< 0) +println("$cnt elements are less than the preceding one.") diff --git a/Task/Hofstadter-Q-sequence/Perl-6/hofstadter-q-sequence-1.pl6 b/Task/Hofstadter-Q-sequence/Perl-6/hofstadter-q-sequence-1.pl6 index f35880a520..54fb84b1e5 100644 --- a/Task/Hofstadter-Q-sequence/Perl-6/hofstadter-q-sequence-1.pl6 +++ b/Task/Hofstadter-Q-sequence/Perl-6/hofstadter-q-sequence-1.pl6 @@ -6,3 +6,14 @@ class Hofstadter { return @!c[$i]; } } + +# Testing: + +my Hofstadter $Q .= new(); + +say "first ten: $Q[^10]"; +say "1000th: $Q[999]"; + +my $count = 0; +$count++ if $Q[$_ +1 ] < $Q[$_] for ^99_999; +say "In the first 100_000 terms, $count terms are less than their preceding terms"; diff --git a/Task/Hofstadter-Q-sequence/Perl-6/hofstadter-q-sequence-2.pl6 b/Task/Hofstadter-Q-sequence/Perl-6/hofstadter-q-sequence-2.pl6 index 9465665abb..f4a9827e7f 100644 --- a/Task/Hofstadter-Q-sequence/Perl-6/hofstadter-q-sequence-2.pl6 +++ b/Task/Hofstadter-Q-sequence/Perl-6/hofstadter-q-sequence-2.pl6 @@ -1,8 +1,12 @@ -my Hofstadter $Q .= new(); +my @Q = 1, 1, -> $a, $b { + (state $n = 1)++; + @Q[$n - $a] + @Q[$n - $b] +} ... *; -say "first ten: $Q[^10]"; -say "1000th: $Q[999]"; +# Testing: -my $count = 0; -$count++ if $Q[$_ +1 ] < $Q[$_] for ^99_999; -say "In the first 100_000 terms, $count terms are less than their preceding terms"; +say "first ten: ", @Q[^10]; +say "1000th: ", @Q[999]; +say "In the first 100_000 terms, ", + [+](@Q[1..100000] Z< @Q[0..99999]), + " terms are less than their preceding terms"; diff --git a/Task/Horizontal-sundial-calculations/GW-BASIC/horizontal-sundial-calculations.gw-basic b/Task/Horizontal-sundial-calculations/GW-BASIC/horizontal-sundial-calculations.gw-basic new file mode 100644 index 0000000000..a777896fd5 --- /dev/null +++ b/Task/Horizontal-sundial-calculations/GW-BASIC/horizontal-sundial-calculations.gw-basic @@ -0,0 +1,23 @@ +10 ' Horizontal sundial calculations +20 PRINT "Enter latitude => "; +30 INPUT LAT +40 PRINT "Enter longitude => "; +50 INPUT LNG +60 PRINT "Enter legal meridian => "; +70 INPUT REF +80 PRINT +90 LET PI = 4 * ATN(1) +100 LET SLAT = SIN(LAT * PI / 180) +110 PRINT " sine of latitude: "; USING "#.##^^^^"; SLAT +120 PRINT " diff longitude: "; USING "####.###"; LNG - REF +130 PRINT +140 PRINT "Hour, sun hour angle, dial hour line angle from 6am to 6pm" +150 FOR H% = -6 TO 6 +160 LET HRA = 15 * H% +170 LET HRA = HRA - (LNG - REF): ' correct for longitude difference +180 LET HLA = ATN(SLAT * TAN(HRA * PI / 180)) * 180 / PI +190 PRINT "HR="; USING "+##"; H%; +200 PRINT "; HRA="; USING "+###.###"; HRA; +210 PRINT "; HLA="; USING "+###.###"; HLA +220 NEXT H% +230 END diff --git a/Task/Horizontal-sundial-calculations/Modula-2/horizontal-sundial-calculations.mod2 b/Task/Horizontal-sundial-calculations/Modula-2/horizontal-sundial-calculations.mod2 new file mode 100644 index 0000000000..7cb525f1f9 --- /dev/null +++ b/Task/Horizontal-sundial-calculations/Modula-2/horizontal-sundial-calculations.mod2 @@ -0,0 +1,49 @@ +MODULE SunDial; + +FROM STextIO IMPORT + WriteString, WriteLn, SkipLine; +FROM SRealIO IMPORT + ReadReal, WriteFixed, WriteFloat; +FROM SWholeIO IMPORT + WriteInt; +FROM RealMath IMPORT + sin, pi, arctan, tan; + +VAR + Lat, Slat, Lng, Ref: REAL; + Hour: INTEGER; + HourAngle, HourLineAngle: REAL; +BEGIN + WriteString("Enter latitude => "); + ReadReal(Lat); + SkipLine; + WriteString("Enter longitude => "); + ReadReal(Lng); + SkipLine; + WriteString("Enter legal meridian => "); + ReadReal(Ref); + SkipLine; + WriteLn; + Slat := sin(Lat * pi / 180.0); + WriteString(" sine of latitude: "); + WriteFloat(Slat, 2, 8); + WriteLn; + WriteString(" diff longitude: "); + WriteFixed(Lng - Ref, 3, 1); + WriteLn; + WriteLn; + WriteString("Hour, sun hour angle, dial hour line angle from 6am to 6pm"); + WriteLn; + FOR Hour := -6 TO 6 DO + HourAngle := FLOAT(15 * Hour); + HourAngle := HourAngle - (Lng - Ref); (* correct for longitude difference *) + HourLineAngle := arctan(Slat * tan(HourAngle * pi / 180.0)) * 180.0 / pi; + WriteString("HR="); + WriteInt(Hour, 3); + WriteString("; HRA="); + WriteFixed(HourAngle, 3, 8); + WriteString("; HLA="); + WriteFixed(HourLineAngle, 3, 8); + WriteLn; + END; +END SunDial. diff --git a/Task/Horizontal-sundial-calculations/REXX/horizontal-sundial-calculations.rexx b/Task/Horizontal-sundial-calculations/REXX/horizontal-sundial-calculations.rexx index 87580aa0a7..25f0c0d63b 100644 --- a/Task/Horizontal-sundial-calculations/REXX/horizontal-sundial-calculations.rexx +++ b/Task/Horizontal-sundial-calculations/REXX/horizontal-sundial-calculations.rexx @@ -3,7 +3,7 @@ numeric digits 60 /*in case sundial is in polar r parse arg lat lng . /*obtain optional arguments from the CL*/ /* ┌───────────◄ None specified? Then use the default*/ /* │ of Jules Verne's Lincoln Island, */ - /* ↓ aka Ernest Legouve Reed. */ + /* ↓ aka Ernest Legouve Reef. */ if lat=='' | lat=="," then lat= -4.95 /*Not specified? Then use the default.*/ if lng=='' | lng=="," then lng= -150.5 /* " " " " " " */ mer=format(lng/15, , 0) * 15 /*calculate legal meridian longitude. */ @@ -18,7 +18,7 @@ L=max(length(lat), length(lng), length(mer) ) /*find maximum length of three indent=left('', 30) /*make prettier: indented presentation.*/ say indent center(' ', w1) center("sun hour", w2) center('dial hour' , w3) say indent center('hour', w1) center("angle" , w2) center('line angle', w3) -call sep /*to help a one-eyed pirate's eyeball. */ +call sep /*to help a one─eyed pirate's eyeball. */ do h=-6 to 6 /*Okey dokey then, now let's show stuff*/ select when abs(h)==12 then hc='midnight' /*Holy smokes! Above the arctic circle.*/ @@ -28,9 +28,10 @@ call sep /*to help a one-eyed pirate's e end /*select*/ hra=15 * h - lng + mer /*calculate sun hour angle (in degrees)*/ hla=r2d( Atan(sineLat * tan( d2r(hra)))) /*this is the heavy lifting calculation*/ + if abs(hra)>90 then hla=hla + 180*sign(hra*lat) /*adjust for negative angle. */ say indent center(hc, w1) right(format(hra, ,1), w2) right(format(hla, ,1), w3) end /*h*/ -call sep /*to help a one-eyed pirate's eyeball. */ +call sep /*to help a one─eyed pirate's eyeball. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ pi: pi= 3.1415926535897932384626433832795028841971693993751058209749445923078; return pi @@ -48,7 +49,7 @@ Acos: procedure; arg x; if x<-1 | x>1 then call AcosErr; return .5 * pi() Atan: procedure; parse arg x; if abs(x)=1 then return pi()/4*x; return Asin(x/sqrt(1+x*x)) /*──────────────────────────────────────────────────────────────────────────────────────*/ Asin: procedure; parse arg x; if x<-1 | x>1 then call AsinErr; s=x*x - if abs(x)>=sqrt(2)*.4 then return sign(x) * Acos(sqrt(1-s)); z=x; o=x; p=z + if abs(x)>=sqrt(2)*.5 then return sign(x) * Acos(sqrt(1-s)); z=x; o=x; p=z do j=2 by 2; o=o*s*(j-1)/j; z=z+o/(j+1); if z=p then leave; p=z; end; return z /*──────────────────────────────────────────────────────────────────────────────────────*/ sin: procedure; parse arg x; x=r2r(x); numeric fuzz min(5, digits() - 3) diff --git a/Task/Horizontal-sundial-calculations/Ring/horizontal-sundial-calculations.ring b/Task/Horizontal-sundial-calculations/Ring/horizontal-sundial-calculations.ring new file mode 100644 index 0000000000..e6f62908f0 --- /dev/null +++ b/Task/Horizontal-sundial-calculations/Ring/horizontal-sundial-calculations.ring @@ -0,0 +1,27 @@ +# Project : Horizontal sundial calculations +# Date : 2017/10/24 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +load "stdlib.ring" +pi = 22/7 +decimals(3) + +latitude = -4.95 +longitude = -150.5 +meridian = -150.0 + +see "enter latitude (degrees): " + latitude + nl +see "enter longitude (degrees): " + longitude + nl +see "enter legal meridian (degrees): " + meridian + nl + +see "time " + " sun hour angle" + " dial hour line angle" + nl + +for hour = 6 to 18 + hra = 15*hour - longitude + meridian - 180 + hla = 180/pi*(atan(sin(pi/180*latitude) * tan(pi/180*hra))) + if fabs(hra) > 90 + hla = hla + 180 * sign(hra * latitude) + ok + see "" + hour + " " + hra + " " + hla + nl +next diff --git a/Task/Horners-rule-for-polynomial-evaluation/Aime/horners-rule-for-polynomial-evaluation.aime b/Task/Horners-rule-for-polynomial-evaluation/Aime/horners-rule-for-polynomial-evaluation.aime index c681fcbd7c..a515810ee3 100644 --- a/Task/Horners-rule-for-polynomial-evaluation/Aime/horners-rule-for-polynomial-evaluation.aime +++ b/Task/Horners-rule-for-polynomial-evaluation/Aime/horners-rule-for-polynomial-evaluation.aime @@ -1,26 +1,23 @@ real horner(list coeffs, real x) { - integer i; - real z; + real c, z; z = 0; - i = l_length(coeffs); - while (i) { - i -= 1; - z *= x; - z += l_q_real(coeffs, i); + for (, c of coeffs) { + z *= x; + z += c; } - return z; + z; } integer main(void) { - o_plan(horner(l_effect(-19r, 7.0, -real(4), 6r), 3), "\n"); + o_(horner(list(-19r, 7.0, -4r, 6r), 3), "\n"); - return 0; + 0; } 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 new file mode 100644 index 0000000000..6aa47d0bcb --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/Elena/horners-rule-for-polynomial-evaluation.elena @@ -0,0 +1,12 @@ +import extensions. +import system'routines. + +horner = (:coefficients:variable) +[ + ^ coefficients clone; sequenceReverse; accumulate(Real new) with(:accumulator:coefficient)(accumulator * variable + coefficient) +]. + +program = +[ + console printLine(horner((-19.0r, 7.0r, -4.0r, 6.0r), 3.0r)). +]. diff --git a/Task/Horners-rule-for-polynomial-evaluation/Julia/horners-rule-for-polynomial-evaluation-1.julia b/Task/Horners-rule-for-polynomial-evaluation/Julia/horners-rule-for-polynomial-evaluation-1.julia index 10e61c411a..55ba3e16d2 100644 --- a/Task/Horners-rule-for-polynomial-evaluation/Julia/horners-rule-for-polynomial-evaluation-1.julia +++ b/Task/Horners-rule-for-polynomial-evaluation/Julia/horners-rule-for-polynomial-evaluation-1.julia @@ -1,7 +1,9 @@ - function horner(coef,x) - sum = coef[end] - for k = length(coef)-1:-1:1 - sum = coef[k] + x*sum - end - sum - end +function horner(coefs, x) + s = coefs[end] + for k in length(coefs)-1:-1:1 + s = coefs[k] + x * s + end + return s +end + +@show horner([-19, 7, -4, 6], 3) diff --git a/Task/Horners-rule-for-polynomial-evaluation/Julia/horners-rule-for-polynomial-evaluation-2.julia b/Task/Horners-rule-for-polynomial-evaluation/Julia/horners-rule-for-polynomial-evaluation-2.julia index d54473fa0e..ff0db657c3 100644 --- a/Task/Horners-rule-for-polynomial-evaluation/Julia/horners-rule-for-polynomial-evaluation-2.julia +++ b/Task/Horners-rule-for-polynomial-evaluation/Julia/horners-rule-for-polynomial-evaluation-2.julia @@ -1,2 +1,3 @@ -julia> horner([-19,7,-4,6], 3) -128 +horner2(coefs, x) = foldr((u, v) -> u + x * v, 0, coefs) + +@show horner2([-19, 7, -4, 6], 3) diff --git a/Task/Horners-rule-for-polynomial-evaluation/Modula-2/horners-rule-for-polynomial-evaluation.mod2 b/Task/Horners-rule-for-polynomial-evaluation/Modula-2/horners-rule-for-polynomial-evaluation.mod2 new file mode 100644 index 0000000000..fcb4912be6 --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/Modula-2/horners-rule-for-polynomial-evaluation.mod2 @@ -0,0 +1,29 @@ +MODULE Horner; +FROM RealStr IMPORT RealToStr; +FROM Terminal IMPORT WriteString,WriteLn,ReadChar; + +PROCEDURE Horner(coeff : ARRAY OF REAL; x : REAL) : REAL; +VAR + ans : REAL; + i : CARDINAL; +BEGIN + ans := 0.0; + FOR i:=HIGH(coeff) TO 0 BY -1 DO + ans := (ans * x) + coeff[i]; + END; + RETURN ans +END Horner; + +TYPE A = ARRAY[0..3] OF REAL; +VAR + buf : ARRAY[0..63] OF CHAR; + coeff : A; + ans : REAL; +BEGIN + coeff := A{-19.0, 7.0, -4.0, 6.0}; + ans := Horner(coeff, 3.0); + RealToStr(ans, buf); + WriteString(buf); + WriteLn; + ReadChar +END Horner. diff --git a/Task/Horners-rule-for-polynomial-evaluation/Nim/horners-rule-for-polynomial-evaluation.nim b/Task/Horners-rule-for-polynomial-evaluation/Nim/horners-rule-for-polynomial-evaluation.nim index 11ab4fb3df..c4954a2e65 100644 --- a/Task/Horners-rule-for-polynomial-evaluation/Nim/horners-rule-for-polynomial-evaluation.nim +++ b/Task/Horners-rule-for-polynomial-evaluation/Nim/horners-rule-for-polynomial-evaluation.nim @@ -1,8 +1,9 @@ -iterator reversed(x) = +# You can also just use `reversed` proc from stdlib `algorithm` module +iterator reversed[T](x: openArray[T]): T = for i in countdown(x.high, x.low): yield x[i] -proc horner(coeffs, x): int = +proc horner[T](coeffs: openArray[T], x: T): int = for c in reversed(coeffs): result = result * x + c diff --git a/Task/Host-introspection/Perl-6/host-introspection.pl6 b/Task/Host-introspection/Perl-6/host-introspection.pl6 index d02e5eee67..4c1f920411 100644 --- a/Task/Host-introspection/Perl-6/host-introspection.pl6 +++ b/Task/Host-introspection/Perl-6/host-introspection.pl6 @@ -1,2 +1,3 @@ +use experimental :pack; say $*VM.config; say pack('N', 123456789).unpack('V') == 123456789 ?? 'big-endian' !! 'little-endian'; diff --git a/Task/Huffman-coding/Lua/huffman-coding.lua b/Task/Huffman-coding/Lua/huffman-coding.lua new file mode 100644 index 0000000000..d6d02e8cb6 --- /dev/null +++ b/Task/Huffman-coding/Lua/huffman-coding.lua @@ -0,0 +1,73 @@ +local build_freqtable = function (data) + local freq = { } + + for i = 1, #data do + local cur = string.sub (data, i, i) + local count = freq [cur] or 0 + freq [cur] = count + 1 + end + + local nodes = { } + for w, f in next, freq do + nodes [#nodes + 1] = { word = w, freq = f } + end + + table.sort (nodes, function (a, b) return a.freq > b.freq end) --- reverse order! + + return nodes +end + +local build_hufftree = function (nodes) + while true do + local n = #nodes + local left = nodes [n] + nodes [n] = nil + + local right = nodes [n - 1] + nodes [n - 1] = nil + + local new = { freq = left.freq + right.freq, left = left, right = right } + + if n == 2 then return new end + + --- insert new node at correct priority + local prio = 1 + while prio < #nodes and nodes [prio].freq > new.freq do + prio = prio + 1 + end + table.insert (nodes, prio, new) + end +end + +local print_huffcodes do + local rec_build_huffcodes + rec_build_huffcodes = function (node, bits, acc) + if node.word == nil then + rec_build_huffcodes (node.left, bits .. "0", acc) + rec_build_huffcodes (node.right, bits .. "1", acc) + return acc + else --- leaf + acc [#acc + 1] = { node.freq, node.word, bits } + end + return acc + end + + print_huffcodes = function (root) + local codes = rec_build_huffcodes (root, "", { }) + table.sort (codes, function (a, b) return a [1] < b [1] end) + print ("frequency\tword\thuffman code") + for i = 1, #codes do + print (string.format ("%9d\t‘%s’\t“%s”", table.unpack (codes [i]))) + end + end +end + + +local huffcode = function (data) + local nodes = build_freqtable (data) + local huff = build_hufftree (nodes) + print_huffcodes (huff) + return 0 +end + +return huffcode "this is an example for huffman encoding" diff --git a/Task/Huffman-coding/Perl-6/huffman-coding-2.pl6 b/Task/Huffman-coding/Perl-6/huffman-coding-2.pl6 index 1917e3f124..bd84f70aaa 100644 --- a/Task/Huffman-coding/Perl-6/huffman-coding-2.pl6 +++ b/Task/Huffman-coding/Perl-6/huffman-coding-2.pl6 @@ -9,3 +9,23 @@ sub huffman (%frequencies) { } @queue[0].value; } + +# Testing + +for huffman 'this is an example for huffman encoding'.comb.Bag { + say "'{.key}' : {.value}"; +} + +# To demonstrate that the table can do a round trip: + +say ''; +my $original = 'this is an example for huffman encoding'; + +my %encode-key = huffman $original.comb.Bag; +my %decode-key = %encode-key.invert; +my @codes = %decode-key.keys; + +my $encoded = $original.subst: /./, { %encode-key{$_} }, :g; +my $decoded = $encoded .subst: /@codes/, { %decode-key{$_} }, :g; + +.say for $original, $encoded, $decoded; diff --git a/Task/Huffman-coding/REXX/huffman-coding.rexx b/Task/Huffman-coding/REXX/huffman-coding.rexx index 563e21756c..77802a0a15 100644 --- a/Task/Huffman-coding/REXX/huffman-coding.rexx +++ b/Task/Huffman-coding/REXX/huffman-coding.rexx @@ -1,6 +1,7 @@ /* REXX --------------------------------------------------------------- * 27.12.2013 Walter Pachl * 29.12.2013 -"- changed for test of s=xrange('00'x,'ff'x) +* 14.03.2018 -"- use format instead of right to diagnose size poblems * Stem m contains eventually the following node data * m.i.0id Node id * m.i.0c character @@ -130,8 +131,8 @@ Do si=1 To 999 While sc<>'' End End End -Say 'Input ' s -Say 'result' sr +Say 'Input ="'s'"' +Say 'result="'sr'"' Exit @@ -139,10 +140,10 @@ show: /*--------------------------------------------------------------------- * show all lines representing node data *--------------------------------------------------------------------*/ -Say ' i pp id c f l r d' +Say ' i pp id c f l r d' Do i=1 To m.0 - Say right(i,2) right(m.i.0o,3) right(m.i.0id,2), - right(m.i.0f,2) right(m.i.0l,2) right(m.i.0r,2) m.i.0d m.i.0t + Say format(i,3) format(m.i.0o,4) format(m.i.0id,3), + format(m.i.0f,3) format(m.i.0l,3) format(m.i.0r,3) m.i.0d m.i.0t End Call dbg copies('-',21) Return diff --git a/Task/Huffman-coding/Red/huffman-coding.red b/Task/Huffman-coding/Red/huffman-coding.red new file mode 100644 index 0000000000..3fe30fc3f1 --- /dev/null +++ b/Task/Huffman-coding/Red/huffman-coding.red @@ -0,0 +1,91 @@ +Red [file: %huffy.red] + +;; message to encode: +msg: "this is an example for huffman encoding" + +;;map to collect leave knots per uniq character of message +m: make map! [] + +knot: make object! [ + left: right: none ;; pointer to left/right sibling + code: none ;; first holds char for debugging, later binary code + count: depth: 1 ;;occurence of character - length of branch +] + +;;----------------------------------------- +set-code: func ["recursive function to generate binary code sequence" + wknot + wcode [string!]] [ +;;----------------------------------------- + either wknot/left = none [ + wknot/code: wcode + ] [ + set-code wknot/left rejoin [wcode "1"] + set-code wknot/right rejoin [wcode "0"] + ] +] ;;-- end func + +;------------------------------- +merge-2knots: func ["function to merge 2 knots into 1 new" + t [block!]][ +;------------------------------- + nknot: copy knot ;; create new knot + nknot/count: t/1/count + t/2/count + nknot/right: t/1 + nknot/left: t/2 + nknot/depth: t/1/depth + 1 + tab: remove/part t 2 ;; delete first 2 knots + insert t nknot ;; insert new generated knot +] ;;-- end func + +;; count occurence of characters, save in map: m +foreach chr msg [ + either k: select/case m chr [ + k/count: k/count + 1 + ][ + put/case m chr nknot: copy knot + nknot/code: chr + ] +] + +;; create sortable block (=tab) for use as prio queue +foreach k keys-of m [ append tab: [] :m/:k ] + +;; build tree +while [ 1 < length? tab][ + sort/compare tab function [a b] [ + a/count < b/count + or ( a/count = b/count and ( a/depth > b/depth ) ) + ] + merge-2knots tab ;; merge 2 knots with lowest count / max depth +] + +set-code tab/1 "" ;; generate binary codes, save at leave knot + +;; display codes +foreach k sort keys-of m [ + print [k " = " m/:k/code] + append codes: "" m/:k/code +] + +;; encode orig message string +foreach chr msg [ + k: select/case m chr + append msg-new: "" k/code +] + +print [ "length of encoded msg " length? msg-new] +print [ "length of (binary) codes " length? codes ] + +print ["orig. message: " msg newline "encoded message: " "^/" msg-new] +prin "decoded: " + +;; decode message (destructive! ): +while [ not empty? msg-new ][ + foreach [k v] body-of m [ + if t: find/match msg-new v/code [ + prin k + msg-new: t + ] + ] + ] diff --git a/Task/Huffman-coding/Tcl/huffman-coding.tcl b/Task/Huffman-coding/Tcl/huffman-coding.tcl index 3f6c8b8e9f..1064f972f0 100644 --- a/Task/Huffman-coding/Tcl/huffman-coding.tcl +++ b/Task/Huffman-coding/Tcl/huffman-coding.tcl @@ -20,14 +20,13 @@ proc huffmanEncode {str args} { } set encoding [walkTree [$pq get]] - set map [dict create {*}[lreverse $encoding]] if {$opts(-dump)} { - foreach key [lsort -command compare [dict keys $map]] { - set char [dict get $map $key] - puts "$char\t[dict get $charcount $char]\t$key" + foreach {char huffCode} [lsort -index 1 -stride 2 -command compare $encoding] { + puts "$char\t[dict get $charcount $char]\t$huffCode" } } + $pq destroy return $encoding } diff --git a/Task/I-before-E-except-after-C/D/i-before-e-except-after-c.d b/Task/I-before-E-except-after-C/D/i-before-e-except-after-c.d new file mode 100644 index 0000000000..05623c4b5d --- /dev/null +++ b/Task/I-before-E-except-after-C/D/i-before-e-except-after-c.d @@ -0,0 +1,124 @@ +import std.file; +import std.stdio; + +int main(string[] args) { + if (args.length < 2) { + stderr.writeln(args[0], " filename"); + return 1; + } + + int cei, cie, ie, ei; + auto file = File(args[1]); + foreach(line; file.byLine) { + auto res = eval(cast(string) line); + cei += res.cei; + cie += res.cie; + ei += res.ei; + ie += res.ie; + } + + writeln("CEI: ", cei, "; CIE: ", cie); + writeln("EI: ", ei, "; IE: ", ie); + + writeln("'I before E when not preceded by C' is ", verdict(ie, ei)); + writeln("'E before I when preceded by C' is ", verdict(cei, cie)); + + return 0; +} + +string verdict(int a, int b) { + import std.format; + if (a > 2*b) { + return format("plausible with evidence %f", cast(double)a/b); + } + return format("not plausible with evidence %f", cast(double)a/b); +} + +struct Evidence { + int cei; + int cie; + int ei; + int ie; +} + +Evidence eval(string word) { + enum State { + START, + C, + E, + I, + CE, + CI, + } + + State state; + Evidence cnt; + for(int i=0; i "plausible" "implausible" ? ; + +: output ( #correct #incorrect rule-str -- ) + [ correct ] curry + [ plausibility "This is %s.\n\n" printf ] 2bi ; + +"unixdict.txt" utf8 file-lines ${ + R/ cei/ R/ cie/ R/ [^c]ie/ R/ [^c]ei/ + [ count-matches ] + [ map-sum ] + [ 4 apply-curry ] bi@ +} cleave + +"I before E when not preceded by C" +"E before I when preceded by C" [ output ] bi@ diff --git a/Task/I-before-E-except-after-C/Ring/i-before-e-except-after-c.ring b/Task/I-before-E-except-after-C/Ring/i-before-e-except-after-c.ring new file mode 100644 index 0000000000..ad674aba8f --- /dev/null +++ b/Task/I-before-E-except-after-C/Ring/i-before-e-except-after-c.ring @@ -0,0 +1,42 @@ +# Project : I before E except after C +# Date : 2017/11/26 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +fn1 = "unixdict.txt" + +fp = fopen(fn1,"r") +str = fread(fp, getFileSize(fp)) +fclose(fp) +strcount = str2list(str) +see "The number of words in unixdict : " + len(strcount) + nl +cei = count(str, "cei") +cie = count(str, "cie") +ei = count(str, "ei") +ie = count(str, "ie") +see "Instances of cei : " + cei + nl +see "Instances of cie : " + cie + nl +see "Rule: 'e' before 'i' when preceded by 'c' is = " +if cei>cie see "plausible" + nl else see"not plausible" + nl ok +see "Instances of *ei, where * is not c : " + (ei-cei) + nl +see "Instances of *ie, where * is not c: " + (ie-cie) + nl +see "Rule: 'i' before 'e' when not preceded by 'c' is = " +if ie>ei see "plausible" + nl else see "not plausible" + nl ok +see "Overall the rule is : " +if cei>cie and ie>ei see "PLAUSIBLE" + nl else see "NOT PLAUSIBLE" + nl ok + +func getFileSize fp + c_filestart = 0 + c_fileend = 2 + fseek(fp,0,c_fileend) + nfilesize = ftell(fp) + fseek(fp,0,c_filestart) + return nfilesize + +func count(cString,dString) + sum = 0 + while substr(cString,dString) > 0 + sum = sum + 1 + cString = substr(cString,substr(cString,dString)+len(string(sum))) + end + return sum diff --git a/Task/IBAN/AWK/iban-1.awk b/Task/IBAN/AWK/iban-1.awk new file mode 100644 index 0000000000..0a590fffb8 --- /dev/null +++ b/Task/IBAN/AWK/iban-1.awk @@ -0,0 +1,50 @@ +@load "ordchr" + +function invalid() { print("INVALID " $0); next } +function valid() { print("VALID__ " $0) } + +BEGIN { + ccibanlen["AL"] = 28; ccibanlen["AD"] = 24; ccibanlen["AT"] = 20; + ccibanlen["AZ"] = 28; ccibanlen["BH"] = 22; ccibanlen["BA"] = 20; + ccibanlen["BR"] = 29; ccibanlen["BG"] = 22; ccibanlen["CR"] = 21; + ccibanlen["HR"] = 21; ccibanlen["CY"] = 28; ccibanlen["CZ"] = 24; + ccibanlen["DK"] = 18; ccibanlen["DO"] = 28; ccibanlen["EE"] = 20; + ccibanlen["FO"] = 18; ccibanlen["FI"] = 18; ccibanlen["FR"] = 27; + ccibanlen["GE"] = 22; ccibanlen["DE"] = 22; ccibanlen["GI"] = 23; + ccibanlen["GR"] = 27; ccibanlen["GL"] = 18; ccibanlen["GT"] = 28; + ccibanlen["HU"] = 28; ccibanlen["IS"] = 26; ccibanlen["IE"] = 22; + ccibanlen["IT"] = 27; ccibanlen["KZ"] = 20; ccibanlen["KW"] = 30; + ccibanlen["LV"] = 21; ccibanlen["LB"] = 28; ccibanlen["LI"] = 21; + ccibanlen["LT"] = 20; ccibanlen["LU"] = 20; ccibanlen["MK"] = 19; + ccibanlen["MT"] = 31; ccibanlen["MR"] = 27; ccibanlen["MU"] = 30; + ccibanlen["MC"] = 27; ccibanlen["MD"] = 24; ccibanlen["ME"] = 22; + ccibanlen["NL"] = 18; ccibanlen["NO"] = 15; ccibanlen["PK"] = 24; + ccibanlen["PS"] = 29; ccibanlen["PL"] = 28; ccibanlen["PT"] = 25; + ccibanlen["RO"] = 24; ccibanlen["SM"] = 27; ccibanlen["SA"] = 24; + ccibanlen["RS"] = 22; ccibanlen["SK"] = 24; ccibanlen["SI"] = 19; + ccibanlen["ES"] = 24; ccibanlen["SE"] = 24; ccibanlen["CH"] = 21; + ccibanlen["TN"] = 24; ccibanlen["TR"] = 26; ccibanlen["AE"] = 23; + ccibanlen["GB"] = 22; ccibanlen["VG"] = 24; ccibanlen["BE"] = 16; +} + +{ + iban = toupper($0) + gsub(/\s+/, "", iban) + ccode = substr(iban, 1, 2) + + if ( ! match(iban, /^[A-Z0-9]+$/) || + ! (ccode in ccibanlen) || + length(iban) != ccibanlen[ccode]) + invalid() + + ibanrev = gensub(/^(.{4})(.+)/, "\\2\\1", 1, iban) + ibancsum = "" + for (i = 1; i <= length(ibanrev); i++) { + currchar = substr(ibanrev, i, 1) + if (match(currchar, /[A-Z]/)) + currchar = ord(currchar) - 55 + ibancsum = ibancsum currchar + } + + ibancsum % 97 == 1 ? valid() : invalid() +} diff --git a/Task/IBAN/AWK/iban-2.awk b/Task/IBAN/AWK/iban-2.awk new file mode 100644 index 0000000000..264c955112 --- /dev/null +++ b/Task/IBAN/AWK/iban-2.awk @@ -0,0 +1,9 @@ +cat > test.iban +FR33 ^__^ 0BAD +AA11 1234 6543 1212 +FR33 1234 5432 +CH93 0076 2011 6238 5295 7 +GB82 WEST 1234 5698 7654 32 +GB82 TEST 1234 5698 7654 32 +^D +gawk -Mf iban.gawk test.iban diff --git a/Task/IBAN/AWK/iban-3.awk b/Task/IBAN/AWK/iban-3.awk new file mode 100644 index 0000000000..332a3bafcf --- /dev/null +++ b/Task/IBAN/AWK/iban-3.awk @@ -0,0 +1,6 @@ +INVALID FR33 ^__^ 0BAD +INVALID AA11 1234 6543 1212 +INVALID FR33 1234 5432 +VALID__ CH93 0076 2011 6238 5295 7 +VALID__ GB82 WEST 1234 5698 7654 32 +INVALID GB82 TEST 1234 5698 7654 32 diff --git a/Task/IBAN/Fortran/iban.f b/Task/IBAN/Fortran/iban.f new file mode 100644 index 0000000000..c2f6f2e5c3 --- /dev/null +++ b/Task/IBAN/Fortran/iban.f @@ -0,0 +1,124 @@ +program ibancheck + + use ISO_FORTRAN_ENV + + implicit none + + character(4), dimension(75) :: cc = (/ & + "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" /) + + character(34), dimension(12) :: ibans = (/ "GB82 WEST 1234 5698 7654 32 ", & + "GB82WEST12345698765432 ", & + "gb82 west 1234 5698 7654 32 ", & + "GB82 TEST 1234 5698 7654 32 ", & + "GR16 0110 1250 0000 0001 2300 695 ", & + "GB29 NWBK 6016 1331 9268 19 ", & + "SA03 8000 0000 6080 1016 7519 ", & + "CH93 0076 2011 6238 5295 7 ", & + "IL62 0108 0000 0009 9999 999 ", & + "IL62-0108-0000-0009-9999-999 ", & + "US12 3456 7890 0987 6543 210 ", & + "GR16 0110 1250 0000 0001 2300 695X" /) + + integer :: i + + do i=1, size(ibans) + if (checkIBAN(trim(ibans(i)))) then + print *, " valid IBAN: ", trim(ibans(i)) + else + print *, "invalid IBAN: ", trim(ibans(i)) + end if + end do + + return + +contains + + function checkIBAN(ibancode) result(valid) + character(len=*), intent(in) :: ibancode + character(len=len(ibancode)) :: iban + logical :: valid + integer(int32) :: j, ascii, ibanSize + character(100) :: ibanRearrange, ibantoint + character(2) :: temp + valid = .false. + + iban = remove_blanks(ibancode) + ibanSize = checkCountryCode(iban) + if (ibanSize == len(trim(iban))) then + ibanRearrange = iban(5:ibanSize)//iban(1:4) + ibantoint = "" + do j=1, ibanSize + ascii = ichar(ibanRearrange(j:j)) + if ((ascii >= 65) .and. (ascii<=90)) then + write (temp,fmt='(I2)') ascii-55 + ibantoint = trim(ibantoint) // temp + else + ibantoint = trim(ibantoint) // ibanRearrange(j:j) + end if + end do + if (mod97(ibantoint) == 1) then + valid = .true. + end if + end if + end function checkIBAN + + function mod97(strint) result(res) + character(len=*), intent(in) :: strint + integer :: i, num, res + res = 0 + do i=1, len(trim(strint)) + read(strint(i:i),*) num + res = mod((res*10 + num),97); + end do + end function mod97 + + function checkCountryCode(iban) result(ibanlength) + character(len=*), intent(in) :: iban + integer(int16) :: ibanlength, i + ibanlength = 0 + do i=1, size(cc) + if (iban(1:2) == cc(i)(1:2)) then + read(cc(i)(3:4),*) ibanlength + exit + end if + end do + end function checkCountryCode + + Recursive Function Stripper(string,ch) Result(stripped) + Implicit None + character(len=*), intent(in) :: string + character, intent(in) :: ch + character(:), allocatable :: stripped + + IF (LEN(string)==1) THEN + IF (string==ch) THEN + stripped = '' + ELSE + stripped = string + END IF + ELSE + IF (string(1:1)==ch) THEN + stripped = stripper(string(2:),ch) + ELSE + stripped = string(1:1)//stripper(string(2:),ch) + END IF + END IF + END Function stripper + + Function Remove_Blanks(string) Result(stripped) + Implicit None + character(len=*), intent(in) :: string + character(:), allocatable :: stripped + + stripped = trim(Stripper(trim(Stripper(string,' ')),achar(9))) + END Function Remove_Blanks + +end program ibancheck diff --git a/Task/IBAN/Julia/iban.julia b/Task/IBAN/Julia/iban.julia index 6bd739af9e..3af539b15b 100644 --- a/Task/IBAN/Julia/iban.julia +++ b/Task/IBAN/Julia/iban.julia @@ -1,28 +1,22 @@ -# v0.6.0 -function validiban(iban::String) - const COUNTRY2LENGTH = Dict( - "AL" => 28, "AD" => 24, "AT" => 20, "AZ" => 28, "BE" => 16, "BH" => 22, "BA" => 20, "BR" => 29, - "BG" => 22, "CR" => 21, "HR" => 21, "CY" => 28, "CZ" => 24, "DK" => 18, "DO" => 28, "EE" => 20, - "FO" => 18, "FI" => 18, "FR" => 27, "GE" => 22, "DE" => 22, "GI" => 23, "GR" => 27, "GL" => 18, - "GT" => 28, "HU" => 28, "IS" => 26, "IE" => 22, "IL" => 23, "IT" => 27, "KZ" => 20, "KW" => 30, - "LV" => 21, "LB" => 28, "LI" => 21, "LT" => 20, "LU" => 20, "MK" => 19, "MT" => 31, "MR" => 27, - "MU" => 30, "MC" => 27, "MD" => 24, "ME" => 22, "NL" => 18, "NO" => 15, "PK" => 24, "PS" => 29, - "PL" => 28, "PT" => 25, "RO" => 24, "SM" => 27, "SA" => 24, "RS" => 22, "SK" => 24, "SI" => 19, - "ES" => 24, "SE" => 24, "CH" => 21, "TN" => 24, "TR" => 26, "AE" => 23, "GB" => 22, "VG" => 24 - ) +function validiban(iban::AbstractString) + country2length = Dict( + "AL" => 28, "AD" => 24, "AT" => 20, "AZ" => 28, "BE" => 16, "BH" => 22, "BA" => 20, "BR" => 29, + "BG" => 22, "CR" => 21, "HR" => 21, "CY" => 28, "CZ" => 24, "DK" => 18, "DO" => 28, "EE" => 20, + "FO" => 18, "FI" => 18, "FR" => 27, "GE" => 22, "DE" => 22, "GI" => 23, "GR" => 27, "GL" => 18, + "GT" => 28, "HU" => 28, "IS" => 26, "IE" => 22, "IL" => 23, "IT" => 27, "KZ" => 20, "KW" => 30, + "LV" => 21, "LB" => 28, "LI" => 21, "LT" => 20, "LU" => 20, "MK" => 19, "MT" => 31, "MR" => 27, + "MU" => 30, "MC" => 27, "MD" => 24, "ME" => 22, "NL" => 18, "NO" => 15, "PK" => 24, "PS" => 29, + "PL" => 28, "PT" => 25, "RO" => 24, "SM" => 27, "SA" => 24, "RS" => 22, "SK" => 24, "SI" => 19, + "ES" => 24, "SE" => 24, "CH" => 21, "TN" => 24, "TR" => 26, "AE" => 23, "GB" => 22, "VG" => 24) # Ensure upper alphanumeric input. - iban = replace(iban, " ", "") - iban = replace(iban, "\t", "") + iban = replace(iban, r"\s", "") rst = ismatch(r"^[\dA-Z]+$", iban) # Validate country code against expected length. - rst = rst && length(iban) == COUNTRY2LENGTH[iban[1:2]] + rst = rst && length(iban) == country2length[iban[1:2]] # Shift and convert. iban = iban[5:end] * iban[1:4] - digits = parse(BigInt, join(string(parse(Int, ch, 36)) for ch in iban)) - return rst && digits % 97 == 1 + digs = parse(BigInt, join(parse(Int, ch, 36) for ch in iban)) + return rst && digs % 97 == 1 end - -@show validiban("GB82 WEST 1234 5698 7654 32") -@show validiban("GB82 TEST 1234 5698 7654 32") diff --git a/Task/IBAN/REXX/iban-1.rexx b/Task/IBAN/REXX/iban-1.rexx index 2b2750f419..e0cc37680c 100644 --- a/Task/IBAN/REXX/iban-1.rexx +++ b/Task/IBAN/REXX/iban-1.rexx @@ -1,47 +1,45 @@ -/*REXX program validates an IBAN (International Bank Account Number). */ - @. = - @.1 = 'GB82 WEST 1234 5698 7654 32 ' - @.2 = 'Gb82 West 1234 5698 7654 32 ' - @.3 = 'GB82 TEST 1234 5698 7654 32 ' - @.4 = 'GR16 0110 1250 0000 0001 2300 695 ' - @.5 = 'GB29 NWBK 6016 1331 9268 19 ' - @.6 = 'SA03 8000 0000 6080 1016 7519 ' - @.7 = 'CH93 0076 2011 6238 5295 7 ' - @.8 = 'IL62 0108 0000 0009 9999 999 ' - @.9 = 'IL62-0108-0000-0009-9999-999 ' - @.10 = 'US12 3456 7890 0987 6543 210 ' - @.11 = 'GR16 0110 1250 0000 0001 2300 695X ' -parse arg @.0 /*get optional first argument from C.L.*/ - do k=0+(arg()==0) while @.k\=='' /*either: 0 or 1 ──► n*/ - r = validateIBAN(@.k) +/*REXX program validates an IBAN (International Bank Account Number). */ +@.=; @.1 = 'GB82 WEST 1234 5698 7654 32 ' + @.2 = 'Gb82 West 1234 5698 7654 32 ' + @.3 = 'GB82 TEST 1234 5698 7654 32 ' + @.4 = 'GR16 0110 1250 0000 0001 2300 695 ' + @.5 = 'GB29 NWBK 6016 1331 9268 19 ' + @.6 = 'SA03 8000 0000 6080 1016 7519 ' + @.7 = 'CH93 0076 2011 6238 5295 7 ' + @.8 = 'IL62 0108 0000 0009 9999 999 ' + @.9 = 'IL62-0108-0000-0009-9999-999 ' + @.10 = 'US12 3456 7890 0987 6543 210 ' + @.11 = 'GR16 0110 1250 0000 0001 2300 695X ' +parse arg @.0 /*get optional 1st arg from CL*/ + do k=0 + (arg()==0) while @.k\=='' /*either: 0 or 1 ──► n */ + r = val_IBAN(@.k) if r==0 then say ' valid IBAN:' @.k else say 'invalid IBAN:' @.k " " r - if k==0 then leave /*User specified IBAN? Then we're done*/ + if k==0 then leave /*User specified IBAN? Then we're done*/ end /*k*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────VALIDATEIBAN subroutine───────────────────*/ -validateIBAN: procedure; arg x; numeric digits 200 /*allow for big #s*/ -x=space(x,0); L=length(x) /*elide blanks; determine the length.*/ -cc = 'AD 24 AE 23 AL 28 AT 20 AZ 28 BA 20 BE 16 BG 22 BH 22 BR 29 CH 21', - 'CR 21 CY 28 CZ 24 DE 22 DK 18 DO 28 EE 20 ES 24 FI 18 FO 18 FR 27', - 'GB 22 GE 22 GI 23 GL 18 GR 27 GT 28 HR 21 HU 28 IE 22 IL 23 IS 26', - 'IT 27 KW 30 KZ 20 LB 28 LI 21 LT 20 LU 20 LV 21 MC 27 MD 24 ME 22', - 'MK 19 MR 27 MT 31 MU 30 NL 18 NO 15 PK 24 PL 28 PS 29 PT 25 RO 24', - 'RS 22 SA 24 SE 24 SI 19 SK 24 SM 27 TN 24 TR 26 VG 24' /*country list.*/ -@abc# = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' /*alphabet and decimal digits.*/ -cc_=left(x,2); kk=substr(x,3,2) /*get IBAN country code and checkDigits*/ -c#=wordpos(cc_,cc) /*find the country code index. */ -cL=word(cc,c#+1) /*get the length of the country's IBAN.*/ -e= '***error!*** invalid IBAN' /*literal used when displaying an error*/ -if c#==0 then return e 'country code:' cc_ -if \datatype(x,'A') then return e 'character:' substr(x,verify(x,@abc#),1) -if cL\==L then return e 'length:' L ' (should be' cL")" -y=substr(x,5)left(x,4) /*put four digs in front ───► the back.*/ -z= /* [↓] translate characters ──► digits*/ - do j=1 for L; _=substr(y,j,1) - if datatype(_,'U') then z=z || pos(_,@abc#)+9 - else z=z || _ - end /*j*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +val_IBAN: procedure; arg x; numeric digits 200 /*allow for big numbers in the IBAN's. */ +x=space(x,0); L=length(x) /*elide blanks; determine the length. */ +cc= 'AD 24 AE 23 AL 28 AT 20 AZ 28 BA 20 BE 16 BG 22 BH 22 BR 29 CH 21 CR 21 CY 28 CZ 24', + 'DE 22 DK 18 DO 28 EE 20 ES 24 FI 18 FO 18 FR 27 GB 22 GE 22 GI 23 GL 18 GR 27 GT 28', + 'HR 21 HU 28 IE 22 IL 23 IS 26 IT 27 KW 30 KZ 20 LB 28 LI 21 LT 20 LU 20 LV 21 MC 27', + 'MD 24 ME 22 MK 19 MR 27 MT 31 MU 30 NL 18 NO 15 PK 24 PL 28 PS 29 PT 25 RO 24 RS 22', + 'SA 24 SE 24 SI 19 SK 24 SM 27 TN 24 TR 26 VG 24' /*a list of valid countries. */ +@ABC# = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' /*the Latin alphabet and decimal digits*/ +cc_=left(x, 2); kk=substr(x, 3, 2) /*get IBAN country code and checkDigits*/ +c#=wordpos(cc_, cc) /*find the country code index. */ +cL=word(cc, c# + 1) /*get the length of the country's IBAN.*/ +e= '***error*** invalid IBAN' /*literal used when displaying an error*/ +if c#==0 then return e 'country code:' cc_ +if \datatype(x, 'A') then return e 'character:' substr(x, verify(x, @ABC#), 1) +if cL\==L then return e 'length:' L ' (should be' cL")" +y=substr(x, 5)left(x, 4) /*put four digs in front ───► the back.*/ +z= /* [↓] translate characters ──► digits*/ + do j=1 for L; _=substr(y, j, 1) + if datatype(_, 'U') then z=z || pos(_, @ABC#) + 9 /*if uppercase, then ··· */ + else z=z || _ + end /*j*/ -if z//97==1 then return 0 /*check if correct remainder (modulus).*/ - return e 'check digits.' +if z//97==1 then return 0 /*check if correct remainder (modulus).*/ + return e 'check digits.' diff --git a/Task/IBAN/REXX/iban-2.rexx b/Task/IBAN/REXX/iban-2.rexx index d55396c3b8..5eca134307 100644 --- a/Task/IBAN/REXX/iban-2.rexx +++ b/Task/IBAN/REXX/iban-2.rexx @@ -1,43 +1,41 @@ -/*REXX program validates an IBAN (International Bank Account Number). */ - @. = - @.1 = 'GB82 WEST 1234 5698 7654 32 ' - @.2 = 'Gb82 West 1234 5698 7654 32 ' - @.3 = 'GB82 TEST 1234 5698 7654 32 ' - @.4 = 'GR16 0110 1250 0000 0001 2300 695 ' - @.5 = 'GB29 NWBK 6016 1331 9268 19 ' - @.6 = 'SA03 8000 0000 6080 1016 7519 ' - @.7 = 'CH93 0076 2011 6238 5295 7 ' - @.8 = 'IL62 0108 0000 0009 9999 999 ' - @.9 = 'IL62-0108-0000-0009-9999-999 ' - @.10 = 'US12 3456 7890 0987 6543 210 ' - @.11 = 'GR16 0110 1250 0000 0001 2300 695X ' - @.12 = 'GT11 2222 3333 4444 5555 6666 7777 ' - @.13 = 'MK11 2222 3333 4444 555 ' -parse arg @.0 /*get optional first argument from C.L.*/ - do k=0+(arg()==0) while @.k\=='' /*either: 0 or 1 ──► n*/ - r = validateIBAN(@.k) +/*REXX pgm validates an IBAN (International Bank Account Number), including date ranges.*/ +@.=; @.1 = 'GB82 WEST 1234 5698 7654 32 ' + @.2 = 'Gb82 West 1234 5698 7654 32 ' + @.3 = 'GB82 TEST 1234 5698 7654 32 ' + @.4 = 'GR16 0110 1250 0000 0001 2300 695 ' + @.5 = 'GB29 NWBK 6016 1331 9268 19 ' + @.6 = 'SA03 8000 0000 6080 1016 7519 ' + @.7 = 'CH93 0076 2011 6238 5295 7 ' + @.8 = 'IL62 0108 0000 0009 9999 999 ' + @.9 = 'IL62-0108-0000-0009-9999-999 ' + @.10 = 'US12 3456 7890 0987 6543 210 ' + @.11 = 'GR16 0110 1250 0000 0001 2300 695X ' + @.12 = 'GT11 2222 3333 4444 5555 6666 7777 ' + @.13 = 'MK11 2222 3333 4444 555 ' +parse arg @.0 /*get optional 1st arg from CL*/ + do k=0 + (arg()==0) while @.k\=='' /*either: 0 or 1 ──► n */ + r = val_IBAN(@.k) if r==0 then say ' valid IBAN:' @.k else say 'invalid IBAN:' @.k " " r - if k==0 then leave /*User specified IBAN? Then we're done*/ + if k==0 then leave /*User specified IBAN? Then we're done*/ end /*k*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────VALIDATEIBAN subroutine───────────────────────────────────────*/ -validateIBAN: procedure; arg x; numeric digits 200 /*allow for big #s*/ -x=space(x,0); L=length(x) /*elide blanks; determine the length.*/ -cc = 'AD 24 AE 23 AL 28 AT 20 AZ 28 BA 20 BE 16 BG 22 BH 22 BR 29 CH 21', - 'CR 21 CY 28 CZ 24 DE 22 DK 18 DO 28 EE 20 ES 24 FI 18 FO 18 FR 27', - 'GB 22 GE 22 GI 23 GL 18 GR 27 GT 28 HR 21 HU 28 IE 22 IL 23 IS 26', - 'IT 27 KW 30 KZ 20 LB 28 LI 21 LT 20 LU 20 LV 21 MC 27 MD 24 ME 22', - 'MK 19 MR 27 MT 31 MU 30 NL 18 NO 15 PK 24 PL 28 PS 29 PT 25 RO 24', - 'RS 22 SA 24 SE 24 SI 19 SK 24 SM 27 TN 24 TR 26 VG 24' /*country list.*/ -@abc# = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' /*alphabet and decimal digits.*/ -cc_=left(x,2); kk=substr(x,3,2) /*get IBAN country code and checkDigits*/ -c#=wordpos(cc_,cc) /*find the country code index. */ -cL=word(cc,c#+1) /*get the length of the country's IBAN.*/ -e= '***error!*** invalid IBAN' /*literal used when displaying an error*/ -if c#==0 then return e 'country code:' cc_ -if \datatype(x,'A') then return e 'character:' substr(x,verify(x,@abc#),1) -if cL\==L then return e 'length:' L ' (should be' cL")" +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +val_IBAN: procedure; arg x; numeric digits 200 /*allow for big numbers in the IBAN's. */ +x=space(x,0); L=length(x) /*elide blanks; determine the length. */ +cc= 'AD 24 AE 23 AL 28 AT 20 AZ 28 BA 20 BE 16 BG 22 BH 22 BR 29 CH 21 CR 21 CY 28 CZ 24', + 'DE 22 DK 18 DO 28 EE 20 ES 24 FI 18 FO 18 FR 27 GB 22 GE 22 GI 23 GL 18 GR 27 GT 28', + 'HR 21 HU 28 IE 22 IL 23 IS 26 IT 27 KW 30 KZ 20 LB 28 LI 21 LT 20 LU 20 LV 21 MC 27', + 'MD 24 ME 22 MK 19 MR 27 MT 31 MU 30 NL 18 NO 15 PK 24 PL 28 PS 29 PT 25 RO 24 RS 22', + 'SA 24 SE 24 SI 19 SK 24 SM 27 TN 24 TR 26 VG 24' /*a list of valid countries. */ +@ABC# = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' /*the Latin alphabet and decimal digits*/ +cc_=left(x, 2); kk=substr(x, 3, 2) /*get IBAN country code and checkDigits*/ +c#=wordpos(cc_, cc) /*find the country code index. */ +cL=word(cc, c# + 1) /*get the length of the country's IBAN.*/ +e= '***error*** invalid IBAN' /*literal used when displaying an error*/ +if c#==0 then return e 'country code:' cc_ +if \datatype(x, 'A') then return e 'character:' substr(x, verify(x, @ABC#), 1) +if cL\==L then return e 'length:' L ' (should be' cL")" if cc_=='BR' & date("S")<20130701 then return e "country, Brazil isn't valid until 1-July-2013." if cc_=='GT' & date("S")<20140701 then return e "country, Guatemala isn't valid until 1-July-2014." if cc_=='BA' & kk\==39 then return e "check digits for Bosnia and Herzegovina:" kk @@ -45,12 +43,12 @@ if cc_=='MK' & kk\==07 then return e "check digits for Macedonia:" if cc_=='ME' & kk\==25 then return e "check digits for Montenegro:" kk if cc_=='PT' & kk\==50 then return e "check digits for Portugal:" kk if cc_=='SI' & kk\==56 then return e "check digits for Slovenia:" kk -y=substr(x,5)left(x,4) /*put four digs in front ───► the back.*/ -z= /* [↓] translate characters ──► digits*/ - do j=1 for L; _=substr(y,j,1) - if datatype(_,'U') then z=z || pos(_,@abc#)+9 - else z=z || _ - end /*j*/ +y=substr(x, 5)left(x, 4) /*put four digs in front ───► the back.*/ +z= /* [↓] translate characters ──► digits*/ + do j=1 for L; _=substr(y, j, 1) + if datatype(_, 'U') then z=z || pos(_, @ABC#) + 9 /*if uppercase, then ··· */ + else z=z || _ + end /*j*/ -if z//97==1 then return 0 /*check if correct remainder (modulus).*/ - return e 'check digits.' +if z//97==1 then return 0 /*check if correct remainder (modulus).*/ + return e 'check digits.' diff --git a/Task/IBAN/Ring/iban.ring b/Task/IBAN/Ring/iban.ring new file mode 100644 index 0000000000..05c604a6c2 --- /dev/null +++ b/Task/IBAN/Ring/iban.ring @@ -0,0 +1,55 @@ +# Project : IBAN +# Date : 2018/01/03 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +codes = list(5) +codes[1] = "GB82 WEST 1234 5698 7654 32" +codes[2] = "GB82 TEST 1234 5698 7654 32" +codes[3] = "GB81 WEST 1234 5698 7654 32" +codes[4] = "SA03 8000 0000 6080 1016 7519" +codes[5] = "CH93 0076 2011 6238 5295 7" + +for y = 1 to len(codes) + see codes[y] + flag = 1 + codes[y] = substr(codes[y], " ", "") + checkcode(codes[y]) + check = checkiban(codes[y]) + if check = 1 + see " is valid" + nl + else + see " is invalid" + nl + ok +next + +func checkcode(code) + for n = 1 to 2 + if ascii(code[n]) < 65 or ascii(code[n]) > 90 + flag = 0 + ok + next + for m = 3 to len(code) + if (ascii(code[m]) > 64 and ascii(code[m]) < 91) or (ascii(code[m]) > 47 and ascii(code[m]) < 58) + else + flag = 0 + ok + next + +func checkiban(code) + code= substr(code, 5, len(code) - 4) + left(code, 4) + for x = 1 to len(code) + if ascii(code[x]) > 64 and ascii(code[x]) < 91 + code = left(code, x-1) + string(ascii(code[x]) - 55) + right(code, len(code) - x) + ok + next + modold = left(code,9) % 97 + for p = 1 to floor((len(code)-9)/7) + modnew = string(modold) + substr(code, 10 + (p-1) * 7, 7) + modnew = number(modnew) % 97 + modold = modnew + next + modrest = right(code, len(code) - ((p-1)*7 + 9)) + modnew = string(modold) + modrest + modnew = number(modnew) % 97 + return modnew diff --git a/Task/Identity-matrix/Go/identity-matrix-1.go b/Task/Identity-matrix/Go/identity-matrix-1.go index 71ac78ad91..df346a6765 100644 --- a/Task/Identity-matrix/Go/identity-matrix-1.go +++ b/Task/Identity-matrix/Go/identity-matrix-1.go @@ -3,11 +3,11 @@ package main import ( "fmt" - "github.com/gonum/matrix/mat64" + "gonum.org/v1/gonum/mat" ) -func eye(n int) *mat64.Dense { - m := mat64.NewDense(n, n, nil) +func eye(n int) *mat.Dense { + m := mat.NewDense(n, n, nil) for i := 0; i < n; i++ { m.Set(i, i, 1) } @@ -15,5 +15,5 @@ func eye(n int) *mat64.Dense { } func main() { - fmt.Println(mat64.Formatted(eye(3))) + fmt.Println(mat.Formatted(eye(3))) } diff --git a/Task/Identity-matrix/Rust/identity-matrix.rust b/Task/Identity-matrix/Rust/identity-matrix.rust new file mode 100644 index 0000000000..9b7b45a40d --- /dev/null +++ b/Task/Identity-matrix/Rust/identity-matrix.rust @@ -0,0 +1,41 @@ +extern crate num; +struct Matrix { + data: Vec, + size: usize, +} + +impl Matrix +where + T: num::Num + Clone + Copy, +{ + fn new(size: usize) -> Self { + Self { + data: vec![T::zero(); size * size], + size: size, + } + } + fn get(&mut self, x: usize, y: usize) -> T { + self.data[x + self.size * y] + } + fn identity(&mut self) { + for (i, item) in self.data.iter_mut().enumerate() { + *item = if i % (self.size + 1) == 0 { + T::one() + } else { + T::zero() + } + } + } +} + +fn main() { + let size = std::env::args().nth(1).unwrap().parse().unwrap(); + let mut matrix = Matrix::::new(size); + matrix.identity(); + for y in 0..size { + for x in 0..size { + print!("{} ", matrix.get(x, y)); + } + println!(); + } +} diff --git a/Task/Identity-matrix/Stata/identity-matrix-1.stata b/Task/Identity-matrix/Stata/identity-matrix-1.stata new file mode 100644 index 0000000000..772af144a5 --- /dev/null +++ b/Task/Identity-matrix/Stata/identity-matrix-1.stata @@ -0,0 +1,8 @@ +. mat a = I(3) +. mat list a + +symmetric a[3,3] + c1 c2 c3 +r1 1 +r2 0 1 +r3 0 0 1 diff --git a/Task/Identity-matrix/Stata/identity-matrix-2.stata b/Task/Identity-matrix/Stata/identity-matrix-2.stata new file mode 100644 index 0000000000..11e3824daf --- /dev/null +++ b/Task/Identity-matrix/Stata/identity-matrix-2.stata @@ -0,0 +1,8 @@ +: I(3) +[symmetric] + 1 2 3 + +-------------+ + 1 | 1 | + 2 | 0 1 | + 3 | 0 0 1 | + +-------------+ diff --git a/Task/Image-convolution/Julia/image-convolution.julia b/Task/Image-convolution/Julia/image-convolution.julia new file mode 100644 index 0000000000..f8853e0b88 --- /dev/null +++ b/Task/Image-convolution/Julia/image-convolution.julia @@ -0,0 +1,9 @@ +using FileIO, Images + +img = load("image.jpg") + +sharpenkernel = reshape([-1.0, -1.0, -1.0, -1.0, 9.0, -1.0, -1.0, -1.0, -1.0], (3,3)) + +imfilt = imfilter(img, sharpenkernel) + +save("imagesharper.png", imfilt) diff --git a/Task/Image-convolution/Kotlin/image-convolution.kotlin b/Task/Image-convolution/Kotlin/image-convolution.kotlin new file mode 100644 index 0000000000..f9e3398677 --- /dev/null +++ b/Task/Image-convolution/Kotlin/image-convolution.kotlin @@ -0,0 +1,116 @@ +// version 1.2.10 + +import kotlin.math.round +import java.awt.image.* +import java.io.File +import javax.imageio.* + +class ArrayData(val width: Int, val height: Int) { + var dataArray = IntArray(width * height) + + operator fun get(x: Int, y: Int) = dataArray[y * width + x] + + operator fun set(x: Int, y: Int, value: Int) { + dataArray[y * width + x] = value + } +} + +fun bound(value: Int, endIndex: Int) = when { + value < 0 -> 0 + value < endIndex -> value + else -> endIndex - 1 +} + +fun convolute( + inputData: ArrayData, + kernel: ArrayData, + kernelDivisor: Int +): ArrayData { + val inputWidth = inputData.width + val inputHeight = inputData.height + val kernelWidth = kernel.width + val kernelHeight = kernel.height + if (kernelWidth <= 0 || (kernelWidth and 1) != 1) + throw IllegalArgumentException("Kernel must have odd width") + if (kernelHeight <= 0 || (kernelHeight and 1) != 1) + throw IllegalArgumentException("Kernel must have odd height") + val kernelWidthRadius = kernelWidth ushr 1 + val kernelHeightRadius = kernelHeight ushr 1 + + val outputData = ArrayData(inputWidth, inputHeight) + for (i in inputWidth - 1 downTo 0) { + for (j in inputHeight - 1 downTo 0) { + var newValue = 0.0 + for (kw in kernelWidth - 1 downTo 0) { + for (kh in kernelHeight - 1 downTo 0) { + newValue += kernel[kw, kh] * inputData[ + bound(i + kw - kernelWidthRadius, inputWidth), + bound(j + kh - kernelHeightRadius, inputHeight) + ].toDouble() + outputData[i, j] = round(newValue / kernelDivisor).toInt() + } + } + } + } + return outputData +} + +fun getArrayDatasFromImage(filename: String): Array { + val inputImage = ImageIO.read(File(filename)) + val width = inputImage.width + val height = inputImage.height + val rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width) + val reds = ArrayData(width, height) + val greens = ArrayData(width, height) + val blues = ArrayData(width, height) + for (y in 0 until height) { + for (x in 0 until width) { + val rgbValue = rgbData[y * width + x] + reds[x, y] = (rgbValue ushr 16) and 0xFF + greens[x,y] = (rgbValue ushr 8) and 0xFF + blues[x, y] = rgbValue and 0xFF + } + } + return arrayOf(reds, greens, blues) +} + +fun writeOutputImage(filename: String, redGreenBlue: Array) { + val (reds, greens, blues) = redGreenBlue + val outputImage = BufferedImage( + reds.width, reds.height, BufferedImage.TYPE_INT_ARGB + ) + for (y in 0 until reds.height) { + for (x in 0 until reds.width) { + val red = bound(reds[x , y], 256) + val green = bound(greens[x , y], 256) + val blue = bound(blues[x, y], 256) + outputImage.setRGB( + x, y, (red shl 16) or (green shl 8) or blue or -0x01000000 + ) + } + } + ImageIO.write(outputImage, "PNG", File(filename)) +} + +fun main(args: Array) { + val kernelWidth = args[2].toInt() + val kernelHeight = args[3].toInt() + val kernelDivisor = args[4].toInt() + println("Kernel size: $kernelWidth x $kernelHeight, divisor = $kernelDivisor") + var y = 5 + val kernel = ArrayData(kernelWidth, kernelHeight) + for (i in 0 until kernelHeight) { + print("[") + for (j in 0 until kernelWidth) { + kernel[j, i] = args[y++].toInt() + print(" ${kernel[j, i]} ") + } + println("]") + } + + val dataArrays = getArrayDatasFromImage(args[0]) + for (i in 0 until dataArrays.size) { + dataArrays[i] = convolute(dataArrays[i], kernel, kernelDivisor) + } + writeOutputImage(args[1], dataArrays) +} diff --git a/Task/Image-noise/C++/image-noise.cpp b/Task/Image-noise/C++/image-noise.cpp index 6e4c82178a..2feaa76a4b 100644 --- a/Task/Image-noise/C++/image-noise.cpp +++ b/Task/Image-noise/C++/image-noise.cpp @@ -1,5 +1,6 @@ #include #include +#include //-------------------------------------------------------------------------------------------------- using namespace std; diff --git a/Task/Image-noise/Kotlin/image-noise.kotlin b/Task/Image-noise/Kotlin/image-noise.kotlin new file mode 100644 index 0000000000..e477925fa0 --- /dev/null +++ b/Task/Image-noise/Kotlin/image-noise.kotlin @@ -0,0 +1,117 @@ +// version 1.2.10 + +import java.awt.* +import java.awt.event.* +import java.awt.image.* +import java.util.Random +import javax.swing.* + +class ImageNoise { + var framecount = 0 + var fps = 0 + lateinit var image: BufferedImage + val kernel: Kernel + lateinit var cop: ConvolveOp + val frame = JFrame("Java Image Noise") + + val panel = object : JPanel() { + private var showFps = 0 // 0 = blur + FPS; 1 = FPS only; 2 = neither + private val ma = object : MouseAdapter() { + override fun mouseClicked(e: MouseEvent) { + showFps = (showFps + 1) % 3 + } + } + + init { + addMouseListener(ma) + preferredSize = Dimension(320, 240) + } + + override fun paintComponent(g1: Graphics) { + val g = g1 as Graphics2D + drawNoise() + g.drawImage(image, 0, 0, null) + if (showFps == 0) { + // add blur behind FPS + val xblur = width - 130 + val yblur = height - 32 + val bc = image.getSubimage(xblur, yblur, 115, 32) + val bs = BufferedImage( + bc.width, bc.height, BufferedImage.TYPE_BYTE_GRAY + ) + cop.filter(bc, bs) + g.drawImage(bs, xblur, yblur, null) + } + if (showFps <= 1) { + // add FPS text + g.color = Color.RED + g.font = Font("Monospaced", Font.BOLD, 20) + g.drawString("FPS: $fps", width - 120, height - 10) + } + framecount++ + } + } + + // Timer to trigger update display, with 1 ms delay + val repainter = Timer(1, object: ActionListener { + override fun actionPerformed(e: ActionEvent) = panel.repaint() + }) + + // Timer to check FPS, once per second + val framerateChecker = Timer(1000, object : ActionListener { + override fun actionPerformed(e: ActionEvent) { + fps = framecount + framecount = 0 + } + }) + + init { + // Intitalize kernel describing blur, and convolve operation based on this + val vals = FloatArray(121) { 1.0f / 121.0f } + kernel = Kernel(11, 11, vals) + cop = ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null) + + // Initialize frame and timers + with (frame) { + add(panel) + defaultCloseOperation = JFrame.EXIT_ON_CLOSE + pack() + isVisible = true + } + repainter.start() + framerateChecker.start() + } + + fun drawNoise() { + val w = panel.width + val h = panel.height + + // Check if our image is initialized or window has been resized, + // requiring new image + if (!this::image.isInitialized || image.width != w || image.height != h) { + image = BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY) + } + val rand = Random() + val data = IntArray(w * h) + // Each int has 32 bits so we can use each bit for a different pixel + // - much faster + for (x in 0 until w * h / 32) { + var r = rand.nextInt() + for (i in 0..31) { + data[x * 32 + i] = (r and 1) * Int.MAX_VALUE + r = r ushr 1 + } + } + // Copy raw data to the image's raster + image.raster.setPixels(0, 0, w, h, data) + } +} + +fun main(args: Array) { + // Invoke GUI on the Event Dispatching Thread + SwingUtilities.invokeLater(object: Runnable { + override fun run() { + ImageNoise() + } + }) +} diff --git a/Task/Image-noise/Perl-6/image-noise.pl6 b/Task/Image-noise/Perl-6/image-noise.pl6 index 98510ed4f6..a5967ffb93 100644 --- a/Task/Image-noise/Perl-6/image-noise.pl6 +++ b/Task/Image-noise/Perl-6/image-noise.pl6 @@ -1,50 +1,78 @@ use NativeCall; +use SDL2::Raw; +use nqp; -class SDL_Window is repr('CStruct') {} -class SDL_Renderer is repr('CStruct') {} - -my ($w, $h) = 320, 240; +my int ($w, $h) = 320, 240; my SDL_Window $window; my SDL_Renderer $renderer; -constant $sdl-lib = 'libSDL2'; -constant SDL_INIT_VIDEO = 0x00000020; -constant SDL_WINDOWPOS_UNDEFINED_MASK = 0x1FFF0000; -constant SDL_WINDOW_SHOWN = 0x00000004; +constant $sdl-lib = 'SDL2'; -sub SDL_Init(int32 $flag) returns int32 is native($sdl-lib) {*} -sub SDL_Quit() is native($sdl-lib) {*} +sub SDL_RenderDrawPoints( SDL_Renderer $, CArray[int32] $points, int32 $count ) returns int32 is native($sdl-lib) {*} -sub SDL_CreateWindow(Str $title, int $x, int $y, int $w, int $h, int32 $flag) returns SDL_Window is native($sdl-lib) {*} -sub SDL_CreateRenderer(SDL_Window $, int $, int $) returns SDL_Renderer is native($sdl-lib) {*} -sub SDL_SetRenderDrawColor(SDL_Renderer $, int $r, int $g, int $b, int $a) returns Int is native($sdl-lib) {*} -sub SDL_RenderClear(SDL_Renderer $) returns Int is native($sdl-lib) {*} -sub SDL_RenderDrawPoint( SDL_Renderer $, int $x, int $y ) returns Int is native($sdl-lib) {*} -sub SDL_RenderPresent(SDL_Renderer $) is native($sdl-lib) {*} +SDL_Init(VIDEO); +$window = SDL_CreateWindow( + "some white noise", + SDL_WINDOWPOS_CENTERED_MASK, SDL_WINDOWPOS_CENTERED_MASK, + $w, $h, + SHOWN +); +$renderer = SDL_CreateRenderer( $window, -1, ACCELERATED +| TARGETTEXTURE ); + +SDL_ClearError(); + +my $noise_texture = SDL_CreateTexture($renderer, %PIXELFORMAT, STREAMING, $w, $h); + +my $pixdatabuf = CArray[int64].new(0, 1234, 1234, 1234); sub render { - SDL_SetRenderDrawColor($renderer, 0, 0, 0, 0); - SDL_RenderClear($renderer); - SDL_SetRenderDrawColor($renderer, 255, 255, 255, 0); - loop (my int $i; $i < $w; $i = $i + 1) { - loop (my int $j; $j < $h; $j = $j + 1) { - SDL_RenderDrawPoint( $renderer, $i, $j ) if Bool.pick + my int $pitch; + my int $cursor; + + # work-around to pass the pointer-pointer. + my $pixdata = nativecast(Pointer[int64], $pixdatabuf); + SDL_LockTexture($noise_texture, SDL_Rect, $pixdata, $pitch); + + $pixdata = nativecast(CArray[int8], Pointer.new($pixdatabuf[0])); + + loop (my int $row; $row < $h; $row = $row + 1) { + loop (my int $col; $col < $w; $col = $col + 1) { + $pixdata[$cursor + $col] = Bool.roll ?? 0xff !! 0x0; } + $cursor = $cursor + $pitch; } + + SDL_UnlockTexture($noise_texture); + + SDL_RenderCopy($renderer, $noise_texture, SDL_Rect, SDL_Rect); SDL_RenderPresent($renderer); } -SDL_Init(SDL_INIT_VIDEO); -$window = SDL_CreateWindow( - "some white noise", - SDL_WINDOWPOS_UNDEFINED_MASK, SDL_WINDOWPOS_UNDEFINED_MASK, - $w, $h, - SDL_WINDOW_SHOWN -); -$renderer = SDL_CreateRenderer( $window, -1, 1 ); -loop { - my $then = now; +my $event = SDL_Event.new; + +my @times; + +main: loop { + my $start = nqp::time_n(); + + while SDL_PollEvent($event) { + my $casted_event = SDL_CastEvent($event); + + given $casted_event { + when *.type == QUIT { + last main; + } + } + } + render(); - note "{1 / (now - $then)} fps"; + + @times.push: nqp::time_n() - $start; } -END { SDL_Quit() } + +@times .= sort; + +my @timings = (@times[* div 50], @times[* div 4], @times[* div 2], @times[* * 3 div 4], @times[* - * div 100]); + +say "frames per second:"; +say (1 X/ @timings).fmt("%3.4f"); diff --git a/Task/Include-a-file/VBScript/include-a-file-3.vb b/Task/Include-a-file/VBScript/include-a-file-3.vb new file mode 100644 index 0000000000..5ae50cdcaf --- /dev/null +++ b/Task/Include-a-file/VBScript/include-a-file-3.vb @@ -0,0 +1,7 @@ +Include "%INCLUDE%\StrFuncs.vbs" + +Function Include ( ByVal file ) + Dim wso: Set wso = CreateObject("Wscript.Shell") + Dim fso: Set fso = CreateObject("Scripting.FileSystemObject") + ExecuteGlobal(fso.OpenTextFile(wso.ExpandEnvironmentStrings(file)).ReadAll) +End Function diff --git a/Task/Increment-a-numerical-string/Elena/increment-a-numerical-string.elena b/Task/Increment-a-numerical-string/Elena/increment-a-numerical-string.elena new file mode 100644 index 0000000000..c0e8816dcc --- /dev/null +++ b/Task/Increment-a-numerical-string/Elena/increment-a-numerical-string.elena @@ -0,0 +1,9 @@ +import extensions. + +program = +[ + literal s := "12345". + s := s toInt + 1. + + console printLine(s). +]. diff --git a/Task/Increment-a-numerical-string/HolyC/increment-a-numerical-string.holyc b/Task/Increment-a-numerical-string/HolyC/increment-a-numerical-string.holyc new file mode 100644 index 0000000000..9b531f87cb --- /dev/null +++ b/Task/Increment-a-numerical-string/HolyC/increment-a-numerical-string.holyc @@ -0,0 +1,9 @@ +I8 *s; + +s = "10"; +s = Str2I64(s) + 1; +Print("%d\n", s); + +s = "-10"; +s = Str2I64(s) + 1; +Print("%d\n", s); 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 3853de8c4e..18cefbb3a8 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,3 +1,5 @@ -import Base.+ +Base.:+(s::AbstractString, n::Real) = string(parse(s) + n) -+(s::String, n::Integer) = string(parse(Int, s) + n) +@show "125" + 1 +@show "125.15" + 1 +@show "1234567890987654321" + 1 diff --git a/Task/Increment-a-numerical-string/Mathematica/increment-a-numerical-string.math b/Task/Increment-a-numerical-string/Mathematica/increment-a-numerical-string.math index 7dd78b9cf6..b386faf8c3 100644 --- a/Task/Increment-a-numerical-string/Mathematica/increment-a-numerical-string.math +++ b/Task/Increment-a-numerical-string/Mathematica/increment-a-numerical-string.math @@ -1 +1 @@ -Print[FromDigits["1234"] + 1] +FromDigits["1234"] + 1 diff --git a/Task/Infinity/Perl-6/infinity.pl6 b/Task/Infinity/Perl-6/infinity.pl6 new file mode 100644 index 0000000000..311a9ee4dd --- /dev/null +++ b/Task/Infinity/Perl-6/infinity.pl6 @@ -0,0 +1,2 @@ +my $x = 1.5/0; # Failure: catchable error, if evaluated will return: "Attempt to divide by zero ... +my $y = (1.5/0).Num; # assigns 'Inf' diff --git a/Task/Infinity/ZX-Spectrum-Basic/infinity-1.zx b/Task/Infinity/ZX-Spectrum-Basic/infinity-1.zx new file mode 100644 index 0000000000..fea88fedf7 --- /dev/null +++ b/Task/Infinity/ZX-Spectrum-Basic/infinity-1.zx @@ -0,0 +1 @@ +PRINT 1/0 diff --git a/Task/Infinity/ZX-Spectrum-Basic/infinity-2.zx b/Task/Infinity/ZX-Spectrum-Basic/infinity-2.zx new file mode 100644 index 0000000000..4eb3f60b1d --- /dev/null +++ b/Task/Infinity/ZX-Spectrum-Basic/infinity-2.zx @@ -0,0 +1,4 @@ +10 LET z=1 +20 PRINT z +30 LET z=z*2 +40 GO TO 20 diff --git a/Task/Inheritance-Multiple/D/inheritance-multiple.d b/Task/Inheritance-Multiple/D/inheritance-multiple-1.d similarity index 100% rename from Task/Inheritance-Multiple/D/inheritance-multiple.d rename to Task/Inheritance-Multiple/D/inheritance-multiple-1.d diff --git a/Task/Inheritance-Multiple/D/inheritance-multiple-2.d b/Task/Inheritance-Multiple/D/inheritance-multiple-2.d new file mode 100644 index 0000000000..1885bbb99e --- /dev/null +++ b/Task/Inheritance-Multiple/D/inheritance-multiple-2.d @@ -0,0 +1,12 @@ +interface Camera { + // A virtual function. + Image takePhoto(); + + // A non-virtual function. + final Image[] takeSeveralPhotos(int count) { + auto result = new Image[count]; + foreach (ref img; result) { + img = takePhoto(); + } + } +} diff --git a/Task/Inheritance-Multiple/D/inheritance-multiple-3.d b/Task/Inheritance-Multiple/D/inheritance-multiple-3.d new file mode 100644 index 0000000000..39df9de084 --- /dev/null +++ b/Task/Inheritance-Multiple/D/inheritance-multiple-3.d @@ -0,0 +1,38 @@ +class A { + string foo() { + return "I am an A."; + } +} +class B { + string foo() { + return "I am a B."; + } +} + +class C : A { + string className = "C"; + override string foo() { + return "I am a "~className~", and thus an A."; + } + @property + BWrapper asB() { + return new BWrapper(); + } + alias asB this; + class BWrapper : B { + override string foo() { + return "I am a "~className~", disguised as a B."; + } + } +} + +unittest { + import std.stdio : writeln; + + auto c = new C(); + A a = c; + B b = c; + + writeln(a.foo()); + writeln(b.foo()); +} diff --git a/Task/Inheritance-Multiple/D/inheritance-multiple-4.d b/Task/Inheritance-Multiple/D/inheritance-multiple-4.d new file mode 100644 index 0000000000..3bdead55e5 --- /dev/null +++ b/Task/Inheritance-Multiple/D/inheritance-multiple-4.d @@ -0,0 +1,19 @@ +template registerable() { + void register() { /* implementation */ } +} + +string makeFunction(string s) { + return `string `~s~`(){ return "`~s~`";}`; +} + +class Foo { + mixin registerable!(); + mixin(makeFunction("myFunction")); +} + +unittest { + import std.stdio : writeln; + Foo foo = new Foo; + foo.register(); + writeln(foo.myFunction()); +} diff --git a/Task/Inheritance-Single/Julia/inheritance-single.julia b/Task/Inheritance-Single/Julia/inheritance-single.julia index ebf34b8b4d..3578b12d89 100644 --- a/Task/Inheritance-Single/Julia/inheritance-single.julia +++ b/Task/Inheritance-Single/Julia/inheritance-single.julia @@ -1,6 +1,6 @@ -abstract Animal -abstract Dog <: Animal -abstract Cat <: Animal +abstract type Animal end +abstract type Dog <: Animal end +abstract type Cat <: Animal end -type Lab <: Dog end -type Collie <: Dog end +struct Lab <: Dog end +struct Collie <: Dog end diff --git a/Task/Input-loop/Java/input-loop-1.java b/Task/Input-loop/Java/input-loop-1.java index aed5752ee6..941388eee6 100644 --- a/Task/Input-loop/Java/input-loop-1.java +++ b/Task/Input-loop/Java/input-loop-1.java @@ -1,9 +1,25 @@ +import java.io.InputStream; import java.util.Scanner; -... -Scanner in = new Scanner(System.in);//stdin -//new Scanner(new FileInputStream(filename)) for a file -//new Scanner(socket.getInputStream()) for a network stream -while(in.hasNext()){ - String input = in.next(); //in.nextLine() for line-by-line - //process the input here + +public class InputLoop { + public static void main(String args[]) { + // To read from stdin: + InputStream source = System.in; + + /* + Or, to read from a file: + InputStream source = new FileInputStream(filename); + + Or, to read from a network stream: + InputStream source = socket.getInputStream(); + */ + + Scanner in = new Scanner(source); + while(in.hasNext()){ + String input = in.next(); // Use in.nextLine() for line-by-line reading + + // Process the input here. For example, you could print it out: + System.out.println(input); + } + } } diff --git a/Task/Input-loop/Java/input-loop-2.java b/Task/Input-loop/Java/input-loop-2.java index e2df7c6f71..5653973e53 100644 --- a/Task/Input-loop/Java/input-loop-2.java +++ b/Task/Input-loop/Java/input-loop-2.java @@ -1,16 +1,31 @@ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; -... -try{ - BufferedReader inp = new BufferedReader(new InputStreamReader(System.in));//stdin - //new BufferedReader(new FileReader(filename)) for a file - //new BufferedReader(new InputStreamReader(socket.getInputStream())) for a network stream - while(inp.ready()){ - String input = inp.readLine();//line-by-line only - //in.read() for character-by-character - //process the input here - } -} catch (IOException e) { - //There was an input error +import java.io.Reader; + +public class InputLoop { + public static void main(String args[]) { + // To read from stdin: + Reader reader = new InputStreamReader(System.in); + + /* + Or, to read from a file: + Reader reader = new FileReader(filename); + + Or, to read from a network stream: + Reader reader = new InputStreamReader(socket.getInputStream()); + */ + + try { + BufferedReader inp = new BufferedReader(reader); + while(inp.ready()) { + int input = inp.read(); // Use in.readLine() for line-by-line + + // Process the input here. For example, you can print it out. + System.out.println(input); + } + } catch (IOException e) { + // There was an input error. + } + } } diff --git a/Task/Input-loop/Julia/input-loop.julia b/Task/Input-loop/Julia/input-loop.julia index 9ab251fac8..111495de17 100644 --- a/Task/Input-loop/Julia/input-loop.julia +++ b/Task/Input-loop/Julia/input-loop.julia @@ -1,5 +1,6 @@ -stream = IOBuffer("1\n2\n3\n4\n\n6") ; +stream = IOBuffer("1\n2\n3\n4\n\n6") -while((line = readline(stream)) != "") - print(line) +while !eof(stream) + line = readline(stream) + println(line) end diff --git a/Task/Integer-comparison/Astro/integer-comparison.astro b/Task/Integer-comparison/Astro/integer-comparison.astro index e8533c15b9..de56a8ae30 100644 --- a/Task/Integer-comparison/Astro/integer-comparison.astro +++ b/Task/Integer-comparison/Astro/integer-comparison.astro @@ -1,5 +1,5 @@ -let a = scan('Enter value of a: ') -let b = scan('Enter value of b: ') +let a = input('Enter value of a: ') +let b = input('Enter value of b: ') if a < b: print 'a is less than b' diff --git a/Task/Integer-comparison/Haskell/integer-comparison-1.hs b/Task/Integer-comparison/Haskell/integer-comparison-1.hs index 10a1be2a37..d0d8a95ed3 100644 --- a/Task/Integer-comparison/Haskell/integer-comparison-1.hs +++ b/Task/Integer-comparison/Haskell/integer-comparison-1.hs @@ -1,11 +1,10 @@ +myCompare :: Integer -> Integer -> String myCompare a b | a < b = "A is less than B" | a > b = "A is greater than B" | a == b = "A equals B" main = do - a' <- getLine - b' <- getLine - let { a :: Integer; a = read a' } - let { b :: Integer; b = read b' } + a <- readLn + b <- readLn putStrLn $ myCompare a b diff --git a/Task/Integer-comparison/HolyC/integer-comparison.holyc b/Task/Integer-comparison/HolyC/integer-comparison.holyc new file mode 100644 index 0000000000..091b579bc6 --- /dev/null +++ b/Task/Integer-comparison/HolyC/integer-comparison.holyc @@ -0,0 +1,12 @@ +I64 *a, *b; +a = Str2I64(GetStr("Enter your first number: ")); +b = Str2I64(GetStr("Enter your second number: ")); + +if (a < b) + Print("%d is less than %d\n", a, b); + +if (a == b) + Print("%d is equal to %d\n", a, b); + +if (a > b) + Print("%d is greater than %d\n", a, b); diff --git a/Task/Integer-overflow/00DESCRIPTION b/Task/Integer-overflow/00DESCRIPTION index ccdf26677a..b61bf3beed 100644 --- a/Task/Integer-overflow/00DESCRIPTION +++ b/Task/Integer-overflow/00DESCRIPTION @@ -99,7 +99,7 @@ For 64-bit unsigned integers: | 18446744073709551616 |} -When the integer overflow does trigger an exception show how the exception is catched. +When the integer overflow does trigger an exception show how the exception is caught. When the integer overflow produces some value print it. It should be explicitly noted when an integer overflow is not recognized and the program continues with wrong results. This should be done for signed and unsigned integers of various sizes supported by the language. diff --git a/Task/Integer-overflow/Julia/integer-overflow-1.julia b/Task/Integer-overflow/Julia/integer-overflow-1.julia index 7479905633..a56c3072d1 100644 --- a/Task/Integer-overflow/Julia/integer-overflow-1.julia +++ b/Task/Integer-overflow/Julia/integer-overflow-1.julia @@ -1,8 +1,8 @@ -s = subtypes(Signed) -u = subtypes(Unsigned) +S = subtypes(Signed) +U = subtypes(Unsigned) -println("Integer Type Limits") -for i in 1:length(s) - println(s[i], " [", typemin(s[i]), ", ", typemax(s[i]), "]") - println(u[i], " [", typemin(u[i]), ", ", typemax(u[i]), "]") +println("Integer limits:") +for (s, u) in zip(S, U) + @printf("%8s: [%s, %s]\n", s, typemin(s), typemax(s)) + @printf("%8s: [%s, %s]\n", u, typemin(u), typemax(u)) end diff --git a/Task/Integer-overflow/Julia/integer-overflow-2.julia b/Task/Integer-overflow/Julia/integer-overflow-2.julia index 2843dcf293..53a8ab1c4d 100644 --- a/Task/Integer-overflow/Julia/integer-overflow-2.julia +++ b/Task/Integer-overflow/Julia/integer-overflow-2.julia @@ -1,5 +1,5 @@ -println("Add to typemax") -for t in s - over = typemax(t) + 1 - println(t, " => ", over, " (", typeof(over), ")") +println("Add one to typemax:") +for t in S + over = typemax(t) + one(t) + @printf("%8s → %-25s (%s)\n", t, over, typeof(over)) end diff --git a/Task/Integer-sequence/Elena/integer-sequence.elena b/Task/Integer-sequence/Elena/integer-sequence.elena new file mode 100644 index 0000000000..e536b5da35 --- /dev/null +++ b/Task/Integer-sequence/Elena/integer-sequence.elena @@ -0,0 +1,12 @@ +import extensions. + +program = +[ + var i := 0u. + while (true) + [ + console printLine(i). + + i += 1u + ] +]. diff --git a/Task/Integer-sequence/Modula-2/integer-sequence.mod2 b/Task/Integer-sequence/Modula-2/integer-sequence.mod2 new file mode 100644 index 0000000000..569cedb6cf --- /dev/null +++ b/Task/Integer-sequence/Modula-2/integer-sequence.mod2 @@ -0,0 +1,16 @@ +MODULE Sequence; +FROM FormatString IMPORT FormatString; +FROM Terminal IMPORT WriteString,ReadChar; + +VAR + buf : ARRAY[0..63] OF CHAR; + i : CARDINAL; +BEGIN + i := 1; + WHILE i>0 DO + FormatString("%c ", buf, i); + WriteString(buf); + INC(i) + END; + ReadChar +END Sequence. diff --git a/Task/Interactive-programming/Forth/interactive-programming.fth b/Task/Interactive-programming/Forth/interactive-programming.fth index 82eda05a4d..8452cf9ce4 100644 --- a/Task/Interactive-programming/Forth/interactive-programming.fth +++ b/Task/Interactive-programming/Forth/interactive-programming.fth @@ -1,9 +1,14 @@ -$ gforth +$ gforth Gforth 0.7.0, Copyright (C) 1995-2008 Free Software Foundation, Inc. Gforth comes with ABSOLUTELY NO WARRANTY; for details type `license' Type `bye' to exit -: f ( separator suffix prefix -- ) compiled - pad place 2swap 2dup pad +place pad +place pad +place compiled - pad count ; ok -s" :" s" Code" s" Rosetta" f cr type + ok +: f ( separator suffix prefix -- ) compiled + pad place 2swap 2dup compiled + pad +place compiled + pad +place compiled + pad +place compiled + pad count ; ok + ok + s" :" s" Code" s" Rosetta" f cr type Rosetta::Code ok diff --git a/Task/Interactive-programming/Java/interactive-programming.java b/Task/Interactive-programming/Java/interactive-programming.java new file mode 100644 index 0000000000..eef4e719dd --- /dev/null +++ b/Task/Interactive-programming/Java/interactive-programming.java @@ -0,0 +1,9 @@ +public static void main(String[] args) { + System.out.println(concat("Rosetta", "Code", ":")); +} + +public static String concat(String a, String b, String c) { + return a + c + c + b; +} + +Rosetta::Code diff --git a/Task/Interactive-programming/Ruby/interactive-programming.rb b/Task/Interactive-programming/Ruby/interactive-programming.rb index 39ed899c54..eb49094f49 100644 --- a/Task/Interactive-programming/Ruby/interactive-programming.rb +++ b/Task/Interactive-programming/Ruby/interactive-programming.rb @@ -2,7 +2,7 @@ $ irb irb(main):001:0> def f(string1, string2, separator) irb(main):002:1> [string1, '', string2].join(separator) irb(main):003:1> end -=> nil +=> :f irb(main):004:0> f('Rosetta', 'Code', ':') => "Rosetta::Code" irb(main):005:0> exit diff --git a/Task/Introspection/Icon/introspection.icon b/Task/Introspection/Icon/introspection.icon index 8152843eaa..30e43f9f1e 100644 --- a/Task/Introspection/Icon/introspection.icon +++ b/Task/Introspection/Icon/introspection.icon @@ -4,8 +4,8 @@ procedure main(A) if older(11,7) then stop("Must have version >= 11.7!") bloop := -5 # global variable floop := -11.3 # local variable - write(proc("abs")(variable("bloop")) - write(proc("abs")(variable("floop")) + write(proc("abs")(variable("bloop"))) + write(proc("abs")(variable("floop"))) end procedure older(maj,min) diff --git a/Task/Introspection/Julia/introspection.julia b/Task/Introspection/Julia/introspection.julia index da74b68602..3e34fd7879 100644 --- a/Task/Introspection/Julia/introspection.julia +++ b/Task/Introspection/Julia/introspection.julia @@ -1,5 +1,11 @@ -julia> VERSION -v"0.3.2" +@show VERSION +VERSION < v"0.4" && exit(1) -julia> VERSION > v"0.3.1" -true +if isdefined(:bloop) && !isempty(methods(abs)) + @show abs(bloop) +end + +a, b, c = 1, 2, 3 +vars = filter(x -> eval(x) isa Integer, names(Main)) +println("Integer variables: ", join(vars, ", "), ".") +println("Sum of integers in the global scope: ", sum(eval.(vars)), ".") diff --git a/Task/Introspection/Perl-6/introspection.pl6 b/Task/Introspection/Perl-6/introspection.pl6 index 22ec7fae58..b7735878b6 100644 --- a/Task/Introspection/Perl-6/introspection.pl6 +++ b/Task/Introspection/Perl-6/introspection.pl6 @@ -1,4 +1,4 @@ -use v6.0; # require Perl 6.0 +use v6; # require Perl 6 my $bloop = -123; diff --git a/Task/Inverted-index/Kotlin/inverted-index.kotlin b/Task/Inverted-index/Kotlin/inverted-index.kotlin new file mode 100644 index 0000000000..a6f78f7341 --- /dev/null +++ b/Task/Inverted-index/Kotlin/inverted-index.kotlin @@ -0,0 +1,58 @@ +// version 1.1.51 + +import java.io.File + +val invIndex = mutableMapOf>() +val fileNames = mutableListOf() +val splitter = Regex("""\W+""") + +class Location(val fileName: String, val wordNum: Int) { + override fun toString() = "{$fileName, word number $wordNum}" +} + +fun indexFile(fileName: String) { + if (fileName in fileNames) { + println("'$fileName' already indexed") + return + } + fileNames.add(fileName) + File(fileName).forEachLine { line -> + for ((i, w) in line.toLowerCase().split(splitter).withIndex()) { + var locations = invIndex[w] + if (locations == null) { + locations = mutableListOf() + invIndex.put(w, locations) + } + locations.add(Location(fileName, i + 1)) + } + } + println("'$fileName' has been indexed") +} + +fun findWord(word: String) { + val w = word.toLowerCase() + val locations = invIndex[w] + if (locations != null) { + println("\n'$word' found in the following locations:") + println(locations.map { " $it" }.joinToString("\n")) + } + else println("\n'$word' not found") + println() +} + +fun main(args: Array) { + // files to be indexed entered as command line arguments + if (args.size == 0) { + println("No file names have been supplied") + return + } + for (arg in args) indexFile(arg) + println() + println("Enter word(s) to be searched for in these files or 'q' to quit") + while (true) { + print(" ? : ") + val word = readLine()!! + if (word.toLowerCase() == "q") return + findWord(word) + } +} diff --git a/Task/Inverted-syntax/D/inverted-syntax.d b/Task/Inverted-syntax/D/inverted-syntax.d new file mode 100644 index 0000000000..2333b50ea0 --- /dev/null +++ b/Task/Inverted-syntax/D/inverted-syntax.d @@ -0,0 +1,14 @@ +#!/usr/bin/rdmd + +import std.algorithm; + +void main() { + assert("Hello, World".length == 12); + assert("Cleanliness".startsWith("Clean")); + + auto r = [1, 4, 2, 8, 5, 7] + .filter!(n => n > 2) + .map!(n => n * 2); + + assert(r.equal([8, 16, 10, 14])); +} diff --git a/Task/Inverted-syntax/Factor/inverted-syntax-1.factor b/Task/Inverted-syntax/Factor/inverted-syntax-1.factor new file mode 100644 index 0000000000..1d8a7140fb --- /dev/null +++ b/Task/Inverted-syntax/Factor/inverted-syntax-1.factor @@ -0,0 +1,4 @@ +1 1 + ! 2 +[ + 1 1 ] reverse call ! 2 +{ 1 2 3 4 5 } [ sq ] map ! { 1 4 9 16 25 } +[ map [ sq ] { 1 2 3 4 5 } ] reverse call ! { 1 4 9 16 25 } diff --git a/Task/Inverted-syntax/Factor/inverted-syntax-2.factor b/Task/Inverted-syntax/Factor/inverted-syntax-2.factor new file mode 100644 index 0000000000..3f4a24b68c --- /dev/null +++ b/Task/Inverted-syntax/Factor/inverted-syntax-2.factor @@ -0,0 +1,4 @@ +USE: infix +[infix + 5*(1+1) ! 10 +infix] diff --git a/Task/Inverted-syntax/Julia/inverted-syntax.julia b/Task/Inverted-syntax/Julia/inverted-syntax.julia new file mode 100644 index 0000000000..ac52de05c3 --- /dev/null +++ b/Task/Inverted-syntax/Julia/inverted-syntax.julia @@ -0,0 +1,7 @@ +macro inv(expr, cond) + cond isa Expr && cond.head == :if || throw(ArgumentError("$cond is not an if expression")) + cond.args[2] = expr + return cond +end + +@inv println("Wow! Lucky Guess!") if true else println("Not!") end diff --git a/Task/Inverted-syntax/Scala/inverted-syntax.scala b/Task/Inverted-syntax/Scala/inverted-syntax.scala new file mode 100644 index 0000000000..704d77b642 --- /dev/null +++ b/Task/Inverted-syntax/Scala/inverted-syntax.scala @@ -0,0 +1,6 @@ +object Main extends App { + + val raining = true + val needUmbrella = raining + println(s"Do I need an umbrella? ${if (needUmbrella) "Yes" else "No"}") +} diff --git a/Task/Iterated-digits-squaring/00DESCRIPTION b/Task/Iterated-digits-squaring/00DESCRIPTION index c68bcd3eeb..c5629a8f5b 100644 --- a/Task/Iterated-digits-squaring/00DESCRIPTION +++ b/Task/Iterated-digits-squaring/00DESCRIPTION @@ -1,6 +1,7 @@ If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:

15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
 7 -> 49 -> 97 -> 130 -> 10 -> 1
+ An example in Python: >>> step = lambda x: sum(int(d) ** 2 for d in str(x)) @@ -8,6 +9,7 @@ An example in Python: >>> [iterate(x) for x in xrange(1, 20)] [1, 89, 89, 89, 89, 89, 1, 89, 89, 1, 89, 89, 1, 89, 89, 89, 89, 89, 1] + ;Task: : Count how many number chains for integers 1 <= n < 100_000_000 end with a value 89. Or, for much less credit - (showing that your algorithm and/or language is slow): @@ -17,8 +19,9 @@ This problem derives from the [https://projecteuler.net/problem=92 Project Euler For a quick algorithm for this task see [[Talk:Iterated_digits_squaring|the talk page]] -;Cf: -*[[Combinations with repetitions]] -*[[Digital root]] -*[[Digital root/Multiplicative digital root]] + +;Related tasks: +* [[Combinations with repetitions]] +* [[Digital root]] +* [[Digital root/Multiplicative digital root]]

diff --git a/Task/Iterated-digits-squaring/C-sharp/iterated-digits-squaring.cs b/Task/Iterated-digits-squaring/C-sharp/iterated-digits-squaring.cs new file mode 100644 index 0000000000..1763c74087 --- /dev/null +++ b/Task/Iterated-digits-squaring/C-sharp/iterated-digits-squaring.cs @@ -0,0 +1,34 @@ +using System; +public static class IteratedDigitsSquaring +{ + public static void Main() { + Console.WriteLine(Count89s(1_000_000)); + Console.WriteLine(Count89s(100_000_000)); + } + + public static int Count89s(int limit) { + if (limit < 1) return 0; + int[] end = new int[Math.Min(limit, 9 * 9 * 9 + 2)]; + int result = 0; + + for (int i = 1; i < end.Length; i++) { + for (end[i] = i; end[i] != 1 && end[i] != 89; end[i] = SquareDigitSum(end[i])) { } + if (end[i] == 89) result++; + } + for (int i = end.Length; i < limit; i++) { + if (end[SquareDigitSum(i)] == 89) result++; + } + return result; + + int SquareDigitSum(int n) { + int sum = 0; + while (n > 0) { + int digit = n % 10; + sum += digit * digit; + n /= 10; + } + return sum; + } + } + +} diff --git a/Task/Iterated-digits-squaring/Factor/iterated-digits-squaring.factor b/Task/Iterated-digits-squaring/Factor/iterated-digits-squaring.factor new file mode 100644 index 0000000000..dc1e925022 --- /dev/null +++ b/Task/Iterated-digits-squaring/Factor/iterated-digits-squaring.factor @@ -0,0 +1,17 @@ +USING: kernel math math.ranges math.text.utils memoize +prettyprint sequences tools.time ; +IN: rosetta-code.iterated-digits-squaring + +: sum-digit-sq ( n -- m ) 1 digit-groups [ sq ] map-sum ; + +MEMO: 1or89 ( n -- m ) + [ dup [ 1 = ] [ 89 = ] bi or ] [ sum-digit-sq ] until ; + +[ + 0 1 + [ + dup sum-digit-sq 1or89 89 = [ [ 1 + ] dip ] when + 1 + dup 100,000,000 < + ] loop + drop . +] time diff --git a/Task/Iterated-digits-squaring/Julia/iterated-digits-squaring-1.julia b/Task/Iterated-digits-squaring/Julia/iterated-digits-squaring-1.julia index 127a46df06..da29ca5abd 100644 --- a/Task/Iterated-digits-squaring/Julia/iterated-digits-squaring-1.julia +++ b/Task/Iterated-digits-squaring/Julia/iterated-digits-squaring-1.julia @@ -1,18 +1,12 @@ -function iterate(m) +function iterate(m::Integer) while m != 1 && m != 89 s = 0 while m > 0 # compute sum of squares of digits m, d = divrem(m, 10) - s += d*d + s += d ^ 2 end m = s end return m end -function itercount(N) - count = 0 - for n in 1:N - count += iterate(n) == 89 - end - return count -end +itercount(k::Integer) = count(x -> iterate(x) == 89, 1:k) diff --git a/Task/Iterated-digits-squaring/Julia/iterated-digits-squaring-2.julia b/Task/Iterated-digits-squaring/Julia/iterated-digits-squaring-2.julia index c2846f90bc..40980f99e9 100644 --- a/Task/Iterated-digits-squaring/Julia/iterated-digits-squaring-2.julia +++ b/Task/Iterated-digits-squaring/Julia/iterated-digits-squaring-2.julia @@ -1,27 +1,28 @@ -function itercount_combinations(ndigits) - count = 0 +using Combinatorics +function itercountcombos(ndigits::Integer) + cnt = 0 f = factorial(ndigits) # loop over all combinations of ndigits decimal digits: - for c in combinations([1:(10+ndigits-1)],ndigits) + for comb in combinations(1:(10+ndigits-1), ndigits) s = 0 perms = 1 - prevdigit = -1 - repeat = 1 - for k = 1:length(c) # sum digits^2 and count permutations - digit = c[k]-k - s += digit*digit + prevd = -1 + rep = 1 + for k = eachindex(comb) # sum digits ^ 2 and count permutations + d = comb[k] - k + s += d ^ 2 # accumulate number of permutations of repeated digits - if digit == prevdigit - repeat += 1 - perms *= repeat + if d == prevd + rep += 1 + perms *= rep else - prevdigit = digit - repeat = 1 + prevd = d + rep = 1 end end if s > 0 && iterate(s) == 89 - count += div(f, perms) # numbers we can get from digits + cnt += f ÷ perms # numbers we can get from digits end end - return count + return cnt end diff --git a/Task/Iterated-digits-squaring/Julia/iterated-digits-squaring-3.julia b/Task/Iterated-digits-squaring/Julia/iterated-digits-squaring-3.julia new file mode 100644 index 0000000000..e6b4296b8c --- /dev/null +++ b/Task/Iterated-digits-squaring/Julia/iterated-digits-squaring-3.julia @@ -0,0 +1,3 @@ +@time itercount(100_000_000) +@time itercountcombos(8) +@time itercountcombos(17) diff --git a/Task/Iterated-digits-squaring/Perl-6/iterated-digits-squaring-3.pl6 b/Task/Iterated-digits-squaring/Perl-6/iterated-digits-squaring-3.pl6 index f880000bf3..7f2da8d431 100644 --- a/Task/Iterated-digits-squaring/Perl-6/iterated-digits-squaring-3.pl6 +++ b/Task/Iterated-digits-squaring/Perl-6/iterated-digits-squaring-3.pl6 @@ -1,3 +1,4 @@ +use nqp; my $cache := nqp::list_i(); nqp::bindpos_i($cache, 650, 0); nqp::bindpos_i($cache, 1, 1); diff --git a/Task/Iterated-digits-squaring/REXX/iterated-digits-squaring-1.rexx b/Task/Iterated-digits-squaring/REXX/iterated-digits-squaring-1.rexx index ffd69cf34b..24a2de2011 100644 --- a/Task/Iterated-digits-squaring/REXX/iterated-digits-squaring-1.rexx +++ b/Task/Iterated-digits-squaring/REXX/iterated-digits-squaring-1.rexx @@ -1,25 +1,22 @@ /*REXX program performs the squaring of iterated digits (until the sum equals 1 or 89).*/ parse arg n . /*obtain optional arguments from the CL*/ if n=='' | n=="," then n=10 * 1000000 /*Not specified? Then use the default.*/ -!.=0; do m=1 for 9; !.m=m**2; end /*m*/ /*build a short─cut for the squares. */ -a.=. /*intermediate counts of some numbers. */ -#.=0 /*count of 1 and 89 results so far.*/ +!.=0; do m=1 for 9; !.m=m**2; end /*m*/ /*build a short─cut for the squares. */ +a.=.; #.=!. /*intermediate counts of some numbers. */ do j=1 for n; x=j /* [↓] process the numbers in the range*/ do q=1 until s==89 | s==1; s=0 /*add sum of the squared decimal digits*/ do until x=='' /*process each of the dec. digits in X.*/ - parse var x _ +1 x; s=s+!._ /*get a digit; sum the fast square, */ - end /*until x== ... */ /* [↑] S≡is sum of the squared digits.*/ + parse var x _ +1 x; s=s + !._ /*get a digit; sum the fast square, */ + end /*until x ··· */ /* [↑] S≡is sum of the squared digits.*/ z.q=s /*assign sum to a temporary auxiliary. */ if a.s\==. then do; s=a.s; leave; end /*Found a previous sum? Then use that.*/ x=s /*substitute the sum for the "new" X. */ - end /*until s== ... */ /* [↑] keep looping 'til S= 1 or 89.*/ - - do f=1 for q /* [↓] use the auxiliary array. */ - _=z.f; a._=s /*assign auxiliaries for future look-up*/ - end /*f*/ - #.s=#.s+1 /*bump the counter for the 1's or 89's.*/ + end /*q*/ /* [↑] keep looping 'til S= 1 or 89.*/ + do f=1 for q; _=a.f; a._=s /*use the auxiliary arrays (for lookup)*/ + end /*f*/ + #.s=#.s + 1 /*bump the counter for the 1's or 89's.*/ end /*j*/ - do k=1 by 88 for 2; @=right('"'k'"', 5) /*display two results; define a literal*/ - say 'count of' @ " chains for all natural numbers up to " n ' is:' #.k + do k=1 by 88 for 2; @k=right('"'k'"', 5) /*display two results; define a literal*/ + say 'count of' @k " chains for all natural numbers up to " n ' is:' #.k end /*k*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Iterated-digits-squaring/REXX/iterated-digits-squaring-2.rexx b/Task/Iterated-digits-squaring/REXX/iterated-digits-squaring-2.rexx index 7760f6e1e6..0332a0ff46 100644 --- a/Task/Iterated-digits-squaring/REXX/iterated-digits-squaring-2.rexx +++ b/Task/Iterated-digits-squaring/REXX/iterated-digits-squaring-2.rexx @@ -1,39 +1,40 @@ /*REXX program performs the squaring of iterated digits (until the sum equals 1 or 89).*/ parse arg n . /*obtain optional arguments from the CL*/ if n=='' | n=="," then n=10 * 1000000 /*Not specified? Then use the default.*/ -!.=0; do m=1 for 9; !.m=m**2; end /*m*/ /*build a short─cut for the squares. */ -$.=.; $.0=0; $.00=0; $.000=0; $.0000=0; @.=. /*short-cuts for sub-group summations. */ +!.=0; do m=1 for 9; !.m=m**2; end /*m*/ /*build a short─cut for the squares. */ +$.=.; $.0=0; $.00=0; $.000=0; $.0000=0; @.=$. /*short-cuts for sub-group summations. */ #.=0 /*count of 1 and 89 results so far.*/ - do j=1 for n; s=sumDs(j) /* [↓] process each number in a range.*/ - #.s=#.s+1 /*bump the counter for 1's or 89's. */ + do j=1 for n; s=sumDs(j) /* [↓] process each number in a range.*/ + #.s=#.s + 1 /*bump the counter for 1's or 89's. */ end /*j*/ do k=1 by 88 for 2; @=right('"'k'"', 5) /*display two results; define a literal*/ say 'count of' @ " chains for all natural numbers up to " n ' is:' #.k - end /*k*/ + end /*k*/ /*stick a fork in it, we're all done. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ sumDs: parse arg z; chunk=3 /*obtain the number (for adding digits)*/ -p=0 /*set partial sum of the decimal digits*/ - do m=1 by chunk to length(z) /*process the number, in chunks of four*/ - y=substr(z, m, chunk) /*extract a 4─byte chunk of the number.*/ - if @.y==. then do; oy=y; a=0 /*Not done before? Then sum the number*/ - do until y=='' /*process each of the dec. digits in Y.*/ - parse var y _ +1 y; a=a+!._ /*obtain a decimal digit; add it to A.*/ - end /*until y ···*/ /* [↑] A ≡ is the sum of squared digs*/ - @.oy=a /*mark original Y as being summed. */ - end - else a=@.y /*use the pre─summed digits of Y. */ - p=p+a /*add all the parts of number together.*/ - end /*m*/ + p=0 /*set partial sum of the decimal digits*/ + do m=1 by chunk to length(z) /*process the number, in chunks of four*/ + y=substr(z, m, chunk) /*extract a 4─byte chunk of the number.*/ + if @.y==. then do; oy=y; a=0 /*Not done before? Then sum the number*/ + do until y=='' /*process each of the dec. digits in Y.*/ + parse var y _ +1 y /*obtain a decimal digit; add it to A.*/ + a=a + !._ /*obtain a decimal digit; add it to A.*/ + end /*until y ···*/ /* [↑] A ≡ is the sum of squared digs*/ + @.oy=a /*mark original Y as being summed. */ + end + else a=@.y /*use the pre─summed digits of Y. */ + p=p + a /*add all the parts of number together.*/ + end /*m*/ -if $.p\==. then return $.p /*Computed before? Then use the value.*/ -y=p /*use a new copy of P. */ - do until s==1 | s==89; s=0 /*add the squared decimal digits of P.*/ - do until y=='' /*process each decimal digits in X.*/ - parse var y _ +1 y; s=s+!._ /*get a dec. digit; sum the fast square*/ - end /*until y=='' ···*/ /* [↑] S ≡ is sum of the squared digs.*/ - y=s /*substitute the sum for a "new" X. */ - end /*until s==1 ···*/ /* [↑] keep looping 'til S=1 or 89.*/ -$.p=s /*use this for memoization for the sum.*/ -return s + if $.p\==. then return $.p /*Computed before? Then use the value.*/ + y=p /*use a new copy of P. */ + do until s==1 | s==89; s=0 /*add the squared decimal digits of P.*/ + do until y=='' /*process each decimal digits in X.*/ + parse var y _ +1 y; s=s + !._ /*get a dec. digit; sum the fast square*/ + end /*until y ···*/ /* [↑] S ≡ is sum of the squared digs.*/ + y=s /*substitute the sum for a "new" X. */ + end /*until s ···*/ /* [↑] keep looping 'til S=1 or 89.*/ + $.p=s /*use this for memoization for the sum.*/ + return s diff --git a/Task/JSON/00DESCRIPTION b/Task/JSON/00DESCRIPTION index b691587027..3b766a6e29 100644 --- a/Task/JSON/00DESCRIPTION +++ b/Task/JSON/00DESCRIPTION @@ -1,5 +1,5 @@ Load a [[wp:JSON|JSON]] string into a data structure. -Also create a new data structure and serialize it into JSON. +Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) -and make sure your JSON is valid (http://www.jsonlint.com/ or https://jsonformatter-online.com/). +and make sure your JSON is valid (https://jsonformatter.org or https://codebeautify.org/jsonvalidator). diff --git a/Task/JSON/Julia/json.julia b/Task/JSON/Julia/json.julia index 3164713e32..5f21c091e2 100644 --- a/Task/JSON/Julia/json.julia +++ b/Task/JSON/Julia/json.julia @@ -1,7 +1,13 @@ -julia> import JSON +# Pkg.add("JSON") ... an external library http://docs.julialang.org/en/latest/packages/packagelist/ +using JSON -julia> JSON.parse("""{ "blue": [1,2], "ocean": "water" }""") -["ocean"=>"water","blue"=>{1,2}] +sample = Dict() +sample["blue"] = [1, 2] +sample["ocean"] = "water" -julia> JSON.json({"blue" => [1,2] , "ocean" => "water"}) -"{\"ocean\":\"water\",\"blue\":[1,2]}" +@show sample jsonstring = json(sample) +@show jsonobj = JSON.parse(jsonstring) + +@assert jsonstring == "{\"ocean\":\"water\",\"blue\":[1,2]}" +@assert jsonobj == Dict("ocean" => "water", "blue" => [1, 2]) +@assert typeof(jsonobj) == Dict{String, Any} diff --git a/Task/JSON/Kotlin/json.kotlin b/Task/JSON/Kotlin/json.kotlin new file mode 100644 index 0000000000..4f8d5be992 --- /dev/null +++ b/Task/JSON/Kotlin/json.kotlin @@ -0,0 +1,15 @@ +// version 1.2.21 + +data class JsonObject(val foo: Int, val bar: Array) + +data class JsonObject2(val ocean: String, val blue: Array) + +fun main(args: Array) { + // JSON to object + val data: JsonObject = JSON.parse("""{ "foo": 1, "bar": ["10", "apples"] }""") + println(JSON.stringify(data)) + + // object to JSON + val data2 = JsonObject2("water", arrayOf(1, 2)) + println(JSON.stringify(data2)) +} diff --git a/Task/Jensens-Device/Julia/jensens-device.julia b/Task/Jensens-Device/Julia/jensens-device.julia index 323d163cd6..1e2aab0576 100644 --- a/Task/Jensens-Device/Julia/jensens-device.julia +++ b/Task/Jensens-Device/Julia/jensens-device.julia @@ -1,17 +1,14 @@ -i = 0 - -macro sum(i, lo_byname, hi_byname, term) - quote - lo = $lo_byname - hi = $hi_byname - temp = 0.0 - - for i=lo:hi - temp += $term +macro sum(i, loname, hiname, term) + return quote + lo = $loname + hi = $hiname + tmp = 0.0 + for i in lo:hi + tmp += $term end - - temp + return tmp end end -println(@sum(i, 1, 100, 1.0 / i)) +i = 0 +@sum(i, 1, 100, 1.0 / i) diff --git a/Task/Jensens-Device/Ring/jensens-device.ring b/Task/Jensens-Device/Ring/jensens-device.ring new file mode 100644 index 0000000000..d517727b66 --- /dev/null +++ b/Task/Jensens-Device/Ring/jensens-device.ring @@ -0,0 +1,16 @@ +# Project : Jensen's Device +# Date : 2018/01/31 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : + +decimals(14) +i = 100 +see sum(i,1,100,"1/n") + nl + +func sum(i,lo,hi,term) + temp = 0 + for n = lo to hi step 1 + eval("num = " + term) + temp = temp + num + next + return temp diff --git a/Task/Josephus-problem/BASIC/josephus-problem-1.basic b/Task/Josephus-problem/BASIC/josephus-problem-1.basic new file mode 100644 index 0000000000..078355d0fe --- /dev/null +++ b/Task/Josephus-problem/BASIC/josephus-problem-1.basic @@ -0,0 +1,7 @@ +10 N=41 +20 K=3 +30 M=0 +40 FOR I=M+1 TO N +50 M=INT(I*((M+K)/I-INT((M+K)/I))+0.5) +60 NEXT I +70 PRINT "Survivor is number";M diff --git a/Task/Josephus-problem/BASIC/josephus-problem-2.basic b/Task/Josephus-problem/BASIC/josephus-problem-2.basic new file mode 100644 index 0000000000..772578efaf --- /dev/null +++ b/Task/Josephus-problem/BASIC/josephus-problem-2.basic @@ -0,0 +1,5 @@ + 10 DEF FN MOD(X) = X - INT (X / A) * A + 20 LM = 0: INPUT "GIVE N AND K (N,K): ";N,K + 30 IF N < 1 or K < 1 THEN GOTO 20 + 40 FOR A = 1 TO N: LM = FN MOD(LM + K): NEXT A + 50 PRINT "N = ";N;", K = ";K;", SURVIVOR: ";LM diff --git a/Task/Josephus-problem/BBC-BASIC/josephus-problem.bbc b/Task/Josephus-problem/BBC-BASIC/josephus-problem.bbc new file mode 100644 index 0000000000..b35b6a8b37 --- /dev/null +++ b/Task/Josephus-problem/BBC-BASIC/josephus-problem.bbc @@ -0,0 +1,10 @@ +REM >josephus +PRINT "Survivor is number "; FNjosephus(41, 3, 0) +END +: +DEF FNjosephus(n%, k%, m%) +LOCAL i% +FOR i% = m% + 1 TO n% + m% = (m% + k%) MOD i% +NEXT += m% diff --git a/Task/Josephus-problem/Julia/josephus-problem-1.julia b/Task/Josephus-problem/Julia/josephus-problem-1.julia index ac5b3ba3ac..5cb046cbb7 100644 --- a/Task/Josephus-problem/Julia/josephus-problem-1.julia +++ b/Task/Josephus-problem/Julia/josephus-problem-1.julia @@ -1 +1,5 @@ -josephus(n, k, m=1) = n == m ? collect(0:m-1) : mod(josephus(n-1, k, m) + k, n) +using Memoize +@memoize josephus(n::Integer, k::Integer, m::Integer=1) = n == m ? collect(0:m .- 1) : mod.(josephus(n - 1, k, m) + k, n) + +@show josephus(41, 3) +@show josephus(41, 3, 5) diff --git a/Task/Josephus-problem/Julia/josephus-problem-2.julia b/Task/Josephus-problem/Julia/josephus-problem-2.julia index 806fa85da8..64cc451a8a 100644 --- a/Task/Josephus-problem/Julia/josephus-problem-2.julia +++ b/Task/Josephus-problem/Julia/josephus-problem-2.julia @@ -1,4 +1,14 @@ -julia> print(josephus(41,3)) -[30] -julia> print(josephus(41,3,5)) -[3,15,21,30,34] +function josephus(n::Integer, k::Integer, m::Integer=1) + p, i, seq = collect(0:n-1), 0, Vector{typeof(n)}(0) + while length(p) > m + i = (i + k - 1) % length(p) + push!(seq, splice!(p, i + 1)) + end + return seq, p +end + +seq, surv = josephus(41, 3) +println("Prisoner killing in order: $seq\nSurvivor: $surv") + +seq, surv = josephus(41, 3, 3) +println("Prisoner killing in order: $seq\nSurvivor: $surv") diff --git a/Task/Josephus-problem/MATLAB/josephus-problem.m b/Task/Josephus-problem/MATLAB/josephus-problem.m new file mode 100644 index 0000000000..acf4f4fc2c --- /dev/null +++ b/Task/Josephus-problem/MATLAB/josephus-problem.m @@ -0,0 +1,38 @@ +function [indAlive] = josephus(numPeople,count) +% Josephus: Given a circle of numPeople individuals, with a count of count, +% find the index (starting at 1) of the survivor [see Josephus Problem] + +%% Definitions: +% 0 = dead position +% 1 = alive position +% index = # of person + +%% Setting up +arrPeople = ones(1, numPeople); +currInd = 0; + +%% Counting +while (length(arrPeople(arrPeople == 1)) > 1) % While more than 1 person is alive + counter = 0; + while counter ~= count % Counting until we hit the count + currInd = currInd + 1; % Move to the next person + + if currInd > numPeople % If overflow, wraparound + currInd = currInd - numPeople; + end + + if arrPeople(currInd) % If the current person is alive + counter = counter + 1; % Add 1 person to the count + %fprintf("Index: %d \t| Counter: %d\n", currInd, counter) % Uncomment to display index and counter location + end + + end + + arrPeople(currInd) = 0; % Kill the person we reached + %fprintf("Killed person %d \n", currInd) % Uncomment to display order of killing + %disp(arrPeople) % Uncomment to display current status of people +end + +indAlive = find(arrPeople); + +end diff --git a/Task/Josephus-problem/Modula-2/josephus-problem.mod2 b/Task/Josephus-problem/Modula-2/josephus-problem.mod2 new file mode 100644 index 0000000000..535f7fedaa --- /dev/null +++ b/Task/Josephus-problem/Modula-2/josephus-problem.mod2 @@ -0,0 +1,26 @@ +MODULE Josephus; +FROM FormatString IMPORT FormatString; +FROM Terminal IMPORT WriteString,WriteLn,ReadChar; + +PROCEDURE Josephus(n,k : INTEGER) : INTEGER; +VAR a,m : INTEGER; +BEGIN + m := 0; + FOR a:=1 TO n DO + m := (m + k) MOD a; + END; + RETURN m +END Josephus; + +VAR + buf : ARRAY[0..63] OF CHAR; + n,k,i : INTEGER; + nl,kl,il : LONGCARD; +BEGIN + n := 41; + k := 3; + FormatString("n = %i, k = %i, final survivor: %i\n", buf, n, k, Josephus(n, k)); + WriteString(buf); + + ReadChar +END Josephus. diff --git a/Task/Josephus-problem/Perl-6/josephus-problem.pl6 b/Task/Josephus-problem/Perl-6/josephus-problem.pl6 new file mode 100644 index 0000000000..42ef468c3c --- /dev/null +++ b/Task/Josephus-problem/Perl-6/josephus-problem.pl6 @@ -0,0 +1,16 @@ +sub Execute(@prisoner, $k) { + until @prisoner == 1 { + @prisoner.=rotate($k - 1); + @prisoner.shift; + } +} + +my @prisoner = ^41; +Execute @prisoner, 3; +say "Prisoner {@prisoner} survived."; + +# We don't have to use numbers. Any list will do: + +my @dalton = ; +Execute @dalton, 2; +say "{@dalton} survived."; diff --git a/Task/Josephus-problem/PicoLisp/josephus-problem.l b/Task/Josephus-problem/PicoLisp/josephus-problem.l new file mode 100644 index 0000000000..b802ed897c --- /dev/null +++ b/Task/Josephus-problem/PicoLisp/josephus-problem.l @@ -0,0 +1,23 @@ +#general solution +(de jo (N K) + (if (=1 N) + 1 + (inc + (% + (+ (dec K) (jo (dec N) K)) + N ) ) ) ) + +#special case when K is 2; much faster than general version. +(de jo2(N) + (let P 1 + (while (<= P N) + (setq P (* 2 P)) + (+ (- (* 2 N) P) 1) ) ) ) + +# find the survivor using an optimal solution +(de survivor (N K) + (if (=0 (% N 2)) + (jo2 N) + (jo N K) ) ) +(print (survivor 5 2)) +(print (survivor 41 3)) diff --git a/Task/Josephus-problem/Python/josephus-problem-4.py b/Task/Josephus-problem/Python/josephus-problem-4.py new file mode 100644 index 0000000000..57326a9d1b --- /dev/null +++ b/Task/Josephus-problem/Python/josephus-problem-4.py @@ -0,0 +1,33 @@ +from itertools import compress, cycle +def josephus(prisoner, kill, surviver): + p = range(prisoner) + k = [0] * kill + k[kill-1] = 1 + s = [1] * kill + s[kill -1] = 0 + queue = p + + queue = compress(queue, cycle(s)) + try: + while True: + p.append(queue.next()) + except StopIteration: + pass + + kil=[] + killed = compress(p, cycle(k)) + try: + while True: + kil.append(killed.next()) + except StopIteration: + pass + + print 'The surviver is: ', kil[-surviver:] + print 'The kill sequence is ', kil[:prisoner-surviver] + +josephus(41,3,2) +The surviver is: [15, 30] +The kill sequence is [2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 38, 0, 4, 9, 13, 18, 22, 27, 31, 36, 40, 6, 12, 19, 25, 33, 39, 7, 16, 28, 37, 10, 24, 1, 21, 3, 34] +josephus(5,2,1) +The surviver is: [2] +The kill sequence is [1, 3, 0, 4] diff --git a/Task/Joystick-position/Haskell/joystick-position.hs b/Task/Joystick-position/Haskell/joystick-position.hs new file mode 100644 index 0000000000..8ada1b853e --- /dev/null +++ b/Task/Joystick-position/Haskell/joystick-position.hs @@ -0,0 +1,22 @@ +import qualified Graphics.UI.GLFW as GLFW -- cabal install GLFW-b +import Graphics.Win32.Key +import Control.Monad.RWS.Strict (liftIO) + +main = do + liftIO $ do + _ <- GLFW.init + GLFW.pollEvents + (jxrot, jyrot) <- liftIO $ getJoystickDirections GLFW.Joystick'1 + putStrLn $ (show jxrot) ++ " " ++ (show jyrot) + w <- getAsyncKeyState 27 -- ESC pressed? + if (w<1) then main else do + GLFW.terminate + return () + +getJoystickDirections :: GLFW.Joystick -> IO (Double, Double) + +getJoystickDirections js = do + maxes <- GLFW.getJoystickAxes js + return $ case maxes of + (Just (x:y:_)) -> (-y, x) + _ -> ( 0, 0) diff --git a/Task/Joystick-position/ZX-Spectrum-Basic/joystick-position.zx b/Task/Joystick-position/ZX-Spectrum-Basic/joystick-position.zx new file mode 100644 index 0000000000..3a57b72ec0 --- /dev/null +++ b/Task/Joystick-position/ZX-Spectrum-Basic/joystick-position.zx @@ -0,0 +1,17 @@ +10 DIM o$(5) +20 LET xm=0: LET xx=31: REM screen limits +30 LET ym=0: LET yx=18 +40 LET xo=16: LET yo=9: REM origin +50 LET xc=xo: LET yc=yo +60 PRINT AT yc,xc;" ": REM entry point for scan loop - blank cursor +70 LET xc=xo: LET yc=yo +80 LET t=IN 31 +90 IF t=1 OR t=5 OR t=9 OR t=17 OR t=21 OR t=25 THEN LET xc=xx: LET o$(2)="R": REM right +100 IF t=2 OR t=6 OR t=10 OR t=18 OR t=22 OR t=26 THEN LET xc=xm: LET o$(1)="L": REM left +110 IF t=4 OR t=5 OR t=6 OR t=20 OR t=21 OR t=22 THEN LET yc=yx: LET o$(4)="D": REM down +120 IF t=8 OR t=9 OR t=10 OR t=24 OR t=25 OR t=26 THEN LET yc=ym: LET o$(3)="U": REM up +130 IF t>=16 THEN LET o$(5)="F": REM fire +140 PRINT AT 21,0;"Input:";o$ +150 PRINT AT yc,xc;"+" +160 LET o$=" ": REM five spaces to blank output line again +170 GO TO 60 diff --git a/Task/Jump-anywhere/Go/jump-anywhere.go b/Task/Jump-anywhere/Go/jump-anywhere.go new file mode 100644 index 0000000000..dacf6f6e3d --- /dev/null +++ b/Task/Jump-anywhere/Go/jump-anywhere.go @@ -0,0 +1,21 @@ +package main + +import "fmt" + +func main() { + outer: + for i := 0; i < 4; i++ { + for j := 0; j < 4; j++ { + if i + j == 4 { continue outer } + if i + j == 5 { break outer } + fmt.Println(i + j) + } + } + + k := 3 + if k == 3 { goto later } + fmt.Println(k) // never executed + later: + k++ + fmt.Println(k) +} diff --git a/Task/Jump-anywhere/Julia/jump-anywhere.julia b/Task/Jump-anywhere/Julia/jump-anywhere.julia new file mode 100644 index 0000000000..f5bb260662 --- /dev/null +++ b/Task/Jump-anywhere/Julia/jump-anywhere.julia @@ -0,0 +1,7 @@ +function example() + println("Hello ") + @goto world + println("Never printed") + @label world + println("world") +end diff --git a/Task/K-d-tree/D/k-d-tree-2.d b/Task/K-d-tree/D/k-d-tree-2.d index 929debb90e..75818ce3ef 100644 --- a/Task/K-d-tree/D/k-d-tree-2.d +++ b/Task/K-d-tree/D/k-d-tree-2.d @@ -1,14 +1,12 @@ -import std.stdio, std.algorithm, std.math, std.random, std.typecons; +import std.stdio, std.algorithm, std.math, std.random; -enum maxDim = 3; - -struct KdNode { - double[maxDim] x; +struct KdNode(size_t dim) { + double[dim] x; KdNode* left, right; } // See QuickSelect method. -KdNode* findMedian(size_t idx)(KdNode[] nodes) pure nothrow @nogc { +KdNode!dim* findMedian(size_t idx, size_t dim)(KdNode!dim[] nodes) pure nothrow @nogc { auto start = nodes.ptr; auto end = &nodes[$ - 1] + 1; @@ -17,7 +15,7 @@ KdNode* findMedian(size_t idx)(KdNode[] nodes) pure nothrow @nogc { if (end == start + 1) return start; - KdNode* md = start + (end - start) / 2; + auto md = start + (end - start) / 2; while (true) { immutable double pivot = md.x[idx]; @@ -44,32 +42,32 @@ KdNode* findMedian(size_t idx)(KdNode[] nodes) pure nothrow @nogc { } } -KdNode* makeTree(size_t dim, size_t i)(KdNode[] nodes) +KdNode!dim* makeTree(size_t dim, size_t i = 0)(KdNode!dim[] nodes) pure nothrow @nogc { if (!nodes.length) return null; - auto n = findMedian!i(nodes); + auto n = nodes.findMedian!i; if (n != null) { enum i2 = (i + 1) % dim; immutable size_t nPos = n - nodes.ptr; - n.left = makeTree!(dim, i2)(nodes[0 .. nPos]); + n.left = makeTree!(dim, i2)(nodes[0 .. nPos]); n.right = makeTree!(dim, i2)(nodes[nPos + 1 .. $]); } return n; } -void nearest(size_t dim)(in KdNode* root, - in ref KdNode nd, +void nearest(size_t dim)(in KdNode!dim* root, + in ref KdNode!dim nd, in size_t i, - ref const(KdNode)* best, + ref const(KdNode!dim)* best, ref double bestDist, ref size_t nVisited) pure nothrow @safe @nogc { - static double dist(in ref KdNode a, in ref KdNode b) + static double dist(in ref KdNode!dim a, in ref KdNode!dim b) pure nothrow @nogc { - typeof(KdNode.x[0]) result = 0; - foreach (immutable i; staticIota!(0, dim)) + double result = 0; + static foreach (i; 0 .. dim) result += (a.x[i] - b.x[i]) ^^ 2; return result; } @@ -101,50 +99,50 @@ void nearest(size_t dim)(in KdNode* root, nd, i2, best, bestDist, nVisited); } -void randPt(size_t dim=3)(ref KdNode v, ref Xorshift rng) +void randPt(size_t dim)(ref KdNode!dim v, ref Xorshift rng) pure nothrow @safe @nogc { - foreach (immutable i; staticIota!(0, dim)) + static foreach (i; 0 .. dim) v.x[i] = rng.uniform01; } -void smallTest() { - KdNode[] wp = [{[2, 3]}, {[5, 4]}, {[9, 6]}, +/// smallTest +unittest { + KdNode!2[] wp = [{[2, 3]}, {[5, 4]}, {[9, 6]}, {[4, 7]}, {[8, 1]}, {[7, 2]}]; - KdNode thisPt = {[9, 2]}; + KdNode!2 thisPt = {[9, 2]}; - KdNode* root = makeTree!(2, 0)(wp); + auto root = makeTree(wp); - const(KdNode)* found = null; + const(KdNode!2)* found = null; double bestDist = 0; size_t nVisited = 0; - nearest!2(root, thisPt, 0, found, bestDist, nVisited); + root.nearest(thisPt, 0, found, bestDist, nVisited); writefln("WP tree:\n Searching for %s\n" ~ " Found %s, dist = %g\n Seen %d nodes.\n", - thisPt.x[0..2], found.x[0..2], sqrt(bestDist), nVisited); + thisPt.x, found.x, sqrt(bestDist), nVisited); } -void bigTest() { +/// bigTest +unittest { enum N = 1_000_000; enum testRuns = 100_000; - auto bigTree = new KdNode[N]; + auto bigTree = new KdNode!3[N]; auto rng = 1.Xorshift; foreach (ref node; bigTree) randPt(node, rng); - KdNode* root = makeTree!(3, 0)(bigTree); - KdNode thisPt; + auto root = makeTree(bigTree); + KdNode!3 thisPt; randPt(thisPt, rng); - const(KdNode)* found = null; + const(KdNode!3)* found = null; double bestDist = 0; size_t nVisited = 0; - nearest!3(root, thisPt, 0, found, bestDist, nVisited); + root.nearest(thisPt, 0, found, bestDist, nVisited); - writefln("Big tree (%d nodes):\n Searching for %s\n"~ - " Found %s, dist = %g\n Seen %d nodes.", - N, thisPt.x, found.x, sqrt(bestDist), nVisited); + writefln("Big tree (%d nodes):\n Searching for %s\n" ~ " Found %s, dist = %g\n Seen %d nodes.", N, thisPt.x, found.x, sqrt(bestDist), nVisited); size_t sum = 0; foreach (immutable _; 0 .. testRuns) { @@ -154,12 +152,7 @@ void bigTest() { nearest!3(root, thisPt, 0, found, bestDist, nVisited); sum += nVisited; } - writefln("\nBig tree:\n Visited %d nodes for %d random "~ + writefln("\nBig tree:\n Visited %d nodes for %d random " ~ "searches (%.2f per lookup).", sum, testRuns, sum / double(testRuns)); } - -void main() { - smallTest; - bigTest; -} diff --git a/Task/K-d-tree/Kotlin/k-d-tree.kotlin b/Task/K-d-tree/Kotlin/k-d-tree.kotlin new file mode 100644 index 0000000000..2b1d746733 --- /dev/null +++ b/Task/K-d-tree/Kotlin/k-d-tree.kotlin @@ -0,0 +1,126 @@ +// version 1.1.51 + +import java.util.Random + +typealias Point = DoubleArray + +fun Point.sqd(p: Point) = this.zip(p) { a, b -> (a - b) * (a - b) }.sum() + +class HyperRect (val min: Point, val max: Point) { + fun copy() = HyperRect(min.copyOf(), max.copyOf()) +} + +data class NearestNeighbor(val nearest: Point?, val distSqd: Double, val nodesVisited: Int) + +class KdNode( + val domElt: Point, + val split: Int, + var left: KdNode?, + var right: KdNode? +) + +class KdTree { + val n: KdNode? + val bounds: HyperRect + + constructor(pts: MutableList, bounds: HyperRect) { + fun nk2(exset: MutableList, split: Int): KdNode? { + if (exset.size == 0) return null + val exset2 = exset.sortedBy { it[split] } + for (i in 0 until exset.size) exset[i] = exset2[i] + var m = exset.size / 2 + val d = exset[m] + while (m + 1 < exset.size && exset[m + 1][split] == d[split]) m++ + var s2 = split + 1 + if (s2 == d.size) s2 = 0 + return KdNode( + d, + split, + nk2(exset.subList(0, m), s2), + nk2(exset.subList(m + 1, exset.size), s2) + ) + } + this.n = nk2(pts, 0) + this.bounds = bounds + } + + fun nearest(p: Point) = nn(n, p, bounds, Double.POSITIVE_INFINITY) + + private fun nn( + kd: KdNode?, + target: Point, + hr: HyperRect, + maxDistSqd: Double + ): NearestNeighbor { + if (kd == null) return NearestNeighbor(null, Double.POSITIVE_INFINITY, 0) + var nodesVisited = 1 + val s = kd.split + val pivot = kd.domElt + val leftHr = hr.copy() + val rightHr = hr.copy() + leftHr.max[s] = pivot[s] + rightHr.min[s] = pivot[s] + val targetInLeft = target[s] <= pivot[s] + val nearerKd = if (targetInLeft) kd.left else kd.right + val nearerHr = if (targetInLeft) leftHr else rightHr + val furtherKd = if (targetInLeft) kd.right else kd.left + val furtherHr = if (targetInLeft) rightHr else leftHr + var (nearest, distSqd, nv) = nn(nearerKd, target, nearerHr, maxDistSqd) + nodesVisited += nv + var maxDistSqd2 = if (distSqd < maxDistSqd) distSqd else maxDistSqd + var d = pivot[s] - target[s] + d *= d + if (d > maxDistSqd2) return NearestNeighbor(nearest, distSqd, nodesVisited) + d = pivot.sqd(target) + if (d < distSqd) { + nearest = pivot + distSqd = d + maxDistSqd2 = distSqd + } + val temp = nn(furtherKd, target, furtherHr, maxDistSqd2) + nodesVisited += temp.nodesVisited + if (temp.distSqd < distSqd) { + nearest = temp.nearest + distSqd = temp.distSqd + } + return NearestNeighbor(nearest, distSqd, nodesVisited) + } +} + +val rand = Random() + +fun randomPt(dim: Int) = Point(dim) { rand.nextDouble() } + +fun randomPts(dim: Int, n: Int) = MutableList(n) { randomPt(dim) } + +fun showNearest(heading: String, kd: KdTree, p: Point) { + println("$heading:") + println("Point : ${p.asList()}") + val (nn, ssq, nv) = kd.nearest(p) + println("Nearest neighbor : ${nn?.asList()}") + println("Distance : ${Math.sqrt(ssq)}") + println("Nodes visited : $nv") + println() +} + +fun main(args: Array) { + val points = mutableListOf( + doubleArrayOf(2.0, 3.0), + doubleArrayOf(5.0, 4.0), + doubleArrayOf(9.0, 6.0), + doubleArrayOf(4.0, 7.0), + doubleArrayOf(8.0, 1.0), + doubleArrayOf(7.0, 2.0) + ) + var hr = HyperRect(doubleArrayOf(0.0, 0.0), doubleArrayOf(10.0, 10.0)) + var kd = KdTree(points, hr) + showNearest("WP example data", kd, doubleArrayOf(9.0, 2.0)) + + hr = HyperRect(doubleArrayOf(0.0, 0.0, 0.0), doubleArrayOf(1.0, 1.0, 1.0)) + kd = KdTree(randomPts(3, 1000), hr) + showNearest("1000 random 3D points", kd, randomPt(3)) + + hr = hr.copy() + kd = KdTree(randomPts(3, 400_000), hr) + showNearest("400,000 random 3D points", kd, randomPt(3)) +} diff --git a/Task/K-means++-clustering/00META.yaml b/Task/K-means++-clustering/00META.yaml new file mode 100644 index 0000000000..29aeacfd2a --- /dev/null +++ b/Task/K-means++-clustering/00META.yaml @@ -0,0 +1,2 @@ +--- +note: Probability and statistics diff --git a/Task/K-means++-clustering/JavaScript/k-means++-clustering.js b/Task/K-means++-clustering/JavaScript/k-means++-clustering.js new file mode 100644 index 0000000000..638d123e8d --- /dev/null +++ b/Task/K-means++-clustering/JavaScript/k-means++-clustering.js @@ -0,0 +1,745 @@ +/** + * kmeans module + * + * cluster(model, k, converged = assignmentsConverged) + * distance(p, q), + * distanceSquared(p, q), + * centroidsConverged(delta) + * assignmentsConverged(model, newModel) + * assignmentsToClusters(model) + */ +define(function () { + "use strict"; + + /** + * @public + * Calculate the squared distance between two vectors. + * + * @param [number] p vector with same dimension as q + * @param [number] q vector with same dimension as p + * @return {number} the distance between p and q squared + */ + function distanceSquared(p, q) { + const d = p.length; // dimension of vectors + + if(d !== q.length) throw Error("p and q vectors must be the same length") + + let sum = 0; + for(let i = 0; i < d; i += 1) { + sum += (p[i] - q[i])**2 + } + return sum; + } + + /** + * @public + * Calculate the distance between two vectors of the same dimension. + * + * @param [number] p vector of same dimension as q + * @param [number] q vector of same dimension as p + * @return the distance between vectors p and q + */ + function distance(p, q) { + return Math.sqrt(distanceSquared(p, q)); + } + + /** + * @private + * find the closest centroid for the given observation and return it's index. + * + * @param [[number]] centroids - array of k vectors, each vector with same dimension as observations. + * these are the center of the k clusters + * @param [[number]] observation - vector with same dimension as centroids. + * this is the observation to be clustered. + * @return {number} the index of the closest centroid in centroids + */ + function findClosestCentroid(centroids, observation) { + const k = centroids.length; // number of clusters/centroids + + let centroid = 0; + let minDistance = distance(centroids[0], observation); + for(let i = 1; i < k; i += 1) { + const dist = distance(centroids[i], observation); + if(dist < minDistance) { + centroid = i; + minDistance = dist; + } + } + return centroid; + } + + /** + * @private + * Calculate the centroid for the given observations. + * This takes the average of all observations (at each dimension). + * This average vector is the centroid for those observations. + * + * @param [[number]] observations - array of observations (each observatino is a vectors) + * @return [number] centroid for given observations (vector of same dimension as observations) + */ + function calculateCentroid(observations) { + const n = observations.length; // number of observations + const d = observations[0].length; // dimension of vectors + + // create zero vector of same dimension as observation + let centroid = []; + for(let i = 0; i < d; i += 1) { + centroid.push(0.0); + } + + // + // sum all observations at each dimension + // + for(let i = 0; i < n; i += 1) { + // + // add the observation to the sum vector, element by element + // to prepare to calculate the average at each dimension. + // + for(let j = 0; j < d; j += 1) { + centroid[j] += observations[i][j]; + } + } + + // + // divide each dimension by the number of observations + // to create the average vector. + // + for(let j = 0; j < d; j += 1) { + centroid[j] /= n; + } + + return centroid; + } + + /** + * @private + * calculate the cluster assignments for the observations, given the centroids. + * + * @param [[number]] centroids - list of vectors with same dimension as observations + * @param [[number]] observations - list of vectors with same dimension as centroids + * @return [number] list of indices into centroids; one per observation. + */ + function assignClusters(centroids, observations) { + const n = observations.length; // number of observations + + const assignments = []; + for(let i = 0; i < n; i += 1) { + assignments.push(findClosestCentroid(centroids, observations[i])); + } + + return assignments; // centroid index for each observation + } + + /** + * @private + * calculate one step of the k-means algorithm; + * - assign each observation to the nearest centroid to create clusters + * - calculate a new centroid for each cluster given the observations in the cluster. + * + * @param [[number]] centroids - list of vectors with same dimension as observations + * @param [[number]] observations - list of vectors with same dimension as centroids + * @return a new model with observations, centroids and assignments + */ + function kmeansStep(centroids, observations) { + const k = centroids.length; // number of clusters/centroids + + // assign each observation to the nearest centroid to create clusters + const assignments = assignClusters(centroids, observations); // array of cluster indices that correspond observations + + // calculate a new centroid for each cluster given the observations in the cluster + const newCentroids = []; + for(let i = 0; i < k; i += 1) { + // get the observations for this cluster/centroid + const clusteredObservations = observations.filter((v, j) => assignments[j] === i); + + // calculate a new centroid for the observations + newCentroids.push(calculateCentroid(clusteredObservations)); + } + return {'observations': observations, 'centroids': newCentroids, 'assignments': assignments } + } + + /** + * @public + * Run k-means on the given model until each centroid converges to with the given delta + * The initial model is NOT modified by the algorithm, rather a new model is returned. + * + * @param {*} model - object with + * observations: array, length n, of data points; each datapoint is + * itself an array of numbers (a vector). + * The length each datapoint (d) vector should be the same. + * centroids: array of data points. + * The length of the centroids array indicates the number of + * of desired clusters (k). + * each datapoint is array (vector) of numbers + * with same dimension as the datapoints in observations. + * assignments: array of integers, one per observation, + * with values 0..centroids.length - 1 + * @param number delta - the maximum difference between each centroid in consecutive runs for convergence + * @return {*} - result with + * model: model, as described above, with updated centroids and assignments, + * iterations: number of iterations, + * durationMs: elapsed time in milliseconds + */ + function kmeans(model, maximumIterations = 200, converged = assignmentsConverged) { + const start = new Date(); + + // calculate new centroids and cluster assignments + let newModel = kmeansStep(model.centroids, model.observations); + + // continue until centroids do not change (within given delta) + let i = 0; + while((i < maximumIterations) && !converged(model, newModel)) { + model = newModel; // new model is our model now + // console.log(model); + + // calculate new centroids and cluster assignments + newModel = kmeansStep(model.centroids, model.observations); + i += 1; + } + + // console.log(newModel); + const finish = new Date(); + return {'model': newModel, 'iterations': i, 'durationMs': (finish.getTime() - start.getTime())}; + } + + /** + * @public + * Return a function that determines convergence based on the centroids. + * If two consecutive sets of centroids remain within a given delta, + * then the algorithm is converged. + * + * @param number delta, the maximum difference between each centroid in consecutive runs for convergence + * @return function to use as the converged function in kmeans call. + */ + function centroidsConverged(delta) { + /** + * determine if two consecutive set of centroids are converged given a maximum delta. + * + * @param [[number]] centroids - list of vectors with same dimension as observations + * @param [[number]] newCentroids - list of vectors with same dimension as observations + * @param number delta - the maximum difference between each centroid in consecutive runs for convergence + */ + return function(model, newModel) { + const centroids = model.centroids; + const newCentroids = newModel.centroids; + + const k = centroids.length; // number of clusters/centroids + for(let i = 0; i < k; i += 1) { + if(distance(centroids[i], newCentroids[i]) > delta) { + return false; + } + } + + return true; + } + } + + /** + * @public + * determine if two consecutive set of clusters are converged; + * the clusters are converged if the cluster assignments are the same. + * + * @param {*} model - object with observations, centroids, assignments + * @param {*} newModel - object with observations, centroids, assignments + * @param number delta - the maximum difference between each centroid in consecutive runs for convergence + */ + function assignmentsConverged(model, newModel) { + function arraysEqual(a, b) { + if (a === b) return true; + if (a === undefined || b === undefined) return false; + if (a === null || b === null) return false; + if (a.length !== b.length) return false; + + // If you don't care about the order of the elements inside + // the array, you should sort both arrays here. + + for (var i = 0; i < a.length; ++i) { + if (a[i] !== b[i]) return false; + } + return true; + } + + return arraysEqual(model.assignments, newModel.assignments); + } + + /** + * Use the model assignments to create + * array of observation indices for each centroid + * + * @param {object} model with observations, centroids and assignments + * @reutrn [[number]] array of observation indices for each cluster + */ + function assignmentsToClusters(model) { + // + // put offset of each data points into clusters using the assignments + // + const n = model.observations.length; + const k = model.centroids.length; + const assignments = model.assignments; + const clusters = []; + for(let i = 0; i < k; i += 1) { + clusters.push([]) + } + for(let i = 0; i < n; i += 1) { + clusters[assignments[i]].push(i); + } + + return clusters; + } + + + // + // return public methods + // + return { + 'cluster': kmeans, + 'distance': distance, + 'distanceSquared': distanceSquared, + 'centroidsConverged': centroidsConverged, + 'assignmentsConverged': assignmentsConverged, + "assignmentsToClusters": assignmentsToClusters + }; + +}); + +/** + * kmeans++ initialization module + */ +define(function (require) { + "use strict"; + + const kmeans = require("./kmeans"); + + /** + * @public + * create an initial model given the data and the number of clusters. + * + * This uses the kmeans++ algorithm: + * 1. Choose one center uniformly at random from among the data points. + * 2. For each data point x, compute D(x), the distance between x and + * the nearest center that has already been chosen. + * 3. Choose one new data point at random as a new center, + * using a weighted probability distribution where a point x is chosen with probability proportional to D(x)^2. + * 4. Repeat Steps 2 and 3 until k centers have been chosen. + * 5. Now that the initial centers have been chosen, proceed using + * standard k-means clustering. + * + * @param {[float]} observations the data as an array of number + * @param {integer} k the number of clusters + */ + return function(observations, k) { + + /** + * given a set of n weights, + * choose a value in the range 0..n-1 + * at random using weights as a distribution. + * + * @param {*} weights + */ + function weightedRandomIndex(weights, normalizationWeight) { + const n = weights.length; + if(typeof normalizationWeight !== 'number') { + normalizationWeight = 0.0; + for(let i = 0; i < n; i += 1) { + normalizationWeight += weights[i]; + } + } + + const r = Math.random(); // uniformly random number 0..1 (a probability) + let index = 0; + let cumulativeWeight = 0.0; + for(let i = 0; i < n; i += 1) { + // + // use the uniform probability to search + // within the normalized weighting (we divide by totalWeight to normalize). + // once we hit the probability, we have found our index. + // + cumulativeWeight += weights[i] / normalizationWeight; + if(cumulativeWeight > r) { + return i; + } + } + + throw Error("algorithmic failure choosing weighted random index"); + } + + const n = observations.length; + const distanceToCloseCentroid = []; // distance D(x) to closest centroid for each observation + const centroids = []; // indices of observations that are chosen as centroids + + // + // keep list of all observations' indices so + // we can remove centroids as they are created + // so they can't be chosen twice + // + const index = []; + for(let i = 0; i < n; i += 1) { + index[i] = i; + } + + // + // 1. Choose one center uniformly at random from among the data points. + // + let centroidIndex = Math.floor(Math.random() * n); + centroids.push(centroidIndex); + + for(let c = 1; c < k; c += 1) { + index.slice(centroids[c - 1], 1); // remove previous centroid from further consideration + distanceToCloseCentroid[centroids[c - 1]] = 0; // this effectively removes it from the probability distribution + + // + // 2. For each data point x, compute D(x), the distance between x and + // the nearest center that has already been chosen. + // + // NOTE: we used the distance squared (L2 norm) + // + let totalWeight = 0.0; + for(let i = 0; i < index.length; i += 1) { + // + // if this is the first time through, the distance is undefined, so just set it. + // Otherwise, choose the minimum of the prior closest and this new centroid + // + const distanceToCentroid = kmeans.distanceSquared(observations[index[i]], observations[centroids[c - 1]]); + distanceToCloseCentroid[index[i]] = + (typeof distanceToCloseCentroid[index[i]] === 'number') + ? Math.min(distanceToCloseCentroid[index[i]], distanceToCentroid) + : distanceToCentroid; + totalWeight += distanceToCloseCentroid[index[i]]; + } + + // + // 3. Choose one new data point at random as a new center, + // using a weighted probability distribution where a point x is chosen with probability proportional to D(x)^2. + // + centroidIndex = index[weightedRandomIndex(distanceToCloseCentroid, totalWeight)]; + centroids.push(centroidIndex); + + // 4. Repeat Steps 2 and 3 until k centers have been chosen. + } + + // + // 5. Now that the initial centers have been chosen, proceed using + // standard k-means clustering. Return the model so that + // kmeans can continue. + // + return { + 'observations': observations, + 'centroids': centroids.map(x => observations[x]), // map centroid index to centroid value + 'assignments': observations.map((x, i) => i % centroids.length) // distribute among centroids + } + } + +}); + +/** + * Extra Credit #1 + * module for creating random models for kmeans clustering + */ +define(function (require) { + "use strict"; + + const kmeans = require("./kmeans"); + + /** + * @return a random, normally distributed number + */ + function randomNormal() { + // n = 6 gives a good enough approximation + return ((Math.random() + Math.random() + Math.random() + Math.random() + Math.random() + Math.random()) - 3) / 3; + } + + /** + * Generate a uniform random unit vector + * + * @param {Integer} d dimension of data + * @return n random datapoints of dimension d with length == 1 + */ + function randomUnitVector(d) { + const range = max - min; + let magnitude = 0.0; + const observation = []; + + // uniform random for each dimension + for(let j = 0; j < d; j += 1) { + const x = Math.random(); + observation[j] = x; + magnitude = x * x; + } + + // normalize + const magnitude = Math.sqrt(magnitude); + for(let j = 0; j < d; j += 1) { + observation[j] /= magnitude; + } + + return observation; + } + + /** + * Generate a uniform random unit vectors for clustering + * + * @param {Integer} n number of data points + * @param {Integer} d dimension of data + * @return n random datapoints of dimension d with length == 1 + */ + function randomUnitVectors(n, d) { + + // create n random observations, each of dimension d + const observations = []; + for(let i = 0; i < n; i += 1) { + // create random observation of dimension d + const observation = randomUnitVector(d); + observations.push(observation); + } + + return observations; + } + + + + /** + * Generate a spherical random vector + * + * @param {Integer} n number of data points + * @param {Integer} d dimension of data + * @param {Number} r radium from center for data point + * @return n random datapoints of dimension d + */ + function randomSphericalVector(d, r) { + const observation = []; + + let magnitude = 0.0; + for(let j = 0; j < d; j += 1) + { + const x = randomNormal(); + observation[j] = x; + magnitude += x * x; + } + + // normalize + magnitude = Math.sqrt(magnitude); + for(let j = 0; j < d; j += 1) { + observation[j] = observation[j] * r / magnitude; + } + + return observation; + } + + + + /** + * Generate a spherical random vectors + * + * @param {Integer} n number of data points + * @param {Integer} d dimension of data + * @param {Number} max radius from center for data points + * @return n random datapoints of dimension d + */ + function randomSphericalVectors(n, d, r) { + + // create n random observations, each of dimension d + const observations = []; + for(let i = 0; i < n; i += 1) { + // create random observation of dimension d with random radius + const observation = randomSphericalVector(d, Math.random() * r); + observations.push(observation); + } + + return observations; + } + + /** + * Generate a uniform random model for clustering + * + * @param {Integer} n number of data points + * @param {Integer} d dimension of data + * @param {Number} radius of sphere + * @return n random datapoints of dimension d + */ + function randomVectors(n, d, min, max) { + + const range = max - min; + + // create n random observations, each of dimension d + const observations = []; + for(let i = 0; i < n; i += 1) { + // create random observation of dimension d + const observation = randomVector(d, min, max); + observations.push(observation); + } + + return observations; + } + + /** + * Generate a uniform random model for clustering + * + * @param {Integer} d dimension of data + * @param {Number} radius of sphere + * @return n random datapoints of dimension d + */ + function randomVector(d, min, max) { + + // create random observation of dimension d + const range = max - min; + const observation = []; + for(let j = 0; j < d; j += 1) { + observation.push(min + Math.random() * range); + } + + return observation; + } + + return { + 'randomVector': randomVector, + 'randomUnitVector': randomUnitVector, + 'randomSphericalVector': randomSphericalVector, + 'randomVectors': randomVectors, + 'randomUnitVectors': randomUnitVectors, + 'randomSphericalVectors': randomSphericalVectors + } + +}); + +/** + * Extra Credit #4 + * Application to cluster random data using kmeans++ + * + * cluster(k, n, d) - cluster n data points of dimension d into k clusters + * plot(canvas, result) - plot the results of cluster() to the given html5 canvas using clusterjs + */ +define(function (require) { + "use strict"; + const kmeans = require("./kmeans/kmeans"); + const kmeanspp = require("./kmeans/kmeanspp"); + const randomCentroidInitializer = require("./kmeans/randomCentroidInitializer"); + const kmeansRandomModel = require("./kmeans/kmeansRandomModel"); + + + /** + * @public + * Load iris dataset and run kmeans on it given the number of clusters + * + * @param {integer} k number of clusters to create + */ + function cluster(k, n, d) { + + // + // map iris data rows from dictionary to vector (array), leaving out the label + // + const observations = kmeansRandomModel.randomSphericalVectors(n, d, 10.0); + + // + // create the intial model and run it + // + // const initialModel = randomCentroidInitializer(observations, k); + const initialModel = kmeanspp(observations, k); + + // + // cluster into given number of clusters + // + const results = kmeans.cluster(initialModel); + + // + // do this for the convenience of the plotting functions + // + results.clusters = kmeans.assignmentsToClusters(results.model); + + return results; + } + + const clusterColor = ['red', 'green', 'blue', 'yellow', 'purple', 'cyan', 'magenta', 'pink', 'brown', 'black']; + let chart = undefined; + + /** + * plot the clustred iris data model. + * + * @param {object} results of cluster(), with model, clusters and clusterCompositions + * @param {boolean} showClusterColor true to show learned cluster points + * @param {boolean} showSpeciesColor true to show known dataset labelled points + */ + function plot(canvas, results) { + + // + // map iris data rows from dictionary to vector (array), leaving out the label + // + const model = results.model; + const observations = model.observations; + const assignments = model.assignments; + const centroids = model.centroids; + const d = observations[0].length; + const n = observations.length; + const k = centroids.length; + + // + // put offset of each data points into clusters using the assignments + // + const clusters = results.clusters; + + // + // plot the clusters + // + const chartData = { + // for the purposes of plotting in 2 dimensions, we will use + // x = dimension 0 and y = dimension 1 + datasets: clusters.map(function(c, i) { + return { + label: "cluster" + i, + data: c.map(d => ({'x': observations[d][0], 'y': observations[d][1]})), + backgroundColor: clusterColor[i % clusterColor.length], + pointBackgroundColor: clusterColor[i % clusterColor.length], + pointBorderColor: clusterColor[i % clusterColor.length] + }; + }) + }; + const chartOptions = { + responsive: true, + maintainAspectRatio: false, + title: { + display: true, + text: 'Random spherical data set (d=$d, n=$n) clustered using K-Means (k=$k)' + .replace("$d", d) + .replace('$n', n) + .replace('$k', k) + }, + legend: { + position: 'bottom', + display: true + }, + scales: { + xAxes: [{ + type: 'linear', + position: 'bottom', + scaleLabel: { + labelString: 'x axis', + display: false, + } + }], + yAxes: [{ + type: 'linear', + position: 'left', + scaleLabel: { + labelString: 'y axis', + display: false + } + }] + } + }; + + // + // we need to destroy the previous chart so it's interactivity + // does not continue to run + // + if(undefined !== chart) { + chart.destroy() + } + chart = new Chart(canvas, { + type: 'scatter', + data: chartData, + options: chartOptions, + }); + + } + + return {'cluster': cluster, 'plot': plot}; +}); diff --git a/Task/K-means++-clustering/Kotlin/k-means++-clustering.kotlin b/Task/K-means++-clustering/Kotlin/k-means++-clustering.kotlin new file mode 100644 index 0000000000..72d69ea545 --- /dev/null +++ b/Task/K-means++-clustering/Kotlin/k-means++-clustering.kotlin @@ -0,0 +1,162 @@ +// version 1.2.21 + +import java.util.Random +import kotlin.math.* + +data class Point(var x: Double, var y: Double, var group: Int) + +typealias LPoint = List +typealias MLPoint = MutableList + +val origin get() = Point(0.0, 0.0, 0) +val r = Random() +val hugeVal = Double.POSITIVE_INFINITY + +const val RAND_MAX = Int.MAX_VALUE +const val PTS = 100_000 +const val K = 11 +const val W = 400 +const val H = 400 + +fun rand() = r.nextInt(RAND_MAX) + +fun randf(m: Double) = m * rand() / (RAND_MAX - 1) + +fun genXY(count: Int, radius: Double): LPoint { + val pts = List(count) { origin } + + /* note: this is not a uniform 2-d distribution */ + for (i in 0 until count) { + val ang = randf(2.0 * PI) + val r = randf(radius) + pts[i].x = r * cos(ang) + pts[i].y = r * sin(ang) + } + return pts +} + +fun dist2(a: Point, b: Point): Double { + val x = a.x - b.x + val y = a.y - b.y + return x * x + y * y +} + +fun nearest(pt: Point, cent: LPoint, nCluster: Int): Pair { + var minD = hugeVal + var minI = pt.group + for (i in 0 until nCluster) { + val d = dist2(cent[i], pt) + if (minD > d) { + minD = d + minI = i + } + } + return minI to minD +} + +fun kpp(pts: LPoint, len: Int, cent: MLPoint) { + val nCent = cent.size + val d = DoubleArray(len) + cent[0] = pts[rand() % len].copy() + for (nCluster in 1 until nCent) { + var sum = 0.0 + for (j in 0 until len) { + d[j] = nearest(pts[j], cent, nCluster).second + sum += d[j] + } + sum = randf(sum) + for (j in 0 until len) { + sum -= d[j] + if (sum > 0.0) continue + cent[nCluster] = pts[j].copy() + break + } + } + for (j in 0 until len) pts[j].group = nearest(pts[j], cent, nCent).first +} + +fun lloyd(pts: LPoint, len: Int, nCluster: Int): LPoint { + val cent = MutableList(nCluster) { origin } + kpp(pts, len, cent) + do { + /* group element for centroids are used as counters */ + for (i in 0 until nCluster) { + with (cent[i]) { x = 0.0; y = 0.0; group = 0 } + } + for (j in 0 until len) { + val p = pts[j] + val c = cent[p.group] + with (c) { group++; x += p.x; y += p.y } + } + for (i in 0 until nCluster) { + val c = cent[i] + c.x /= c.group + c.y /= c.group + } + var changed = 0 + + /* find closest centroid of each point */ + for (j in 0 until len) { + val p = pts[j] + val minI = nearest(p, cent, nCluster).first + if (minI != p.group) { + changed++ + p.group = minI + } + } + } + while (changed > (len shr 10)) /* stop when 99.9% of points are good */ + + for (i in 0 until nCluster) cent[i].group = i + return cent +} + +fun printEps(pts: LPoint, len: Int, cent: LPoint, nCluster: Int) { + val colors = DoubleArray(nCluster * 3) + for (i in 0 until nCluster) { + colors[3 * i + 0] = (3 * (i + 1) % 11) / 11.0 + colors[3 * i + 1] = (7 * i % 11) / 11.0 + colors[3 * i + 2] = (9 * i % 11) / 11.0 + } + var minX = hugeVal + var minY = hugeVal + var maxX = -hugeVal + var maxY = -hugeVal + for (j in 0 until len) { + val p = pts[j] + if (maxX < p.x) maxX = p.x + if (minX > p.x) minX = p.x + if (maxY < p.y) maxY = p.y + if (minY > p.y) minY = p.y + } + val scale = minOf(W / (maxX - minX), H / (maxY - minY)) + val cx = (maxX + minX) / 2.0 + val cy = (maxY + minY) / 2.0 + + print("%%!PS-Adobe-3.0\n%%%%BoundingBox: -5 -5 %${W + 10} ${H + 10}\n") + print("/l {rlineto} def /m {rmoveto} def\n") + print("/c { .25 sub exch .25 sub exch .5 0 360 arc fill } def\n") + print("/s { moveto -2 0 m 2 2 l 2 -2 l -2 -2 l closepath ") + print(" gsave 1 setgray fill grestore gsave 3 setlinewidth") + print(" 1 setgray stroke grestore 0 setgray stroke }def\n") + val f1 = "%g %g %g setrgbcolor" + val f2 = "%.3f %.3f c" + val f3 = "\n0 setgray %g %g s" + for (i in 0 until nCluster) { + val c = cent[i] + println(f1.format(colors[3 * i], colors[3 * i + 1], colors[3 * i + 2])) + for (j in 0 until len) { + val p = pts[j] + if (p.group != i) continue + println(f2.format((p.x - cx) * scale + W / 2, (p.y - cy) * scale + H / 2)) + } + println(f3.format((c.x - cx) * scale + W / 2, (c.y - cy) * scale + H / 2)) + } + print("\n%%%%EOF") +} + +fun main(args: Array) { + val v = genXY(PTS, 10.0) + val c = lloyd(v, PTS, K) + printEps(v, PTS, c, K) +} diff --git a/Task/Kaprekar-numbers/Erlang/kaprekar-numbers.erl b/Task/Kaprekar-numbers/Erlang/kaprekar-numbers.erl new file mode 100644 index 0000000000..f93ac26fea --- /dev/null +++ b/Task/Kaprekar-numbers/Erlang/kaprekar-numbers.erl @@ -0,0 +1,27 @@ +-mode(compile). +-import(lists, [seq/2]). + +kaprekar(1) -> true; +kaprekar(N) when N < 1 -> false; +kaprekar(N) -> + Sq = N*N, + if + (N rem 9) =/= (Sq rem 9) -> false; + true -> kaprekar(N, Sq, 10) + end. + +kaprekar(_, Sq, M) when (Sq div M) =:= 0 -> false; +kaprekar(N, Sq, M) -> + L = Sq div M, + R = Sq rem M, + if + R =/= 0 andalso (L + R) =:= N -> true; + true -> kaprekar(N, Sq, M * 10) + end. + +main(_) -> + Numbers = [N || N <- seq(1, 9999), kaprekar(N)], + io:format("The Kaprekar numbers < 10,000 are ~p~n", [Numbers]), + + CountTo1e6 = length(Numbers) + length([N || N <- seq(10001, 999999), kaprekar(N)]), + io:format("There are ~p Kaprekar numbers < 1,000,000", [CountTo1e6]). diff --git a/Task/Kaprekar-numbers/Factor/kaprekar-numbers.factor b/Task/Kaprekar-numbers/Factor/kaprekar-numbers.factor new file mode 100644 index 0000000000..b1205ff450 --- /dev/null +++ b/Task/Kaprekar-numbers/Factor/kaprekar-numbers.factor @@ -0,0 +1,27 @@ +USING: grouping.extras kernel math math.parser math.ranges +math.text.utils prettyprint sequences sequences.extras +splitting ; +IN: rosetta-code.kaprekar + +: digits ( n -- digits ) + 1 digit-groups reverse ; + +: digit-pairs ( digits -- seq1 seq2 ) + [ tail-clump ] [ head-clump ] bi [ 1 rotate ] dip ; + +: digit-pairs>number-pairs ( seq1 seq2 -- seq1' seq2' ) + [ [ 10 digits>integer ] map but-last ] bi@ ; + +: remove-zeros ( seq1 seq2 -- seq1' seq2' ) + [ [ 0 = ] split1-when drop ] bi@ ; + +: kaprekar-pairs ( n -- seq1 seq2 ) + digits digit-pairs digit-pairs>number-pairs remove-zeros ; + +: kaprekar? ( n -- ? ) + dup sq kaprekar-pairs [ + ] 2map member? ; + +: main ( -- ) + 10000 [1,b) [ kaprekar? ] filter { 1 } prepend . ; + +MAIN: main diff --git a/Task/Kaprekar-numbers/Julia/kaprekar-numbers.julia b/Task/Kaprekar-numbers/Julia/kaprekar-numbers.julia index 564b4b409d..e830a8581b 100644 --- a/Task/Kaprekar-numbers/Julia/kaprekar-numbers.julia +++ b/Task/Kaprekar-numbers/Julia/kaprekar-numbers.julia @@ -1,6 +1,11 @@ -function iskaprekar(n) - str = string(n^2) - n == 1 ? true : - any([ n == parse(Int,str[1:i]) + parse(Int,str[i+1:end]) && parse(Int,str[i+1:end]) != 0 - for i = 1:length(str)-1]) +function iskaprekar(n::Integer) + str = dec(n ^ 2) + if n == 1 return true + else + return any(n == parse(Int, str[1:i]) + parse(Int, str[i+1:end]) && parse(Int, str[i+1:end]) != 0 + for i = 1:length(str)-1) + end end + +@show filter(iskaprekar, 1:10000) +@show count(iskaprekar, 1:10000) diff --git a/Task/Kaprekar-numbers/Modula-2/kaprekar-numbers.mod2 b/Task/Kaprekar-numbers/Modula-2/kaprekar-numbers.mod2 new file mode 100644 index 0000000000..284ec661d1 --- /dev/null +++ b/Task/Kaprekar-numbers/Modula-2/kaprekar-numbers.mod2 @@ -0,0 +1,63 @@ +MODULE Kaprekar; +FROM FormatString IMPORT FormatString; +FROM Terminal IMPORT Write,WriteString,WriteLn,ReadChar; + +PROCEDURE kaprekar(n,base : LONGCARD) : BOOLEAN; +VAR + nn,r,tens : LONGCARD; +BEGIN + nn := n*n; + tens := 1; + IF ((nn - n) MOD (base - 1)) # 0 THEN RETURN FALSE END; + + WHILE tens < n DO tens := tens * base END; + IF n = tens THEN + IF 1 = n THEN RETURN TRUE END; + RETURN FALSE + END; + + LOOP + r := nn MOD tens; + IF r >= n THEN BREAK END; + IF nn DIV tens + r = n THEN RETURN tens#0 END; + tens := tens * base; + END; + + RETURN FALSE +END kaprekar; + +PROCEDURE print_num(n,base : LONGCARD); +VAR q,d : LONGCARD; +BEGIN + d := base; + + WHILE d1 then call tell 1 /*unity is defined to be a Kaprekar #. */ + if aN>0 then call tell 1 /*unity is defined to be a Kaprekar #. */ /* [↑] handle case of N being unity.*/ if aN>1 then do j=2 for aN-2; s=j*j /*calculate the square of J (S). */ if j//9==s//9 then do k=1 for length(s)%2 /*≡ casted out 9's?*/ diff --git a/Task/Kaprekar-numbers/Sidef/kaprekar-numbers.sidef b/Task/Kaprekar-numbers/Sidef/kaprekar-numbers.sidef index 3c280f1f15..46be6f2f23 100644 --- a/Task/Kaprekar-numbers/Sidef/kaprekar-numbers.sidef +++ b/Task/Kaprekar-numbers/Sidef/kaprekar-numbers.sidef @@ -1,19 +1,18 @@ -require('ntheory') var kap = Hash() -for n (1..15) { +for n in (1..15) { var np = (10**n - 1) - %S.fordivisors({ |d| - var dp = np//d - if ((d `gcd` dp) == 1) { + np.divisors.each { |d| + var dp = np/d + if (is_coprime(dp, d)) { kap{ dp == 1 ? d : d*invmod(d, dp) } := 0 ++ } - }, np) + } } -var nums = kap.keys.map{.to_n}.sort +var nums = kap.keys.map{ Num(_) }.sort -for n (6 .. 14) { +for n in (6 .. 14) { var np = (10**n - 1) printf("Kaprekar numbers <= 10^%2d: %5d\n", n, nums.count_by { .<= np }) } diff --git a/Task/Keyboard-input-Flush-the-keyboard-buffer/Julia/keyboard-input-flush-the-keyboard-buffer.julia b/Task/Keyboard-input-Flush-the-keyboard-buffer/Julia/keyboard-input-flush-the-keyboard-buffer.julia new file mode 100644 index 0000000000..d629df2498 --- /dev/null +++ b/Task/Keyboard-input-Flush-the-keyboard-buffer/Julia/keyboard-input-flush-the-keyboard-buffer.julia @@ -0,0 +1,9 @@ +using Gtk + +function flush_keyboard() + win = GtkWindow("", 1, 1) + keyget(w, event) = Int32(0) + signal_connect(keyget, win, "key-press-event") + visible(win, false) + sleep(0.25) +end diff --git a/Task/Keyboard-input-Keypress-check/Elena/keyboard-input-keypress-check.elena b/Task/Keyboard-input-Keypress-check/Elena/keyboard-input-keypress-check.elena new file mode 100644 index 0000000000..f1828a0b56 --- /dev/null +++ b/Task/Keyboard-input-Keypress-check/Elena/keyboard-input-keypress-check.elena @@ -0,0 +1,10 @@ +import extensions. + +program = +[ + literal chr := emptyLiteralValue. + if (console isKeyAvailable) + [ + chr := console readChar + ]. +]. diff --git a/Task/Keyboard-input-Keypress-check/Perl/keyboard-input-keypress-check-1.pl b/Task/Keyboard-input-Keypress-check/Perl/keyboard-input-keypress-check-1.pl new file mode 100644 index 0000000000..7109245f20 --- /dev/null +++ b/Task/Keyboard-input-Keypress-check/Perl/keyboard-input-keypress-check-1.pl @@ -0,0 +1,12 @@ +#!/usr/bin/perl +use strict; +use warnings; +use Term::ReadKey; +ReadMode 4; +my $key; +until(defined($key = ReadKey(-1))){ + # anything + sleep 1; +} +print "got key '$key'\n"; +ReadMode('restore'); diff --git a/Task/Keyboard-input-Keypress-check/Perl/keyboard-input-keypress-check-2.pl b/Task/Keyboard-input-Keypress-check/Perl/keyboard-input-keypress-check-2.pl new file mode 100644 index 0000000000..d3ad7eca9b --- /dev/null +++ b/Task/Keyboard-input-Keypress-check/Perl/keyboard-input-keypress-check-2.pl @@ -0,0 +1,50 @@ +#!/usr/bin/perl +use strict; +use warnings; +use Carp; +use POSIX; +use Term::ReadKey; +$| = 1; # don't buffer; stdout is hot now + +#avoid creation of zombies +sub _cleanup_and_die{ + ReadMode('restore'); + print "process $$ dying\n"; + die; +} +sub _cleanup_and_exit{ + ReadMode('restore'); + print "process $$ exiting\n"; + exit 1; +} +$SIG{'__DIE__'} = \&_cleanup_and_die; +$SIG{'INT'} = \&_cleanup_and_exit; +$SIG{'KILL'} = \&_cleanup_and_exit; +$SIG{'TERM'} = \&_cleanup_and_exit; +$SIG{__WARN__} = \&_warn; + +# fork into two processes: +# child process is doing anything +# parent process just listens to keyboard input +my $pid = fork(); +if(not defined $pid){ + print "error: resources not available.\n"; + die "$!"; +}elsif($pid == 0){ # child + for(0..9){ + print "doing something\n"; + sleep 1; + } + exit 0; +}else{ # parent + ReadMode('cbreak'); + # wait until child has exited/died + while(waitpid($pid, POSIX::WNOHANG) == 0){ + my $seq = ReadKey(-1); + if(defined $seq){ + print "got key '$seq'\n"; + } + sleep 1; # if ommitted, the cpu-load will reach up to 100% + } + ReadMode('restore'); +} diff --git a/Task/Keyboard-input-Keypress-check/Scala/keyboard-input-keypress-check.scala b/Task/Keyboard-input-Keypress-check/Scala/keyboard-input-keypress-check.scala new file mode 100644 index 0000000000..63b98f8fc3 --- /dev/null +++ b/Task/Keyboard-input-Keypress-check/Scala/keyboard-input-keypress-check.scala @@ -0,0 +1,33 @@ +import java.awt.event.{KeyAdapter, KeyEvent} + +import javax.swing.{JFrame, SwingUtilities} + +class KeypressCheck() extends JFrame { + + addKeyListener(new KeyAdapter() { + override def keyPressed(e: KeyEvent): Unit = { + val keyCode = e.getKeyCode + if (keyCode == KeyEvent.VK_ENTER) { + dispose() + System.exit(0) + } + else + println(keyCode) + } + }) +} + +object KeypressCheck extends App { + println("Press any key to see its code or 'enter' to quit\n") + SwingUtilities.invokeLater(() => { + def foo() = { + val f = new KeypressCheck + f.setFocusable(true) + f.setVisible(true) + f.setSize(200, 200) + f.setEnabled(true) + } + + foo() + }) +} diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/C/keyboard-input-obtain-a-y-or-n-response.c b/Task/Keyboard-input-Obtain-a-Y-or-N-response/C/keyboard-input-obtain-a-y-or-n-response.c index b53c4285c5..042de6cb5c 100644 --- a/Task/Keyboard-input-Obtain-a-Y-or-N-response/C/keyboard-input-obtain-a-y-or-n-response.c +++ b/Task/Keyboard-input-Obtain-a-Y-or-N-response/C/keyboard-input-obtain-a-y-or-n-response.c @@ -1,8 +1,8 @@ #include -#include #include #include #include +#include void set_mode(int want_key) { diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/Julia/keyboard-input-obtain-a-y-or-n-response.julia b/Task/Keyboard-input-Obtain-a-Y-or-N-response/Julia/keyboard-input-obtain-a-y-or-n-response.julia new file mode 100644 index 0000000000..f8a8388506 --- /dev/null +++ b/Task/Keyboard-input-Obtain-a-Y-or-N-response/Julia/keyboard-input-obtain-a-y-or-n-response.julia @@ -0,0 +1,18 @@ +using Gtk.ShortNames + +function keypresswindow() + txt = "Type Y or N" + win = Window("Keypress Test", 250, 30) |> (Frame() |> ((vbox = Box(:v))|> (lab = Label(txt)))) + function keycall(w, event) + ch = Char(event.keyval) + setproperty!(lab,:label, ch in('n','N','y','Y') ? "You hit the $ch key.": txt) + end + signal_connect(keycall, win, "key-press-event") + c = Condition() + endit(w) = notify(c) + signal_connect(endit, win, :destroy) + showall(win) + wait(c) +end + +keypresswindow() diff --git a/Task/Keyboard-macros/Java/keyboard-macros.java b/Task/Keyboard-macros/Java/keyboard-macros.java index a69f179aba..b83d1acb2b 100644 --- a/Task/Keyboard-macros/Java/keyboard-macros.java +++ b/Task/Keyboard-macros/Java/keyboard-macros.java @@ -13,6 +13,7 @@ class KeyboardMacroDemo { +"Ctrl-H to hide it"; frame.add( new JLabel(directions)); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.addKeyListener( new KeyAdapter(){ public void keyReleased( KeyEvent e ) { diff --git a/Task/Keyboard-macros/Kotlin/keyboard-macros.kotlin b/Task/Keyboard-macros/Kotlin/keyboard-macros.kotlin new file mode 100644 index 0000000000..5bd92e1f63 --- /dev/null +++ b/Task/Keyboard-macros/Kotlin/keyboard-macros.kotlin @@ -0,0 +1,25 @@ +// version 1.2.31 + +import javax.swing.JFrame +import javax.swing.JLabel +import java.awt.event.KeyAdapter +import java.awt.event.KeyEvent + +fun main(args: Array) { + val directions = "Ctrl-S to show frame title
" + + "Ctrl-H to hide it" + with (JFrame()) { + add(JLabel(directions)) + defaultCloseOperation = JFrame.EXIT_ON_CLOSE + addKeyListener(object : KeyAdapter() { + override fun keyReleased(e: KeyEvent) { + if (e.isControlDown() && e.keyCode == KeyEvent.VK_S) + title = "Hello there" + else if( e.isControlDown() && e.keyCode == KeyEvent.VK_H) + title = "" + } + }) + pack() + isVisible = true + } +} diff --git a/Task/Knapsack-problem-0-1/Julia/knapsack-problem-0-1-1.julia b/Task/Knapsack-problem-0-1/Julia/knapsack-problem-0-1-1.julia index aab7f00b1a..cfd9f14007 100644 --- a/Task/Knapsack-problem-0-1/Julia/knapsack-problem-0-1-1.julia +++ b/Task/Knapsack-problem-0-1/Julia/knapsack-problem-0-1-1.julia @@ -1,20 +1,17 @@ -using MathProgBase - -immutable KPDSupply{S<:String, T<:Integer} - item::S +struct KPDSupply{T<:Integer} + item::String weight::T value::T quant::T end -function KPDSupply{S<:String, T<:Integer}(item::S, weight::T, value::T) - KPDSupply(item, weight, value, one(T)) -end -function solve{S<:String, T<:Integer}(gear::Array{KPDSupply{S,T},1}, - capacity::T) - w = map(x->x.weight, gear) - v = map(x->x.value, gear) - sol = mixintprog(-v, w', '<', capacity, :Bin, 0, 1) - sol.status == :Optimal || error("This Problem could not be solved") - gear[sol.sol .== 1.0] +KPDSupply{T<:Integer}(itm::AbstractString, w::T, v::T, q::T=one(T)) = KPDSupply(itm, w, v, q) +Base.show(io::IO, kdps::KPDSupply) = print(io, kdps.quant, " ", kdps.item, " ($(kdps.weight) kg, $(kdps.value) €)") + +using MathProgBase, Cbc +function solve(gear::Vector{<:KPDSupply}, capacity::Integer) + w = getfield.(gear, :weight) + v = getfield.(gear, :value) + sol = mixintprog(-v, w', '<', capacity, :Bin, 0, 1, CbcSolver()) + gear[sol.sol .≈ 1] end diff --git a/Task/Knapsack-problem-0-1/Julia/knapsack-problem-0-1-2.julia b/Task/Knapsack-problem-0-1/Julia/knapsack-problem-0-1-2.julia index 6cd7417793..9db80627e2 100644 --- a/Task/Knapsack-problem-0-1/Julia/knapsack-problem-0-1-2.julia +++ b/Task/Knapsack-problem-0-1/Julia/knapsack-problem-0-1-2.julia @@ -22,11 +22,6 @@ gear = [KPDSupply("map", 9, 150), KPDSupply("book", 30, 10)] pack = solve(gear, 400) - -println("The hiker should pack:") -for s in pack - println(" ", s.item) -end -println() -println("Packed Weight: ", mapreduce(x->x.weight, +, pack)) -println("Packed Value: ", mapreduce(x->x.value, +, pack)) +println("The hicker should pack: \n - ", join(pack, "\n - ")) +println("\nPacked weight: ", mapreduce(x -> x.weight, +, pack), " kg") +println("Packed value: ", mapreduce(x -> x.value, +, pack), " €") diff --git a/Task/Knapsack-problem-0-1/Racket/knapsack-problem-0-1-3.rkt b/Task/Knapsack-problem-0-1/Racket/knapsack-problem-0-1-3.rkt new file mode 100644 index 0000000000..c2a5ba54d1 --- /dev/null +++ b/Task/Knapsack-problem-0-1/Racket/knapsack-problem-0-1-3.rkt @@ -0,0 +1,33 @@ +#lang racket + +(define items '((map 9 150) (compass 13 35) (water 153 200) (sandwich 50 160) + (glucose 15 60) (tin 68 45)(banana 27 60) (apple 39 40) + (cheese 23 30) (beer 52 10) (cream 11 70) (camera 32 30) + (T-shirt 24 15) (trousers 48 10) (umbrella 73 40) + (trousers 42 70) (overclothes 43 75) (notecase 22 80) + (glasses 7 20) (towel 18 12) (socks 4 50) (book 30 10))) + +(define max-weight 400) + +(define (item-value item) + (caddr item)) + +(define (item-weight item) + (cadr item)) + +(define (pack-weight pack) + (apply + (map item-weight pack))) + +(define (pack-value pack) + (apply + (map item-value pack))) + +(define (max-pack-value pack-with pack-without max-weight) + (if (and + (not (> (pack-weight pack-with) max-weight)) + (> (pack-value pack-with) (pack-value pack-without))) + pack-with pack-without)) + +(define (display-solution pack) + (displayln (list 'weight: (pack-weight pack) + 'value: (pack-value pack) + 'items: (map car pack)))) diff --git a/Task/Knapsack-problem-0-1/Racket/knapsack-problem-0-1-4.rkt b/Task/Knapsack-problem-0-1/Racket/knapsack-problem-0-1-4.rkt new file mode 100644 index 0000000000..ac9b0b03b7 --- /dev/null +++ b/Task/Knapsack-problem-0-1/Racket/knapsack-problem-0-1-4.rkt @@ -0,0 +1,17 @@ +(define (show-brute) + + (define empty-accumulator '()) + + (define (knapsack-brute included items) + (cond + ((null? items) included) + (else + (max-pack-value + (knapsack-brute (cons (car items) included) (cdr items)) + (knapsack-brute included (cdr items)) + max-weight + )))) + + (display-solution (reverse (knapsack-brute empty-accumulator items)))) + +(show-brute); takes around five seconds on my machine diff --git a/Task/Knapsack-problem-0-1/Racket/knapsack-problem-0-1-5.rkt b/Task/Knapsack-problem-0-1/Racket/knapsack-problem-0-1-5.rkt new file mode 100644 index 0000000000..98dad3dbf8 --- /dev/null +++ b/Task/Knapsack-problem-0-1/Racket/knapsack-problem-0-1-5.rkt @@ -0,0 +1,24 @@ +(define (show-memoized) + + (define (memoize func) + (let ([result-ht (make-hash)]) + (lambda args ; this is the rest-id pattern + (when (not (hash-has-key? result-ht args)) + (hash-set! result-ht args (apply func args))) + (hash-ref result-ht args)))) + + (define knapsack + (memoize + (lambda (max-weight items) + (cond + ((null? items) '()) + (else + (let ([item (car items)] [items (cdr items)]) + (max-pack-value + (cons item (knapsack (- max-weight (item-weight item)) items)) + (knapsack max-weight items) + max-weight))))))) + + (display-solution (knapsack max-weight items))) + +(show-memoized) diff --git a/Task/Knapsack-problem-0-1/Racket/knapsack-problem-0-1-6.rkt b/Task/Knapsack-problem-0-1/Racket/knapsack-problem-0-1-6.rkt new file mode 100644 index 0000000000..44be1e0ef8 --- /dev/null +++ b/Task/Knapsack-problem-0-1/Racket/knapsack-problem-0-1-6.rkt @@ -0,0 +1 @@ +(weight: 396 value: 1030 items: (map compass water sandwich glucose banana cream trousers overclothes notecase glasses socks)) diff --git a/Task/Knapsack-problem-0-1/Ring/knapsack-problem-0-1.ring b/Task/Knapsack-problem-0-1/Ring/knapsack-problem-0-1.ring new file mode 100644 index 0000000000..c013127be9 --- /dev/null +++ b/Task/Knapsack-problem-0-1/Ring/knapsack-problem-0-1.ring @@ -0,0 +1,88 @@ +# Project : Knapsack problem/0-1 +# Date : 2018/01/27 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : + +knap = [["map",9,150], + ["compass",13,35], + ["water",153,20], + ["sandwich",50,160], + ["glucose",15,60], + ["tin",68,45], + ["banana",27,60], + ["apple",39,40], + ["cheese",23,30], + ["beer",52,10], + ["suntan cream",11,70], + ["camera",32,30], + ["T-shirt",24,15], + ["trousers",48,10], + ["umbrella",73,40], + ["waterproof trousers",42,70], + ["waterproof overclothes",43,75], + ["note-case",22,80], + ["sunglasses",7,20], + ["towel",18,12], + ["socks",4,50], + ["book",30,10]] +knapsack = createDimList([pow(2, len(knap)),len(knap)+2]) +lenknap = list(pow(2, len(knap))) + +sacksize = 400 +powerset(knap) + +for n = 1 to pow(2, len(knap))-2 + for m = n + 1 to pow(2, len(knap))-1 + if knapsack[m][lenknap[m]-1] <= sacksize and + knapsack[m][lenknap[m]] > knapsack[n][lenknap[n]] + temp = knapsack[n] + lentemp = lenknap[n] + knapsack[n] = knapsack[m] + knapsack[n+1] = temp + lenknap[n] = lenknap[m] + lenknap[n+1] = lentemp + ok + next +next + +for n = 1 to lenknap[1] - 2 + see knapsack[1][n] + nl +next + +see "Total weight = " + knapsack[1][lenknap[1]-1] + nl +see "Total value = " + knapsack[1][lenknap[1]] + nl + +func powerset(list) + n1 = 0 + for i = 2 to (2 << len(list)) - 1 step 2 + n2 = 0 + n1 = n1 + 1 + weight = 0 + value = 0 + for j = 1 to len(list) + if i & (1 << j) + n2 = n2 + 1 + knapsack[n1][n2] = list[j][1] + weight = weight + list[j][2] + value = value + list[j][3] + knapsack[n1][n2+1] = weight + knapsack[n1][n2+2] = value + ok + next + lenknap[n1] = n2+2 + next + +func createDimList(dimArray) + sizeList = len(dimArray) + newParms = [] + for i = 2 to sizeList + Add(newParms, dimArray[i]) + next + alist = list(dimArray[1]) + if sizeList = 1 + return aList + ok + for t in alist + t = createDimList(newParms) + next + return alist diff --git a/Task/Knapsack-problem-Bounded/Julia/knapsack-problem-bounded-1.julia b/Task/Knapsack-problem-Bounded/Julia/knapsack-problem-bounded-1.julia index b5b958ebfa..28ba9e3293 100644 --- a/Task/Knapsack-problem-Bounded/Julia/knapsack-problem-bounded-1.julia +++ b/Task/Knapsack-problem-Bounded/Julia/knapsack-problem-bounded-1.julia @@ -1,26 +1,27 @@ -using MathProgBase +using MathProgBase, Cbc -immutable KPDSupply{S<:String, T<:Integer} - item::S +struct KPDSupply{T<:Integer} + item::String weight::T value::T quant::T end +Base.show(io::IO, kdps::KPDSupply) = print(io, kdps.quant, " ", kdps.item, " ($(kdps.weight) kg, $(kdps.value) €)") -function solve{S<:String, T<:Integer}(gear::Array{KPDSupply{S,T},1}, - capacity::T) - w = map(x->x.weight, gear) - v = map(x->x.value, gear) - q = map(x->x.quant, gear) - sol = mixintprog(-v, w', '<', capacity, :Int, 0, q) - sol.status == :Optimal || error("This Problem could not be solved") - if all(q .== 1) - return gear[sol.sol .== 1.0] +function solve(gear::Vector{KPDSupply{T}}, capacity::Integer) where T<:Integer + w = getfield.(gear, :weight) + v = getfield.(gear, :value) + q = getfield.(gear, :quant) + sol = mixintprog(-v, w', '<', capacity, :Int, 0, q, CbcSolver()) + sol.status == :Optimal || error("this problem could not be solved") + + if all(q .== 1) # simpler case + return gear[sol.sol == 1.0] else - pack = KPDSupply[] - s = int(sol.sol) + pack = similar(gear, 0) + s = round.(Int, sol.sol) for (i, g) in enumerate(gear) - s[i] != 0 || continue + iszero(s[i]) && continue push!(pack, KPDSupply(g.item, g.weight, g.value, s[i])) end return pack diff --git a/Task/Knapsack-problem-Bounded/Julia/knapsack-problem-bounded-2.julia b/Task/Knapsack-problem-Bounded/Julia/knapsack-problem-bounded-2.julia index aa27e44f30..1e0f0ee78e 100644 --- a/Task/Knapsack-problem-Bounded/Julia/knapsack-problem-bounded-2.julia +++ b/Task/Knapsack-problem-Bounded/Julia/knapsack-problem-bounded-2.julia @@ -22,11 +22,6 @@ gear = [KPDSupply("map", 9, 150, 1), KPDSupply("book", 30, 10, 2)] pack = solve(gear, 400) - -println("The hiker should pack:") -for s in pack - println(" ", s.quant, " ", s.item) -end -println() -println("Packed Weight: ", mapreduce(x->x.weight*x.quant, +, pack)) -println("Packed Value: ", mapreduce(x->x.value*x.quant, +, pack)) +println("The hiker should pack: \n - ", join(pack, "\n - ")) +println("\nPacked weight: ", sum(getfield.(pack, :weight)), " kg") +println("Packed value: ", sum(getfield.(pack, :value)), " €") diff --git a/Task/Knapsack-problem-Bounded/R/knapsack-problem-bounded-1.r b/Task/Knapsack-problem-Bounded/R/knapsack-problem-bounded-1.r new file mode 100644 index 0000000000..c5cf63d3e1 --- /dev/null +++ b/Task/Knapsack-problem-Bounded/R/knapsack-problem-bounded-1.r @@ -0,0 +1,11 @@ +library(tidyverse) +library(rvest) + +task_html= read_html("http://rosettacode.org/wiki/Knapsack_problem/Bounded") +task_table= html_nodes(html, "table")[[1]] %>% + html_table(table, header= T, trim= T) %>% + set_names(c("items", "weight", "value", "pieces")) %>% + filter(items != "knapsack") %>% + mutate(weight= as.numeric(weight), + value= as.numeric(value), + pieces= as.numeric(pieces)) diff --git a/Task/Knapsack-problem-Bounded/R/knapsack-problem-bounded-2.r b/Task/Knapsack-problem-Bounded/R/knapsack-problem-bounded-2.r new file mode 100644 index 0000000000..29e29a86c0 --- /dev/null +++ b/Task/Knapsack-problem-Bounded/R/knapsack-problem-bounded-2.r @@ -0,0 +1,21 @@ +library(rgenoud) + +fitness= function(x= rep(1, nrow(task_table))){ + total_value= sum(task_table$value * x) + total_weight= sum(task_table$weight * x) + ifelse(total_weight <= 400, total_value, 400-total_weight) +} + +allowed= matrix(c(rep(0, nrow(task_table)), task_table$pieces), ncol = 2) +set.seed(42) +evolution= genoud(fn= fitness, + nvars= nrow(allowed), + max= TRUE, + pop.size= 10000, + data.type.int= TRUE, + Domains= allowed) + +cat("Value: ", evolution$value, "\n") +cat("Weight:", sum(task_table$weight * evolution$par), "dag", "\n") +data.frame(item= task_table$items, pieces= as.integer(solution)) %>% + filter(solution> 0) diff --git a/Task/Knapsack-problem-Continuous/00DESCRIPTION b/Task/Knapsack-problem-Continuous/00DESCRIPTION index a569e6e08c..29bf984191 100644 --- a/Task/Knapsack-problem-Continuous/00DESCRIPTION +++ b/Task/Knapsack-problem-Continuous/00DESCRIPTION @@ -45,7 +45,6 @@ Show which items the thief carries in his knapsack so that their total weight do *   [[Knapsack problem/0-1]]

- ;See also: *   Wikipedia article:   [[wp:Continuous_knapsack_problem|continuous knapsack]].

diff --git a/Task/Knapsack-problem-Continuous/Julia/knapsack-problem-continuous-1.julia b/Task/Knapsack-problem-Continuous/Julia/knapsack-problem-continuous-1.julia index a8e54ef276..d1ad718f8e 100644 --- a/Task/Knapsack-problem-Continuous/Julia/knapsack-problem-continuous-1.julia +++ b/Task/Knapsack-problem-Continuous/Julia/knapsack-problem-continuous-1.julia @@ -1,29 +1,30 @@ -immutable KPCSupply{S<:String, T<:Real} - item::S +struct KPCSupply{T<:Real} + item::String weight::T value::T uvalue::T end -Base.isless(a::KPCSupply, b::KPCSupply) = a.uvaluex.weight, +, sack) -v = mapreduce(x->x.value, +, sack) -println(@sprintf("%12s %4.1f %6.2f", - "Total", float(w), float(v))) +sack = solve(store, 15) +println("The store contains:\n - ", join(store, "\n - ")) +println("\nThe thief should take::\n - ", join(sack, "\n - ")) +@printf("\nTotal value in the sack: %.2f €\n", sum(getfield.(sack, :value))) diff --git a/Task/Knapsack-problem-Continuous/Scala/knapsack-problem-continuous.scala b/Task/Knapsack-problem-Continuous/Scala/knapsack-problem-continuous.scala new file mode 100644 index 0000000000..7020efa6a1 --- /dev/null +++ b/Task/Knapsack-problem-Continuous/Scala/knapsack-problem-continuous.scala @@ -0,0 +1,57 @@ +import scala.annotation.tailrec + +object ContinousKnapsackForRobber extends App { + val MaxWeight = 15.0 + val items = Seq( + Item("Beef", 3.8, 3600), + Item("Pork", 5.4, 4300), + Item("Ham", 3.6, 9000), + Item("Greaves", 2.4, 4500), + Item("Flitch", 4.0, 3000), + Item("Brawn", 2.5, 5600), + Item("Welt", 3.7, 6700), + Item("Salami", 3.0, 9500), + Item("Sausage", 5.9, 9800)) + + // sort items by value per unit weight in descending order + def sortedItems = items.sortBy(it => -it.value / it.weight) + + @tailrec + def packer(notPacked: Seq[Item], packed: Lootsack): Lootsack = { + + if (!packed.isNotFull || notPacked.isEmpty) packed + else { + val try2fit = packed.copy(bagged = notPacked.head +: packed.bagged) + if (try2fit.isNotFull) packer(notPacked.tail, try2fit) + else { + try2fit.copy(lastPiece = packed.weightLeft / notPacked.head.weight) + } + } + } + + case class Item(name: String, weight: Double, value: Int) + + case class Lootsack(bagged: Seq[Item], lastPiece: Double = 1.0) { + private val totWeight = if (bagged.isEmpty) 0.0 + else bagged.tail.map(_.weight).sum + bagged.head.weight * lastPiece + + def isNotFull: Boolean = weightLeft > 0 + + def weightLeft: Double = MaxWeight - totWeight + + override def toString = f"${show(bagged, lastPiece)}Totals: weight: $totWeight%4.1f, value: $totValue%6.2f" + + private def totValue: BigDecimal = if (bagged.isEmpty) 0.0 + else (bagged.tail.map(_.value).sum + bagged.head.value * lastPiece) / 100 + + private def show(is: Seq[Item], percentage: Double) = { + def toStr(is: Seq[Item], percentage: Double = 1): String = + is.map(it => f"${percentage * 100}%6.2f%% ${it.name}%-7s ${ + it.weight * percentage}%4.1f ${it.value * percentage / 100}%6.2f\n").mkString + + toStr(is.tail.reverse) + toStr(Seq(is.head), percentage) + } + } + + println(packer(sortedItems, Lootsack(Nil))) +} diff --git a/Task/Knapsack-problem-Unbounded/Julia/knapsack-problem-unbounded.julia b/Task/Knapsack-problem-Unbounded/Julia/knapsack-problem-unbounded.julia new file mode 100644 index 0000000000..30f9ab0168 --- /dev/null +++ b/Task/Knapsack-problem-Unbounded/Julia/knapsack-problem-unbounded.julia @@ -0,0 +1,23 @@ +using JuMP +using GLPKMathProgInterface + +model = Model(solver=GLPKSolverMIP()) + +@variable(model, vials_of_panacea >= 0, Int) +@variable(model, ampules_of_ichor >= 0, Int) +@variable(model, bars_of_gold >= 0, Int) + +@objective(model, Max, 3000*vials_of_panacea + 1800*ampules_of_ichor + 2500*bars_of_gold) + +@constraint(model, 0.3*vials_of_panacea + 0.2*ampules_of_ichor + 2.0*bars_of_gold <= 25.0) +@constraint(model, 0.025*vials_of_panacea + 0.015*ampules_of_ichor + 0.002*bars_of_gold <= 0.25) + +println("The optimization problem to be solved is:") +println(model) + +status = solve(model) + +println("Objective value: ", getobjectivevalue(model)) +println("vials of panacea = ", getvalue(vials_of_panacea)) +println("ampules of ichor = ", getvalue(ampules_of_ichor)) +println("bars of gold = ", getvalue(bars_of_gold)) diff --git a/Task/Knapsack-problem-Unbounded/Scala/knapsack-problem-unbounded.scala b/Task/Knapsack-problem-Unbounded/Scala/knapsack-problem-unbounded.scala index 0ae5ab3c8f..94bdf9ebd5 100644 --- a/Task/Knapsack-problem-Unbounded/Scala/knapsack-problem-unbounded.scala +++ b/Task/Knapsack-problem-Unbounded/Scala/knapsack-problem-unbounded.scala @@ -1,42 +1,38 @@ import scala.annotation.tailrec -case class Item(name: String, value: Int, weight: Double, volume: Double) +object UnboundedKnapsack extends App { + private val (maxWeight, maxVolume) = (BigDecimal(25.0), BigDecimal(0.25)) + private val items = Seq(Item("panacea", 3000, 0.3, 0.025), Item("ichor", 1800, 0.2, 0.015), Item("gold", 2500, 2.0, 0.002)) -val items = List( - Item("panacea", 3000, 0.3, 0.025), - Item("ichor", 1800, 0.2, 0.015), - Item("gold", 2500, 2.0, 0.002)) + @tailrec + private def packer(notPacked: Seq[Knapsack], packed: Seq[Knapsack]): Seq[Knapsack] = { + def fill(knapsack: Knapsack): Seq[Knapsack] = items.map(i => Knapsack(i +: knapsack.bagged)) -val (maxWeight, maxVolume) = (25, 0.25) + def stuffer(Seq: Seq[Knapsack]): Seq[Knapsack] = // Cause brute force + Seq.map(k => Knapsack(k.bagged.sortBy(_.name))).distinct -def show(is: List[Item]) = - (items.map(_.name) zip items.map(i => is.count(_ == i))).map { - case (i, c) => s"$i: $c" - }.mkString(", ") - -case class Knapsack(items: List[Item]) { - def value = items.foldLeft(0)(_ + _.value) - def weight = items.foldLeft(0.0)(_ + _.weight) - def volume = items.foldLeft(0.0)(_ + _.volume) - def isFull = !((weight <= maxWeight) && (volume <= maxVolume)) - override def toString = - s"[${show(items)} | value: $value, weight: $weight, volume: $volume]" -} - -def fill(knapsack: Knapsack): List[Knapsack] = - items.map(i => Knapsack(i :: knapsack.items)) - -//cause brute force -def distinct(list: List[Knapsack]) = - list.map(k => Knapsack(k.items.sortBy(_.name))).distinct - -@tailrec -def f(notPacked: List[Knapsack], packed: List[Knapsack]): List[Knapsack] = - notPacked match { - case Nil => packed.sortBy(_.value).takeRight(4) - case _ => - val notFull = distinct(notPacked.flatMap(fill)).filterNot(_.isFull) - f(notFull, notPacked ::: packed) + if (notPacked.isEmpty) packed.sortBy(-_.totValue).take(4) + else packer(stuffer(notPacked.flatMap(fill)).filter(_.isNotFull), notPacked ++ packed) } -f(items.map(i => Knapsack(List(i))), Nil).foreach(println) + private case class Item(name: String, value: Int, weight: BigDecimal, volume: BigDecimal) + + private case class Knapsack(bagged: Seq[Item]) { + def isNotFull: Boolean = totWeight <= maxWeight && totVolume <= maxVolume + + override def toString = s"[${show(bagged)} | value: $totValue, weight: $totWeight, volume: $totVolume]" + + def totValue: Int = bagged.map(_.value).sum + + private def totVolume = bagged.map(_.volume).sum + + private def totWeight = bagged.map(_.weight).sum + + private def show(is: Seq[Item]) = + (items.map(_.name) zip items.map(i => is.count(_ == i))) + .map { case (i, c) => f"$i:$c%3d" } + .mkString(", ") + } + + packer(items.map(i => Knapsack(Seq(i))), Nil).foreach(println) +} diff --git a/Task/Knuth-shuffle/BASIC/knuth-shuffle-2.basic b/Task/Knuth-shuffle/BASIC/knuth-shuffle-2.basic index 615864481d..21598d8911 100644 --- a/Task/Knuth-shuffle/BASIC/knuth-shuffle-2.basic +++ b/Task/Knuth-shuffle/BASIC/knuth-shuffle-2.basic @@ -1,14 +1,13 @@ - 10 RAND - 20 LET A$="" - 30 FOR I=1 TO 26 - 40 LET A$=A$+CHR$ (37+I) - 50 NEXT I - 60 PRINT A$ - 70 FOR I=26 TO 2 STEP -1 - 80 LET J=1+INT (RND*I) - 90 LET T$=A$(I) -100 LET A$(I)=A$(J) -110 LET A$(J)=T$ -120 PRINT AT 0,I-1;CHR$ (CODE A$(I)+128) -130 PRINT AT 0,J-1;CHR$ (CODE A$(J)+128) -140 NEXT I + 100 : + 110 REM KNUTH SHUFFLE + 120 : + 130 DIM A(25) + 140 FOR I = 1 TO 25 + 150 A(I) = I: PRINT A(I);" ";: NEXT I + 160 PRINT : PRINT + 170 FOR I = 25 TO 2 STEP - 1 + 180 J = INT ( RND (1) * I + 1) + 190 T = A(I):A(I) = A(J):A(J) = T: NEXT I + 200 FOR I = 1 TO 25 + 210 PRINT A(I);" ";: NEXT I + 220 END diff --git a/Task/Knuth-shuffle/BASIC/knuth-shuffle-3.basic b/Task/Knuth-shuffle/BASIC/knuth-shuffle-3.basic new file mode 100644 index 0000000000..615864481d --- /dev/null +++ b/Task/Knuth-shuffle/BASIC/knuth-shuffle-3.basic @@ -0,0 +1,14 @@ + 10 RAND + 20 LET A$="" + 30 FOR I=1 TO 26 + 40 LET A$=A$+CHR$ (37+I) + 50 NEXT I + 60 PRINT A$ + 70 FOR I=26 TO 2 STEP -1 + 80 LET J=1+INT (RND*I) + 90 LET T$=A$(I) +100 LET A$(I)=A$(J) +110 LET A$(J)=T$ +120 PRINT AT 0,I-1;CHR$ (CODE A$(I)+128) +130 PRINT AT 0,J-1;CHR$ (CODE A$(J)+128) +140 NEXT I diff --git a/Task/Knuth-shuffle/JavaScript/knuth-shuffle-2.js b/Task/Knuth-shuffle/JavaScript/knuth-shuffle-2.js index 1c785cb2bb..e7f1a18e4f 100644 --- a/Task/Knuth-shuffle/JavaScript/knuth-shuffle-2.js +++ b/Task/Knuth-shuffle/JavaScript/knuth-shuffle-2.js @@ -1,38 +1,46 @@ -(lst => { +(() => { // knuthShuffle :: [a] -> [a] - let knuthShuffle = lst => - range(0, lst.length - 1) + const knuthShuffle = xs => + enumFromTo(0, xs.length - 1) .reduceRight((a, i) => { - let iRand = i ? randomInteger(0, i) : 0, + const + iRand = randomRInt(0, i), tmp = a[iRand]; - - return iRand !== i ? ( + return iRand !== i ? ( a[iRand] = a[i], a[i] = tmp, a ) : a; - }, lst), + }, xs); - // randomInteger :: Int -> Int -> Int - randomInteger = (low, high) => + const test = () => knuthShuffle( + (`alpha beta gamma delta epsilon zeta + eta theta iota kappa lambda mu`) + .split(/\s+/) + ); + + // GENERIC FUNCTIONS ---------------------------------- + + // enumFromTo :: Int -> Int -> [Int] + const enumFromTo = (m, n) => + n >= m ? ( + iterateUntil(x => x >= n, x => 1 + x, m) + ) : []; + + // iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a] + const iterateUntil = (p, f, x) => { + let vs = [x], + h = x; + while (!p(h))(h = f(h), vs.push(h)); + return vs; + }; + + // randomRInt :: Int -> Int -> Int + const randomRInt = (low, high) => low + Math.floor( (Math.random() * ((high - low) + 1)) - ), + ); - // range :: 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)); - }; - - - return knuthShuffle(lst); - -})( - 'alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu' - .split(' ') - ); + return test(); +})(); diff --git a/Task/Knuth-shuffle/JavaScript/knuth-shuffle-4.js b/Task/Knuth-shuffle/JavaScript/knuth-shuffle-4.js index cfed619f20..5ab263b21f 100644 --- a/Task/Knuth-shuffle/JavaScript/knuth-shuffle-4.js +++ b/Task/Knuth-shuffle/JavaScript/knuth-shuffle-4.js @@ -1,56 +1,61 @@ -(lst => { +(() => { // knuthShuffle :: [a] -> [a] - function knuthShuffle(lst) { - let lng = lst.length; + const knuthShuffle = xs => + enumFromTo(0, xs.length - 1) + .reduceRight((a, i) => { + const iRand = randomRInt(0, i); + return i !== iRand ? ( + swapped(i, iRand, a) + ) : a; + }, xs); - return lng ? range(0, lng - 1) - .reduceRight((a, i) => { - let iRand = i > 0 ? randomInteger(0, i) : 0; + const test = () => knuthShuffle( + (`alpha beta gamma delta epsilon zeta + eta theta iota kappa lambda mu`) + .split(/\s+/) + ); - return i !== iRand ? swapped(a, i, iRand) : a; - }, lst) : []; + // Non mutating version of swapped + + // swapped :: Int -> Int -> [a] -> [a] + const swapped = (iFrom, iTo, xs) => + xs.map( + (x, i) => iFrom !== i ? ( + iTo !== i ? ( + x + ) : xs[iFrom] + ) : xs[iTo] + ); + + // GENERIC FUNCTIONS ---------------------------------- + + // enumFromTo :: Int -> Int -> [Int] + const enumFromTo = (m, n) => + n >= m ? ( + iterateUntil(x => x >= n, x => 1 + x, m) + ) : []; + + // iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a] + const iterateUntil = (p, f, x) => { + let vs = [x], + h = x; + while (!p(h))(h = f(h), vs.push(h)); + return vs; }; - - // A non-mutating variant of swapped(): - - // swapped :: [a] -> Int -> Int -> [a] - let swapped = (lst, iFrom, iTo) => { - let [iLow, iHigh] = iTo > iFrom ? ( - [iFrom, iTo] - ) : [iTo, iFrom]; - - return iLow !== iHigh ? ( - [].concat( - (iLow > 0 ? lst.slice(0, iLow) : []), // pre - lst[iHigh], // DOWN - lst.slice(iLow + 1, iHigh), // mid - lst[iLow], // UP - lst.slice(iHigh + 1) // post - ) - ) : lst.slice(0) // (unchanged copy) - }, - - // randomInteger :: Int -> Int -> Int - randomInteger = (low, high) => + // randomRInt :: Int -> Int -> Int + const randomRInt = (low, high) => low + Math.floor( (Math.random() * ((high - low) + 1)) - ), + ); - // range :: Int -> Int -> Maybe Int -> [Int] - range = (m, n, step) => { - let d = (step || 1) * (n >= m ? 1 : -1); + // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] + const zipWith = (f, xs, ys) => + Array.from({ + length: Math.min(xs.length, ys.length) + }, (_, i) => f(xs[i], ys[i], i)); - return Array.from({ - length: Math.floor((n - m) / d) + 1 - }, (_, i) => m + (i * d)); - }; - - - return knuthShuffle(lst); - -})( - 'alpha beta gamma delta epsilon zeta eta theta iota kappa lambda mu' - .split(' ') -); + // MAIN --- + return test(); +})(); diff --git a/Task/Knuth-shuffle/Julia/knuth-shuffle.julia b/Task/Knuth-shuffle/Julia/knuth-shuffle.julia new file mode 100644 index 0000000000..c2e61f9595 --- /dev/null +++ b/Task/Knuth-shuffle/Julia/knuth-shuffle.julia @@ -0,0 +1,11 @@ +function knuthshuffle!(r::AbstractRNG, v::AbstractVector) + for i in length(v):-1:2 + j = rand(r, 1:i) + v[i], v[j] = v[j], v[i] + end + return v +end +knuthshuffle!(v::AbstractVector) = knuthshuffle!(Base.Random.GLOBAL_RNG, v) + +v = collect(1:20) +println("# v = $v\n -> ", knuthshuffle!(v)) diff --git a/Task/Knuth-shuffle/PicoLisp/knuth-shuffle.l b/Task/Knuth-shuffle/PicoLisp/knuth-shuffle.l index 9ee26eb142..ba4521f950 100644 --- a/Task/Knuth-shuffle/PicoLisp/knuth-shuffle.l +++ b/Task/Knuth-shuffle/PicoLisp/knuth-shuffle.l @@ -1,7 +1,11 @@ -(de shuffle (Lst) - (make - (for (N (length Lst) (gt0 N)) - (setq Lst - (conc - (cut (rand 0 (dec 'N)) 'Lst) - (prog (link (car Lst)) (cdr Lst)) ) ) ) ) ) +(seed (in "/dev/urandom" (rd 8))) + +(de knuth (Lst) + (for (N (length Lst) (>= N 2) (dec N)) + (let I (rand 1 N) + (xchg (nth Lst N) (nth Lst I)) ) ) ) + +(let L (range 1 15) + (println 'before L) + (knuth L) + (println 'after L) ) diff --git a/Task/Knuth-shuffle/Ring/knuth-shuffle.ring b/Task/Knuth-shuffle/Ring/knuth-shuffle.ring index 3e2decffd5..1e5bdf82d2 100644 --- a/Task/Knuth-shuffle/Ring/knuth-shuffle.ring +++ b/Task/Knuth-shuffle/Ring/knuth-shuffle.ring @@ -1,16 +1,31 @@ -a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] -shuffle(a) -for n = 1 to len(a) - see "" + a[n] + " " -next +# Project : Knuth shuffle +# Date : 2017/11/08 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : -func shuffle t - n = len(t) - while n > 1 - k = random(n-1)+1 - temp = t[n] - t[n] = t[k] - t[k] = temp - n = n - 1 - end - return t +items = list(52) +for n = 1 to len(items) + items[n] = n +next +knuth(items) +showarray(items) + +func knuth(items) + for i = len(items) to 1 step -1 + j = random(i-1) + 1 + if i != j + temp = items[i] + items[i] = items[j] + items[j] = temp + ok + next + +func showarray(vect) + see "[" + svect = "" + for n = 1 to len(vect) + svect = svect + vect[n] + " " + next + svect = left(svect, len(svect) - 1) + see svect + see "]" + nl diff --git a/Task/Knuth-shuffle/Stata/knuth-shuffle.stata b/Task/Knuth-shuffle/Stata/knuth-shuffle.stata new file mode 100644 index 0000000000..b650cc3b42 --- /dev/null +++ b/Task/Knuth-shuffle/Stata/knuth-shuffle.stata @@ -0,0 +1,15 @@ +mata +function shuffle(a) { + n = length(a) + r = runiformint(1,1,1,1..n) + for (i=n; i>=2; i--) { + j = r[i] + x = a[i] + a[i] = a[j] + a[j] = x + } + return(a) +} + +shuffle(1..10) +end diff --git a/Task/Knuths-algorithm-S/00DESCRIPTION b/Task/Knuths-algorithm-S/00DESCRIPTION index d300270bd3..a88e4e10b0 100644 --- a/Task/Knuths-algorithm-S/00DESCRIPTION +++ b/Task/Knuths-algorithm-S/00DESCRIPTION @@ -1,23 +1,29 @@ This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end. This means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive samples can change). + ;The algorithm: -# Select the first n items as the sample as they become available; -# For the i-th item where i > n, have a random chance of n/i of keeping it. If failing this chance, the sample remains the same. If not, have it randomly (1/n) replace one of the previously selected n items of the sample. -# Repeat #2 for any subsequent items. +:* Select the first n items as the sample as they become available; +:* For the i-th item where i > n, have a random chance of n/i of keeping it. If failing this chance, the sample remains the same. If not, have it randomly (1/n) replace one of the previously selected n items of the sample. +:* Repeat   2nd step   for any subsequent items. + ;The Task: -# Create a function s_of_n_creator that given n the maximum sample size, returns a function s_of_n that takes one parameter, item. -# Function s_of_n when called with successive items returns an equi-weighted random sample of up to n of its items so far, each time it is called, calculated using Knuths Algorithm S. -# Test your functions by printing and showing the frequency of occurrences of the selected digits from 100,000 repetitions of: -:# Use the s_of_n_creator with n == 3 to generate an s_of_n. -:# call s_of_n with each of the digits 0 to 9 in order, keeping the returned three digits of its random sampling from its last call with argument item=9. +:* Create a function s_of_n_creator that given n the maximum sample size, returns a function s_of_n that takes one parameter, item. +:* Function s_of_n when called with successive items returns an equi-weighted random sample of up to n of its items so far, each time it is called, calculated using Knuths Algorithm S. +:* Test your functions by printing and showing the frequency of occurrences of the selected digits from 100,000 repetitions of: +:::# Use the s_of_n_creator with n == 3 to generate an s_of_n. +:::# call s_of_n with each of the digits 0 to 9 in order, keeping the returned three digits of its random sampling from its last call with argument item=9. + Note: A class taking n and generating a callable instance/function might also be used. + ;Reference: * The Art of Computer Programming, Vol 2, 3.4.2 p.142 -;Cf. + +;Related tasks: * [[One of n lines in a file]] * [[Accumulator factory]] +

diff --git a/Task/Knuths-algorithm-S/Julia/knuths-algorithm-s.julia b/Task/Knuths-algorithm-S/Julia/knuths-algorithm-s.julia index ca54a5cfc6..3500b11539 100644 --- a/Task/Knuths-algorithm-S/Julia/knuths-algorithm-s.julia +++ b/Task/Knuths-algorithm-S/Julia/knuths-algorithm-s.julia @@ -1,35 +1,26 @@ -function makesofn(n::Int) - buf = Any[] +function makesofn(n::Integer) + buf = Vector{typeof(n)}(0) i = 0 - function sofn(item) + return function sofn(item) i += 1 - if i <= n + if i ≤ n push!(buf, item) else j = rand(1:i) - if j <= n - buf[j] = item - end + if j ≤ n buf[j] = item end end return buf end - return sofn end - nhist = zeros(Int, 10) - -for i in 1:10^5 +for _ in 1:10^5 kas = makesofn(3) - for j in 0:8 - kas(j) - end - for k in kas(9) - nhist[k+1] += 1 - end + for j in 0:8 kas(j) end + for k in kas(9) nhist[k+1] += 1 end end println("Simulating sof3(0:9) 100000 times:") for (i, c) in enumerate(nhist) - println(@sprintf " %2d => %5d" i-1 c) + @printf("%5d → %5d\n", i-1, c) end diff --git a/Task/Knuths-algorithm-S/REXX/knuths-algorithm-s.rexx b/Task/Knuths-algorithm-S/REXX/knuths-algorithm-s.rexx index dd14e25d8a..2e27d075e7 100644 --- a/Task/Knuths-algorithm-S/REXX/knuths-algorithm-s.rexx +++ b/Task/Knuths-algorithm-S/REXX/knuths-algorithm-s.rexx @@ -1,40 +1,39 @@ -/*REXX program using Knuth's algorithm S (a random sampling N of M items).*/ -parse arg trials size . /*obtain optional arguments from the CL*/ -if trials=='' then trials=100000 /*Not specified? Then use the default.*/ -if size=='' then size= 3 /* " " " " " " */ -#.=0 /*initialize frequency counter array. */ - do trials /*OK, now let's light this candle. */ - call s_of_n_creator size /*create an initial list of N items. */ +/*REXX program using Knuth's algorithm S (a random sampling N of M items). */ +parse arg trials size . /*obtain optional arguments from the CL*/ +if trials=='' | trials=="," then trials=100000 /*Not specified? Then use the default.*/ +if size=='' | size=="," then size= 3 /* " " " " " " */ +#.=0 /*initialize frequency counter array. */ + do trials /*OK, now let's light this candle. */ + call s_of_n_creator size /*create an initial list of N items. */ - do gener=0 for 10 - call s_of_n gener /*call s_of_n with a single decimal dig*/ - end /*gener*/ + do gener=0 for 10 + call s_of_n gener /*call s_of_n with a single decimal dig*/ + end /*gener*/ - do count=1 for size /*let's examine what SofN generated. */ - _=!.count /*get a decimal digit from the Nth */ - #._=#._+1 /* ··· item, and count it, of course.*/ - end /*count*/ - end /*trials*/ - @='trials, and with size=' -say "Using Knuth's algorithm S for" commas(trials) @ || commas(size)":" -say - do dig=0 to 9 /* [↓] display the frequency of a dig.*/ - say left('',20) "frequency of the" dig 'digit is:' commas(#.dig) - end /*dig*/ -exit /*stick a fork in it, we're all done. */ -/*────────────────────────────────────────────────────────────────────────────*/ -commas: procedure; parse arg _; n=_'.9'; #=123456789; b=verify(n,#,"M") - e=verify(n, #'0', , verify(n, #"0.", 'M')) - 4 - do j=e to b by -3; _=insert(',',_,j); end /*j*/; return _ -/*────────────────────────────────────────────────────────────────────────────*/ -s_of_n: parse arg item; items=items+1 /*get "item", bump the items counter.*/ - c=random(1, items) /* [↓] should replace a previous item?*/ - if c>size then return /*probability isn't good, so skip it. */ - _=random(1, size); !._=item /*now, figure out which previous ··· */ - return /* ··· item to replace with ITEM.*/ -/*────────────────────────────────────────────────────────────────────────────*/ -s_of_n_creator: parse arg item 1 items /*generate ITEM number of items. */ - do k=1 for item /*traipse through the first N items. */ - !.k=random(0, 9) /*set the Kth item with random digit.*/ - end /*k*/ - return /*the piddly stuff is done (for now). */ + /* [↓] examine what SofN generated. */ + do count=1 for size; _= !.count /*get a dec. digit from the Nth item. */ + #._=#._ + 1 /*bump counter for the decimal digit. */ + end /*count*/ + end /*trials*/ + @= ' trials, and with a size of ' +hdr=" Using Knuth's algorithm S for " commas(trials) @ || commas(size)": " +say hdr; say copies("═", length(hdr) ) /*display the header and its separator.*/ + + do dig=0 to 9 /* [↓] display the frequency of a dig.*/ + say left('', 20) "frequency of the" dig 'digit is: ' commas(#.dig) + end /*dig*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +commas: parse arg _; do jc=length(_)-3 to 1 by -3; _=insert(',', _, jc); end; return _ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +s_of_n: parse arg item; items=items + 1 /*get "item", bump the items counter.*/ + c=random(1, items) /* [↓] should replace a previous item?*/ + if c>size then return /*probability isn't good, so skip it. */ + _=random(1, size); !._=item /*now, figure out which previous ··· */ + return /* ··· item to replace with ITEM.*/ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +s_of_n_creator: parse arg item 1 items /*generate ITEM number of items. */ + do k=1 for item /*traipse through the first N items. */ + !.k=random(0, 9) /*set the Kth item with random digit.*/ + end /*k*/ + return /*the piddly stuff is done (for now). */ diff --git a/Task/Knuths-algorithm-S/Rust/knuths-algorithm-s.rust b/Task/Knuths-algorithm-S/Rust/knuths-algorithm-s.rust new file mode 100644 index 0000000000..9c3b37672e --- /dev/null +++ b/Task/Knuths-algorithm-S/Rust/knuths-algorithm-s.rust @@ -0,0 +1,46 @@ +use rand::{Rng,weak_rng}; + +struct SofN { + rng: R, + sample: Vec, + i: usize, + n: usize, +} + +impl SofN { + fn new(rng: R, n: usize) -> Self { + SofN{rng, sample: Vec::new(), i: 0, n} + } + + fn add(&mut self, item: T) { + self.i += 1; + if self.i <= self.n { + self.sample.push(item); + } else if self.rng.gen_range(0, self.i) < self.n { + self.sample[self.rng.gen_range(0, self.n)] = item; + } + } + + fn sample(&self) -> &Vec { + &self.sample + } +} + + +pub fn main() { + const MAX: usize = 10; + let mut bin: [i32; MAX] = Default::default(); + for _ in 0..100000 { + let mut s_of_n = SofN::new(weak_rng(), 3); + + for i in 0..MAX { s_of_n.add(i); } + + for s in s_of_n.sample() { + bin[*s] += 1; + } + } + + for (i, x) in bin.iter().enumerate() { + println!("frequency of {}: {}", i, x); + } +} diff --git a/Task/Knuths-algorithm-S/Scala/knuths-algorithm-s.scala b/Task/Knuths-algorithm-S/Scala/knuths-algorithm-s.scala new file mode 100644 index 0000000000..e51747de73 --- /dev/null +++ b/Task/Knuths-algorithm-S/Scala/knuths-algorithm-s.scala @@ -0,0 +1,21 @@ +import java.util +import scala.util.Random + +object KnuthsAlgorithmS extends App { + + import scala.collection.JavaConverters._ + + val (n, rand, bin) = (3, Random, new Array[Int](10)) + + for (_ <- 0 until 100000) { + val sample = new util.ArrayList[Int](n) + for (item <- 0 until 10) { + if (item < n) sample.add(item) + else if (rand.nextInt(item + 1) < n) + sample.asScala(rand.nextInt(n)) = item + } + for (s <- sample.asScala.toList) bin(s) += 1 + } + + println(bin.mkString("[", ", ", "]")) +} diff --git a/Task/LU-decomposition/Go/lu-decomposition-3.go b/Task/LU-decomposition/Go/lu-decomposition-3.go index 5a132d64f1..8ae29aca3d 100644 --- a/Task/LU-decomposition/Go/lu-decomposition-3.go +++ b/Task/LU-decomposition/Go/lu-decomposition-3.go @@ -3,17 +3,17 @@ package main import ( "fmt" - "github.com/gonum/matrix/mat64" + "gonum.org/v1/gonum/mat" ) func main() { - showLU(mat64.NewDense(3, 3, []float64{ + showLU(mat.NewDense(3, 3, []float64{ 1, 3, 5, 2, 4, 7, 1, 1, 0, })) fmt.Println() - showLU(mat64.NewDense(4, 4, []float64{ + showLU(mat.NewDense(4, 4, []float64{ 11, 9, 24, 2, 1, 5, 2, 6, 3, 17, 18, 1, @@ -21,14 +21,13 @@ func main() { })) } -func showLU(a *mat64.Dense) { - fmt.Printf("a: %v\n\n", mat64.Formatted(a, mat64.Prefix(" "))) - var lu mat64.LU +func showLU(a *mat.Dense) { + fmt.Printf("a: %v\n\n", mat.Formatted(a, mat.Prefix(" "))) + var lu mat.LU lu.Factorize(a) - var l, u mat64.TriDense - l.LFrom(&lu) - u.UFrom(&lu) - fmt.Printf("l: %.5f\n\n", mat64.Formatted(&l, mat64.Prefix(" "))) - fmt.Printf("u: %.5f\n\n", mat64.Formatted(&u, mat64.Prefix(" "))) + l := lu.LTo(nil) + u := lu.UTo(nil) + fmt.Printf("l: %.5f\n\n", mat.Formatted(l, mat.Prefix(" "))) + fmt.Printf("u: %.5f\n\n", mat.Formatted(u, mat.Prefix(" "))) fmt.Println("p:", lu.Pivot(nil)) } diff --git a/Task/LU-decomposition/Kotlin/lu-decomposition.kotlin b/Task/LU-decomposition/Kotlin/lu-decomposition.kotlin new file mode 100644 index 0000000000..2e00a8dfe6 --- /dev/null +++ b/Task/LU-decomposition/Kotlin/lu-decomposition.kotlin @@ -0,0 +1,102 @@ +// version 1.1.4-3 + +typealias Vector = DoubleArray +typealias Matrix = Array + +operator fun Matrix.times(other: Matrix): Matrix { + val rows1 = this.size + val cols1 = this[0].size + val rows2 = other.size + val cols2 = other[0].size + require(cols1 == rows2) + val result = Matrix(rows1) { Vector(cols2) } + for (i in 0 until rows1) { + for (j in 0 until cols2) { + for (k in 0 until rows2) { + result[i][j] += this[i][k] * other[k][j] + } + } + } + return result +} + +fun pivotize(m: Matrix): Matrix { + val n = m.size + val im = Array(n) { Vector(n) } + for (i in 0 until n) im[i][i] = 1.0 + for (i in 0 until n) { + var max = m[i][i] + var row = i + for (j in i until n) { + if (m[j][i] > max) { + max = m[j][i] + row = j + } + } + if (i != row) { + val t = im[i] + im[i] = im[row] + im[row] = t + } + } + return im +} + +fun lu(a: Matrix): Array { + val n = a.size + val l = Array(n) { Vector(n) } + val u = Array(n) { Vector(n) } + val p = pivotize(a) + val a2 = p * a + + for (j in 0 until n) { + l[j][j] = 1.0 + for (i in 0 until j + 1) { + var sum = 0.0 + for (k in 0 until i) sum += u[k][j] * l[i][k] + u[i][j] = a2[i][j] - sum + } + for (i in j until n) { + var sum2 = 0.0 + for(k in 0 until j) sum2 += u[k][j] * l[i][k] + l[i][j] = (a2[i][j] - sum2) / u[j][j] + } + } + return arrayOf(l, u, p) +} + +fun printMatrix(title: String, m: Matrix, f: String) { + val n = m.size + println("\n$title\n") + for (i in 0 until n) { + for (j in 0 until n) print("${f.format(m[i][j])} ") + println() + } +} + +fun main(args: Array) { + val a1 = arrayOf( + doubleArrayOf( 1.0, 3.0, 5.0), + doubleArrayOf( 2.0, 4.0, 7.0), + doubleArrayOf( 1.0, 1.0, 0.0) + ) + val (l1, u1, p1) = lu(a1) + println("EXAMPLE 1:-") + printMatrix("A:", a1, "%1.0f") + printMatrix("L:", l1, "% 7.5f") + printMatrix("U:", u1, "% 8.5f") + printMatrix("P:", p1, "%1.0f") + + val a2 = arrayOf( + doubleArrayOf(11.0, 9.0, 24.0, 2.0), + doubleArrayOf( 1.0, 5.0, 2.0, 6.0), + doubleArrayOf( 3.0, 17.0, 18.0, 1.0), + doubleArrayOf( 2.0, 5.0, 7.0, 1.0) + ) + val (l2, u2, p2) = lu(a2) + println("\nEXAMPLE 2:-") + printMatrix("A:", a2, "%2.0f") + printMatrix("L:", l2, "%7.5f") + printMatrix("U:", u2, "%8.5f") + printMatrix("P:", p2, "%1.0f") +} diff --git a/Task/LU-decomposition/REXX/lu-decomposition.rexx b/Task/LU-decomposition/REXX/lu-decomposition.rexx index 3840b4af10..a6de95fa87 100644 --- a/Task/LU-decomposition/REXX/lu-decomposition.rexx +++ b/Task/LU-decomposition/REXX/lu-decomposition.rexx @@ -1,73 +1,62 @@ /*REXX program creates a matrix from console input, performs/shows LU decomposition.*/ #=0; P.=0; PA.=0; L.=0; U.=0 /*initialize some variables to zero. */ parse arg x /*obtain matrix elements from the C.L. */ -call makeMat /*make the A matrix from the numbers.*/ -call showMat 'A', N /*display the A matrix. */ -call manPmat /*manufacture P (permutation). */ -call showMat 'P', N /*display the P matrix. */ -call multMat /*multiply the A and P matrices. */ -call showMat 'PA', N /*display the PA matrix. */ - do y=1 for N; call manUmat y /*manufacture U matrix, parts. */ - call manLmat y /*manufacture L matrix, parts. */ - end -call showMat 'L', N /*display the L matrix. */ -call showMat 'U', N /*display the U matrix. */ + call bldAMat; call showMat 'A' /*build and display A matrix.*/ + call bldPmat; call showMat 'P' /* " " " P " */ + call multMat; call showMat 'PA' /* " " " PA " */ + do y=1 for N; call bldUmat; call bldLmat /*build U and L " */ + end /*y*/ + call showMat 'L'; call showMat 'U' /*display L and U " */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -er: say; say '***error!***'; say; say arg(1); say; exit 13 +bldAMat: ?=words(x); do N=1 for ? until N**2>=? /*find matrix size. */ + end /*N*/ + if N**2\==? then do; say '***error*** wrong # of elements entered:' ?; exit 9 + end + do r=1 for N /*build A matrix.*/ + do c=1 for N; #=# + 1; _=word(x, #); A.r.c=_ + if \datatype(_, 'N') then call er "element isn't numeric: " _ + end /*c*/ + end /*r*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ -makeMat: ?=words(x); do N=1 for ?; if N**2==? then leave; end /*N*/ - if N**2\==? then call er 'not correct number of elements entered: ' ? - - do r=1 for N /*build the "A" matrix from the input*/ - do c=1 for N; #=#+1; _=word(x,#); A.r.c=_ - if \datatype(_,'N') then call er "element isn't numeric: " _ - end /*c*/ - end /*r*/ - return +bldLmat: do r=1 for N /*build lower matrix*/ + do c=1 for N; if r==c then do; L.r.c=1; iterate; end + if c\==y | r==c | c>r then iterate + _=PA.r.c + do k=1 for c-1; _=_ - U.k.c * L.r.k + end /*k*/ + L.r.c=_ / U.c.c + end /*c*/ + end /*r*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ -manLmat: parse arg ? /*manufacture L (lower) matrix.*/ - do r=1 for N - do c=1 for N; if r==c then do; L.r.c=1; iterate; end - if c\==? | r==c | c>r then iterate - _=PA.r.c - do k=1 for c-1; _=_-U.k.c*L.r.k; end /*k*/ - L.r.c=_/U.c.c - end /*c*/ - end /*r*/ - return +bldPmat: c=N; do r=N by -1 for N; P.r.c=1; c=c+1 /*build perm. matrix*/ + if c>N then c=N%2; if c==N then c=1 + end /*r*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ -manPmat: c=N; do r=N by -1 for N /*manufacture P (permutation). */ - P.r.c=1; c=c+1; if c>N then c=N%2; if c==N then c=1 - end /*r*/ - return +bldUmat: do r=1 for N; if r\==y then iterate /*build upper matrix*/ + do c=1 for N; if c int but + // slices are not acceptable map key types. + dictionary := make(map[string]int, dictSize) + for i := 0; i < dictSize; i++ { + // Ugly mess to work around not having a []byte key type. + // Using `string(i)` would do utf8 encoding for i>127. + dictionary[string([]byte{byte(i)})] = i + } - w := "" - result := make([]int, 0) - for _, c := range []byte(uncompressed) { - wc := w + string(c) - if _, ok := dictionary[wc]; ok { - w = wc - } else { - result = append(result, dictionary[w]) - // Add wc to the dictionary. - dictionary[wc] = dictSize - dictSize++ - w = string(c) - } - } + var result []int + var w []byte + for i := 0; i < len(uncompressed); i++ { + c := uncompressed[i] + wc := append(w, c) + if _, ok := dictionary[string(wc)]; ok { + w = wc + } else { + result = append(result, dictionary[string(w)]) + // Add wc to the dictionary. + dictionary[string(wc)] = dictSize + dictSize++ + //w = []byte{c}, but re-using wc + wc[0] = c + w = wc[:1] + } + } - // Output the code for w. - if w != "" { - result = append(result, dictionary[w]) - } - return result + if len(w) > 0 { + // Output the code for w. + result = append(result, dictionary[string(w)]) + } + return result } -// Decompress a list of output ks to a string. -func decompress(compressed []int) string { - // Build the dictionary. - dictSize := 256 - dictionary := make(map[int]string) - for i := 0; i < 256; i++ { - dictionary[i] = string(i) - } +type BadSymbolError int - w := string(compressed[0]) - result := w - for _, k := range compressed[1:] { - var entry string - if x, ok := dictionary[k]; ok { - entry = x - } else if k == dictSize { - entry = w + w[:1] - } else { - panic(fmt.Sprintf("Bad compressed k: %d", k)) - } +func (e BadSymbolError) Error() string { + return fmt.Sprint("Bad compressed symbol ", int(e)) +} - result += entry +// Decompress a list of output symbols to a string. +func decompress(compressed []int) (string, error) { + // Build the dictionary. + dictSize := 256 + dictionary := make(map[int][]byte, dictSize) + for i := 0; i < dictSize; i++ { + dictionary[i] = []byte{byte(i)} + } - // Add w+entry[0] to the dictionary. - dictionary[dictSize] = w + entry[:1] - dictSize++ + var result strings.Builder + var w []byte + for _, k := range compressed { + var entry []byte + if x, ok := dictionary[k]; ok { + //entry = x, but ensuring any append will make a copy + entry = x[:len(x):len(x)] + } else if k == dictSize && len(w) > 0 { + entry = append(w, w[0]) + } else { + return result.String(), BadSymbolError(k) + } + result.Write(entry) - w = entry - } - return result + if len(w) > 0 { + // Add w+entry[0] to the dictionary. + w = append(w, entry[0]) + dictionary[dictSize] = w + dictSize++ + } + w = entry + } + return result.String(), nil } func main() { - compressed := compress("TOBEORNOTTOBEORTOBEORNOT") - fmt.Println(compressed) - decompressed := decompress(compressed) - fmt.Println(decompressed) + compressed := compress("TOBEORNOTTOBEORTOBEORNOT") + fmt.Println(compressed) + decompressed, err := decompress(compressed) + if err != nil { + log.Fatal(err) + } + fmt.Println(decompressed) } diff --git a/Task/LZW-compression/Julia/lzw-compression.julia b/Task/LZW-compression/Julia/lzw-compression.julia new file mode 100644 index 0000000000..fd56763df5 --- /dev/null +++ b/Task/LZW-compression/Julia/lzw-compression.julia @@ -0,0 +1,50 @@ +function compressLZW(decompressed::String) + dictsize = 256 + dict = Dict{String,Int}(string(Char(i)) => i for i in range(0, dictsize)) + result = Vector{Int}(0) + w = "" + for c in decompressed + wc = string(w, c) + if haskey(dict, wc) + w = wc + else + push!(result, dict[w]) + dict[wc] = dictsize + dictsize += 1 + w = string(c) + end + end + if !isempty(w) push!(result, dict[w]) end + return result +end + +function decompressLZW(compressed::Vector{Int}) + dictsize = 256 + dict = Dict{Int,String}(i => string('\0' + i) for i in range(0, dictsize)) + result = IOBuffer() + w = string(Char(shift!(compressed))) + write(result, w) + for k in compressed + if haskey(dict, k) + entry = dict[k] + elseif k == dictsize + entry = string(w, w[1]) + else + error("bad compressed k: $k") + end + write(result, entry) + dict[dictsize] = string(w, entry[1]) + dictsize += 1 + w = entry + end + return String(result) +end + +original = ["0123456789", "TOBEORNOTTOBEORTOBEORNOT", "dudidudidudida"] +compressed = compressLZW.(original) +decompressed = decompressLZW.(compressed) + +for (word, comp, decomp) in zip(original, compressed, decompressed) + comprate = (length(word) - length(comp)) / length(word) * 100 + println("Original: $word\n-> Compressed: $comp (compr.rate: $(round(comprate, 2))%)\n-> Decompressed: $decomp") +end diff --git a/Task/LZW-compression/REXX/lzw-compression-2.rexx b/Task/LZW-compression/REXX/lzw-compression-2.rexx index fed66f723a..f4b75dba5b 100644 --- a/Task/LZW-compression/REXX/lzw-compression-2.rexx +++ b/Task/LZW-compression/REXX/lzw-compression-2.rexx @@ -1,31 +1,29 @@ /*REXX program compresses text using the LZW (Lempel─Ziv─Welch), and reconstitutes it.*/ parse arg x /*get an optional argument from the CL.*/ -if x=='' then x= '"There is nothing permanent except change." ─── Heraclitus [540-475 BC]' - say 'original text=' x +if x='' then x= '"There is nothing permanent except change." ─── Heraclitus [540-475 BC]' + say 'original text=' x cypher=LZWc(x) /*compress text using the LZW algorithm*/ -say; say 'reconstituted=' LZWd(cypher) /*display the original cypher text. */ -say; say ' LZW integers=' cypher /*also display the LZW integers used.*/ + say 'reconstituted=' LZWd(cypher) + say ' LZW integers=' cypher exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ LZWc: procedure; parse arg y,,w $ @.; #=256 /*the LZW compress algorithm.*/ - do j=0 for #; _=d2c(j); @._=j; end /*j*/ + do j=0 for #; _=d2c(j); @._=j; end /*j*/ - do k=1 for length(y); _=w || substr(y, k, 1) - if @._=='' then do; $=$ @.w; @._=#; #=#+1 - w=substr(y, k, 1) + do k=1 for length(y); _=w || substr(y, k, 1) + if @._=='' then do; $=$ @.w; @._=#; #=#+1; w=substr(y,k,1) end else w=_ end /*k*/ return strip($ @.w) /*remove any superfluous blanks*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ LZWd: procedure; parse arg w y,,@.; #=256 /*the LZW decompress algorithm.*/ - do j=0 for #; @.j=d2c(j); end /*j*/ + do j=0 for #; @.j=d2c(j); end /*j*/ $=@.w; w=$ do k=1 for words(y); _=word(y, k) if @._\=='' | @.k==" " then ?=@._ - else if _=# then ?=w || left(w, 1) + else if _==# then ?=w || left(w, 1) $=$ || ? - @.#=w || left(?, 1); #=#+1 - w=? + @.#=w || left(?, 1); #=#+1; w=? end /*k*/ return $ diff --git a/Task/LZW-compression/Ring/lzw-compression.ring b/Task/LZW-compression/Ring/lzw-compression.ring new file mode 100644 index 0000000000..3faae6e99d --- /dev/null +++ b/Task/LZW-compression/Ring/lzw-compression.ring @@ -0,0 +1,81 @@ +# Project : LZW compression +# Date : 2018/04/07 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +plaintext = "TOBEORNOTTOBEORTOBEORNOT" +result = [] +encode = encodelzw(plaintext) +for i = 1 to len(encode) step 2 + add(result,ascii(substr(encode,i,1)) + 256*ascii(substr(encode,i+1,1))) +next +showarray(result) +see decodelzw(encode) + +func encodelzw(text) + o = "" + dict = list(4096) + for i = 1 to 255 + dict[i] = char(i) + next + l = i + i = 1 + w = left(text,1) + while i < len(text) + d = 0 + while d < l + c = d + if i > len(text) + exit + ok + for d = 1 to l + if w = dict[d] + exit + ok + next + if d < l + i = i + 1 + w = w + substr(text,i,1) + ok + end + dict[l] = w + l = l + 1 + w = right(w,1) + o = o + char(c % 256) + char(floor(c / 256)) + end + return o + +func decodelzw(text) + o = "" + dict = list(4096) + for i = 1 to 255 + dict[i] = char(i) + next + l = i + c = ascii(left(text,1)) + 256*ascii(substr(text,2,1)) + w = dict[c] + o = w + if len(text) < 4 + return o + ok + for i = 3 to len(text) step 2 + c = ascii(substr(text,i,1)) + 256*ascii(substr(text,i+1,1)) + if c < l + t = dict[c] + else + t = w + left(w,1) + ok + o = o + t + dict[l] = w + left(t,1) + l = l + 1 + w = t + next + return o + +func showarray(vect) + svect = "" + for n = 1 to len(vect) + svect = svect + vect[n] + " " + next + svect = left(svect, len(svect) - 1) + see svect + nl diff --git a/Task/Langtons-ant/00DESCRIPTION b/Task/Langtons-ant/00DESCRIPTION index cf3339fed2..49e4ca237d 100644 --- a/Task/Langtons-ant/00DESCRIPTION +++ b/Task/Langtons-ant/00DESCRIPTION @@ -1,16 +1,18 @@ -[[wp:Langton's ant|Langton's ant]] is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, facing in one of four directions. +[[wp:Langton's ant|Langton's ant]] is a cellular automaton that models an [https://en.wikipedia.org/wiki/Ant ant] sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions. + Each cell can either be black or white. + The ant moves according to the color of the cell it is currently sitting in, with the following rules: ::#   If the cell is black, it changes to white and the ant turns left; ::#   If the cell is white, it changes to black and the ant turns right; ::#   The ant then moves forward to the next cell, and repeat from step 1. -
This rather simple ruleset leads to an initially chaotic movement pattern, and after about 10000 steps, a cycle appears where the ant moves steadily away from the starting location in a diagonal corridor about 10 pixels wide. -Conceptually the ant can then travel infinitely far away. +
This rather simple ruleset leads to an initially chaotic movement pattern, and after about 10000 steps, a cycle appears where the ant moves steadily away from the starting location in a diagonal corridor about 10 cells wide. +Conceptually the ant can then walk infinitely far away. ;Task: -Start the ant near the center of a 100 by 100 field of cells, which is about big enough to contain the initial chaotic part of the movement. +Start the ant near the center of a 100x100 field of cells, which is about big enough to contain the initial chaotic part of the movement. Follow the movement rules for the ant, terminate when it moves out of the region, and show the cell colors it leaves behind. diff --git a/Task/Langtons-ant/Aime/langtons-ant.aime b/Task/Langtons-ant/Aime/langtons-ant.aime index aede7dae81..0409766f56 100644 --- a/Task/Langtons-ant/Aime/langtons-ant.aime +++ b/Task/Langtons-ant/Aime/langtons-ant.aime @@ -4,25 +4,20 @@ is_white(list map, integer x, integer y) integer p, w; data b; - b = l_q_data(map, y); - w = b_character(b, x >> 3); + b = map[y]; + w = b[x >> 3]; p = 1 << (7 - (x & 7)); - b_replace(b, x >> 3, w ^ p); + b[x >> 3] = w ^ p; - return !(w & p); + !(w & p); } void ant(integer x, integer y, integer d, list map) { while (-1 < x && x < 100 && -1 < y && y < 100) { - if (is_white(map, x, y)) { - d += 3; - d &= 3; - } else { - d += 1; - d &= 3; - } + d += is_white(map, x, y) ? 3 : 1; + d &= 3; if (d & 1) { y += (d & 2) - 1; @@ -41,29 +36,16 @@ main(void) i = 100; while (i) { - data b; - integer j; - i -= 1; - j = 13; - while (j) { - j -= 1; - b_append(b, 0); - } - - l_l_data(l, -1, b); + l_n_data(l, -1).run(13, 0); } ant(50, 50, 2, l); - f_open(f, "ant.pbm", OPEN_CREATE | OPEN_TRUNCATE | OPEN_WRITEONLY, 00644); + f.create("ant.pbm", 00644); - f_text(f, "P4\n100 100\n"); - i = 100; - while (i) { - f_b_post(f, l_q_data(l, -i)); - i -= 1; - } + f.text("P4\n100 100\n"); + l.ucall(f_data, 1, f); - return 0; + 0; } diff --git a/Task/Langtons-ant/Kotlin/langtons-ant.kotlin b/Task/Langtons-ant/Kotlin/langtons-ant.kotlin new file mode 100644 index 0000000000..2ea0eeb575 --- /dev/null +++ b/Task/Langtons-ant/Kotlin/langtons-ant.kotlin @@ -0,0 +1,34 @@ +// version 1.2.0 + +enum class Direction { UP, RIGHT, DOWN, LEFT } + +const val WHITE = 0 +const val BLACK = 1 + +fun main(args: Array) { + val width = 75 + val height = 52 + val maxSteps = 12_000 + var x = width / 2 + var y = height / 2 + val m = Array(height) { IntArray(width) } + var dir = Direction.UP + var i = 0 + while (i < maxSteps && x in 0 until width && y in 0 until height) { + val turn = m[y][x] == BLACK + val index = (dir.ordinal + if (turn) 1 else -1) and 3 + dir = Direction.values()[index] + m[y][x] = if (m[y][x] == BLACK) WHITE else BLACK + when (dir) { + Direction.UP -> y-- + Direction.RIGHT -> x-- + Direction.DOWN -> y++ + Direction.LEFT -> x++ + } + i++ + } + for (j in 0 until height) { + for (k in 0 until width) print(if(m[j][k] == WHITE) '.' else '#') + println() + } +} diff --git a/Task/Langtons-ant/REXX/langtons-ant-1.rexx b/Task/Langtons-ant/REXX/langtons-ant-1.rexx new file mode 100644 index 0000000000..4a3cc0e89b --- /dev/null +++ b/Task/Langtons-ant/REXX/langtons-ant-1.rexx @@ -0,0 +1,37 @@ +/*REXX program implements Langton's ant walk and displays the ant's path (finite field).*/ +parse arg dir char seed . /*obtain optional arguments from the CL*/ +if datatype(seed, 'W') then call random ,,seed /*Integer? Then use it as a RANDOM SEED*/ +if dir=='' | dir=="," then dir=random(1, 4) /*ant is facing a random direction, */ +if char=='' | char=="," then char= '#' /*binary colors: 0≡white, 1≡black. */ +parse value scrSize() with sd sw . /*obtain the terminal's depth and width*/ + sd=sd -6; sw=sw -1 /*adjust for terminal's useable area. */ + xHome=1000000; yHome=1000000 /*initially in the middle of nowhere. */ + x=xHome; y=yHome /*start ant's walk in middle of nowhere*/ +$.=1; $.0=4 ; $.2=2; $.3=3; $.4=4 /* 1≡north 2≡east 3≡south 4≡west.*/ +minX=x; minY=y; maxX=x; maxY=y /*initialize the min/max values for X,Y*/ +@.=0 /*the universe (walk field) is white.*/ + do #=1 until (maxX-minY>sw)|(maxY-minY>sd) /*is the path out─of─bounds for screen?*/ + black=@.x.y; @.x.y= \@.x.y /*invert (flip) ant's cell color code.*/ + if black then dir=dir - 1 /*if cell color was black, turn left.*/ + else dir=dir + 1 /* " " " " white, turn right.*/ + dir=$.dir /*$ array handles/adjusts under & over.*/ + select /*ant walks the direction it's facing. */ + when dir==1 then y= y + 1 /*is ant walking north? Then go up. */ + when dir==2 then x= x + 1 /* " " " east? " " right.*/ + when dir==3 then y= y - 1 /* " " " south? " " down. */ + when dir==4 then x= x - 1 /* " " " west? " " left. */ + end /*select*/ /*the DIRection is always normalized.*/ + minX=min(minX, x); maxX=max(maxX, x) /*find the minimum and maximum of X. */ + minY=min(minY, y); maxY=max(maxY, y) /* " " " " " " Y. */ + end /*steps*/ /* [↑] ant walks hither and thither. */ + /*finished walking, it's out─of─bounds.*/ +say center(" Langton's ant walked " # ' steps ', sw, "─") +@.xHome.yHome='█' /*show the ant's initial starting point*/ +@.x.y= '∙' /*show where the ant went out─of─bounds*/ + /* [↓] show Langton's ant's trail. */ + do y=maxY to minY by -1; _= /*display a single row of cells. */ + do x=minX to maxX; _=_ || @.x.y /*build a cell row for the display. */ + end /*x*/ /* [↓] strip trailing blanks from line*/ + _=strip( translate(_, char, 10), 'T') /*color the cells: black or white. */ + if _\=='' then say _ /*display line (strip trailing blanks).*/ + end /*y*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Langtons-ant/REXX/langtons-ant-2.rexx b/Task/Langtons-ant/REXX/langtons-ant-2.rexx new file mode 100644 index 0000000000..d7b56d6daa --- /dev/null +++ b/Task/Langtons-ant/REXX/langtons-ant-2.rexx @@ -0,0 +1 @@ + when dir==4 then x= x - 1 /* " " " west? " " left. */ diff --git a/Task/Langtons-ant/REXX/langtons-ant-3.rexx b/Task/Langtons-ant/REXX/langtons-ant-3.rexx new file mode 100644 index 0000000000..9193cf19a7 --- /dev/null +++ b/Task/Langtons-ant/REXX/langtons-ant-3.rexx @@ -0,0 +1 @@ + otherwise x= x - 1 /* " " " west? " " left. */ diff --git a/Task/Langtons-ant/REXX/langtons-ant.rexx b/Task/Langtons-ant/REXX/langtons-ant.rexx deleted file mode 100644 index b26acf64d9..0000000000 --- a/Task/Langtons-ant/REXX/langtons-ant.rexx +++ /dev/null @@ -1,36 +0,0 @@ -/*REXX program implements Langton's ant walk and displays the ant's path (finite field).*/ -parse arg dir char seed . /*obtain optional arguments from the CL*/ -if datatype(seed, 'W') then call random ,,seed /*Integer? Then use it as a RANDOM SEED*/ -if dir=='' | dir=="," then dir=random(1, 4) /*ant is facing a random direction, */ -if char=='' | char=="," then char= '#' /*binary colors: 0≡white, 1≡black. */ -parse value scrSize() with sd sw . /*obtain the terminal's depth and width*/ - sd=sd-6; sw=sw-1 /*adjust for terminal's useable area. */ -x=1000000 ; y=1000000 /*start ant's walk in middle of nowhere*/ -$.=1; $.0=4 ; $.2=2; $.3=3; $.4=4 /* 1≡north 2≡east 3≡south 4≡west.*/ -@.=0 ; minx=x; miny=y; maxx=x; maxy=y /*define stem array, default: all white*/ - /* [↓] ant walks hither and thither. */ - do steps=1 until (maxx-miny>sw) | (maxy-miny>sd) /*'til the ant is out─of─bounds.*/ - black=@.x.y; @.x.y= \ @.x.y /*invert (flip) ant's cell color code.*/ - if black then dir=dir-1 /*if cell color was black, turn left.*/ - else dir=dir+1 /* " " " " white, turn right.*/ - dir=$.dir /*possibly adjust for under/over. */ - select /*ant walks the direction it's facing. */ - when dir==1 then y= y + 1 /*is ant walking north? Then go up. */ - when dir==2 then x= x + 1 /* " " " east? " " right.*/ - when dir==3 then y= y - 1 /* " " " south? " " down. */ - when dir==4 then x= x - 1 /* " " " west? " " left. */ - end /*select*/ - minx=min(minx, x); maxx=max(maxx, x) /*find the minimum and maximum of X. */ - miny=min(miny, y); maxy=max(maxy, y) /* " " " " " " Y. */ - end /*steps*/ - /*finished walking, it's out-of-bounds.*/ -say center(" Langton's ant walked " steps ' steps. ', 79, "─") -@.1000000.1000000='█' /*show the ant's initial starting point*/ -@.x.y= '∙' /*show where the ant went out-of-bounds*/ - /* [↓] show Langton's ant's trail. */ - do y=maxy to miny by -1; _= /*display a single row of cells. */ - do x=minx to maxx; _=_ || @.x.y /*build a cell row for the display. */ - end /*x*/ - _=strip( translate(_, char, 10), 'T') /*color the cells: black or white. */ - if _\=='' then say _ /*display line (strip trailing blanks).*/ - end /*y*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Langtons-ant/Sidef/langtons-ant.sidef b/Task/Langtons-ant/Sidef/langtons-ant.sidef index c5100aa550..51e0a4512f 100644 --- a/Task/Langtons-ant/Sidef/langtons-ant.sidef +++ b/Task/Langtons-ant/Sidef/langtons-ant.sidef @@ -4,20 +4,20 @@ define size = 100 enum |White, Black| var plane = size.of { size.of (White) } -var (x, y) = @|([size/2 -> int]*2) +var (x, y) = ([size >> 1] * 2)... var dir = dirs.len.irand var moves = 0 loop { (x >= 0) && (y >= 0) && (x < size) && (y < size) || break - given(plane[x][y]) { + given (plane[x][y]) { when (White) { dir--; plane[x][y] = Black } when (Black) { dir++; plane[x][y] = White } } ++moves - [\x, \y]:dirs[dir %= dirs.len] -> each {|a,b| *a += b } + [[\x, \y], dirs[dir %= dirs.len]].zip {|a,b| *a += b } } say "Out of bounds after #{moves} moves at (#{x}, #{y})" diff --git a/Task/Langtons-ant/VBA/langtons-ant.vba b/Task/Langtons-ant/VBA/langtons-ant.vba new file mode 100644 index 0000000000..b8b6287bd8 --- /dev/null +++ b/Task/Langtons-ant/VBA/langtons-ant.vba @@ -0,0 +1,59 @@ +Option Explicit + +Sub Ant() +Dim TablDatas(1 To 200, 1 To 256) As String, sDir As String, sFile As String, Str As String +Dim ColA As Integer, LigA As Long, ColF As Integer, LigF As Long, i As Long, j As Integer, Num As Long +Dim Top As Boolean, Left As Boolean, Bottom As Boolean, Right As Boolean + + 'init variables + Top = True + LigF = 80 + ColF = 50 + For i = 1 To 200 + For j = 1 To 256 + TablDatas(i, j) = " " + Next + Next + 'directory + sDir = "C:\Users\yourname\Desktop\" + 'name txt file + sFile = "Langton_Ant.txt" + + 'start + For i = 1 To 15000 + LigA = LigF + ColA = ColF + If LigA = 1 Or ColA = 1 Or ColA = 256 Or LigA = 200 Then GoTo Fin + If TablDatas(LigA, ColA) = " " Then + TablDatas(LigA, ColA) = "#" + Select Case True + Case Top: Top = False: Left = True: LigF = LigA: ColF = ColA - 1 + Case Left: Left = False: Bottom = True: LigF = LigA + 1: ColF = ColA + Case Bottom: Bottom = False: Right = True: LigF = LigA: ColF = ColA + 1 + Case Right: Right = False: Top = True: LigF = LigA - 1: ColF = ColA + End Select + Else + TablDatas(LigA, ColA) = " " + Select Case True + Case Top: Top = False: Right = True: LigF = LigA: ColF = ColA + 1 + Case Left: Left = False: Top = True: LigF = LigA - 1: ColF = ColA + Case Bottom: Bottom = False: Left = True: LigF = LigA: ColF = ColA - 1 + Case Right: Right = False: Bottom = True: LigF = LigA + 1: ColF = ColA + End Select + End If + Next i + 'result in txt file + Num = FreeFile + Open sDir & sFile For Output As #Num + For i = 1 To UBound(TablDatas, 1) + Str = vbNullString + For j = 1 To UBound(TablDatas, 2) + Str = Str & TablDatas(i, j) + Next j + Print #1, Str + Next i + Close #Num + Exit Sub +Fin: +MsgBox "Stop ! The ant is over limits." +End Sub diff --git a/Task/Largest-int-from-concatenated-ints/Aime/largest-int-from-concatenated-ints.aime b/Task/Largest-int-from-concatenated-ints/Aime/largest-int-from-concatenated-ints.aime index 5eeb499ca9..550ac17b57 100644 --- a/Task/Largest-int-from-concatenated-ints/Aime/largest-int-from-concatenated-ints.aime +++ b/Task/Largest-int-from-concatenated-ints/Aime/largest-int-from-concatenated-ints.aime @@ -7,14 +7,12 @@ largest(...) while (i) { data b; call_n(9, b_, b, $(i -= 1)); - b_size(b, 9); - x[999999999 - atoi(b_string(b))] = $i; + x[999999999 - b.size(9).atoi] = $i; } - i_wcall(x, o_form, 1, 1, "~"); + x.ucall(o_, 0); o_newline(); } - integer main(void) { diff --git a/Task/Largest-int-from-concatenated-ints/Common-Lisp/largest-int-from-concatenated-ints-1.lisp b/Task/Largest-int-from-concatenated-ints/Common-Lisp/largest-int-from-concatenated-ints-1.lisp new file mode 100644 index 0000000000..6eb17dabbc --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/Common-Lisp/largest-int-from-concatenated-ints-1.lisp @@ -0,0 +1,8 @@ +(defun int-concat (ints) + (read-from-string (format nil "~{~a~}" ints))) + +(defun by-biggest-result (first second) + (> (int-concat (list first second)) (int-concat (list second first)))) + +(defun make-largest-int (ints) + (int-concat (sort ints #'by-biggest-result))) diff --git a/Task/Largest-int-from-concatenated-ints/Common-Lisp/largest-int-from-concatenated-ints.lisp b/Task/Largest-int-from-concatenated-ints/Common-Lisp/largest-int-from-concatenated-ints-2.lisp similarity index 100% rename from Task/Largest-int-from-concatenated-ints/Common-Lisp/largest-int-from-concatenated-ints.lisp rename to Task/Largest-int-from-concatenated-ints/Common-Lisp/largest-int-from-concatenated-ints-2.lisp diff --git a/Task/Largest-int-from-concatenated-ints/Factor/largest-int-from-concatenated-ints.factor b/Task/Largest-int-from-concatenated-ints/Factor/largest-int-from-concatenated-ints.factor new file mode 100644 index 0000000000..14c2f2e72b --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/Factor/largest-int-from-concatenated-ints.factor @@ -0,0 +1,15 @@ +USING: assocs io kernel math qw sequences sorting ; +IN: rosetta-code.largest-int + +: pad ( target seq -- padded ) + 2dup length / swap concat swap head ; + +: largest-int ( seq -- ) + dup dup [ length ] map supremum ! find longest length so we know how much to pad + [ swap pad ] curry map ! pad the integers + sort-values ! sort the padded integers + keys ! find the original indices of the sorted integers + swap nths ! order non-padded integers according to their sorted order + reverse concat print ; + +qw{ 1 34 3 98 9 76 45 4 } qw{ 54 546 548 60 } [ largest-int ] bi@ diff --git a/Task/Largest-int-from-concatenated-ints/Julia/largest-int-from-concatenated-ints.julia b/Task/Largest-int-from-concatenated-ints/Julia/largest-int-from-concatenated-ints.julia index 51cef06e81..b2342d1f30 100644 --- a/Task/Largest-int-from-concatenated-ints/Julia/largest-int-from-concatenated-ints.julia +++ b/Task/Largest-int-from-concatenated-ints/Julia/largest-int-from-concatenated-ints.julia @@ -1,18 +1,12 @@ -function maxconcat{T<:Integer}(a::Array{T,1}) - b = map(string, a) - b = sort(b, lt=(x,y)->x*y < y*x, rev=true) - b = join(b, "") - try - b = parseint(b) - catch - b = parseint(BigInt, b) - end +function maxconcat(arr::Vector{<:Integer}) + b = sort(dec.(arr); lt=(x, y) -> x * y < y * x, rev=true) |> join + return try parse(Int, b) catch parse(BigInt, b) end end -tests = {[1, 34, 3, 98, 9, 76, 45, 4], +tests = ([1, 34, 3, 98, 9, 76, 45, 4], [54, 546, 548, 60], - [1, 34, 3, 98, 9, 76, 45, 4, 54, 546, 548, 60]} + [1, 34, 3, 98, 9, 76, 45, 4, 54, 546, 548, 60]) -for t in tests - println("Maxconcating ", t) - println(" ", maxconcat(t)) +for arr in tests + println("Max concatenating in $arr:\n -> ", maxconcat(arr)) +end diff --git a/Task/Largest-int-from-concatenated-ints/REXX/largest-int-from-concatenated-ints-1.rexx b/Task/Largest-int-from-concatenated-ints/REXX/largest-int-from-concatenated-ints-1.rexx new file mode 100644 index 0000000000..a24eff816e --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/REXX/largest-int-from-concatenated-ints-1.rexx @@ -0,0 +1,23 @@ +/*REXX program constructs the largest integer from an integer list using concatenation.*/ +@.=.; @.1 = '1 34 3 98 9 76 45 4' /*the 1st integer list to be used. */ + @.2 = '54 546 548 60' /* " 2nd " " " " " */ + @.3 = ' 4 45 54 5' /* " 3rd " " " " " */ +w=0 /* [↓] process all the integer lists.*/ + do j=1 while @.j\==.; z=space(@.j) /*keep truckin' until lists exhausted. */ + w=max(w, length(z) ); $= /*obtain maximum width to align output.*/ + do while z\=''; idx=1; big=norm(1) /*keep examining the list until done.*/ + do k=2 to words(z); #=norm(k) /*obtain an a number from the list. */ + L=max(length(big), length(#) ) /*get the maximum length of the integer*/ + if left(#, L, left(#, 1) ) <<= left(big, L, left(big, 1) ) then iterate + big=#; idx=k /*we found a new biggie (and the index)*/ + end /*k*/ /* [↑] find max concatenated integer. */ + z=delword(z, idx, 1) /*delete this maximum integer from list*/ + $=$ || big /*append " " " ───► $. */ + end /*while z*/ /* [↑] process all integers in a list.*/ + say 'largest concatenatated integer from ' left( space(@.j), w) " is ─────► " $ + end /*j*/ /* [↑] process each list of integers. */ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +norm: arg i; #=word(z, i); er=' ***error*** '; if left(#, 1)=="-" then #=substr(#, 2) + if \datatype(#,'W') then do; say er 'number' # "isn't an integer."; exit 13; end + return # / 1 /*it's an integer, then normalize it. */ diff --git a/Task/Largest-int-from-concatenated-ints/REXX/largest-int-from-concatenated-ints-2.rexx b/Task/Largest-int-from-concatenated-ints/REXX/largest-int-from-concatenated-ints-2.rexx new file mode 100644 index 0000000000..5a6acf8ece --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/REXX/largest-int-from-concatenated-ints-2.rexx @@ -0,0 +1,29 @@ +/*REXX program constructs the largest integer from an integer list using concatenation.*/ +@.=.; @.1 = '1 34 3 98 9 76 45 4' /*the 1st integer list to be used. */ + @.2 = '54 546 548 60' /* " 2nd " " " " " */ + @.3 = ' 4 45 54 5' /* " 3rd " " " " " */ + @.4 = ' 4 45 54 5 6.6e77' /* " 4th " " " " " */ +w=0 /* [↓] process all the integer lists.*/ + do j=1 while @.j\==.; z=space(@.j) /*keep truckin' until lists exhausted. */ + w=max(w, length(z) ); $= /*obtain maximum width to align output.*/ + do while z\=''; idx=1; big=norm(1) /*keep examining the list until done.*/ + do k=2 to words(z); #=norm(k) /*obtain an a number from the list. */ + L=max(length(big), length(#) ) /*get the maximum length of the integer*/ + if left(#, L, left(#, 1) ) <<= left(big, L, left(big, 1) ) then iterate + big=#; idx=k /*we found a new biggie (and the index)*/ + end /*k*/ /* [↑] find max concatenated integer. */ + z=delword(z, idx, 1) /*delete this maximum integer from list*/ + $=$ || big /*append " " " ───► $. */ + end /*while z*/ /* [↑] process all integers in a list.*/ + say 'largest concatenatated integer from ' left( space(@.j), w) " is " $ + end /*j*/ /* [↑] process each list of integers. */ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +norm: arg i; #=word(z, i); er=' ***error*** '; if left(#, 1)=="-" then #=substr(#, 2) + if \datatype(#,'N') then do; say er 'number' # "isn't an number."; exit 13; end + else #=# / 1 /*a #, so normalize it*/ + if pos('E',#)>0 then do; parse var # mant "E" pow /*Has exponent? Expand*/ + numeric digits pow + length(mand) /*expand digs, adjust#*/ + end + if \datatype(#,'W') then do; say er 'number' # "isn't an integer."; exit 13; end + return #/1 diff --git a/Task/Largest-int-from-concatenated-ints/REXX/largest-int-from-concatenated-ints-3.rexx b/Task/Largest-int-from-concatenated-ints/REXX/largest-int-from-concatenated-ints-3.rexx new file mode 100644 index 0000000000..f70b02466a --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/REXX/largest-int-from-concatenated-ints-3.rexx @@ -0,0 +1,56 @@ +/*REXX program constructs the largest integer from an integer list using concatenation.*/ +l.=''; l.1 = '1 34 3 98 9 76 45 4' /*the 1st integer list to be used. */ + l.2 = '54 546 548 60' /* " 2nd " " " " " */ + l.3 = ' 4 45 54 5' /* " 3rd " " " " " */ + l.4 = ' 4 45 54 5 6.6e77' /* " 4th " " " " " */ + l.5 = ' 3 3 .2' /* " 5th " " " " " */ +/* +soll.1=998764543431 +soll.2=6054854654 +soll.3=554454 +soll.4=660000000000000000000000000000000000000000000000000000000000000000000000000000545454 +*/ +l_length=0 +Do li=1 By 1 While l.li<>'' + l_length=max(l_length,length(space(l.li))) + End + +Do li=1 By 1 While l.li<>'' + z='' + Do j=1 To words(l.li) + int=integer(word(l.li,j)) + If int='?' Then Do + Say left(space(l.li),l_length) '-> ** invalid ** bad integer' word(l.li,j) + Iterate li + End + Else + z=z int + End +/*Say copies(' ',l_length) ' ' soll.li */ + Say left(space(l.li),l_length) '->' largeint(l.li) + End +Exit + +integer: Procedure +Numeric Digits 1000 +Parse Arg z +If Datatype(z,'W') Then + Return z+0 +Else + Return '?' + +largeint: +result='' +Do While z<>'' /* [?] check the rest of the integers.*/ + big=word(z,1); index=1; LB=length(big) /*assume that first integer is biggest.*/ + do k=2 to words(z); + n=word(z,k) /*obtain an integer from the list. */ + L=max(LB,length(n)) /*get the maximum length of the integer*/ + if left(n,L,left(n,1))<<=left(big,L,left(big,1)) then iterate + big=n; index=k /*we found a new biggie (and the index)*/ + LB=length(big) + End /*k*/ + z=delword(z,index,1) /*delete this maximum integer from list*/ + result=result||big /*append " " " ---? $. */ + end /*while z*/ /* [?] process all integers in a list.*/ +Return result diff --git a/Task/Largest-int-from-concatenated-ints/REXX/largest-int-from-concatenated-ints-4.rexx b/Task/Largest-int-from-concatenated-ints/REXX/largest-int-from-concatenated-ints-4.rexx new file mode 100644 index 0000000000..d2ac74338c --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/REXX/largest-int-from-concatenated-ints-4.rexx @@ -0,0 +1,81 @@ +/*REXX program constructs the largest integer from an integer list using concatenation.*/ +l.=''; l.1 = '1 34 3 98 9 76 45 4' /*the 1st integer list to be used. */ + l.2 = '54 546 548 60' /* " 2nd " " " " " */ + l.3 = ' 4 45 54 5' /* " 3rd " " " " " */ + l.4 = ' 4 45 54 5 6.6e77' /* " 4th " " " " " */ + l.5 = ' 3 3 .2' /* " 5th " " " " " */ + l.6 = ' 4 45 54 5 6.6e1001' /* " 6th " " " " " */ + l.7 = ' 4.0000 45 54 5.00' /* " 7th " " " " " */ + l.8 = ' 10e999999999 5' /* " 8th " " " " " */ +l_length=0 +Do li=1 By 1 While l.li<>'' + l_length=max(l_length,length(space(l.li))) + End + +Do li=1 By 1 While l.li<>'' + z='' + msg='' + Do j=1 To words(l.li) + int=integer(word(l.li,j)) + If int='?' Then Do + Say left(space(l.li),l_length) '-> ** invalid ** bad list item:' word(l.li,j) msg + Iterate li + End + Else + z=z int + End + zz=largeint(z) + If length(zz)<60 Then + Say left(space(l.li),l_length) '->' zz + Else + Say left(space(l.li),l_length) '->' left(zz,5)'...'right(zz,5) + End +Exit + +integer: Procedure Expose msg +Numeric Digits 1000 +Parse Arg z +If Datatype(z,'W') Then + Return z/1 +Else Do + If Datatype(z,'NUM') Then Do + Do i=1 To 6 Until dig>=999999999 + dig= digits()*10 + dig=min(dig,999999999) + Numeric Digits dig + If Datatype(z,'W') Then + Return z/1 + End + msg='cannot convert it to an integer' + Return '?' + End + Else Do + msg='not a number (larger than what this REXX can handle)' + Return '?' + End + End + +largeint: Procedure +Parse Arg list +w.0=words(list) +Do i=1 To w.0 + w.i=word(list,i) + End +Do wx=1 To w.0-1 + Do wy=wx+1 To w.0 + xx=w.wx + yy=w.wy + xy=xx||yy + yx=yy||xx + if xy < yx then do + /* swap xx and yy */ + w.wx = yy + w.wy = xx + end + End + End +list='' +Do ww=1 To w.0 + list=list w.ww + End +Return space(list,0) diff --git a/Task/Largest-int-from-concatenated-ints/REXX/largest-int-from-concatenated-ints.rexx b/Task/Largest-int-from-concatenated-ints/REXX/largest-int-from-concatenated-ints.rexx deleted file mode 100644 index 00272dd033..0000000000 --- a/Task/Largest-int-from-concatenated-ints/REXX/largest-int-from-concatenated-ints.rexx +++ /dev/null @@ -1,29 +0,0 @@ -/*REXX program constructs the largest integer from an integer list using concatenation.*/ -@.=.; @.1 = '{1, 34, 3, 98, 9, 76, 45, 4}' /*the 1st integer list to be used. */ - @.2 = '{54, 546, 548, 60}' /* " 2nd " " " " " */ - @.3 = '{ 4, 45, 54, 5}' /* " 3rd " " " " " */ - /* [↓] process all the integer lists.*/ - do j=1 while @.j\==.; $= /*keep truckin' until lists exhausted. */ - z=space( translate(@.j, , '])},{([') ) /*perform scrubbing on the integer list*/ - _=length( space(z, 0) ) + 2 /*determine the largest possibility. */ - if _>digits() then numeric digits _ /*use enough decimal digits for maximum*/ - /* [↓] examine each number in the list*/ - do while z\==''; index=1 /*keep examining the list until done.*/ - big=isOK( word(z, 1) ); LB=length(big) /*assume that first integer is biggest.*/ - /* [↓] check the rest of the integers.*/ - do k=2 to words(z); #=isOK(word(z,k)) /*obtain an an integer from the list. */ - L=max(LB, length(#) ) /*get the maximum length of the integer*/ - if left(#, L, left(#, 1) ) <<= left(big, L, left(big, 1) ) then iterate - big=#; index=k /*we found a new biggie (and the index)*/ - end /*k*/ /* [↑] find max concatenated integer. */ - - z=space( delword(z, index, 1) ) /*delete this maximum integer from list*/ - $=$ || big /*append " " " ───► $. */ - end /*while z*/ /* [↑] process all integers in a list.*/ - - say right($, digits()) ' max for: ' @.j /*show the maximum integer and the list*/ - end /*j*/ /* [↑] process each list of integers. */ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -isOK: parse arg ?; if datatype(?,'W') then return abs(?)/1 /*normalize the integer.*/ - say; say '***error*** number ' ? "isn't an integer."; say; exit 13 diff --git a/Task/Last-Friday-of-each-month/Factor/last-friday-of-each-month.factor b/Task/Last-Friday-of-each-month/Factor/last-friday-of-each-month.factor new file mode 100644 index 0000000000..67b1670f1b --- /dev/null +++ b/Task/Last-Friday-of-each-month/Factor/last-friday-of-each-month.factor @@ -0,0 +1,6 @@ +USING: calendar calendar.format command-line io kernel math.parser sequences ; +IN: rosetta-code.last-fridays + +(command-line) second string>number 12 iota +[ months time+ last-friday-of-month ] with map +[ timestamp>ymd print ] each diff --git a/Task/Last-Friday-of-each-month/Maple/last-friday-of-each-month.maple b/Task/Last-Friday-of-each-month/Maple/last-friday-of-each-month.maple new file mode 100644 index 0000000000..e12a25ec16 --- /dev/null +++ b/Task/Last-Friday-of-each-month/Maple/last-friday-of-each-month.maple @@ -0,0 +1,18 @@ +fridays := proc(year) + local i, dt, change, last_days; + last_days := [31,28,31,30,31,30,31,31,30,31,30,31]; + if (Calendar:-IsLeapYear(year)) then + last_days[2] := 28; + end if; + for i to 12 do + dt := Date(year, i, last_days[i]); + change := 0; + if not(Calendar:-DayOfWeek(dt) = 6) then + change := -(Calendar:-DayOfWeek(dt) mod 7)-1; + end if; + dt := Calendar:-AdjustDateField(dt, "date", change); + printf("%d-%d-%d\n", year, Month(dt), DayOfMonth(dt)); + end do; +end proc; + +fridays(2012); diff --git a/Task/Last-Friday-of-each-month/Stata/last-friday-of-each-month.stata b/Task/Last-Friday-of-each-month/Stata/last-friday-of-each-month.stata new file mode 100644 index 0000000000..052960aa2f --- /dev/null +++ b/Task/Last-Friday-of-each-month/Stata/last-friday-of-each-month.stata @@ -0,0 +1,27 @@ +program last_fridays + args year + clear + qui set obs 12 + gen day=dofm(mofd(mdy(_n,1,`year'))+1)-1 + qui replace day=day-mod(dow(day)-5,7) + format %td day + list, noobs noheader sep(6) +end + +last_fridays 2012 + + +-----------+ + | 27jan2012 | + | 24feb2012 | + | 30mar2012 | + | 27apr2012 | + | 25may2012 | + | 29jun2012 | + |-----------| + | 27jul2012 | + | 31aug2012 | + | 28sep2012 | + | 26oct2012 | + | 30nov2012 | + | 28dec2012 | + +-----------+ diff --git a/Task/Last-letter-first-letter/BaCon/last-letter-first-letter-1.bacon b/Task/Last-letter-first-letter/BaCon/last-letter-first-letter-1.bacon new file mode 100644 index 0000000000..1a2c3c4f85 --- /dev/null +++ b/Task/Last-letter-first-letter/BaCon/last-letter-first-letter-1.bacon @@ -0,0 +1,31 @@ +all$ = "audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon " \ +"cresselia croagunk darmanitan deino emboar emolga exeggcute gabite " \ +"girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan " \ +"kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine " \ +"nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2 " \ +"porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking " \ +"sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko " \ +"tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask" + +SUB check(list$, rest$) + + LOCAL x + + FOR x = 1 TO AMOUNT(rest$) + IF RIGHT$(list$, 1) = LEFT$(TOKEN$(rest$, x), 1) THEN check(APPEND$(list$, 0, TOKEN$(rest$, x)), DEL$(rest$, x)) + NEXT + + IF AMOUNT(list$) > total THEN + total = AMOUNT(list$) + result$ = list$ + END IF + +END SUB + +FOR z = 1 TO AMOUNT(all$) + CALL check(TOKEN$(all$, z), DEL$(all$,z)) +NEXT + +PRINT total, ": ", result$ + +PRINT NL$, "Speed: ", TIMER, " msecs." diff --git a/Task/Last-letter-first-letter/BaCon/last-letter-first-letter-2.bacon b/Task/Last-letter-first-letter/BaCon/last-letter-first-letter-2.bacon new file mode 100644 index 0000000000..f63f35735c --- /dev/null +++ b/Task/Last-letter-first-letter/BaCon/last-letter-first-letter-2.bacon @@ -0,0 +1,53 @@ +all$ = "audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon " \ +"cresselia croagunk darmanitan deino emboar emolga exeggcute gabite " \ +"girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan " \ +"kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine " \ +"nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2 " \ +"porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking " \ +"sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko " \ +"tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask" + +SPLIT all$ TO name$ SIZE MaxSize + +DECLARE start, end, used, result ARRAY MaxSize + +FOR y = 0 TO MaxSize-1 + start[y] = ASC(LEFT$(name$[y], 1)) + end[y] = ASC(RIGHT$(name$[y], 1)) + used[y] = -1 +NEXT + +FOR i = 0 TO MaxSize-1 + used[i] = 0 + CALL check(used, i, 1) + used[i] = -1 +NEXT + +PRINT maxtotal, ": "; +FOR a = 0 TO maxtotal-1 + FOR y = 0 TO MaxSize-1 + IF result[y] = a THEN PRINT name$[y]," "; + NEXT +NEXT + +PRINT NL$, "Speed: ", TIMER, " msecs." + +SUB check(ya[], ultim, nr) + + LOCAL x + + FOR x = 0 TO MaxSize-1 + IF end[ultim] = start[x] AND ya[x] = -1 THEN + ya[x] = nr + CALL check(ya, x, nr+1) + ya[x] = -1 + END IF + + IF nr > maxtotal THEN + maxtotal = nr + OPTION MEMTYPE long + COPY ya TO result SIZE MaxSize + END IF + NEXT + +END SUB diff --git a/Task/Last-letter-first-letter/Clojure/last-letter-first-letter-1.clj b/Task/Last-letter-first-letter/Clojure/last-letter-first-letter-1.clj new file mode 100644 index 0000000000..e8c8ae681a --- /dev/null +++ b/Task/Last-letter-first-letter/Clojure/last-letter-first-letter-1.clj @@ -0,0 +1,38 @@ +(ns rosetta-code.last-letter-first-letter + (:require clojure.string)) + +(defn by-first-letter + "Returns a map from letters to a set of words that start with that letter" + [words] + (into {} (map (fn [[k v]] + [k (set v)])) + (group-by first words))) + +(defn longest-path-from + "Find a longest path starting at word, using only words-by-first-letter for successive words. + Returns a pair of [length list-of-words] to describe the path." + [word words-by-first-letter] + (let [words-without-word (update words-by-first-letter (first word) + disj word) + next-words (words-without-word (last word))] + (if (empty? next-words) + [1 [word]] + (let [sub-paths (map #(longest-path-from % words-without-word) next-words) + [length words-of-path] (apply max-key first sub-paths)] + [(inc length) (cons word words-of-path)])))) + +(defn longest-word-chain + "Find a longest path among the words in word-list, by performing a longest path search + starting at each word in the list." + [word-list] + (let [words-by-letter (by-first-letter word-list)] + (apply max-key first + (pmap #(longest-path-from % words-by-letter) + word-list)))) + +(defn word-list-from-file [file-name] + (let [contents (slurp file-name) + words (clojure.string/split contents #"[ \n]")] + (filter #(not (empty? %)) words))) + +(time (longest-word-chain (word-list-from-file "pokemon.txt"))) diff --git a/Task/Last-letter-first-letter/Clojure/last-letter-first-letter-2.clj b/Task/Last-letter-first-letter/Clojure/last-letter-first-letter-2.clj new file mode 100644 index 0000000000..af49e512ed --- /dev/null +++ b/Task/Last-letter-first-letter/Clojure/last-letter-first-letter-2.clj @@ -0,0 +1,25 @@ +"Elapsed time: 2867.337816 msecs" +[23 + ("machamp" + "pinsir" + "relicanth" + "heatmor" + "registeel" + "landorus" + "seaking" + "girafarig" + "gabite" + "exeggcute" + "emboar" + "rufflet" + "trapinch" + "haxorus" + "simisear" + "remoraid" + "darmanitan" + "nosepass" + "scrafty" + "yamask" + "kricketune" + "emolga" + "audino")] diff --git a/Task/Last-letter-first-letter/Julia/last-letter-first-letter.julia b/Task/Last-letter-first-letter/Julia/last-letter-first-letter.julia new file mode 100644 index 0000000000..fdac504291 --- /dev/null +++ b/Task/Last-letter-first-letter/Julia/last-letter-first-letter.julia @@ -0,0 +1,37 @@ +using IterTools.groupby + +orderwords(words::Vector) = Dict(w[1][1] => Set(w) for w in groupby(first, words)) +longest(a, b) = ifelse(length(a) > length(b), a, b) +function linkfirst(byfirst::Dict, sofar::Vector) + @assert(!isempty(sofar)) + chmatch = sofar[end][end] + if ! haskey(byfirst, chmatch) return sofar end + options = setdiff(byfirst[chmatch], sofar) + if isempty(options) + return sofar + else + alternatives = ( linkfirst(byfirst, vcat(sofar, word)) for word in options ) + mx = reduce(longest, alternatives) + return mx + end +end +function llfl(words) + byfirst = orderwords(words) + alternatives = ( linkfirst(byfirst, [word]) for word in words ) + return reduce(longest, alternatives) +end + +pokemon = String.(unique(split(""" + audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon + cresselia croagunk darmanitan deino emboar emolga exeggcute gabite + girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan + kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine + nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2 + porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking + sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko + tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask + """))) + +l = llfl(pokemon) +println("Example of longest seq.:\n", join(l, ", ")) +println("Max length: ", length(l) diff --git a/Task/Last-letter-first-letter/REXX/last-letter-first-letter-1.rexx b/Task/Last-letter-first-letter/REXX/last-letter-first-letter-1.rexx index 5172258e02..035f154326 100644 --- a/Task/Last-letter-first-letter/REXX/last-letter-first-letter-1.rexx +++ b/Task/Last-letter-first-letter/REXX/last-letter-first-letter-1.rexx @@ -25,7 +25,7 @@ exit /*stick a fork in it, we're al s: if arg(1)==1 then return arg(3); return word( arg(2) 's', 1) /*a pluralizer.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ scan: procedure expose @. MP # MPL $$$; parse arg $$$,!; p=! - 1 - parse var @.p '' -1 LC /*obtain the last character of prev. @ */ + parse var @.p '' -1 LC /*obtain last character of previous @. */ /* [↓] PARSE obtains first char of @.i*/ do i=! to #; parse var @.i p 2 /* [↓] scan for the longest word path.*/ if p==LC then do /*is the first─char ≡ last─char ? */ diff --git a/Task/Last-letter-first-letter/REXX/last-letter-first-letter-2.rexx b/Task/Last-letter-first-letter/REXX/last-letter-first-letter-2.rexx index ed46967f01..16242d3064 100644 --- a/Task/Last-letter-first-letter/REXX/last-letter-first-letter-2.rexx +++ b/Task/Last-letter-first-letter/REXX/last-letter-first-letter-2.rexx @@ -9,12 +9,11 @@ parse arg limit .; if limit\=='' then #=limit /*allow user to specify a scan limit. */ @.=; ig=0; !.=0 /*nullify array and the longest path. */ call build@ /*build a stemmed array from the @ list*/ - do v=# by -1 for # /*scrub the @ list for unusuable words.*/ + do v=# by -1 for # /*scrub the @ list for unusable words. */ parse var @.v F 2 '' -1 L /*obtain first and last letter of word.*/ if !.1.F>1 | !.9.L>1 then iterate /*is this a dead word?*/ - say 'ignorning dead word:' @.v; ig=ig+1; @=delword(@, v, 1) - /*delete from @ list.*/ - end /*v*/ /*delete dead wprd from @ ──┘ */ + say 'ignoring dead word:' @.v; ig=ig+1; @=delword(@, v, 1) + end /*v*/ /*delete dead word from @ ──┘ */ $$$= /*nullify the possible longest path. */ if ig\==0 then do; call build@; say; say 'ignoring' ig "dead word"s(ig).; say end @@ -37,7 +36,7 @@ build@: do i=1 for #; @.i=word(@, i) /*build a stemmed array from th s: if arg(1)==1 then return arg(3); return word( arg(2) 's', 1) /*a pluralizer.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ scan: procedure expose @. # !. $$$ MP MPL; parse arg $$$,!; p=! - 1 - parse var @.p '' -1 LC /*obtain the last character of prev. @ */ + parse var @.p '' -1 LC /*obtain last character of previous @. */ if !.1.LC==0 then return /*is this a dead─end word? */ /* [↓] PARSE obtains first char of @.i*/ do i=! to #; parse var @.i p 2 /*scan for the longest word path. */ diff --git a/Task/Last-letter-first-letter/Ring/last-letter-first-letter.ring b/Task/Last-letter-first-letter/Ring/last-letter-first-letter.ring new file mode 100644 index 0000000000..06d020eaf3 --- /dev/null +++ b/Task/Last-letter-first-letter/Ring/last-letter-first-letter.ring @@ -0,0 +1,70 @@ +# Project : Last letter-first letter +# Date : 2017/12/30 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +ready = [] +names = ["audino", "bagon", "baltoy", "banette", + "bidoof", "braviary", "bronzor", "carracosta", "charmeleon", + "cresselia", "croagunk", "darmanitan", "deino", "emboar", + "emolga", "exeggcute", "gabite", "girafarig", "gulpin", + "haxorus", "heatmor", "heatran", "ivysaur", "jellicent", + "jumpluff", "kangaskhan", "kricketune", "landorus", "ledyba", + "loudred", "lumineon", "lunatone", "machamp", "magnezone", + "mamoswine", "nosepass", "petilil", "pidgeotto", "pikachu", + "pinsir", "poliwrath", "poochyena", "porygon2", "porygonz", + "registeel", "relicanth", "remoraid", "rufflet", "sableye", + "scolipede", "scrafty", "seaking", "sealeo", "silcoon", + "simisear", "snivy", "snorlax", "spoink", "starly", "tirtouga", + "trapinch", "treecko", "tyrogue", "vigoroth", "vulpix", + "wailord", "wartortle", "whismur", "wingull", "yamask"] +strbegin = "gabite" +strdir = "first" +nr = 1 +add(ready,strbegin) +see strbegin + nl +while true + if strdir = "first" + strc = right(strbegin, 1) + flag = 1 + nr = nr + 1 + if nr <= len(names) + if left(names[nr],1) = strc + for n = 1 to len(ready) + if names[nr] = ready[n] + flag = 0 + ok + next + if flag = 1 + add(ready,names[nr]) + see names[nr] + nl + strbegin = names[nr] + nr = 0 + strdir = "last" + loop + ok + ok + ok + else + strc = right(strbegin, 1) + flag = 1 + nr = nr + 1 + if nr <= len(names) + if left(names[nr],1) = strc + for n = 1 to len(ready) + if names[nr] = ready[n] + flag = 0 + ok + next + if flag = 1 + add(ready,names[nr]) + see names[nr] + nl + strbegin = names[nr] + nr = 0 + strdir = "first" + loop + ok + ok + ok + ok +end diff --git a/Task/Leap-year/GW-BASIC/leap-year.gw-basic b/Task/Leap-year/GW-BASIC/leap-year.gw-basic new file mode 100644 index 0000000000..cb4cbdc97a --- /dev/null +++ b/Task/Leap-year/GW-BASIC/leap-year.gw-basic @@ -0,0 +1,11 @@ +10 ' Leap year +20 DEF FN ISLEAPYEAR(Y%) = ((Y% MOD 4 = 0) AND (Y% MOD 100 <> 0)) OR (Y% MOD 400 = 0) +95 ' *** Test *** +100 FOR I% = 1 TO 5 +110 READ YEAR% +120 PRINT YEAR%; "is "; +130 IF FN ISLEAPYEAR(YEAR%) = 0 THEN PRINT "not "; ELSE PRINT ""; +140 PRINT "a leap year." +150 NEXT I% +160 END +200 DATA 1900, 1994, 1996, 1997, 2000 diff --git a/Task/Leap-year/Java/leap-year.java b/Task/Leap-year/Java/leap-year-1.java similarity index 100% rename from Task/Leap-year/Java/leap-year.java rename to Task/Leap-year/Java/leap-year-1.java diff --git a/Task/Leap-year/Java/leap-year-2.java b/Task/Leap-year/Java/leap-year-2.java new file mode 100644 index 0000000000..885b5977ce --- /dev/null +++ b/Task/Leap-year/Java/leap-year-2.java @@ -0,0 +1,8 @@ +import java.time.Year; + +public class IsLeap { + + public static void main(String[] args) { + System.out.println(Year.isLeap(2004)); + } +} diff --git a/Task/Leap-year/Julia/leap-year.julia b/Task/Leap-year/Julia/leap-year.julia index 7c8e9ee071..c9f7f5d361 100644 --- a/Task/Leap-year/Julia/leap-year.julia +++ b/Task/Leap-year/Julia/leap-year.julia @@ -1,5 +1,4 @@ -leap(y) = y%4==0 && (y<1582 || y%400==0 || y%100!=0) +isleap(yr::Integer) = yr % 4 == 0 && (yr < 1582 || yr % 400 == 0 || yr % 100 != 0) -# some tests -@assert all([leap(yr) for yr in [2400, 2012, 2000, 1600, 1500, 1400]]) -@assert all([~leap(yr) for yr in [2100, 2014, 1900, 1800, 1700, 1499]]) +@assert all(isleap, [2400, 2012, 2000, 1600, 1500, 1400]) +@assert !any(isleap, [2100, 2014, 1900, 1800, 1700, 1499]) diff --git a/Task/Leap-year/MATLAB/leap-year.m b/Task/Leap-year/MATLAB/leap-year-1.m similarity index 100% rename from Task/Leap-year/MATLAB/leap-year.m rename to Task/Leap-year/MATLAB/leap-year-1.m diff --git a/Task/Leap-year/MATLAB/leap-year-2.m b/Task/Leap-year/MATLAB/leap-year-2.m new file mode 100644 index 0000000000..6ae8f8604a --- /dev/null +++ b/Task/Leap-year/MATLAB/leap-year-2.m @@ -0,0 +1 @@ +x = ~mod(YEAR, 4) & (mod(YEAR, 100) | ~mod(YEAR, 400)) diff --git a/Task/Leap-year/Modula-2/leap-year.mod2 b/Task/Leap-year/Modula-2/leap-year.mod2 new file mode 100644 index 0000000000..c04d6f1c0e --- /dev/null +++ b/Task/Leap-year/Modula-2/leap-year.mod2 @@ -0,0 +1,30 @@ +MODULE LeapYear; +FROM FormatString IMPORT FormatString; +FROM Terminal IMPORT WriteString,ReadChar; + +PROCEDURE IsLeapYear(year : INTEGER) : BOOLEAN; +BEGIN + IF year MOD 100 = 0 THEN + RETURN year MOD 400 = 0; + END; + RETURN year MOD 4 = 0 +END IsLeapYear; + +PROCEDURE Print(year : INTEGER); +VAR + buf : ARRAY[0..63] OF CHAR; + leap : BOOLEAN; +BEGIN + leap := IsLeapYear(year); + FormatString("Is %i a leap year? %b\n", buf, year, leap); + WriteString(buf) +END Print; + +BEGIN + Print(1900); + Print(1994); + Print(1996); + Print(1997); + Print(2000); + ReadChar +END LeapYear. diff --git a/Task/Leap-year/R/leap-year.r b/Task/Leap-year/R/leap-year.r index fea3487696..50cc305f6f 100644 --- a/Task/Leap-year/R/leap-year.r +++ b/Task/Leap-year/R/leap-year.r @@ -3,5 +3,5 @@ isLeapYear <- function(year) { } for (y in c(1900, 1994, 1996, 1997, 2000)) { - print(paste(y, " is ", ifelse(isLeapYear(y), "", "not "), "a leap year.", sep="")) + cat(y, ifelse(isLeapYear(y), "is", "isn't"), "a leap year.\n") } diff --git a/Task/Leap-year/Rust/leap-year.rust b/Task/Leap-year/Rust/leap-year.rust index f538236a6c..cab7fcbc5a 100644 --- a/Task/Leap-year/Rust/leap-year.rust +++ b/Task/Leap-year/Rust/leap-year.rust @@ -1,5 +1,4 @@ fn is_leap(year: i32) -> bool { let factor = |x| year % x == 0; factor(4) && (!factor(100) || factor(400)) - } } diff --git a/Task/Leap-year/Visual-Basic/leap-year-1.vb b/Task/Leap-year/Visual-Basic/leap-year-1.vb new file mode 100644 index 0000000000..d13f4514f6 --- /dev/null +++ b/Task/Leap-year/Visual-Basic/leap-year-1.vb @@ -0,0 +1,9 @@ +Public Function IsLeapYear1(ByVal theYear As Integer) As Boolean +'this function utilizes documented behaviour of the built-in DateSerial function +IsLeapYear1 = (VBA.Day(VBA.DateSerial(theYear, 2, 29)) = 29) +End Function + +Public Function IsLeapYear2(ByVal theYear As Integer) As Boolean +'this function uses the well-known formula +IsLeapYear2 = IIf(theYear Mod 100 = 0, theYear Mod 400 = 0, theYear Mod 4 = 0) +End Function diff --git a/Task/Leap-year/Visual-Basic/leap-year-2.vb b/Task/Leap-year/Visual-Basic/leap-year-2.vb new file mode 100644 index 0000000000..ce6d12ae42 --- /dev/null +++ b/Task/Leap-year/Visual-Basic/leap-year-2.vb @@ -0,0 +1,7 @@ +Sub Main() +'testing the above functions +Dim i As Integer + For i = 1750 To 2150 + Debug.Assert IsLeapYear1(i) Eqv IsLeapYear2(i) + Next i +End Sub diff --git a/Task/Least-common-multiple/00DESCRIPTION b/Task/Least-common-multiple/00DESCRIPTION index cf2e4ffe61..54f2dd99ef 100644 --- a/Task/Least-common-multiple/00DESCRIPTION +++ b/Task/Least-common-multiple/00DESCRIPTION @@ -18,7 +18,7 @@ If you already have   ''gcd''   for [[greatest common divisor]],   One can also find   ''lcm''   by merging the [[prime decomposition]]s of both   ''m''   and   ''n''. -;References: -*   [http://mathworld.wolfram.com/LeastCommonMultiple.html MathWorld]. -*   [[wp:Least common multiple|Wikipedia]]. +;See also: +*   MathWorld entry:   [http://mathworld.wolfram.com/LeastCommonMultiple.html Least Common Multiple]. +*   Wikipedia entry:   [[wp:Least common multiple|Least common multiple]].

diff --git a/Task/Least-common-multiple/C++/least-common-multiple-2.cpp b/Task/Least-common-multiple/C++/least-common-multiple-2.cpp index 00863dcc7b..78e942a191 100644 --- a/Task/Least-common-multiple/C++/least-common-multiple-2.cpp +++ b/Task/Least-common-multiple/C++/least-common-multiple-2.cpp @@ -2,13 +2,11 @@ #include #include -using namespace std; - int gcd(int a, int b) { a = abs(a); b = abs(b); while (b != 0) { - tie(a, b) = make_tuple(b, a % b); + std::tie(a, b) = std::make_tuple(b, a % b); } return a; } @@ -19,8 +17,8 @@ int lcm(int a, int b) { } int main() { - cout << "The least common multiple of 12 and 18 is " << lcm(12, 18) - << " ,\n" - << "and the greatest common divisor " << gcd(12, 18) << " !" << endl; + std::cout << "The least common multiple of 12 and 18 is " << lcm(12, 18) << ",\n" + << "and their greatest common divisor is " << gcd(12, 18) << "!" + << std::endl; return 0; } diff --git a/Task/Least-common-multiple/Elena/least-common-multiple.elena b/Task/Least-common-multiple/Elena/least-common-multiple.elena new file mode 100644 index 0000000000..3841f29458 --- /dev/null +++ b/Task/Least-common-multiple/Elena/least-common-multiple.elena @@ -0,0 +1,11 @@ +import extensions. +import system'math. + +gcd = (:m:n)((n == 0)iif(m absolute, $(gcd(n,n mod:m)))). + +lcm = (:m:n)((m * n) absolute / gcd(m,n)). + +program = +[ + console printLine("lcm(12,18)=",lcm(12,18)). +]. diff --git a/Task/Least-common-multiple/GW-BASIC/least-common-multiple.gw-basic b/Task/Least-common-multiple/GW-BASIC/least-common-multiple.gw-basic new file mode 100644 index 0000000000..659768cf2b --- /dev/null +++ b/Task/Least-common-multiple/GW-BASIC/least-common-multiple.gw-basic @@ -0,0 +1,22 @@ +10 PRINT "LCM(35, 21) = "; +20 LET MLCM = 35 +30 LET NLCM = 21 +40 GOSUB 200: ' Calculate LCM +50 PRINT LCM +60 END + +195 ' Calculate LCM +200 LET MGCD = MLCM +210 LET NGCD = NLCM +220 GOSUB 400: ' Calculate GCD +230 LET LCM = MLCM / GCD * NLCM +240 RETURN + +395 ' Calculate GCD +400 WHILE MGCD <> 0 +410 LET TMP = MGCD +420 LET MGCD = NGCD MOD MGCD +430 LET NGCD = TMP +440 WEND +450 LET GCD = NGCD +460 RETURN diff --git a/Task/Least-common-multiple/Modula-2/least-common-multiple.mod2 b/Task/Least-common-multiple/Modula-2/least-common-multiple.mod2 new file mode 100644 index 0000000000..773b252687 --- /dev/null +++ b/Task/Least-common-multiple/Modula-2/least-common-multiple.mod2 @@ -0,0 +1,29 @@ +MODULE LeastCommonMultiple; + +FROM STextIO IMPORT + WriteString, WriteLn; +FROM SWholeIO IMPORT + WriteInt; + +PROCEDURE GCD(M, N: INTEGER): INTEGER; +VAR + Tmp: INTEGER; +BEGIN + WHILE M <> 0 DO + Tmp := M; + M := N MOD M; + N := Tmp; + END; + RETURN N; +END GCD; + +PROCEDURE LCM(M, N: INTEGER): INTEGER; +BEGIN + RETURN M / GCD(M, N) * N; +END LCM; + +BEGIN + WriteString("LCM(35, 21) = "); + WriteInt(LCM(35, 21), 1); + WriteLn; +END LeastCommonMultiple. diff --git a/Task/Least-common-multiple/Perl/least-common-multiple-1.pl b/Task/Least-common-multiple/Perl/least-common-multiple-1.pl index 3a6b8d0d63..405f0fa8a6 100644 --- a/Task/Least-common-multiple/Perl/least-common-multiple-1.pl +++ b/Task/Least-common-multiple/Perl/least-common-multiple-1.pl @@ -1,12 +1,12 @@ sub gcd { - my ($a, $b) = @_; - while ($a) { ($a, $b) = ($b % $a, $a) } - $b + my ($x, $y) = @_; + while ($x) { ($x, $y) = ($y % $x, $x) } + $y } sub lcm { - my ($a, $b) = @_; - ($a && $b) and $a / gcd($a, $b) * $b or 0 + my ($x, $y) = @_; + ($x && $y) and $x / gcd($x, $y) * $y or 0 } print lcm(1001, 221); diff --git a/Task/Least-common-multiple/Perl/least-common-multiple-2.pl b/Task/Least-common-multiple/Perl/least-common-multiple-2.pl index 1408466d43..857336a6a5 100644 --- a/Task/Least-common-multiple/Perl/least-common-multiple-2.pl +++ b/Task/Least-common-multiple/Perl/least-common-multiple-2.pl @@ -1,13 +1,13 @@ sub lcm { use integer; my ($x, $y) = @_; - my ($a, $b) = @_; - while ($a != $b) { - ($a, $b, $x, $y) = ($b, $a, $y, $x) if $a > $b; - $a = $b / $x * $x; - $a += $x if $a < $b; + my ($f, $s) = @_; + while ($f != $s) { + ($f, $s, $x, $y) = ($s, $f, $y, $x) if $f > $s; + $f = $s / $x * $x; + $f += $x if $f < $s; } - $a + $f } print lcm(1001, 221); diff --git a/Task/Least-common-multiple/REXX/least-common-multiple-1.rexx b/Task/Least-common-multiple/REXX/least-common-multiple-1.rexx index d838e61195..e1ee94b261 100644 --- a/Task/Least-common-multiple/REXX/least-common-multiple-1.rexx +++ b/Task/Least-common-multiple/REXX/least-common-multiple-1.rexx @@ -14,7 +14,7 @@ lcm: procedure; parse arg $,_; $=$ _; do i=3 to arg(); $=$ arg(i); parse var $ x $ /*obtain the first value in args. */ x=abs(x) /*use the absolute value of X. */ do while $\=='' /*process the remainder of args. */ - parse var $ ! $; !=abs(!) /*pick off the next arg (ABS val).*/ + parse var $ ! $; if !<0 then !=-! /*pick off the next arg (ABS val).*/ if !==0 then return 0 /*if zero, then LCM is also zero. */ d=x*! /*calculate part of the LCM here. */ do until !==0; parse value x//! ! with ! x diff --git a/Task/Least-common-multiple/Rust/least-common-multiple.rust b/Task/Least-common-multiple/Rust/least-common-multiple.rust index 71c106e879..3e4832632c 100644 --- a/Task/Least-common-multiple/Rust/least-common-multiple.rust +++ b/Task/Least-common-multiple/Rust/least-common-multiple.rust @@ -1,16 +1,23 @@ -use std::cmp::{min, max}; -fn gcd_stein(a: usize, b: usize) -> usize { +use std::cmp::{max, min}; + +fn gcd(a: usize, b: usize) -> usize { match ((a, b), (a & 1, b & 1)) { - ((x, y), _) if x == y => y, - ((0, x), _) | ((x, 0), _) => x, + ((x, y), _) if x == y => y, + ((0, x), _) | ((x, 0), _) => x, ((x, y), (0, 1)) | ((y, x), (1, 0)) => gcd(x >> 1, y), - ((x, y), (0, 0)) => gcd(x >> 1, y >> 1) << 1, - ((x, y), (1, 1)) => { let (x, y) = (min(x, y), max(x, y)); - gcd((y - x) >> 1, x) - } - _ => unreachable!(), + ((x, y), (0, 0)) => gcd(x >> 1, y >> 1) << 1, + ((x, y), (1, 1)) => { + let (x, y) = (min(x, y), max(x, y)); + gcd((y - x) >> 1, x) + } + _ => unreachable!(), } } + fn lcm(a: usize, b: usize) -> usize { - a * b / gcd_stein(a,b) + a * b / gcd(a, b) +} + +fn main() { + println!("{}", lcm(6324, 234)) } diff --git a/Task/Left-factorials/00DESCRIPTION b/Task/Left-factorials/00DESCRIPTION index 4d9f11e6e4..8ca16bbff7 100644 --- a/Task/Left-factorials/00DESCRIPTION +++ b/Task/Left-factorials/00DESCRIPTION @@ -1,3 +1,5 @@ + + '''Left factorials''',   !n,   may refer to either   ''subfactorials''   or to   ''factorial sums'';
the same notation can be confusingly seen used for the two different definitions. diff --git a/Task/Left-factorials/Factor/left-factorials.factor b/Task/Left-factorials/Factor/left-factorials.factor new file mode 100644 index 0000000000..d210644d47 --- /dev/null +++ b/Task/Left-factorials/Factor/left-factorials.factor @@ -0,0 +1,26 @@ +USING: formatting fry io kernel math math.factorials +math.functions math.parser math.ranges sequences ; +IN: rosetta-code.left-factorials + +: left-factorial ( n -- m ) iota [ n! ] map-sum ; + +: print-left-factorials ( seq quot -- ) + '[ + dup left-factorial @ + [ number>string "!" prepend ] dip + "%6s %-6d\n" printf + ] each nl ; inline + +: digit-count ( n -- count ) log10 floor >integer 1 + ; + +: part1 ( -- ) 11 iota [ ] print-left-factorials ; + +: part2 ( -- ) 20 110 10 [ ] print-left-factorials ; + +: part3 ( -- ) "Number of digits for" print + 1,000 10,000 1,000 + [ digit-count ] print-left-factorials ; + +: main ( -- ) part1 part2 part3 ; + +MAIN: main diff --git a/Task/Left-factorials/Forth/left-factorials.fth b/Task/Left-factorials/Forth/left-factorials.fth new file mode 100644 index 0000000000..736a833b96 --- /dev/null +++ b/Task/Left-factorials/Forth/left-factorials.fth @@ -0,0 +1,48 @@ +36000 CONSTANT #DIGITS \ Enough for !10000 +CREATE S #DIGITS ALLOT S #DIGITS ERASE VARIABLE S# +CREATE F #DIGITS ALLOT F #DIGITS ERASE VARIABLE F# +1 F C! 1 F# ! \ F = 1 = 0! + +\ "Bignums": represented by two cells on the stack: +\ 1) An address pointing to the least-significant unit +\ 2) An integer size representing the number of character-size units +: mod/ /mod swap ; +: B+ ( addr u addr' u' -- u'') \ Add the second "bignum" into the first + over + >R -rot over + >R ( addr' addr R:end' R:end) + swap >R 0 over R> ( addr 0 addr addr' R:end' R:end) + \ 0: Assume second has equal or more digits, as in our problem + BEGIN over R@ < WHILE \ 1: add all digits from S + dup >R C@ swap dup >R C@ ( addr c a a' R:end' R:end R:addr'* R:addr*) + + + 10 mod/ R@ C! R> 1+ R> 1+ + REPEAT R> drop ( addr c addr* addr'* R:end') + BEGIN dup R@ < WHILE \ 2: add any remaining digits from F + dup >R C@ swap >R ( addr c a' R:end' R:addr'* R:addr*) + + 10 mod/ R@ C! R> 1+ R> 1+ + REPEAT R> drop drop ( addr c addr*) + BEGIN over WHILE \ 3: add any carry digits + >R 10 mod/ ( addr m d R:addr*) R@ C! R> 1+ + REPEAT rot - nip ; \ calculate travel distance, discard 0 carry +: B* ( addr u u' -- u'') \ Multiply "bignum" inplace by U' + 0 2swap over >R dup >R bounds ( u' 0 addr+u addr R:addr R:u) + DO ( u' c) over I C@ * + 10 mod/ I C! LOOP + nip R> BEGIN ( c u) over WHILE \ insert carry, may have multiple digits + >R 10 mod/ R@ swap R> R@ + ( m u d addr+u R:addr) C! 1+ + REPEAT nip R> ( u'' addr) drop ; +: .B ( addr u) over + BEGIN 1- \ print bignum + dup C@ [char] 0 + EMIT over over >= + UNTIL drop drop ; +: .!n 0 <# #s [char] ! hold #> 6 over - spaces type space ; +: REPORT ( n) + dup 10 <= over dup 20 111 within swap 10 mod 0= and or + IF .!n [char] = emit space S S# @ .B cr + ELSE dup 1000 mod 0= + IF .!n ." has " S# @ . ." digits" cr + ELSE drop THEN + THEN ; +: GO 0 REPORT + 1 BEGIN dup 10000 <= + WHILE + S S# @ F F# @ B+ S# ! + dup REPORT + dup F F# @ rot B* F# ! + 1+ REPEAT drop ; diff --git a/Task/Left-factorials/Julia/left-factorials.julia b/Task/Left-factorials/Julia/left-factorials.julia index d907f835ca..852525f39a 100644 --- a/Task/Left-factorials/Julia/left-factorials.julia +++ b/Task/Left-factorials/Julia/left-factorials.julia @@ -1,2 +1,4 @@ -leftfactorial(n::Integer) = n <= 0 ? zero(n) : sum(factorial, 0:n-1) -@vectorize_1arg Integer leftfactorial +leftfactorial(n::Integer) = n ≤ 0 ? zero(n) : sum(factorial, 0:n-1) + +@show leftfactorial.(0:10) +@show ndigits.(leftfactorial.(big.(1000:1000:10_000))) diff --git a/Task/Left-factorials/Ruby/left-factorials-1.rb b/Task/Left-factorials/Ruby/left-factorials-1.rb index 68635d71a1..954affba9e 100644 --- a/Task/Left-factorials/Ruby/left-factorials-1.rb +++ b/Task/Left-factorials/Ruby/left-factorials-1.rb @@ -1,8 +1,7 @@ left_fact = Enumerator.new do |y| - n, f, lf = 0, 1, 0 - loop do + f, lf = 1, 0 + 1.step do |n| y << lf #yield left_factorial - n += 1 lf += f f *= n end diff --git a/Task/Left-factorials/Ruby/left-factorials-2.rb b/Task/Left-factorials/Ruby/left-factorials-2.rb index 954affba9e..06272f27cf 100644 --- a/Task/Left-factorials/Ruby/left-factorials-2.rb +++ b/Task/Left-factorials/Ruby/left-factorials-2.rb @@ -1,8 +1,12 @@ -left_fact = Enumerator.new do |y| - f, lf = 1, 0 - 1.step do |n| - y << lf #yield left_factorial - lf += f - f *= n +tens = 20.step(110, 10) +thousands = 1000.step(10_000, 1000) + +10001.times do |n| + lf = left_fact.next + case n + when 0..10, *tens + puts "!#{n} = #{lf}" + when *thousands + puts "!#{n} has #{lf.to_s.size} digits" end end diff --git a/Task/Left-factorials/Standard-ML/left-factorials.ml b/Task/Left-factorials/Standard-ML/left-factorials.ml new file mode 100644 index 0000000000..63f42ffa11 --- /dev/null +++ b/Task/Left-factorials/Standard-ML/left-factorials.ml @@ -0,0 +1,29 @@ +(* reuse earlier factorial calculations in dfac, apply to listed arguments in cumlfac *) +(* example: left factorial n, is #3 (dfac (0,n-1,1,1) ) *) +(* output list contains (number, factorial, left factorial) *) +(* tested in PolyML *) + + +val store = ref 0; + +val rec dfac = fn + (from,to,acc,cm) => if from = to then (from,acc,cm) else (store:=(from+1)*acc;dfac (from+1,to,!store,!store+cm ) ); + +val rec cumlfac = fn + (x::y::rm) => x :: cumlfac ( dfac (#1 x, #1 y, #2 x, #3 x) :: rm ) | + rm =>rm ; + +val arguments = List.tabulate (10,fn 0=>(0,1,1)|i=>(i,0,0)) @ + List.tabulate (10,fn i=> (10*i+19,0,0) ) @ + List.tabulate ( 10,fn i=> (1000*i+999,0,0)); + +val result = (~1,0,0)::(cumlfac arguments); + +(* done *) +(* display: *) + +List.app (fn triple :int*int*int => + print(Int.toString (1+ #1 triple ) ^ " : " ^ Int.fmt StringCvt.DEC (#3 triple ) ^" \n" ) + ) (List.take(result,21) ) ; +List.app (fn triple :int*int*int => + print( Int.toString (1+ #1 triple ) ^ " : " ^ Int.toString (size(Int.toString (#3 triple ))) ^" \n" ) ) (List.drop(result,21) ); diff --git a/Task/Letter-frequency/Aime/letter-frequency-1.aime b/Task/Letter-frequency/Aime/letter-frequency-1.aime new file mode 100644 index 0000000000..8f96502535 --- /dev/null +++ b/Task/Letter-frequency/Aime/letter-frequency-1.aime @@ -0,0 +1,15 @@ +file f; +index x; +integer c; + +f.affix("unixdict.txt"); + +while ((c = f.pick) ^ -1) { + x[c] += 1; +} + +c = 'A'; +while (c <= 'Z') { + o_form("%c: /w5/\n", c, x[c] += x[c + 'a' - 'A'] += 0); + c += 1; +} diff --git a/Task/Letter-frequency/Aime/letter-frequency-2.aime b/Task/Letter-frequency/Aime/letter-frequency-2.aime new file mode 100644 index 0000000000..eb459d75d6 --- /dev/null +++ b/Task/Letter-frequency/Aime/letter-frequency-2.aime @@ -0,0 +1,13 @@ +file f; +index x; +integer c, n; + +f.affix("unixdict.txt"); + +while ((c = f.pick) ^ -1) { + x[c] += 1; +} + +for (c, n in x) { + o_form("%c: /w5/\n", c, n); +} diff --git a/Task/Letter-frequency/BaCon/letter-frequency.bacon b/Task/Letter-frequency/BaCon/letter-frequency.bacon new file mode 100644 index 0000000000..a0d0987c4a --- /dev/null +++ b/Task/Letter-frequency/BaCon/letter-frequency.bacon @@ -0,0 +1,5 @@ +txt$ = LOAD$("bible.txt") + +FOR x = 97 TO 122 + PRINT CHR$(x-32), " ", CHR$(x), " : ", COUNT(txt$, x-32), " - ", COUNT(txt$, x) +NEXT diff --git a/Task/Letter-frequency/Julia/letter-frequency.julia b/Task/Letter-frequency/Julia/letter-frequency.julia index 0f5e6f9751..84f58f3d95 100644 --- a/Task/Letter-frequency/Julia/letter-frequency.julia +++ b/Task/Letter-frequency/Julia/letter-frequency.julia @@ -1,5 +1,7 @@ -function freq(file) - h = Dict{Char, Integer}() - for x in open(readstring ,file) h[x] = get(h,x,0)+1 end - sort(collect(h)) +using DataStructures + +function letterfreq(file::AbstractString; fltr::Function=(_) -> true) + sort(Dict(counter(filter(fltr, readstring(file))))) end + +display(letterfreq("src/Letter_frequency.jl"; fltr=isalpha)) diff --git a/Task/Letter-frequency/Perl-6/letter-frequency.pl6 b/Task/Letter-frequency/Perl-6/letter-frequency.pl6 index d4db30f4d3..828fa13fd6 100644 --- a/Task/Letter-frequency/Perl-6/letter-frequency.pl6 +++ b/Task/Letter-frequency/Perl-6/letter-frequency.pl6 @@ -1 +1,9 @@ -say bag lines».comb +.&ws.say for slurp.comb.Bag.sort: -*.value; + +sub ws ($pair) { + $pair.key ~~ /\n/ + ?? ('NEW LINE' => $pair.value) + !! $pair.key ~~ /\s/ + ?? ($pair.key.uniname => $pair.value) + !! $pair +} diff --git a/Task/Levenshtein-distance/Aime/levenshtein-distance.aime b/Task/Levenshtein-distance/Aime/levenshtein-distance.aime index 59d6991e07..4e193a5d9e 100644 --- a/Task/Levenshtein-distance/Aime/levenshtein-distance.aime +++ b/Task/Levenshtein-distance/Aime/levenshtein-distance.aime @@ -1,46 +1,38 @@ integer -dist(text s, integer i, integer ls, text t, integer j, integer lt, list d) +dist(data s, integer i, data t, integer j, list d) { integer x; - x = d[i * (lt + 1) + j]; + x = d[i * (~t + 1) + j]; if (x == -1) { - if (i == ls) { - x = lt - j; - } elif (j == lt) { - x = ls - i; + if (i == ~s) { + x = ~t - j; + } elif (j == ~t) { + x = ~s - i; } elif (s[i] == t[j]) { - x = dist(s, i + 1, ls, t, j + 1, lt, d); + x = dist(s, i + 1, t, j + 1, d); } else { - x = dist(s, i + 1, ls, t, j + 1, lt, d); - x = min(x, dist(s, i, ls, t, j + 1, lt, d)); - x = min(x, dist(s, i + 1, ls, t, j, lt, d)); + x = dist(s, i + 1, t, j + 1, d); + x = min(x, dist(s, i, t, j + 1, d)); + x = min(x, dist(s, i + 1, t, j, d)); x += 1; } - d[i * (lt + 1) + j] = x; + d[i * (~t + 1) + j] = x; } - return x; + x; } integer -levenshtein(text s, text t) +levenshtein(data s, data t) { - integer i, ls, lt; list d; - ls = length(s); - lt = length(t); + d.pn_integer(0, (~s + 1) * (~t + 1), -1); - i = (ls + 1) * (lt + 1); - while (i) { - lb_p_integer(d, -1); - i -= 1; - } - - return dist(s, 0, ls, t, 0, lt, d); + dist(s, 0, t, 0, d); } integer diff --git a/Task/Levenshtein-distance/Factor/levenshtein-distance.factor b/Task/Levenshtein-distance/Factor/levenshtein-distance.factor new file mode 100644 index 0000000000..4a2d2ca0bd --- /dev/null +++ b/Task/Levenshtein-distance/Factor/levenshtein-distance.factor @@ -0,0 +1,2 @@ +USING: lcs prettyprint ; +"kitten" "sitting" levenshtein . diff --git a/Task/Levenshtein-distance/Julia/levenshtein-distance-1.julia b/Task/Levenshtein-distance/Julia/levenshtein-distance-1.julia new file mode 100644 index 0000000000..e0ae6d01a4 --- /dev/null +++ b/Task/Levenshtein-distance/Julia/levenshtein-distance-1.julia @@ -0,0 +1,16 @@ +function levendist(s::AbstractString, t::AbstractString) + ls, lt = length(s), length(t) + ls == 0 && return lt + lt == 0 && return ls + + s₁, t₁ = s[2:end], t[2:end] + ld₁ = levendist(s₁, t₁) + if s[1] == t[1] + return ld₁ + else + return 1 + min(ld₁, levendist(s, t₁), levendist(s₁, t)) + end +end + +@show levendist("kitten", "sitting") # 3 +@show levendist("rosettacode", "raisethysword") # 8 diff --git a/Task/Levenshtein-distance/Julia/levenshtein-distance-2.julia b/Task/Levenshtein-distance/Julia/levenshtein-distance-2.julia new file mode 100644 index 0000000000..6460f73a49 --- /dev/null +++ b/Task/Levenshtein-distance/Julia/levenshtein-distance-2.julia @@ -0,0 +1,21 @@ +function levendist1(s::AbstractString, t::AbstractString) + ls, lt = length(s), length(t) + if ls > lt + s, t = t, s + ls, lt = lt, ls + end + dist = collect(0:ls) + for (ind2, chr2) in enumerate(t) + newdist = Vector{Int}(ls+1) + newdist[1] = ind2 + for (ind1, chr1) in enumerate(s) + if chr1 == chr2 + newdist[ind1+1] = dist[ind1] + else + newdist[ind1+1] = 1 + min(dist[ind1], dist[ind1+1], newdist[end]) + end + end + dist = newdist + end + return dist[end] +end diff --git a/Task/Levenshtein-distance/Julia/levenshtein-distance-3.julia b/Task/Levenshtein-distance/Julia/levenshtein-distance-3.julia new file mode 100644 index 0000000000..8b3cf794ee --- /dev/null +++ b/Task/Levenshtein-distance/Julia/levenshtein-distance-3.julia @@ -0,0 +1,13 @@ +using BenchmarkTools +println("\n# levendist(kitten, sitting)") +s, t = "kitten", "sitting" +println(" - Recursive:") +@btime levendist(s, t) +println(" - Iterative:") +@btime levendist1(s, t) +println("\n# levendist(rosettacode, raisethysword)") +s, t = "rosettacode", "raisethysword" +println(" - Recursive:") +@btime levendist(s, t) +println(" - Iterative:") +@btime levendist1(s, t) diff --git a/Task/Levenshtein-distance/Julia/levenshtein-distance.julia b/Task/Levenshtein-distance/Julia/levenshtein-distance.julia deleted file mode 100644 index 8bbcc4c005..0000000000 --- a/Task/Levenshtein-distance/Julia/levenshtein-distance.julia +++ /dev/null @@ -1,20 +0,0 @@ -function leven(s, t) - - length(s) == 0 && return length(t); - length(t) == 0 && return length(s); - - s1 = s[2:end]; - t1 = t[2:end]; - - return (s[1] == t[1] - ? leven(s1, t1) - : 1 + min( - leven(s1, t1), - leven(s, t1), - leven(s1, t) - ) - ); -end - -println(leven("kitten", "sitting")); # => 3 -println(leven("rosettacode","raisethysword")); # => 8 diff --git a/Task/Levenshtein-distance/Kotlin/levenshtein-distance.kotlin b/Task/Levenshtein-distance/Kotlin/levenshtein-distance-1.kotlin similarity index 100% rename from Task/Levenshtein-distance/Kotlin/levenshtein-distance.kotlin rename to Task/Levenshtein-distance/Kotlin/levenshtein-distance-1.kotlin diff --git a/Task/Levenshtein-distance/Kotlin/levenshtein-distance-2.kotlin b/Task/Levenshtein-distance/Kotlin/levenshtein-distance-2.kotlin new file mode 100644 index 0000000000..fef7c62d3a --- /dev/null +++ b/Task/Levenshtein-distance/Kotlin/levenshtein-distance-2.kotlin @@ -0,0 +1,19 @@ +fun levenshtein(s: String, t: String, + charScore : (Char, Char) -> Int = { c1, c2 -> if (c1 == c2) 0 else 1}) : Int { + + // Special cases + if (s == t) return 0 + if (s == "") return t.length + if (t == "") return s.length + + val initialRow : List = (0 until t.length + 1).map { it }.toList() + return (0 until s.length).fold(initialRow, { previous, u -> + (0 until t.length).fold( mutableListOf(u+1), { + row, v -> row.add(listOf(row.last() + 1, + previous[v+1] + 1, + previous[v] + charScore(s[u],t[v])).min()!!) + row + }) + }).last() + +} diff --git a/Task/Levenshtein-distance/Ring/levenshtein-distance.ring b/Task/Levenshtein-distance/Ring/levenshtein-distance.ring new file mode 100644 index 0000000000..7b941d8855 --- /dev/null +++ b/Task/Levenshtein-distance/Ring/levenshtein-distance.ring @@ -0,0 +1,42 @@ +# Project : Levenshtein distance +# Date : 2017/12/15 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +load "stdlib.ring" +see "" + "distance(kitten, sitting) = " + levenshteindistance("kitten", "sitting") + nl +see "" + "distance(saturday, sunday) = " + levenshteindistance("saturday", "sunday") + nl +see "" + "distance(rosettacode, raisethysword) = " + levenshteindistance("rosettacode", "raisethysword") + nl + +func levenshteindistance(s1, s2) + n = len(s1) + m = len(s2) + if n = 0 + levenshteindistance = m + return + ok + if m = 0 + levenshteindistance = n + return + ok + d = newlist(n, m) + for i = 1 to n + d[i][1] = i + next i + for i = 1 to m + d[1][i] = i + next + for i = 2 to n + si = substr(s1, i, 1) + for j = 2 to m + tj = substr(s2, j, 1) + if si = tj + cost = 0 + else + cost = 1 + ok + d[i][ j] = min((d[i - 1][ j]), min((d[i][j - 1] + 1), (d[i - 1][j - 1] + cost))) + next + next + levenshteindistance = d[n][m] + return levenshteindistance diff --git a/Task/Levenshtein-distance/Rust/levenshtein-distance.rust b/Task/Levenshtein-distance/Rust/levenshtein-distance.rust index ea79dfeb23..3292bb0ff3 100644 --- a/Task/Levenshtein-distance/Rust/levenshtein-distance.rust +++ b/Task/Levenshtein-distance/Rust/levenshtein-distance.rust @@ -3,6 +3,7 @@ fn main() { println!("{}", levenshtein_distance("saturday", "sunday")); println!("{}", levenshtein_distance("rosettacode", "raisethysword")); } + fn levenshtein_distance(word1: &str, word2: &str) -> usize { let w1 = word1.chars().collect::>(); let w2 = word2.chars().collect::>(); diff --git a/Task/Linear-congruential-generator/Julia/linear-congruential-generator.julia b/Task/Linear-congruential-generator/Julia/linear-congruential-generator.julia index ac955ae378..478ed5b3dc 100644 --- a/Task/Linear-congruential-generator/Julia/linear-congruential-generator.julia +++ b/Task/Linear-congruential-generator/Julia/linear-congruential-generator.julia @@ -1,29 +1,22 @@ -function lcg_maker{T<:Integer}(r::T, a::T, c::T, m::T, sh::T) +function getlgc(r::Integer, a::Integer, c::Integer, m::Integer, sh::Integer) state = r - function lcg_rand() - state = mod(a*state + c, m) + return function lgcrand() + state = mod(a * state + c, m) return state >> sh end - return lcg_rand end -snum = 10 -seed = 0 -bsd_rand = lcg_maker(seed, 1103515245, 12345, 2^31, 0) +seed, nrep = 0, 10 +bsdrand = getlgc(seed, 1103515245, 12345, 2 ^ 31, 0) -print("The first ", snum, " results for a BSD rand() seeded with ") -println(seed, ":") - -for i in 1:snum - println(@sprintf "%14d" bsd_rand()) +println("The first $nrep results for a BSD rand seeded with $seed:") +for _ in 1:nrep + @printf("%14d\n", bsdrand()) end -ms_rand = lcg_maker(seed, 214013, 2531011, 2^31, 16) +msrand = getlgc(seed, 214013, 2531011, 2 ^ 31, 16) -println() -print("The first ", snum, " results for a M\$ rand() seeded with ") -println(seed, ":") - -for i in 1:snum - println(@sprintf "%14d" ms_rand()) +println("\nThe first $nrep results for a M\$ rand seeded with $seed:") +for _ in 1:nrep + @printf("%14d\n", msrand()) end diff --git a/Task/Linear-congruential-generator/Rust/linear-congruential-generator.rust b/Task/Linear-congruential-generator/Rust/linear-congruential-generator.rust new file mode 100644 index 0000000000..b63429bfbe --- /dev/null +++ b/Task/Linear-congruential-generator/Rust/linear-congruential-generator.rust @@ -0,0 +1,71 @@ +extern crate rand; + +pub use rand::{Rng, SeedableRng}; + +pub struct BsdLcg { + state: u32, +} + +impl Rng for BsdLcg { + // Because the output is in the range [0, 2147483647], this should technically be `next_u16` + // (the largest integer size which is fully covered, as `rand::Rng` assumes). The `rand` + // crate does not provide it however. If serious usage is required, implementing this + // function as a concatenation of two `next_u16`s (elsewhere defined) should work. + fn next_u32(&mut self) -> u32 { + self.state = self.state.wrapping_mul(1_103_515_245).wrapping_add(12_345); + self.state %= 1 << 31; + self.state + } +} + +impl SeedableRng for BsdLcg { + fn from_seed(seed: u32) -> Self { + Self { state: seed } + } + fn reseed(&mut self, seed: u32) { + self.state = seed; + } +} + +pub struct MsLcg { + state: u32, +} + +impl Rng for MsLcg { + // Similarly, this outputs in the range [0, 32767] and should output a `u8`. Concatenate + // four `next_u8`s for serious usage. + fn next_u32(&mut self) -> u32 { + self.state = self.state.wrapping_mul(214_013).wrapping_add(2_531_011); + self.state %= 1 << 31; + self.state >> 16 // rand_n = state_n / 2^16 + } +} + +impl SeedableRng for MsLcg { + fn from_seed(seed: u32) -> Self { + Self { state: seed } + } + fn reseed(&mut self, seed: u32) { + self.state = seed; + } +} + +fn main() { + println!("~~~ BSD ~~~"); + let mut bsd = BsdLcg::from_seed(0); + for _ in 0..10 { + println!("{}", bsd.next_u32()); + } + + println!("~~~ MS ~~~"); + let mut ms = MsLcg::from_seed(0); + for _ in 0..10 { + println!("{}", ms.next_u32()); + } + + // Because we have implemented the `rand::Rng` trait, we can generate a variety of other types. + println!("~~~ Others ~~~"); + println!("{:?}", ms.gen::<[u32; 5]>()); + println!("{}", ms.gen::()); + println!("{}", ms.gen_ascii_chars().take(15).collect::()); +} diff --git a/Task/Linear-congruential-generator/Stata/linear-congruential-generator.stata b/Task/Linear-congruential-generator/Stata/linear-congruential-generator.stata new file mode 100644 index 0000000000..d31935b043 --- /dev/null +++ b/Task/Linear-congruential-generator/Stata/linear-congruential-generator.stata @@ -0,0 +1,25 @@ +mata +function rand_bsd(u) { + m = 65536 + u1 = floor(u/m) + u2 = mod(u,m) + a1 = 16838 + a2 = 20077 + b = 12345 + u = mod((a1*u2+a2*u1)*m+a2*u2+b,2147483648) + return(u) +} + +function rand_ms(u) { + u = mod(214013*u+2531011,2147483648) + return(floor(u/65536)) +} + +function rand_seq(f,seed,n) { + a = J(n,1,.) + for (i=1; i<=n; i++) a[i] = (*f)(seed) + return(a) +} + +rand_seq(&rand_bsd(),1,10) +rand_seq(&rand_ms(),0,10) diff --git a/Task/List-comprehensions/00DESCRIPTION b/Task/List-comprehensions/00DESCRIPTION index 6ced18bd14..8e33cbbfc4 100644 --- a/Task/List-comprehensions/00DESCRIPTION +++ b/Task/List-comprehensions/00DESCRIPTION @@ -1,5 +1,3 @@ -{{Omit From|C}} -{{Omit From|Java}} {{Omit From|Modula-3}} {{omit from|ACL2}} {{omit from|BBC BASIC}} diff --git a/Task/List-comprehensions/AppleScript/list-comprehensions-1.applescript b/Task/List-comprehensions/AppleScript/list-comprehensions-1.applescript index 909e9cea61..deb2798e02 100644 --- a/Task/List-comprehensions/AppleScript/list-comprehensions-1.applescript +++ b/Task/List-comprehensions/AppleScript/list-comprehensions-1.applescript @@ -51,24 +51,19 @@ end run -- (>>=) :: Monad m => m a -> (a -> m b) -> m b on |>>=|(xs, f) - concat(map(f, xs)) + concatMap(f, xs) end |>>=| --- concat :: [[a]] -> [a] | [String] -> String -on concat(xs) - script append - on |λ|(a, b) - a & b - end |λ| - end script - - if length of xs > 0 and class of (item 1 of xs) is string then - set empty to "" - else - set empty to {} - end if - foldl(append, empty, xs) -end concat +-- concatMap :: (a -> [b]) -> [a] -> [b] +on concatMap(f, xs) + set acc to {} + tell mReturn(f) + repeat with x in xs + set acc to acc & |λ|(contents of x) + end repeat + end tell + return acc +end concatMap -- enumFromTo :: Int -> Int -> [Int] on enumFromTo(m, n) @@ -84,30 +79,6 @@ on enumFromTo(m, n) return lst end enumFromTo --- foldl :: (a -> b -> a) -> a -> [b] -> a -on foldl(f, startValue, xs) - tell mReturn(f) - set v to startValue - set lng to length of xs - repeat with i from 1 to lng - set v to |λ|(v, item i of xs, i, xs) - end repeat - return v - end tell -end foldl - --- map :: (a -> b) -> [a] -> [b] -on map(f, xs) - tell mReturn(f) - set lng to length of xs - set lst to {} - repeat with i from 1 to lng - set end of lst to |λ|(item i of xs, i, xs) - end repeat - return lst - end tell -end map - -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script on mReturn(f) diff --git a/Task/List-comprehensions/C/list-comprehensions-1.c b/Task/List-comprehensions/C/list-comprehensions-1.c new file mode 100644 index 0000000000..2ca50ef542 --- /dev/null +++ b/Task/List-comprehensions/C/list-comprehensions-1.c @@ -0,0 +1 @@ +for (int i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); } diff --git a/Task/List-comprehensions/C/list-comprehensions-2.c b/Task/List-comprehensions/C/list-comprehensions-2.c new file mode 100644 index 0000000000..cf77936a44 --- /dev/null +++ b/Task/List-comprehensions/C/list-comprehensions-2.c @@ -0,0 +1,2 @@ +int i; +for (i = f + 1; i <= t; i ++) { e = e->nx = listNew(sizeof i, &i); } diff --git a/Task/List-comprehensions/C/list-comprehensions.c b/Task/List-comprehensions/C/list-comprehensions-3.c similarity index 100% rename from Task/List-comprehensions/C/list-comprehensions.c rename to Task/List-comprehensions/C/list-comprehensions-3.c diff --git a/Task/List-comprehensions/Haskell/list-comprehensions-5.hs b/Task/List-comprehensions/Haskell/list-comprehensions-5.hs new file mode 100644 index 0000000000..a4476e1939 --- /dev/null +++ b/Task/List-comprehensions/Haskell/list-comprehensions-5.hs @@ -0,0 +1 @@ +triplets n = [(x, y, z) | x <- [1 .. n], y <- [x .. n], z <- [y .. n]] diff --git a/Task/List-comprehensions/Haskell/list-comprehensions-6.hs b/Task/List-comprehensions/Haskell/list-comprehensions-6.hs new file mode 100644 index 0000000000..455dac90ee --- /dev/null +++ b/Task/List-comprehensions/Haskell/list-comprehensions-6.hs @@ -0,0 +1 @@ +[(x, y, z) | (x, y, z) <- triplets n, x^2 + y^2 == z^2] diff --git a/Task/List-comprehensions/Java/list-comprehensions.java b/Task/List-comprehensions/Java/list-comprehensions.java new file mode 100644 index 0000000000..f50c9ad03f --- /dev/null +++ b/Task/List-comprehensions/Java/list-comprehensions.java @@ -0,0 +1,33 @@ +// Boilerplate +import java.util.Arrays; +import java.util.List; +import static java.util.function.Function.identity; +import static java.util.stream.Collectors.toList; +import static java.util.stream.IntStream.range; +public interface PythagComp{ + static void main(String... args){ + System.out.println(run(20)); + } + + static List> run(int n){ + return + // Here comes the list comprehension bit + // input stream - bit clunky + range(1, n).mapToObj( + x -> range(x, n).mapToObj( + y -> range(y, n).mapToObj( + z -> new Integer[]{x, y, z} + ) + ) + ) + .flatMap(identity()) + .flatMap(identity()) + // predicate + .filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2]) + // output expression + .map(Arrays::asList) + // the result is a list + .collect(toList()) + ; + } +} diff --git a/Task/List-comprehensions/JavaScript/list-comprehensions-4.js b/Task/List-comprehensions/JavaScript/list-comprehensions-4.js index ed27a9dcb6..f5b47a4006 100644 --- a/Task/List-comprehensions/JavaScript/list-comprehensions-4.js +++ b/Task/List-comprehensions/JavaScript/list-comprehensions-4.js @@ -1 +1,41 @@ -[[3, 4, 5], [5, 12, 13], [6, 8, 10], [8, 15, 17], [9, 12, 15], [12, 16, 20]] +(n => { + 'use strict'; + + // GENERIC FUNCTIONS ------------------------------------------------------ + + // bind (>>=) :: Monad m => m a -> (a -> m b) -> m b + const bind = (m, mf) => + Array.isArray(m) ? ( + bindList(m, mf) + ) : bindMay(m, mf); + + // bindList (>>=) :: [a] -> (a -> [b]) -> [b] + const bindList = (xs, mf) => [].concat.apply([], xs.map(mf)); + + // enumFromTo :: Enum a => a -> a -> [a] + const enumFromTo = (m, n) => + (typeof m !== 'number' ? ( + enumFromToChar + ) : enumFromToInt) + .apply(null, [m, n]); + + // enumFromToInt :: Int -> Int -> [Int] + const enumFromToInt = (m, n) => + Array.from({ + length: Math.floor(n - m) + 1 + }, (_, i) => m + i); + + + // EXAMPLE ---------------------------------------------------------------- + + // [(x, y, z) | x <- [1..n], y <- [x..n], z <- [y..n], x ^ 2 + y ^ 2 == z ^ 2] + + return bind(enumFromTo(1, n), + x => bind(enumFromTo(x, n), + y => bind(enumFromTo(y, n), + z => x * x + y * y === z * z ? [ + [x, y, z] + ] : [] + ))); + +})(20); diff --git a/Task/List-comprehensions/JavaScript/list-comprehensions-5.js b/Task/List-comprehensions/JavaScript/list-comprehensions-5.js new file mode 100644 index 0000000000..ed27a9dcb6 --- /dev/null +++ b/Task/List-comprehensions/JavaScript/list-comprehensions-5.js @@ -0,0 +1 @@ +[[3, 4, 5], [5, 12, 13], [6, 8, 10], [8, 15, 17], [9, 12, 15], [12, 16, 20]] diff --git a/Task/List-comprehensions/OCaml/list-comprehensions-4.ocaml b/Task/List-comprehensions/OCaml/list-comprehensions-4.ocaml new file mode 100644 index 0000000000..2792d8eba8 --- /dev/null +++ b/Task/List-comprehensions/OCaml/list-comprehensions-4.ocaml @@ -0,0 +1,7 @@ +# #camlp4o;; +# #require "camlp4.listcomprehension";; +/home/user//.opam/4.06.1+trunk+flambda/lib/ocaml/camlp4/Camlp4Parsers/Camlp4ListComprehension.cmo: loaded +# [ x * 2 | x <- [1;2;3;4] ];; +- : int list = [2; 4; 6; 8] +# [ x * 2 | x <- [1;2;3;4]; x > 2 ];; +- : int list = [6; 8] diff --git a/Task/List-comprehensions/Python/list-comprehensions-3.py b/Task/List-comprehensions/Python/list-comprehensions-3.py new file mode 100644 index 0000000000..83ebbbf616 --- /dev/null +++ b/Task/List-comprehensions/Python/list-comprehensions-3.py @@ -0,0 +1 @@ +[(x, y, z) for (x, y, z) in itertools.product(xrange(1,n+1),repeat=3) if x**2 + y**2 == z**2 and x <= y <= z] diff --git a/Task/List-comprehensions/Python/list-comprehensions-4.py b/Task/List-comprehensions/Python/list-comprehensions-4.py new file mode 100644 index 0000000000..e1614674d0 --- /dev/null +++ b/Task/List-comprehensions/Python/list-comprehensions-4.py @@ -0,0 +1 @@ +((x, y, z) for (x, y, z) in itertools.product(xrange(1,n+1),repeat=3) if x**2 + y**2 == z**2 and x <= y <= z) diff --git a/Task/List-comprehensions/Python/list-comprehensions-5.py b/Task/List-comprehensions/Python/list-comprehensions-5.py new file mode 100644 index 0000000000..72cc85c6bd --- /dev/null +++ b/Task/List-comprehensions/Python/list-comprehensions-5.py @@ -0,0 +1,5 @@ +def triplets(n): + for x in xrange(1, n + 1): + for y in xrange(x, n + 1): + for z in xrange(y, n + 1): + yield x, y, z diff --git a/Task/List-comprehensions/Python/list-comprehensions-6.py b/Task/List-comprehensions/Python/list-comprehensions-6.py new file mode 100644 index 0000000000..c02b3d1b26 --- /dev/null +++ b/Task/List-comprehensions/Python/list-comprehensions-6.py @@ -0,0 +1 @@ +[(x, y, z) for (x, y, z) in triplets(n) if x**2 + y**2 == z**2] diff --git a/Task/List-comprehensions/Python/list-comprehensions-7.py b/Task/List-comprehensions/Python/list-comprehensions-7.py new file mode 100644 index 0000000000..4621e59ef6 --- /dev/null +++ b/Task/List-comprehensions/Python/list-comprehensions-7.py @@ -0,0 +1 @@ +((x, y, z) for (x, y, z) in triplets(n) if x**2 + y**2 == z**2) diff --git a/Task/List-comprehensions/REXX/list-comprehensions-1.rexx b/Task/List-comprehensions/REXX/list-comprehensions-1.rexx index 1c408c1ca7..937b29c6b3 100644 --- a/Task/List-comprehensions/REXX/list-comprehensions-1.rexx +++ b/Task/List-comprehensions/REXX/list-comprehensions-1.rexx @@ -1,17 +1,17 @@ /*REXX program displays a vertical list of Pythagorean triples up to a specified number.*/ -parse arg n . /*get the optional argument from the CL*/ +parse arg n . /*obtain optional argument from the CL.*/ if n=='' | n=="," then n=100 /*Not specified? Then use the default.*/ say 'Pythagorean triples (a² + b² = c², c ≤' n"):" /*display the list's title. */ $= /*assign a null to the triples list. */ - do a=1 for n-2; aa=a*a /*Note: A*A is faster than A**2, but */ - do b=a+1 to n-1; aabb=aa+b*b /* ··· but not by much.*/ - do c=b+1 to n - if aabb==c*c then $=$ '{'a"," || b','c"}" - end /*c*/ - end /*b*/ - end /*a*/ + do a=1 for n-2; aa=a*a /*Note: A*A is faster than A**2, but */ + do b=a+1 to n-1; aabb=aa + b*b /* ··· not by much.*/ + do c=b+1 to n + if aabb==c*c then $=$ '{'a"," || b','c"}" + end /*c*/ + end /*b*/ + end /*a*/ #=words($) - do j=1 for # - say left('', 20) word($, j) /*display a member of the list, */ - end /*j*/ /* [↑] list the members vertically. */ + do j=1 for # + say left('', 20) word($, j) /*display a member of the list, */ + end /*j*/ /* [↑] list the members vertically. */ say # 'members listed.' /*stick a fork in it, we're all done. */ diff --git a/Task/List-comprehensions/REXX/list-comprehensions-2.rexx b/Task/List-comprehensions/REXX/list-comprehensions-2.rexx index be33ca0180..87e0b6269d 100644 --- a/Task/List-comprehensions/REXX/list-comprehensions-2.rexx +++ b/Task/List-comprehensions/REXX/list-comprehensions-2.rexx @@ -3,13 +3,13 @@ parse arg n . /*get the optional argument fro if n=='' | n=="," then n=100 /*Not specified? Then use the default.*/ say 'Pythagorean triples (a² + b² = c², c ≤' n"):" /*display the list's title. */ $= /*assign a null to the triples list. */ - do a=1 for n-2; aa=a*a /*Note: A*A is faster than A**2, but */ - do b=a+1 to n-1; aabb=aa+b*b /* ··· but not by much.*/ - do c=b+1 to n - if aabb==c*c then $=$ '{'a"," || b','c"}" - end /*c*/ - end /*b*/ - end /*a*/ /*stick a fork in it, we're all done. */ + do a=1 for n-2; aa=a*a /*Note: A*A is faster than A**2, but */ + do b=a+1 to n-1; aabb=aa + b*b /* ··· not by much.*/ + do c=b+1 to n + if aabb==c*c then $=$ '{'a"," || b','c"}" + end /*c*/ + end /*b*/ + end /*a*/ /*stick a fork in it, we're all done. */ #=words($) /*number of members in the list. */ -say; say strip($) /*show the Pythagorean triples to term.*/ -say; say # 'members listed.' /*triples are listed in order of 1st #.*/ +say; say strip($) /*show the Pythagorean triples to term.*/ +say; say # 'members listed.' /*triples are listed in order of 1st #.*/ diff --git a/Task/List-comprehensions/Stata/list-comprehensions.stata b/Task/List-comprehensions/Stata/list-comprehensions.stata new file mode 100644 index 0000000000..3f930aabc2 --- /dev/null +++ b/Task/List-comprehensions/Stata/list-comprehensions.stata @@ -0,0 +1,8 @@ +function grid(n,p) { + return(colshape(J(p,1,1..n)',1),J(n,1,1::p)) +} + +n = 20 +a = grid(n,n) +a = a,sqrt(a[.,1]:^2+a[.,2]:^2) +a[selectindex(floor(a[.,3]):==a[.,3] :& a[.,3]:<=n),] diff --git a/Task/Literals-Floating-point/Elena/literals-floating-point.elena b/Task/Literals-Floating-point/Elena/literals-floating-point.elena new file mode 100644 index 0000000000..cd21533676 --- /dev/null +++ b/Task/Literals-Floating-point/Elena/literals-floating-point.elena @@ -0,0 +1,3 @@ +real r := 1. +r := 23.2r. +r := 1.2e+11r. diff --git a/Task/Literals-Floating-point/Julia/literals-floating-point.julia b/Task/Literals-Floating-point/Julia/literals-floating-point.julia new file mode 100644 index 0000000000..d90251c0c7 --- /dev/null +++ b/Task/Literals-Floating-point/Julia/literals-floating-point.julia @@ -0,0 +1,7 @@ +0.1 +.1 +1. +1e-1 # scientific notation +1e+10 +1e-10 +0x01p-1 # hex float diff --git a/Task/Literals-Floating-point/Stata/literals-floating-point.stata b/Task/Literals-Floating-point/Stata/literals-floating-point.stata new file mode 100644 index 0000000000..0c5c6bce41 --- /dev/null +++ b/Task/Literals-Floating-point/Stata/literals-floating-point.stata @@ -0,0 +1,4 @@ +.3 +1.5 +-1.5e10 +3.15e-100 diff --git a/Task/Literals-Integer/Factor/literals-integer-1.factor b/Task/Literals-Integer/Factor/literals-integer-1.factor new file mode 100644 index 0000000000..50185fe8fe --- /dev/null +++ b/Task/Literals-Integer/Factor/literals-integer-1.factor @@ -0,0 +1,4 @@ +10 . ! decimal +0b10 . ! binary +-0o10 . ! octal +0x10 . ! hexadecimal diff --git a/Task/Literals-Integer/Factor/literals-integer-2.factor b/Task/Literals-Integer/Factor/literals-integer-2.factor new file mode 100644 index 0000000000..af8d3e87dc --- /dev/null +++ b/Task/Literals-Integer/Factor/literals-integer-2.factor @@ -0,0 +1,2 @@ +1,234,567 . +1,23,4,567 . diff --git a/Task/Literals-Integer/HolyC/literals-integer-1.holyc b/Task/Literals-Integer/HolyC/literals-integer-1.holyc new file mode 100644 index 0000000000..0af31d827b --- /dev/null +++ b/Task/Literals-Integer/HolyC/literals-integer-1.holyc @@ -0,0 +1,4 @@ +U8 i; // 8 bit integer +U16 i; // 16 bit integer +U32 i; // 32 bit integer +U64 i; // 64 bit integer diff --git a/Task/Literals-Integer/HolyC/literals-integer-2.holyc b/Task/Literals-Integer/HolyC/literals-integer-2.holyc new file mode 100644 index 0000000000..c1f2da026c --- /dev/null +++ b/Task/Literals-Integer/HolyC/literals-integer-2.holyc @@ -0,0 +1,2 @@ +U16 i = 727; // decimal +U16 i = 0x2d7; // hexadecimal diff --git a/Task/Literals-Integer/Limbo/literals-integer.limbo b/Task/Literals-Integer/Limbo/literals-integer.limbo new file mode 100644 index 0000000000..03abeeaf82 --- /dev/null +++ b/Task/Literals-Integer/Limbo/literals-integer.limbo @@ -0,0 +1,18 @@ +implement Command; + +include "sys.m"; +sys: Sys; + +include "draw.m"; + +include "sh.m"; + +init(nil: ref Draw->Context, nil: list of string) +{ + sys = load Sys Sys->PATH; + + sys->print("%d\n", 2r1111); # binary + sys->print("%d\n", 8r17); # octal + sys->print("%d\n", 15); # decimal + sys->print("%d\n", 16rF); # hexadecimal +} diff --git a/Task/Literals-Integer/REXX/literals-integer.rexx b/Task/Literals-Integer/REXX/literals-integer.rexx index 41e49c9171..8dc30648c3 100644 --- a/Task/Literals-Integer/REXX/literals-integer.rexx +++ b/Task/Literals-Integer/REXX/literals-integer.rexx @@ -1,10 +1,31 @@ -thing = 37 -thing = '37' /*this is exactly the same as above. */ -thing = "37" /*this is exactly the same as above also. */ -thing = '25'x /*this as well, expressed in hexadecimal. */ -thing = '00100101'b /*this too, expressed as binary. */ +/*REXX pgm displays an integer (expressed in the pgm as a literal) in different bases*/ + /*────────── expressing decimal numbers ──────────*/ +ddd = 123 /*a decimal number (expressed as a literal). */ +ddd = '123' /*this is exactly the same as above. */ +ddd = "123" /*this is exactly the same as above also. */ + /*────────── expressing hexadecimal numbers ──────*/ +hhh = '7b'x /*a value, expressed as a hexadecimal literal. */ +hhh = '7B'x /* (same as above) using a capital "B". */ +hhh = '7B'X /* (same as above) using a capital "X". */ +cow = 'dead beef'x /*another value, with a blank for the eyeballs.*/ +cow = 'de ad be ef'x /* (same as above) with blanks for the eyeballs.*/ + /*────────── expressing binary numbers ───────────*/ +bbb = '1111011'b /*a value, expressed as a binary literal. */ +bbb = '01111011'b /* (same as above) with a full 8 binary digits. */ +bbb = '0111 1011'b /* (same as above) with a blank for the eyeballs.*/ -say 'base 10=' thing -say 'base 2=' x2b(d2x(thing)) -say 'base 16=' d2x(thing) -say 'base 256=' d2c(thing) /*the output shown is ASCII (or maybe EBCDIC).*/ +say ' base 10=' ddd +say ' base 2=' x2b( d2x( ddd ) ) +say ' base 16=' d2x( ddd ) +say ' base 256=' d2c( ddd ) /*the output displayed is ASCII (or maybe EBCDIC).*/ + +thingy1= +123 /*╔══════════════════════════════════════════════╗*/ +thingy2= '+123' /*║ All of the THINGYs variables aren't strictly ║*/ +thingy3= ' 123' /*║ (exactly) equal to the DDD variable, but ║*/ +thingy4= 123. /*║ they do compare numerically equal. When ║*/ +thingy5= 12.3e+1 /*║ compared numerically, numbers are rounded to ║*/ +thingy6= 1230e-1 /*║ the current setting of NUMERIC DIGITS. The ║*/ +thingy7= 1230E-0001 /*║ default for (decimal) NUMERIC DIGITS is 9 ║*/ +thingy8= ' + 123 ' /*╚══════════════════════════════════════════════╝*/ + + /*stick a fork in it, we're all done. */ diff --git a/Task/Literals-Integer/Rust/literals-integer.rust b/Task/Literals-Integer/Rust/literals-integer.rust index 7a5440eaf6..0c58db740b 100644 --- a/Task/Literals-Integer/Rust/literals-integer.rust +++ b/Task/Literals-Integer/Rust/literals-integer.rust @@ -4,3 +4,4 @@ 0o10 // Octal 1_000 // Underscores may appear anywhere in the numeric literal for clarity 10_i32 // The type (in this case i32, a 32-bit signed integer) may also be appended. +10i32 // With or without underscores diff --git a/Task/Logical-operations/Elena/logical-operations.elena b/Task/Logical-operations/Elena/logical-operations.elena new file mode 100644 index 0000000000..49a8f917e9 --- /dev/null +++ b/Task/Logical-operations/Elena/logical-operations.elena @@ -0,0 +1,12 @@ +import extensions. + +program = +[ + bool a := true. + bool b := false. + + console printLine("a and b is ", a && b). + console printLine("a or b is ", a || b). + console printLine("Not a is ", a inverted). + console printLine("a xor b is ", a ^^ b). +]. diff --git a/Task/Logical-operations/Haskell/logical-operations.hs b/Task/Logical-operations/Haskell/logical-operations-1.hs similarity index 51% rename from Task/Logical-operations/Haskell/logical-operations.hs rename to Task/Logical-operations/Haskell/logical-operations-1.hs index 5713bf7600..7fb58dd33e 100644 --- a/Task/Logical-operations/Haskell/logical-operations.hs +++ b/Task/Logical-operations/Haskell/logical-operations-1.hs @@ -4,3 +4,6 @@ b = True a_and_b = a && b a_or_b = a || b not_a = not a +a_xor_b = a /= b +a_nxor_b = a == b +a_implies_b = a <= b -- sic! diff --git a/Task/Logical-operations/Haskell/logical-operations-2.hs b/Task/Logical-operations/Haskell/logical-operations-2.hs new file mode 100644 index 0000000000..c9e8799c95 --- /dev/null +++ b/Task/Logical-operations/Haskell/logical-operations-2.hs @@ -0,0 +1,8 @@ +*Main > False && undefined +False +Prelude> undefined && False +*** Exception: Prelude.undefined +Prelude> True || undefined +True +Prelude> undefined || True +*** Exception: Prelude.undefined diff --git a/Task/Logical-operations/Haskell/logical-operations-3.hs b/Task/Logical-operations/Haskell/logical-operations-3.hs new file mode 100644 index 0000000000..7b7ae7ca3b --- /dev/null +++ b/Task/Logical-operations/Haskell/logical-operations-3.hs @@ -0,0 +1,8 @@ +Prelude> False <= undefined +*** Exception: Prelude.undefined +Prelude> undefined <= True +*** Exception: Prelude.undefined +Prelude> True < undefined +*** Exception: Prelude.undefined +Prelude> undefined < False +*** Exception: Prelude.undefined diff --git a/Task/Logical-operations/HolyC/logical-operations.holyc b/Task/Logical-operations/HolyC/logical-operations.holyc new file mode 100644 index 0000000000..bc726b60b4 --- /dev/null +++ b/Task/Logical-operations/HolyC/logical-operations.holyc @@ -0,0 +1,7 @@ +U0 PrintLogic(Bool a, Bool b) { + Print("a and b is %d\n", a && b); + Print("a or b is %d\n", a || b); + Print("not a is %d\n", !a); +} + +PrintLogic(TRUE, FALSE); diff --git a/Task/Logical-operations/Modula-2/logical-operations.mod2 b/Task/Logical-operations/Modula-2/logical-operations.mod2 new file mode 100644 index 0000000000..123200fff7 --- /dev/null +++ b/Task/Logical-operations/Modula-2/logical-operations.mod2 @@ -0,0 +1,24 @@ +MODULE LogicalOps; +FROM FormatString IMPORT FormatString; +FROM Terminal IMPORT WriteString,WriteLn,ReadChar; + +PROCEDURE Print(a,b : BOOLEAN); +VAR buf : ARRAY[0..31] OF CHAR; +BEGIN + FormatString("a and b is %b\n", buf, a AND b); + WriteString(buf); + FormatString("a or b is %b\n", buf, a OR b); + WriteString(buf); + FormatString("not a is %b\n", buf, NOT a); + WriteString(buf); + WriteLn +END Print; + +BEGIN + Print(FALSE, FALSE); + Print(FALSE, TRUE); + Print(TRUE, TRUE); + Print(TRUE, FALSE); + + ReadChar +END LogicalOps. diff --git a/Task/Logical-operations/REXX/logical-operations-1.rexx b/Task/Logical-operations/REXX/logical-operations-1.rexx new file mode 100644 index 0000000000..7013d3130f --- /dev/null +++ b/Task/Logical-operations/REXX/logical-operations-1.rexx @@ -0,0 +1,26 @@ +/*REXX program demonstrates some binary (also known as bit or logical) operations.*/ + x= 1 ; y= 0 /*set the initial values of X and Y. */ + @x= ' x '; @y= ' y ' /*define a couple of literals for HDRs.*/ + /* [↓] echo the X and Y values.*/ +call $ 'name', "value" /*display the header (title) line. */ +call $ 'x' , x /*display "x" and then the value of X.*/ +call $ 'y' , y /* " "y" " " " " " Y */ + /* [↓] negate the X; then the Y value.*/ +call $ 'name', "negated" /*some REXXes support the ¬ character*/ +call $ 'x' , \x /*display "x" and then the value of ¬X*/ +call $ 'y' , \y /* " "y" " " " " " ¬Y*/ +say +say +call $ @x, @y, 'AND'; do x=0 to 1; do y=0 to 1; call $ x, y, x & y; end; end +call $ @x, @y, 'OR' ; do x=0 to 1; do y=0 to 1; call $ x, y, x | y; end; end +call $ @x, @y, 'XOR'; do x=0 to 1; do y=0 to 1; call $ x, y, x && y; end; end +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +$: parse arg @.1, @.2, @.3, @.4; hdr= length(@.1) \== 1; if hdr then say + do j=0 to hdr; _= + do k=1 for arg(); _=_ center(@.k, 7) + end /*k*/ + say _ + @.=copies('═', 7) /*define a new header separator line. */ + end /*j*/ + return diff --git a/Task/Logical-operations/REXX/logical-operations-2.rexx b/Task/Logical-operations/REXX/logical-operations-2.rexx new file mode 100644 index 0000000000..7797ef0982 --- /dev/null +++ b/Task/Logical-operations/REXX/logical-operations-2.rexx @@ -0,0 +1,29 @@ +/*REXX pgm demonstrates some binary (also known as bit or logical) extended operations.*/ + x= 1 ; y= 0 /*set the initial values of X and Y. */ + @x= ' x '; @y= ' y ' /*define a couple of literals for HDRs.*/ + /* [↓] echo the X and Y values.*/ +call $ 'name', "value" /*display the header (title) line. */ +call $ 'x' , x /*display "x" and then the value of X.*/ +call $ 'y' , y /* " "y" " " " " " Y */ + /* [↓] negate the X; then the Y value.*/ +call $ 'name', "negated" /*some REXXes support the ¬ character*/ +call $ 'x' , \x /*display "x" and then the value of ¬X*/ +call $ 'y' , \y /* " "y" " " " " " ¬Y*/ +say /*note: NXOR is also known as XNOR. */ +say /*all 16 bit operations could be shown.*/ +call $ @x, @y, 'AND' ; do x=0 to 1; do y=0 to 1; call $ x, y, x & y ; end; end +call $ @x, @y, 'NAND'; do x=0 to 1; do y=0 to 1; call $ x, y, \(x & y); end; end +call $ @x, @y, 'OR' ; do x=0 to 1; do y=0 to 1; call $ x, y, x | y ; end; end +call $ @x, @y, 'NOR' ; do x=0 to 1; do y=0 to 1; call $ x, y, \(x | y); end; end +call $ @x, @y, 'XOR' ; do x=0 to 1; do y=0 to 1; call $ x, y, x && y ; end; end +call $ @x, @y, 'NXOR'; do x=0 to 1; do y=0 to 1; call $ x, y, \(x && y); end; end +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +$: parse arg @.1, @.2, @.3, @.4; hdr= length(@.1) \== 1; if hdr then say + do j=0 to hdr; _= + do k=1 for arg(); _=_ center(@.k, 7) + end /*k*/ + say _ + @.= copies('═', 7) /*define a new separator (header) line.*/ + end /*j*/ + return diff --git a/Task/Logical-operations/REXX/logical-operations.rexx b/Task/Logical-operations/REXX/logical-operations.rexx deleted file mode 100644 index 26c695bc30..0000000000 --- a/Task/Logical-operations/REXX/logical-operations.rexx +++ /dev/null @@ -1,27 +0,0 @@ -/*REXX program demonstrates some binary (also known as bit or logical) operations.*/ - x=1; y=0; @v= 'value' /*set initial values of X & Y; literal.*/ - /* [↓] echo the X and Y values.*/ -call TT 'name', "value" /*display the header (title) line. */ -call TT 'x' , x /*display "x" and then the value of X.*/ -call TT 'y' , y /* " "y" " " " " " Y */ - /* [↓] negate the X; then the Y value.*/ -call TT 'name', "negated" /*some REXXes support the ¬ character*/ -call TT 'x' , \x /*display "x" and then the value of ¬X*/ -call TT 'y' , \y /* " "y" " " " " " ¬Y*/ - /*both DO loops use 0 and 1 for values.*/ -call TT @v, @v, 'AND'; do x=0 for 2; do y=0 for 2; call TT x, y, x & y; end /*y*/ - end /*x*/ - -call TT @v, @v, 'OR'; do x=0 for 2; do y=0 for 2; call TT x, y, x | y; end /*y*/ - end /*x*/ - -call TT @v, @v, 'XOR'; do x=0 for 2; do y=0 for 2; call TT x, y, x && y; end /*y*/ - end /*x*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -TT: parse arg @.1,@.2,@.3,@.4; hdr=length(@.1)\==1; if hdr then say; w=7 - do j=0 to hdr; _=; do k=1 for arg(); _=_ center(@.k,w); end /*k*/ - say _ - @.=copies('═', w) /*define the header separator line. */ - end /*j*/ /*W: is used for the width of a column*/ - return diff --git a/Task/Long-multiplication/COBOL/long-multiplication.cobol b/Task/Long-multiplication/COBOL/long-multiplication.cobol new file mode 100644 index 0000000000..48eaefefa1 --- /dev/null +++ b/Task/Long-multiplication/COBOL/long-multiplication.cobol @@ -0,0 +1,88 @@ + identification division. + program-id. long-mul. + data division. + replace ==ij-lim== by ==7== ==ir-lim== by ==14==. + working-storage section. + 1 input-string pic x(26) value "18,446,744,073,709,551,616". + 1 a-table. + 2 a pic 999 occurs ij-lim. + 1 b-table. + 2 b pic 999 occurs ij-lim. + 1 ir-table value all "0". + 2 occurs ij-lim. + 3 ir pic 999 occurs ir-lim. + 1 s-table value all "0". + 2 s pic 999 occurs ir-lim. + 1 display. + 2 temp-result pic 9(6) value 0. + 2 carry pic 999 value 0. + 2 remain pic 999 value 0. + 1 binary. + 2 i pic 9(4) value 0. + 2 j pic 9(4) value 0. + 2 k pic 9(4) value 0. + procedure division. + begin. + move 1 to j + perform varying i from 1 by 1 until i > ij-lim + unstring input-string delimited "," + into a (i) with pointer j + end-perform + move a-table to b-table + perform intermediate-calc + perform sum-ir + perform display-result + stop run + . + + intermediate-calc. + perform varying i from ij-lim by -1 until i < 1 + move 0 to carry + perform varying j from ij-lim by -1 until j < 1 + compute temp-result = a (i) * b (j) + carry + divide temp-result by 1000 giving carry + remainder remain + compute k = i + j + move remain to ir (i k) + end-perform + subtract 1 from k + move carry to ir (i k) + end-perform + . + + sum-ir. + move 0 to carry + perform varying k from ir-lim by -1 until k < 1 + move carry to temp-result + perform varying i from ij-lim by -1 until i < 1 + compute temp-result = temp-result + ir (i k) + end-perform + divide temp-result by 1000 giving carry + remainder remain + move remain to s (k) + end-perform + . + + display-result. + display " " input-string + display " * " input-string + display " = " with no advancing + perform varying k from 1 by 1 + until k > ir-lim or s (k) not = 0 + end-perform + if s (k) < 100 + move 1 to i + inspect s (k) tallying i for leading "0" + display s (k) (i:) "," with no advancing + add 1 to k + end-if + perform varying k from k by 1 until k > ir-lim + display s (k) with no advancing + if k < ir-lim + display "," with no advancing + end-if + end-perform + display space + . + + end program long-mul. diff --git a/Task/Long-multiplication/Ceylon/long-multiplication.ceylon b/Task/Long-multiplication/Ceylon/long-multiplication.ceylon new file mode 100644 index 0000000000..508fb22684 --- /dev/null +++ b/Task/Long-multiplication/Ceylon/long-multiplication.ceylon @@ -0,0 +1,58 @@ +"run() is the main function of this module." + +shared void run() { + + function multiply(String|Integer|Integer[] top, String|Integer|Integer[] bottom, Integer base = 10) { + + function fromString(String s) => + s + .filter(not(','.equals)) + .map((char) => Integer.parse(char.string)) + .narrow() + .sequence() + .reversed; + + function toString(Integer[] ints) => + "" + .join(ints.interpose(',', 3)) + .reversed + .trimLeading((char) => char in "0,"); + + function fromInteger(Integer int) => fromString(int.string); + + function convertArg(String|Integer|Integer[] arg) => + switch(arg) + case (is String) fromString(arg) + case (is Integer) fromInteger(arg) + case (is Integer[]) arg; + + value a = convertArg(top); + value b = convertArg(bottom); + + value p = a.size; + value q = b.size; + value product = Array.ofSize(p + q, 0); + + for (bIndex->bDigit in b.indexed) { + variable value carry = 0; + for (aIndex->aDigit in a.indexed) { + assert (exists prodDigit = product[aIndex + bIndex]); + value temp = prodDigit + carry + aDigit * bDigit; + carry = temp / base; + product[aIndex + bIndex] = temp % base; + } + assert (exists lastDigit = product[bIndex + p]); + product[bIndex + p] = lastDigit + carry; + } + + return toString(product.sequence()); + } + + value twoToThe64th = "18,446,744,073,709,551,616"; + value expectedResult = "340,282,366,920,938,463,463,374,607,431,768,211,456"; + value result = multiply(twoToThe64th, twoToThe64th); + + print("The expected result is ``expectedResult``"); + print("The actual result is ``result``"); + print("Do they match? ``expectedResult == result then "Yes!" else "No!"``"); +} diff --git a/Task/Long-multiplication/Common-Lisp/long-multiplication.lisp b/Task/Long-multiplication/Common-Lisp/long-multiplication.lisp index a74c28ede5..4b64a765b4 100644 --- a/Task/Long-multiplication/Common-Lisp/long-multiplication.lisp +++ b/Task/Long-multiplication/Common-Lisp/long-multiplication.lisp @@ -20,7 +20,7 @@ significant digit first. The digits returned by long-add do have the most significant bit first." (if (every 'endp digitses) - (nconc (digits carry) sum) + (nconc (number->digits carry) sum) (let ((column-sum (reduce '+ (mapcar #'first-digit digitses) :initial-value carry))) (multiple-value-bind (carry column-digit) @@ -30,8 +30,8 @@ ;; get the digits of a and b (least significant bit first), and ;; compute the zero padded rows. Then, add these rows (using ;; long-add) and convert the digits back to a number. - (do ((a (nreverse (digits a))) - (b (nreverse (digits b))) + (do ((a (nreverse (number->digits a))) + (b (nreverse (number->digits b))) (prefix '() (list* 0 prefix)) (rows '())) ((endp b) (digits->number (long-add rows))) diff --git a/Task/Long-multiplication/JavaScript/long-multiplication-1.js b/Task/Long-multiplication/JavaScript/long-multiplication-1.js index 3b60af9204..453326283b 100644 --- a/Task/Long-multiplication/JavaScript/long-multiplication-1.js +++ b/Task/Long-multiplication/JavaScript/long-multiplication-1.js @@ -11,7 +11,7 @@ function mult(strNum1,strNum2){ if ( aResult[idxIter] > 9 ) { // Carrying aResult[idxIter + 1] = Math.floor( aResult[idxIter] / 10 ) + ( idxIter + 1 >= aResult.length ? 0 : aResult[idxIter + 1] ); - aResult[idxIter] -= Math.floor( aResult[idxIter] / 10 ) * 10; + aResult[idxIter] %= 10; } } } diff --git a/Task/Long-multiplication/Julia/long-multiplication-1.julia b/Task/Long-multiplication/Julia/long-multiplication-1.julia new file mode 100644 index 0000000000..c00eb72a53 --- /dev/null +++ b/Task/Long-multiplication/Julia/long-multiplication-1.julia @@ -0,0 +1,45 @@ +module LongMultiplication + +using Compat + +function addwithcarry!(r, addend, addendpos) + while true + pad = max(0, addendpos - lastindex(r)) + append!(r, fill(0, pad)) + addendrst = addend + r[addendpos] + addend, r[addendpos] = divrem(addendrst, 10) + iszero(addend) && break + addendpos += 1 + end + return r +end + +function longmult(mult1::AbstractVector{T}, mult2::AbstractVector{T}) where T <: Integer + r = T[] + for (offset1, digit1) in enumerate(mult1), (offset2, digit2) in zip(eachindex(mult2) + offset1 - 1, mult2) + single_multrst = digits(digit1 * digit2) + for (addoffset, rstdigit) in zip(eachindex(single_multrst) + offset2 - 1, single_multrst) + addwithcarry!(r, rstdigit, addoffset) + end + end + return r +end + +function longmult(a::T, b::T)::T where T <: Integer + mult1 = digits(a) + mult2 = digits(b) + r = longmult(mult1, mult2) + return sum(d * T(10) ^ (e - 1) for (e, d) in enumerate(r)) +end + +function longmult(a::AbstractString, b::AbstractString) + if !ismatch(r"^\d+", a) || !ismatch(r"^\d+", b) + throw(ArgumentError("string must contain only digits")) + end + mult1 = reverse(collect(Char, a) .- '0') + mult2 = reverse(collect(Char, b) .- '0') + r = longmult(mult1, mult2) + return reverse(join(r)) +end + +end # module LongMultiplication diff --git a/Task/Long-multiplication/Julia/long-multiplication-2.julia b/Task/Long-multiplication/Julia/long-multiplication-2.julia new file mode 100644 index 0000000000..e5a32aa020 --- /dev/null +++ b/Task/Long-multiplication/Julia/long-multiplication-2.julia @@ -0,0 +1,2 @@ +@show LongMultiplication.longmult(big(2) ^ 64, big(2) ^ 64) +@show LongMultiplication.longmult("18446744073709551616", "18446744073709551616") diff --git a/Task/Long-multiplication/Maple/long-multiplication.maple b/Task/Long-multiplication/Maple/long-multiplication.maple index 3f5a796851..b4a314ec50 100644 --- a/Task/Long-multiplication/Maple/long-multiplication.maple +++ b/Task/Long-multiplication/Maple/long-multiplication.maple @@ -1,9 +1,11 @@ -> longmult := proc( a, b ) - local la, lb, digit; - la := length(a); - lb := length(b); - digit := (n,i)->iquo(n,10^(i-1)) mod 10; - add( add( digit(a,la-i+1) * digit(b,lb-j+1) *10^(la-i+lb-j), i=1..la), j=1..lb ); +longmult := proc(a::integer,b::integer) + local A,B,m,n,i,j; + # Note, return a*b; works in Maple for any sized integer + A := convert(a,base,10); + B := convert(b,base,10); + m := numelems(A); + n := numelems(B); + add( add( A[i]*B[j]*10^(j-1), j=1..n )*10^(i-1), i=1..m ); end; > longmult( 2^64, 2^64 ); diff --git a/Task/Long-multiplication/Perl-6/long-multiplication.pl6 b/Task/Long-multiplication/Perl-6/long-multiplication.pl6 index cc3163ddac..a5fab1df93 100644 --- a/Task/Long-multiplication/Perl-6/long-multiplication.pl6 +++ b/Task/Long-multiplication/Perl-6/long-multiplication.pl6 @@ -16,4 +16,8 @@ sub long_multiply ( Str $x, Str $y ) { return groups_to_num @group_sums; } -long_multiply( '18446744073709551616', '18446744073709551616' ).say; +my $str = '18446744073709551616'; +long_multiply( $str, $str ).say; + +# cross-check with native implementation +say +$str * +$str; diff --git a/Task/Long-multiplication/Ruby/long-multiplication.rb b/Task/Long-multiplication/Ruby/long-multiplication.rb index 1d89ce85ac..f4d98913cc 100644 --- a/Task/Long-multiplication/Ruby/long-multiplication.rb +++ b/Task/Long-multiplication/Ruby/long-multiplication.rb @@ -1,11 +1,10 @@ def longmult(x,y) - digits = reverse_split_number(x) result = [0] j = 0 - reverse_split_number(y).each do |m| + y.digits.each do |m| c = 0 i = j - digits.each do |d| + x.digits.each do |d| v = result[i] result << 0 if v.zero? c, v = (v + c + d*m).divmod(10) @@ -19,15 +18,6 @@ def longmult(x,y) result.reverse.inject(0) {|sum, n| 10*sum + n} end -def reverse_split_number(m) - digits = [] - while m > 0 - m, v = m.divmod 10 - digits << v - end - digits -end - n=2**64 printf " %d * %d = %d\n", n, n, n*n printf "longmult(%d, %d) = %d\n", n, n, longmult(n,n) diff --git a/Task/Long-multiplication/Sidef/long-multiplication-2.sidef b/Task/Long-multiplication/Sidef/long-multiplication-2.sidef index 51bc885534..310338a8d7 100644 --- a/Task/Long-multiplication/Sidef/long-multiplication-2.sidef +++ b/Task/Long-multiplication/Sidef/long-multiplication-2.sidef @@ -1,37 +1,37 @@ func add_with_carry(result, addend, addendpos) { loop { while (result.len < addendpos+1) { - result.append(0); - }; - var addend_digits = (addend.to_i + result[addendpos].to_i -> to_chars); - result[addendpos] = addend_digits.pop; - addend_digits.len > 0 || break; - addend = addend_digits.pop; - addendpos++; + result.append(0) + } + var addend_digits = (addend.to_i + result[addendpos] -> to_s.chars) + result[addendpos] = addend_digits.pop + addend_digits.len > 0 || break + addend = addend_digits.pop + addendpos++ } } - +  func longhand_multiplication(multiplicand, multiplier) { - - var result = []; - var multiplicand_offset = 0; - +  + var result = [] + var multiplicand_offset = 0 +  multiplicand.reverse.each { |multiplicand_digit| - var multiplier_offset = multiplicand_offset; + var multiplier_offset = multiplicand_offset multiplier.reverse.each { |multiplier_digit| - var multiplication_result = (multiplicand_digit.to_i * multiplier_digit.to_i -> to_s); - - var addend_offset = multiplier_offset; + var multiplication_result = (multiplicand_digit.to_i * multiplier_digit.to_i -> to_s) +  + var addend_offset = multiplier_offset multiplication_result.reverse.each { |result_digit_addend| - add_with_carry(result, result_digit_addend, addend_offset); - addend_offset++; - }; - multiplier_offset++; - }; - multiplicand_offset++; - }; - - return result.join.reverse; + add_with_carry(result, result_digit_addend, addend_offset) + addend_offset++ + } + multiplier_offset++ + } + multiplicand_offset++ + } +  + return result.join.reverse } - -say longhand_multiplication('18446744073709551616', '18446744073709551616'); +  +say longhand_multiplication('18446744073709551616', '18446744073709551616') diff --git a/Task/Longest-increasing-subsequence/Julia/longest-increasing-subsequence.julia b/Task/Longest-increasing-subsequence/Julia/longest-increasing-subsequence.julia new file mode 100644 index 0000000000..857f6089e0 --- /dev/null +++ b/Task/Longest-increasing-subsequence/Julia/longest-increasing-subsequence.julia @@ -0,0 +1,20 @@ +function lis(arr::Vector) + if length(arr) == 0 return copy(arr) end + L = Vector{typeof(arr)}(length(arr)) + L[1] = [arr[1]] + + for i in 2:length(arr) + nextL = [] + for j in 1:i + if arr[j] < arr[i] && length(L[j]) ≥ length(nextL) + nextL = L[j] + end + end + L[i] = vcat(nextL, arr[i]) + end + + return L[indmax(length.(L))] +end + +@show lis([3, 2, 6, 4, 5, 1]) +@show lis([0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]) diff --git a/Task/Longest-increasing-subsequence/Ring/longest-increasing-subsequence.ring b/Task/Longest-increasing-subsequence/Ring/longest-increasing-subsequence.ring new file mode 100644 index 0000000000..dc5a4c180a --- /dev/null +++ b/Task/Longest-increasing-subsequence/Ring/longest-increasing-subsequence.ring @@ -0,0 +1,61 @@ +# Project : Longest increasing subsequence +# Date : 2017/11/23 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +tests = [[3, 2, 6, 4, 5, 1], [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]] +res = [] +for x=1 to len(tests) + lis(tests[x]) + showarray(res) +end + +func lis(X) + N = len(X) + P = list(N) + M = list(N) + for nr = 1 to len(P) + P[nr] = 0 + next + for nr = 1 to len(M) + P[nr] = 0 + next + len = 0 + for i=1 to N + lo = 1 + hi = len + while lo <= hi + mid = floor((lo+hi)/2) + if X[M[mid]]1 + P[i] = M[lo-1] + ok + M[lo] = i + if lo>len + len = lo + ok + next + res = list(len) + if len>0 + k = M[len] + for i=len to 1 step -1 + res[i] = X[k] + k = P[k] + next + ok + return res + +func showarray(vect) + see "{" + svect = "" + for n = 1 to len(vect) + svect = svect + vect[n] + ", " + next + svect = left(svect, len(svect) - 2) + see svect + see "}" + nl diff --git a/Task/Longest-increasing-subsequence/Rust/longest-increasing-subsequence.rust b/Task/Longest-increasing-subsequence/Rust/longest-increasing-subsequence.rust new file mode 100644 index 0000000000..6c1fb2d036 --- /dev/null +++ b/Task/Longest-increasing-subsequence/Rust/longest-increasing-subsequence.rust @@ -0,0 +1,40 @@ +fn lower_bound(list: &Vec, value: &T) -> usize { + if list.is_empty() { + return 0; + } + let mut lower = 0usize; + let mut upper = list.len(); + while lower != upper { + let middle = lower + upper >> 1; + if list[middle] < *value { + lower = middle + 1; + } else { + upper = middle; + } + } + return lower; +} + +fn lis(list: &Vec) -> Vec { + if list.is_empty() { + return Vec::new(); + } + let mut subseq: Vec = Vec::new(); + subseq.push(*list.first().unwrap()); + for i in list[1..].iter() { + if *i <= *subseq.last().unwrap() { + let index = lower_bound(&subseq, i); + subseq[index] = *i; + } else { + subseq.push(*i); + } + } + return subseq; +} + +fn main() { + let list = vec![3, 2, 6, 4, 5, 1]; + println!("{:?}", lis(&list)); + let list = vec![0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]; + println!("{:?}", lis(&list)); +} diff --git a/Task/Longest-increasing-subsequence/Scala/longest-increasing-subsequence-1.scala b/Task/Longest-increasing-subsequence/Scala/longest-increasing-subsequence-1.scala index 1f734f534c..9d925be7d9 100644 --- a/Task/Longest-increasing-subsequence/Scala/longest-increasing-subsequence-1.scala +++ b/Task/Longest-increasing-subsequence/Scala/longest-increasing-subsequence-1.scala @@ -1,25 +1,36 @@ object LongestIncreasingSubsequence extends App { - def longest(l: Array[Int]) = l match { - case _ if l.length < 2 => Array(l) - case l => - def increasing(done: Array[Int], remaining: Array[Int]): Array[Array[Int]] = remaining match { - case Array() => Array(done) - case Array(head, _*) => - (if (head > done.last) increasing(done :+ head, remaining.tail) else Array()) ++ - increasing(done, remaining.tail) // all increasing combinations - } - val all = (1 to l.length).flatMap(i => increasing(l take i takeRight 1, l.drop(i+1))).sortBy(-_.length) - all.takeWhile(_.length == all.head.length).toArray // longest from all increasing combinations - } - val tests = Map( - "3,2,6,4,5,1" -> Array("2,4,5", "3,4,5"), - "0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15" -> Array("0,2,6,9,11,15", "0,2,6,9,13,15", "0,4,6,9,13,15", "0,4,6,9,11,15") + "3,2,6,4,5,1" -> Seq("2,4,5", "3,4,5"), + "0,8,4,12,2,10,6,14,1,9,5,13,3,11,7,15" -> + Seq("0,2,6,9,11,15", "0,2,6,9,13,15", "0,4,6,9,13,15", "0,4,6,9,11,15") ) - def asInts(s: String): Array[Int] = s split "," map Integer.parseInt - assert(tests forall {case (given, expect) => - val lis = longest(asInts(given)) - println(s"$given has ${lis.size} longest increasing subsequences, e.g. "+lis.last.mkString(",")) - expect contains lis.last.mkString(",") + + def lis(l: Array[Int]): Seq[Array[Int]] = + if (l.length < 2) Seq(l) + else { + def increasing(done: Array[Int], remaining: Array[Int]): Seq[Array[Int]] = + if (remaining.isEmpty) Seq(done) + else + (if (remaining.head > done.last) + increasing(done :+ remaining.head, remaining.tail) + else Nil) ++ increasing(done, remaining.tail) // all increasing combinations + + val all = (1 to l.length) + .flatMap(i => increasing(l take i takeRight 1, l.drop(i + 1))) + .sortBy(-_.length) + all.takeWhile(_.length == all.head.length) // longest of all increasing combinations + } + + def asInts(s: String): Array[Int] = s split "," map (_.toInt) + + assert(tests forall { + case (given, expect) => + val allLongests: Seq[Array[Int]] = lis(asInts(given)) + println( + s"$given has ${allLongests.length} longest increasing subsequences, e.g. ${ + allLongests.last + .mkString(",") + }") + allLongests.forall(lis => expect.contains(lis.mkString(","))) }) } diff --git a/Task/Longest-string-challenge/00DESCRIPTION b/Task/Longest-string-challenge/00DESCRIPTION index 8bc20fbd8c..912bf7cfbf 100644 --- a/Task/Longest-string-challenge/00DESCRIPTION +++ b/Task/Longest-string-challenge/00DESCRIPTION @@ -1,8 +1,6 @@ ;Background: This "longest string challenge" is inspired by a problem that used to be given to students learning Icon. Students were expected to try to solve the problem in Icon and another language with which the student was already familiar. The basic problem is quite simple; the challenge and fun part came through the introduction of restrictions. Experience has shown that the original restrictions required some adjustment to bring out the intent of the challenge and make it suitable for Rosetta Code. -The original programming challenge and some solutions can be found at [https://tapestry.tucson.az.us/twiki/bin/view/Main/LongestStringsPuzzle Unicon Programming TWiki / Longest Strings Puzzle]. (See notes on the talk page if you have trouble with the site). - ;Basic problem statement Write a program that reads lines from standard input and, upon end of file, writes the longest line to standard output. @@ -54,7 +52,7 @@ The guiding principle here should be to be creative in demonstrating some of the Now having said that, the restrictions require some elaboration. * In general, the restrictions are meant to avoid the explicit use of these features. -* "No comparison operators may be used" - At some level there must be some test that allows the solution to get at the length and determine if one string is longer. Comparison operators, in particular any less/greater comparison should be avoided. Representing the length of any string as a number should also be avoided. Various approaches allow for detecting the end of a string. Some of these involve implicitly using equal/not-equal; however, explicitly using equal/not-equal should be acceptable. +* "No comparison operators may be used" - At some level there must be some test that allows the solution to get at the length and determine if one string is longer. Comparison operators, in particular any less/greater comparison should be avoided. Representing the length of any string as a number should also be avoided. Various approaches allow for detecting the end of a string. Some of these involve implicitly using equal/not-equal; however, explicitly using equal/not-equal should be acceptable. * "No arithmetic operations" - Again, at some level something may have to advance through the string. Often there are ways a language can do this implicitly advance a cursor or pointer without explicitly using a +, - , ++, --, add, subtract, etc. * The datatype restrictions are amongst the most difficult to reinterpret. In the language of the original challenge strings are atomic datatypes and structured datatypes like lists are quite distinct and have many different operations that apply to them. This becomes a bit fuzzier with languages with a different programming paradigm. The intent would be to avoid using an easy structure to accumulate the longest strings and spit them out. There will be some natural reinterpretation here. diff --git a/Task/Longest-string-challenge/Haskell/longest-string-challenge.hs b/Task/Longest-string-challenge/Haskell/longest-string-challenge.hs new file mode 100644 index 0000000000..8c34689286 --- /dev/null +++ b/Task/Longest-string-challenge/Haskell/longest-string-challenge.hs @@ -0,0 +1,25 @@ +module Main where + +import System.Environment + +cmp :: String -> String -> Ordering +cmp [] [] = EQ +cmp [] (_:_) = LT +cmp (_:_) [] = GT +cmp (_:xs) (_:ys) = cmp xs ys + +longest :: String -> String +longest = longest' "" "" . lines + where + longest' acc l [] = acc + longest' [] l (x:xs) = longest' x x xs + longest' acc l (x:xs) = case cmp l x of + LT -> longest' x x xs + EQ -> longest' (acc ++ '\n':x) l xs + GT -> longest' acc l xs + +main :: IO () +main = do + (file:_) <- getArgs + contents <- readFile file + putStrLn $ longest contents diff --git a/Task/Longest-string-challenge/Julia/longest-string-challenge.julia b/Task/Longest-string-challenge/Julia/longest-string-challenge.julia new file mode 100644 index 0000000000..d29a6d22d0 --- /dev/null +++ b/Task/Longest-string-challenge/Julia/longest-string-challenge.julia @@ -0,0 +1,24 @@ +function longer(a, b) + try + b[endof(a)] + catch + return true + end + return false +end + +function printlongest(io::IO) + lines = longest = "" + while !eof(io) + line = readline(io) + if longer(line, longest) + longest = lines = line + elseif !longer(longest, line) + lines *= "\n" * line + end + end + println(lines) +end +printlongest(str::String) = printlongest(IOBuffer(str)) + +printlongest("a\nbb\nccc\nddd\nee\nf\nggg") diff --git a/Task/Longest-string-challenge/Python/longest-string-challenge.py b/Task/Longest-string-challenge/Python/longest-string-challenge.py index d18ef2d2a8..64403846d2 100644 --- a/Task/Longest-string-challenge/Python/longest-string-challenge.py +++ b/Task/Longest-string-challenge/Python/longest-string-challenge.py @@ -1,14 +1,16 @@ import fileinput -# originally, return len(a) - len(b) if positive, 0 otherwise. -# Observing that longer is used for its Boolean result, -# and that '' is False, while any other string is True, -# longer need only to return a after removing len(b) characters, -# which is done without resorting to len(). +# This returns True if the second string has a value on the +# same index as the last index of the first string. It runs +# faster than trimming the strings because it runs len once +# and is a single index lookup versus slicing both strings +# one character at a time. def longer(a, b): - while a and b: - a, b = a[1:], b[1:] - return a + try: + b[len(a)-1] + return False + except: + return True longest, lines = '', '' for x in fileinput.input(): diff --git a/Task/Longest-string-challenge/REXX/longest-string-challenge-1.rexx b/Task/Longest-string-challenge/REXX/longest-string-challenge-1.rexx index 27594ef1e4..228dd4b7bd 100644 --- a/Task/Longest-string-challenge/REXX/longest-string-challenge-1.rexx +++ b/Task/Longest-string-challenge/REXX/longest-string-challenge-1.rexx @@ -1,17 +1,19 @@ -/*REXX pgm reads a file & prints the longest [widest] record(s)/line(s).*/ -!.='' /*initialize stemmed array to nul*/ -fileID='LONGEST1.TXT' /*point to the input file. */ -m=0 - - do while min(lines(fileID),1); _=linein(fileID); w=length(_) - say 'input =' _ /*display the input to terminal. */ - !.w=!.w || '0a'x || _ /*build a stemmed array element. */ - m=max(m,w) /*find the maximum width so far. */ - end /*while min(lines(... */ - - do j=m for m /*handle the case of no input. */ - say center(' longest record(s): ',79,'═') - say substr(!.m,2) - say center(' list end ',79,'═') - exit /*stick a fork in it, we're done.*/ - end /*j*/ +/*REXX program reads a file and displays the longest [widest] record(s) [line(s)]. */ +signal on notReady /*when E-O-F is reached, jump/branch. */ +iFID= 'LONGEST.TXT' /*the default file identifier for input*/ +parse arg fid . /*obtain optional argument from the CL.*/ + do #=1 to length(fid); iFID=fid /*Specified? Then use what's given. */ + end /*#*/ +!= /*the maximum width (so far). */ + do forever; _=linein(iFID); ?=_ /*read a line from the input file. */ + t=0 /*don't do the initialization next time*/ + do #=t for t; !=?; ?=; $=. || _; end /*just do 1st time.*/ + do #=length(!' ') to length(?) for 1; $=; end /*found widest rec.*/ + do #=length(!) to length(?) for 1; $=$'a0d'x || _; end /*append it to $. */ + /* [↑] variable # isn't really used.*/ + !=left(., max( length(!), length(?) ) ) /*!: is the max length record, so far.*/ + end /*forever*/ + /* [↓] comes here when file gets E─O─F*/ +notReady: do j=length(!) to length(!) for length(!) /*handle the case of no input*/ + say substr($, 2) /*display (all) the longest records. */ + end /*j*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Longest-string-challenge/REXX/longest-string-challenge-2.rexx b/Task/Longest-string-challenge/REXX/longest-string-challenge-2.rexx index edcea230c4..10d88bcde5 100644 --- a/Task/Longest-string-challenge/REXX/longest-string-challenge-2.rexx +++ b/Task/Longest-string-challenge/REXX/longest-string-challenge-2.rexx @@ -1,18 +1,44 @@ -/*REXX pgm reads a file & prints the longest [widest] record(s)/line(s).*/ -!.='' /*initialize stemmed array to nul*/ -fileID='LONGEST2.TXT' /*point to the input file. */ -signal on notready /*when E-O-F is reached, jump. */ -m=0 /*maximum width line so far. */ - - do forever; _=linein(fileID); w=length(_) /*read a line. */ - say 'input =' _ /*display the input to terminal. */ - !.w=!.w || '0a'x || _ /*build a stemmed array element. */ - m=max(m,w) /*find the maximum width so far. */ - end /*forever*/ - -notready: do j=m for m /*handle the case of no input. */ - say center(' longest record(s): ',79,'═') - say substr(!.m,2) - say center(' list end ',79,'═') - exit /*stick a fork in it, we're done.*/ - end /*j*/ +/* REXX *************************************************************** +* 27.10.2010 Walter Pachl +**********************************************************************/ +Parse Arg fid +If fid='' Then Do + "ALLOC FI(IN) DA('N561985.PRIV.V100(LL)') SHR REUSE" + 'EXECIO * DISKR IN (STEM L. FINIS' /* read all lines */ + 'FREE FI(IN)' + End +Else Do + Do i=1 By 1 While lines(fid)>0 + l.i=linein(fid) + End + l.0=i-1 + End +maxl = 0 /* initialize maximum length */ +Do i=1 To l.0 /* loop through all lines */ + linl=length(l.i) /* length of current line */ + Select + When linl>maxl Then Do /* line longer than preceding */ + maxl=linl /* initialize maximum length */ + mem.0=1 /* memory has one entry */ + mem.1=l.i /* the current line */ + lin.1=i /* its line number */ + End + When linl=maxl Then Do /* line as long as maximum */ + z=mem.0+1 /* new memory index */ + mem.z=l.i /* the current line */ + lin.z=i /* its line number */ + mem.0=z /* memory size */ + End + Otherwise /* line is shorter than max. */ + Nop /* ignore */ + End + End +If mem.0>0 Then Do + Say 'Maximum line length='maxl + Say ' Line Contents' + Do i=1 To mem.0 + Say right(lin.i,5) mem.i + End + End +Else + Say 'No lines in input file or file does not exist' diff --git a/Task/Longest-string-challenge/Ring/longest-string-challenge.ring b/Task/Longest-string-challenge/Ring/longest-string-challenge.ring new file mode 100644 index 0000000000..1cb8a43051 --- /dev/null +++ b/Task/Longest-string-challenge/Ring/longest-string-challenge.ring @@ -0,0 +1,26 @@ +# Project : Longest string challenge +# Date : 2017/10/11 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +load "stdlib.ring" + +test = ["a", "bb", "ccc", "ddd", "ee", "f", "ggg"] +test1 = [] +test2 = [] + +for n = 1 to len(test) + add(test1, [test[n], len(test[n])]) +next +sortFirstSecond(test1, 2) + +for n = len(test1) to 2 step -1 + if test1[n][2] = test1[n-1][2] + add(test2, test1[n][1]) + else + add(test2, test1[n][1]) + exit + ok +next +test2 = sort(test2) +see test2 + nl diff --git a/Task/Look-and-say-sequence/BASIC256/look-and-say-sequence.basic256 b/Task/Look-and-say-sequence/BASIC256/look-and-say-sequence.basic256 new file mode 100644 index 0000000000..3c681c4396 --- /dev/null +++ b/Task/Look-and-say-sequence/BASIC256/look-and-say-sequence.basic256 @@ -0,0 +1,25 @@ +# look and say + +dim a$(2) + +i = 0 # input string index + +a$[i] = "1" + +print a$[i] + +for n=1 to 10 + j = 1 - i # output string index + a$[j] = "" + k = 1 + while (k <= length(a$[i])) + k0 = k + 1 + while ((k0 <= length(a$[i])) and (mid(a$[i], k, 1) = mid(a$[i], k0, 1))) + k0 = k0 + 1 + end while + a$[j] += string(k0 - k) + mid(a$[i], k, 1) + k = k0 + end while + i = j + print a$[j] +next n diff --git a/Task/Look-and-say-sequence/C++/look-and-say-sequence.cpp b/Task/Look-and-say-sequence/C++/look-and-say-sequence.cpp index 5d42b10a26..f044799d24 100644 --- a/Task/Look-and-say-sequence/C++/look-and-say-sequence.cpp +++ b/Task/Look-and-say-sequence/C++/look-and-say-sequence.cpp @@ -1,32 +1,32 @@ -#include -#include - -std::string lookandsay(const std::string &s) -{ - std::ostringstream r; - - for (unsigned int i = 0; i != s.length(); ) { - unsigned int new_i = s.find_first_not_of(s[i], i+1); - if (new_i == std::string::npos) - new_i = s.length(); - - r << new_i - i << s[i]; - i = new_i; - } - return r.str(); -} - #include +#include +#include + +std::string lookandsay(const std::string& s) +{ + std::ostringstream r; + + for (std::size_t i = 0; i != s.length();) { + auto new_i = s.find_first_not_of(s[i], i + 1); + + if (new_i == std::string::npos) + new_i = s.length(); + + r << new_i - i << s[i]; + i = new_i; + } + return r.str(); +} int main() { - std::string laf = "1"; + std::string laf = "1"; - std::cout << laf << std::endl; - for (int i = 0; i < 10; i++) { - laf = lookandsay(laf); std::cout << laf << std::endl; - } + for (int i = 0; i < 10; ++i) { + laf = lookandsay(laf); + std::cout << laf << std::endl; + } - return 0; + return 0; } diff --git a/Task/Look-and-say-sequence/Ceylon/look-and-say-sequence.ceylon b/Task/Look-and-say-sequence/Ceylon/look-and-say-sequence.ceylon new file mode 100644 index 0000000000..b349b2cf75 --- /dev/null +++ b/Task/Look-and-say-sequence/Ceylon/look-and-say-sequence.ceylon @@ -0,0 +1,28 @@ +shared void run() { + + function lookAndSay(Integer|String input) { + + variable value digits = if (is Integer input) then input.string else input; + value builder = StringBuilder(); + + while (exists currentChar = digits.first) { + if (exists index = digits.firstIndexWhere((char) => char != currentChar)) { + digits = digits[index...]; + builder.append("``index````currentChar``"); + } + else { + builder.append("``digits.size````currentChar``"); + break; + } + } + + return builder.string; + } + + variable String|Integer result = 1; + print(result); + for (i in 1..14) { + result = lookAndSay(result); + print(result); + } +} diff --git a/Task/Look-and-say-sequence/Perl-6/look-and-say-sequence.pl6 b/Task/Look-and-say-sequence/Perl-6/look-and-say-sequence.pl6 index ebbdd0862f..3da04d5684 100644 --- a/Task/Look-and-say-sequence/Perl-6/look-and-say-sequence.pl6 +++ b/Task/Look-and-say-sequence/Perl-6/look-and-say-sequence.pl6 @@ -1 +1 @@ -.say for '1', *.subst(/(.)$0*/, { .chars ~ .[0] }, :g) ... *; +.say for ('1', *.subst(/(.)$0*/, { .chars ~ .[0] }, :g) ... *)[^15]; diff --git a/Task/Look-and-say-sequence/Q/look-and-say-sequence.q b/Task/Look-and-say-sequence/Q/look-and-say-sequence.q new file mode 100644 index 0000000000..57e4bbb318 --- /dev/null +++ b/Task/Look-and-say-sequence/Q/look-and-say-sequence.q @@ -0,0 +1,2 @@ +las:{{raze string[count@'x],'@'[;0]x:where[differ x]_x}\[x;1#"1"]} +las 8 diff --git a/Task/Look-and-say-sequence/Scala/look-and-say-sequence-1.scala b/Task/Look-and-say-sequence/Scala/look-and-say-sequence-1.scala index c513102d28..d36061db5e 100644 --- a/Task/Look-and-say-sequence/Scala/look-and-say-sequence-1.scala +++ b/Task/Look-and-say-sequence/Scala/look-and-say-sequence-1.scala @@ -1,11 +1,27 @@ -def lookAndSay(seed: BigInt) = { - val s = seed.toString - ( 1 until s.size).foldLeft((1, s(0), new StringBuilder)) { - case ((len, c, sb), index) if c != s(index) => sb.append(len); sb.append(c); (1, s(index), sb) - case ((len, c, sb), _) => (len + 1, c, sb) - } match { - case (len, c, sb) => sb.append(len); sb.append(c); BigInt(sb.toString) - } -} +import scala.annotation.tailrec -def lookAndSayIterator(seed: BigInt) = Iterator.iterate(seed)(lookAndSay) +object LookAndSay extends App { + + loop(10, "1") + + @tailrec + private def loop(n: Int, num: String): Unit = { + println(num) + if (n <= 0) () else loop(n - 1, lookandsay(num)) + } + + private def lookandsay(number: String): String = { + val result = new StringBuilder + + @tailrec + def loop(numberString: String, repeat: Char, times: Int): String = + if (numberString.isEmpty) result.toString() + else if (numberString.head != repeat) { + result.append(times).append(repeat) + loop(numberString.tail, numberString.head, 1) + } else loop(numberString.tail, numberString.head, times + 1) + + loop(number.tail + " ", number.head, 1) + } + +} diff --git a/Task/Look-and-say-sequence/Scala/look-and-say-sequence-2.scala b/Task/Look-and-say-sequence/Scala/look-and-say-sequence-2.scala index 9d76326c80..c513102d28 100644 --- a/Task/Look-and-say-sequence/Scala/look-and-say-sequence-2.scala +++ b/Task/Look-and-say-sequence/Scala/look-and-say-sequence-2.scala @@ -1,17 +1,11 @@ -object Main extends App { - - def lookAndSay(previous: List[BigInt]): Stream[List[BigInt]] = { - - def next(num: List[BigInt]): List[BigInt] = num match { - case Nil => Nil - case head :: Nil => 1 :: head :: Nil - case head :: tail => - val size = (num takeWhile (_ == head)).size - List(BigInt(size), head) ::: next(num.drop(size)) - } - val x = next(previous) - x #:: lookAndSay(x) +def lookAndSay(seed: BigInt) = { + val s = seed.toString + ( 1 until s.size).foldLeft((1, s(0), new StringBuilder)) { + case ((len, c, sb), index) if c != s(index) => sb.append(len); sb.append(c); (1, s(index), sb) + case ((len, c, sb), _) => (len + 1, c, sb) + } match { + case (len, c, sb) => sb.append(len); sb.append(c); BigInt(sb.toString) } - - (lookAndSay(1 :: Nil) take 10).foreach(s => println(s.mkString(""))) } + +def lookAndSayIterator(seed: BigInt) = Iterator.iterate(seed)(lookAndSay) diff --git a/Task/Look-and-say-sequence/Scala/look-and-say-sequence-3.scala b/Task/Look-and-say-sequence/Scala/look-and-say-sequence-3.scala new file mode 100644 index 0000000000..9d76326c80 --- /dev/null +++ b/Task/Look-and-say-sequence/Scala/look-and-say-sequence-3.scala @@ -0,0 +1,17 @@ +object Main extends App { + + def lookAndSay(previous: List[BigInt]): Stream[List[BigInt]] = { + + def next(num: List[BigInt]): List[BigInt] = num match { + case Nil => Nil + case head :: Nil => 1 :: head :: Nil + case head :: tail => + val size = (num takeWhile (_ == head)).size + List(BigInt(size), head) ::: next(num.drop(size)) + } + val x = next(previous) + x #:: lookAndSay(x) + } + + (lookAndSay(1 :: Nil) take 10).foreach(s => println(s.mkString(""))) +} diff --git a/Task/Loop-over-multiple-arrays-simultaneously/00DESCRIPTION b/Task/Loop-over-multiple-arrays-simultaneously/00DESCRIPTION index 07402bde0b..befbd6ee78 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/00DESCRIPTION +++ b/Task/Loop-over-multiple-arrays-simultaneously/00DESCRIPTION @@ -17,4 +17,20 @@ to produce the output:
If possible, also describe what happens when the arrays are of different lengths. + + +;Related tasks: +*   [[Loop over multiple arrays simultaneously]] +*   [[Loops/Break]] +*   [[Loops/Continue]] +*   [[Loops/Do-while]] +*   [[Loops/Downward for]] +*   [[Loops/For]] +*   [[Loops/For with a specified step]] +*   [[Loops/Foreach]] +*   [[Loops/Increment loop index within loop body]] +*   [[Loops/Infinite]] +*   [[Loops/N plus one half]] +*   [[Loops/Nested]] +*   [[Loops/While]]

diff --git a/Task/Loop-over-multiple-arrays-simultaneously/AppleScript/loop-over-multiple-arrays-simultaneously.applescript b/Task/Loop-over-multiple-arrays-simultaneously/AppleScript/loop-over-multiple-arrays-simultaneously-1.applescript similarity index 100% rename from Task/Loop-over-multiple-arrays-simultaneously/AppleScript/loop-over-multiple-arrays-simultaneously.applescript rename to Task/Loop-over-multiple-arrays-simultaneously/AppleScript/loop-over-multiple-arrays-simultaneously-1.applescript diff --git a/Task/Loop-over-multiple-arrays-simultaneously/AppleScript/loop-over-multiple-arrays-simultaneously-2.applescript b/Task/Loop-over-multiple-arrays-simultaneously/AppleScript/loop-over-multiple-arrays-simultaneously-2.applescript new file mode 100644 index 0000000000..eb5d3405e6 --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/AppleScript/loop-over-multiple-arrays-simultaneously-2.applescript @@ -0,0 +1,75 @@ +-- CONCAT MAPPED OVER A TRANSPOSITION ---------------------------------------- +on run + + unlines(map(concat, transpose([["a", "b", "c"], ["A", "B", "C"], [1, 2, 3]]))) + +end run + +-- GENERIC FUNCTIONS --------------------------------------------------------- + +-- concat :: [[a]] -> [a] | [String] -> String +on concat(xs) + if length of xs > 0 and class of (item 1 of xs) is string then + set acc to "" + else + set acc to {} + end if + repeat with i from 1 to length of xs + set acc to acc & item i of xs + end repeat + acc +end concat + +-- intercalate :: String -> [String] -> String +on intercalate(s, xs) + set {dlm, my text item delimiters} to {my text item delimiters, s} + set str to xs as text + set my text item delimiters to dlm + return str +end intercalate + +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn + +-- transpose :: [[a]] -> [[a]] +on transpose(xss) + script column + on |λ|(_, iCol) + script row + on |λ|(xs) + item iCol of xs + end |λ| + end script + + map(row, xss) + end |λ| + end script + + map(column, item 1 of xss) +end transpose + +-- unlines :: [String] -> String +on unlines(xs) + intercalate(linefeed, xs) +end unlines diff --git a/Task/Loop-over-multiple-arrays-simultaneously/JavaScript/loop-over-multiple-arrays-simultaneously-5.js b/Task/Loop-over-multiple-arrays-simultaneously/JavaScript/loop-over-multiple-arrays-simultaneously-5.js index 9d1865b7f3..d9d00a67d4 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/JavaScript/loop-over-multiple-arrays-simultaneously-5.js +++ b/Task/Loop-over-multiple-arrays-simultaneously/JavaScript/loop-over-multiple-arrays-simultaneously-5.js @@ -11,23 +11,15 @@ }); } - - - - // Sample function over a list - // concat :: [a] -> s function concat(lst) { return ''.concat.apply('', lst); } - - // TEST - + // TEST return zipListsWith( concat, [["a", "b", "c"], ["A", "B", "C"], [1, 2, 3]] ) .join('\n'); - })(); diff --git a/Task/Loop-over-multiple-arrays-simultaneously/JavaScript/loop-over-multiple-arrays-simultaneously-7.js b/Task/Loop-over-multiple-arrays-simultaneously/JavaScript/loop-over-multiple-arrays-simultaneously-7.js new file mode 100644 index 0000000000..d3db50152a --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/JavaScript/loop-over-multiple-arrays-simultaneously-7.js @@ -0,0 +1,33 @@ +(() => { + 'use strict'; + + // GENERIC FUNCTIONS ----------------------------------------------------- + + // concat :: [[a]] -> [a] + const concat = xs => + xs.length > 0 ? (() => { + const unit = typeof xs[0] === 'string' ? '' : []; + return unit.concat.apply(unit, xs); + })() : []; + + // map :: (a -> b) -> [a] -> [b] + const map = (f, xs) => xs.map(f); + + // transpose :: [[a]] -> [[a]] + const transpose = xs => + xs[0].map((_, col) => xs.map(row => row[col])); + + // unlines :: [String] -> String + const unlines = xs => xs.join('\n'); + + // TEST ------------------------------------------------------------------ + const xs = [ + ['a', 'b', 'c'], + ['A', 'B', 'C'], + [1, 2, 3] + ]; + + return unlines( + map(concat, transpose(xs)) + ); +})(); diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Julia/loop-over-multiple-arrays-simultaneously-1.julia b/Task/Loop-over-multiple-arrays-simultaneously/Julia/loop-over-multiple-arrays-simultaneously-1.julia index 681e51a6f6..c423d88ba0 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Julia/loop-over-multiple-arrays-simultaneously-1.julia +++ b/Task/Loop-over-multiple-arrays-simultaneously/Julia/loop-over-multiple-arrays-simultaneously-1.julia @@ -1,5 +1 @@ -julia> map(println, -('a','b','c'),('A','B','C'),(1,2,3)) ; -aA1 -bB2 -cC3 +foreach(println, ('a', 'b', 'c'), ('A', 'B', 'C'), (1, 2, 3)) diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Julia/loop-over-multiple-arrays-simultaneously-2.julia b/Task/Loop-over-multiple-arrays-simultaneously/Julia/loop-over-multiple-arrays-simultaneously-2.julia index c28963bed7..507b03c3ed 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Julia/loop-over-multiple-arrays-simultaneously-2.julia +++ b/Task/Loop-over-multiple-arrays-simultaneously/Julia/loop-over-multiple-arrays-simultaneously-2.julia @@ -1,7 +1,3 @@ -julia> for (i,j,k) in -zip(('a','b','c'),('A','B','C'),(1,2,3)) - println(i,j,k) - end -aA1 -bB2 -cC3 +for (i, j, k) in zip(('a', 'b', 'c'), ('A', 'B', 'C'), (1, 2, 3)) + println(i, j, k) +end diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Red/loop-over-multiple-arrays-simultaneously.red b/Task/Loop-over-multiple-arrays-simultaneously/Red/loop-over-multiple-arrays-simultaneously.red new file mode 100644 index 0000000000..b5d6f156f3 --- /dev/null +++ b/Task/Loop-over-multiple-arrays-simultaneously/Red/loop-over-multiple-arrays-simultaneously.red @@ -0,0 +1,7 @@ +>>blk: [["a" "b" "c"] ["A" "B" "C"] [1 2 3]] +== [["a" "b" "c"] ["A" "B" "C"] [1 2 3]] + +>> repeat counter 3 [print [blk/1/:counter blk/2/:counter blk/3/:counter]] +a A 1 +b B 2 +c C 3 diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Sidef/loop-over-multiple-arrays-simultaneously.sidef b/Task/Loop-over-multiple-arrays-simultaneously/Sidef/loop-over-multiple-arrays-simultaneously.sidef index b339a883cd..be0509c23c 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/Sidef/loop-over-multiple-arrays-simultaneously.sidef +++ b/Task/Loop-over-multiple-arrays-simultaneously/Sidef/loop-over-multiple-arrays-simultaneously.sidef @@ -1,3 +1,3 @@ -MultiArray.new(%w(a b c),%w(A B C),%w(1 2 3)).each { |i,j,k| - say (i, j, k); +[%w(a b c),%w(A B C),%w(1 2 3)].zip { |i,j,k| + say (i, j, k) } diff --git a/Task/Loops-Break/00DESCRIPTION b/Task/Loops-Break/00DESCRIPTION index 4ab8eb5a1c..99bc55d578 100644 --- a/Task/Loops-Break/00DESCRIPTION +++ b/Task/Loops-Break/00DESCRIPTION @@ -1,9 +1,25 @@ ;Task: -Show a loop which prints random numbers (each number newly generated each loop) from   '''0'''   to   '''19'''   (inclusive). +Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). -If a number is   '''0'''   stop the loop after printing it, and do not generate any further numbers. +If a number is 10, stop the loop after printing it, and do not generate any further numbers. Otherwise, generate and print a second random number before restarting the loop. -If the number   '''0'''   is never generated as the first number in a loop, loop forever. +If the number 10 is never generated as the first number in a loop, loop forever. + + +;Related tasks: +*   [[Loop over multiple arrays simultaneously]] +*   [[Loops/Break]] +*   [[Loops/Continue]] +*   [[Loops/Do-while]] +*   [[Loops/Downward for]] +*   [[Loops/For]] +*   [[Loops/For with a specified step]] +*   [[Loops/Foreach]] +*   [[Loops/Increment loop index within loop body]] +*   [[Loops/Infinite]] +*   [[Loops/N plus one half]] +*   [[Loops/Nested]] +*   [[Loops/While]]

diff --git a/Task/Loops-Break/ALGOL-60/loops-break.alg b/Task/Loops-Break/ALGOL-60/loops-break.alg new file mode 100644 index 0000000000..f8b732f946 --- /dev/null +++ b/Task/Loops-Break/ALGOL-60/loops-break.alg @@ -0,0 +1,25 @@ +'BEGIN' 'COMMENT' Loops/Break - ALGOL60 - 18/06/2018; + 'INTEGER' SEED; + 'INTEGER' 'PROCEDURE' RANDOM(N); + 'VALUE' N; 'INTEGER' N; + 'BEGIN' + SEED:=(SEED*19157+12347) '/' 21647; + RANDOM:=SEED-(SEED '/' N)*N+1 + 'END' RANDOM; + 'INTEGER' I,J,K; + SYSACT(1,6,120);SYSACT(1,8,60);SYSACT(1,12,1);'COMMENT' open print; + SEED:=31567; + J:=0; + 'FOR' I:=1, I+1 'WHILE' I 'LESS' 100 'DO' 'BEGIN' + J:=J+1; + K:=RANDOM(20); + OUTINTEGER(1,K); + 'IF' J=8 'THEN' 'BEGIN' + SYSACT(1,14,1); 'COMMENT' skip line; + J:=0 + 'END'; + 'IF' K=10 'THEN' 'GOTO' LAB + 'END'; +LAB: + SYSACT(1,14,1); 'COMMENT' skip line; +'END' diff --git a/Task/Loops-Break/Arc/loops-break.arc b/Task/Loops-Break/Arc/loops-break.arc index 6c96c12327..05913189d5 100644 --- a/Task/Loops-Break/Arc/loops-break.arc +++ b/Task/Loops-Break/Arc/loops-break.arc @@ -2,6 +2,6 @@ (while t (let x (rand 20) (prn "a: " x) - (if (is x 0) + (if (is x 10) (break))) (prn "b: " (rand 20)))) diff --git a/Task/Loops-Break/BASIC/loops-break-1.basic b/Task/Loops-Break/BASIC/loops-break-1.basic index 16db0aca4a..a238d0663f 100644 --- a/Task/Loops-Break/BASIC/loops-break-1.basic +++ b/Task/Loops-Break/BASIC/loops-break-1.basic @@ -1,7 +1,7 @@ REPEAT number = RANDOM(20) PRINT "first " ,number - IF number = 0 THEN + IF number = 10 THEN BREAK ENDIF PRINT "second ",RANDOM(20) diff --git a/Task/Loops-Break/C++/loops-break.cpp b/Task/Loops-Break/C++/loops-break.cpp index 995f1f9806..cb174cf5ac 100644 --- a/Task/Loops-Break/C++/loops-break.cpp +++ b/Task/Loops-Break/C++/loops-break.cpp @@ -2,17 +2,15 @@ #include #include -int main() -{ - srand(time(0)); - while(true) - { - int a = 0 + rand() % 19; - std::cout << a << std::endl; - if (a == 10) - break; - int b = 0 + rand() % 19; - std::cout << b << std::endl; - } - return 0; +int main(){ + srand(time(NULL)); // randomize seed + while(true){ + const int a = rand() % 20; // biased towards lower numbers if RANDMAX % 20 > 0 + std::cout << a << std::endl; + if(a == 10) + break; + const int b = rand() % 20; + std::cout << b << std::endl; + } + return 0; } diff --git a/Task/Loops-Break/C/loops-break.c b/Task/Loops-Break/C/loops-break.c index 74a4447c0a..c82373ef38 100644 --- a/Task/Loops-Break/C/loops-break.c +++ b/Task/Loops-Break/C/loops-break.c @@ -1,18 +1,14 @@ -/*Corrected by Abhishek Ghosh, Mahalaya (19th September) 2017*/ - -#include -#include -#include - -int main() { +int main(){ time_t t; - int a; - srand((unsigned)time(&t)); - - for (;;) { - a = rand()%20; - printf("%d\n", a); - if (a == 0) break; - } - return 0; + int a, b; + srand((unsigned)time(&t)); + for(;;){ + a = rand() % 20; + printf("%d\n", a); + if(a == 10) + break; + b = rand() % 20; + printf("%d\n", b); + } + return 0; } diff --git a/Task/Loops-Break/HolyC/loops-break.holyc b/Task/Loops-Break/HolyC/loops-break.holyc index e525d99b74..fbcecb7fb9 100644 --- a/Task/Loops-Break/HolyC/loops-break.holyc +++ b/Task/Loops-Break/HolyC/loops-break.holyc @@ -3,7 +3,7 @@ while (1) { a = RandU16 % 20; Print("%d\n", a); - if (a == 0) break; + if (a == 10) break; b = RandU16 % 20; Print("%d\n", b); diff --git a/Task/Loops-Break/REXX/loops-break.rexx b/Task/Loops-Break/REXX/loops-break.rexx index 25a2aa6977..0ffb1b6838 100644 --- a/Task/Loops-Break/REXX/loops-break.rexx +++ b/Task/Loops-Break/REXX/loops-break.rexx @@ -1,10 +1,10 @@ -/*REXX program demonstrates a FOREVER DO loop with a test to LEAVE (break). */ - +/*REXX program demonstrates a FOREVER DO loop with a test to LEAVE (break). */ + /*REXX's RANDOM BIF returns an integer.*/ do forever /*perform loop until da cows come home.*/ a=random(19) /*same as: random(0, 19) */ call charout , right(a, 5) /*show A right─justified, column 1.*/ if a==10 then leave /*is random #=10? Then cows came home.*/ b=random(19) /*same as: random(0, 19) */ say right(b, 5) /*show B right─justified, column 2.*/ - end /*forever*/ + end /*forever*/ /* [↑] CHAROUT , xxx writes to term.*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Loops-Break/Stata/loops-break.stata b/Task/Loops-Break/Stata/loops-break-1.stata similarity index 100% rename from Task/Loops-Break/Stata/loops-break.stata rename to Task/Loops-Break/Stata/loops-break-1.stata diff --git a/Task/Loops-Break/Stata/loops-break-2.stata b/Task/Loops-Break/Stata/loops-break-2.stata new file mode 100644 index 0000000000..c7b9902246 --- /dev/null +++ b/Task/Loops-Break/Stata/loops-break-2.stata @@ -0,0 +1,5 @@ +for (; 1; ) { + printf("%f\n",n=runiformint(1,1,0,19)) + if (n==10) break + printf("%f\n",runiformint(1,1,0,19)) +} diff --git a/Task/Loops-Continue/00DESCRIPTION b/Task/Loops-Continue/00DESCRIPTION index 51874ceb71..23cffdc6af 100644 --- a/Task/Loops-Continue/00DESCRIPTION +++ b/Task/Loops-Continue/00DESCRIPTION @@ -9,4 +9,20 @@ Show the following output using one loop. Try to achieve the result by forcing the next iteration within the loop upon a specific condition, if your language allows it. + + +;Related tasks: +*   [[Loop over multiple arrays simultaneously]] +*   [[Loops/Break]] +*   [[Loops/Continue]] +*   [[Loops/Do-while]] +*   [[Loops/Downward for]] +*   [[Loops/For]] +*   [[Loops/For with a specified step]] +*   [[Loops/Foreach]] +*   [[Loops/Increment loop index within loop body]] +*   [[Loops/Infinite]] +*   [[Loops/N plus one half]] +*   [[Loops/Nested]] +*   [[Loops/While]]

diff --git a/Task/Loops-Continue/D/loops-continue.d b/Task/Loops-Continue/D/loops-continue-1.d similarity index 100% rename from Task/Loops-Continue/D/loops-continue.d rename to Task/Loops-Continue/D/loops-continue-1.d diff --git a/Task/Loops-Continue/D/loops-continue-2.d b/Task/Loops-Continue/D/loops-continue-2.d new file mode 100644 index 0000000000..a295fa121b --- /dev/null +++ b/Task/Loops-Continue/D/loops-continue-2.d @@ -0,0 +1,6 @@ +import std.stdio; + +void main() +{ + foreach(i; 1..11) i % 5 ? writef("%s, ", i) : writeln(i); +} diff --git a/Task/Loops-Continue/Red/loops-continue.red b/Task/Loops-Continue/Red/loops-continue.red new file mode 100644 index 0000000000..5e734b3f6e --- /dev/null +++ b/Task/Loops-Continue/Red/loops-continue.red @@ -0,0 +1,7 @@ +repeat i 10 [ + prin i + if i = 10 [break] + either i = 5 [print ""][prin ","] +] +1,2,3,4,5 +6,7,8,9,10 diff --git a/Task/Loops-Do-while/00DESCRIPTION b/Task/Loops-Do-while/00DESCRIPTION index 06410343d4..c29de3843e 100644 --- a/Task/Loops-Do-while/00DESCRIPTION +++ b/Task/Loops-Do-while/00DESCRIPTION @@ -2,5 +2,23 @@ Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. + +;Related tasks: +*   [[Loop over multiple arrays simultaneously]] +*   [[Loops/Break]] +*   [[Loops/Continue]] +*   [[Loops/Do-while]] +*   [[Loops/Downward for]] +*   [[Loops/For]] +*   [[Loops/For with a specified step]] +*   [[Loops/Foreach]] +*   [[Loops/Increment loop index within loop body]] +*   [[Loops/Infinite]] +*   [[Loops/N plus one half]] +*   [[Loops/Nested]] +*   [[Loops/While]] + + ;Reference: * [[wp:Do while loop|Do while loop]] Wikipedia. +

diff --git a/Task/Loops-Do-while/Fortress/loops-do-while.fortress b/Task/Loops-Do-while/Fortress/loops-do-while.fortress new file mode 100644 index 0000000000..ce5dec58f0 --- /dev/null +++ b/Task/Loops-Do-while/Fortress/loops-do-while.fortress @@ -0,0 +1,15 @@ +component loops_do_while + export Executable + + var x:ZZ32 = 0 + run() = label loop + while true do + x += 1 + println(x) + + if (x MOD 6) = 0 + then exit loop + end + end + end loop +end diff --git a/Task/Loops-Do-while/GW-BASIC/loops-do-while-1.gw-basic b/Task/Loops-Do-while/GW-BASIC/loops-do-while-1.gw-basic new file mode 100644 index 0000000000..98043fd782 --- /dev/null +++ b/Task/Loops-Do-while/GW-BASIC/loops-do-while-1.gw-basic @@ -0,0 +1,8 @@ +10 LET I% = 0 +20 ' first iteration - before the WHILE +30 PRINT I% +40 LET I% = I% + 1 +50 WHILE I% MOD 6 <> 0 +60 PRINT I% +70 LET I% = I% + 1 +80 WEND diff --git a/Task/Loops-Do-while/GW-BASIC/loops-do-while-2.gw-basic b/Task/Loops-Do-while/GW-BASIC/loops-do-while-2.gw-basic new file mode 100644 index 0000000000..3f8cee5975 --- /dev/null +++ b/Task/Loops-Do-while/GW-BASIC/loops-do-while-2.gw-basic @@ -0,0 +1,4 @@ +10 LET I% = 0 +20 PRINT I% +30 LET I% = I% + 1 +40 IF I% MOD 6 <> 0 THEN GOTO 20 diff --git a/Task/Loops-Do-while/Haskell/loops-do-while-4.hs b/Task/Loops-Do-while/Haskell/loops-do-while-4.hs new file mode 100644 index 0000000000..1dd3d7083f --- /dev/null +++ b/Task/Loops-Do-while/Haskell/loops-do-while-4.hs @@ -0,0 +1,10 @@ +import Data.IORef +import Control.Monad.Loops + +main = do + x <- newIORef 0; + iterateWhile (\val -> val `mod` 6 /= 0 ) $ do + modifyIORef x (+1) + val <- readIORef x + print val + return val diff --git a/Task/Loops-Do-while/JavaScript/loops-do-while-8.js b/Task/Loops-Do-while/JavaScript/loops-do-while-8.js new file mode 100644 index 0000000000..3a3a9a142d --- /dev/null +++ b/Task/Loops-Do-while/JavaScript/loops-do-while-8.js @@ -0,0 +1,20 @@ +// generator with the do while loop +function* getValue(stop) { + var i = 0; + do { + yield ++i; + } while (i % stop != 0); +} + +// function to print the value and invoke next +function printVal(g, v) { + if (!v.done) { + console.log(v.value); + setImmediate(printVal, g, g.next()); + } +} + +(() => { + var gen = getValue(6); + printVal(gen, gen.next()); +})(); diff --git a/Task/Loops-Do-while/JavaScript/loops-do-while-9.js b/Task/Loops-Do-while/JavaScript/loops-do-while-9.js new file mode 100644 index 0000000000..b414108e81 --- /dev/null +++ b/Task/Loops-Do-while/JavaScript/loops-do-while-9.js @@ -0,0 +1,6 @@ +1 +2 +3 +4 +5 +6 diff --git a/Task/Loops-Do-while/Nim/loops-do-while.nim b/Task/Loops-Do-while/Nim/loops-do-while.nim index 279db83be2..8cabbb9c78 100644 --- a/Task/Loops-Do-while/Nim/loops-do-while.nim +++ b/Task/Loops-Do-while/Nim/loops-do-while.nim @@ -1,4 +1,4 @@ -template doWhile(a: expr, b: stmt): stmt = +template doWhile(a, b: untyped): untyped = b while a: b diff --git a/Task/Loops-Do-while/Red/loops-do-while.red b/Task/Loops-Do-while/Red/loops-do-while.red new file mode 100644 index 0000000000..1b021df3b7 --- /dev/null +++ b/Task/Loops-Do-while/Red/loops-do-while.red @@ -0,0 +1,7 @@ +Red [] +i: 0 +until [ + ?? i + i: i + 1 + i % 6 = 0 ;; loop , until this is true... +] diff --git a/Task/Loops-Downward-for/00DESCRIPTION b/Task/Loops-Downward-for/00DESCRIPTION index e7e122640e..6714247524 100644 --- a/Task/Loops-Downward-for/00DESCRIPTION +++ b/Task/Loops-Downward-for/00DESCRIPTION @@ -1,3 +1,19 @@ ;Task: Write a   ''for''   loop which writes a countdown from   '''10'''   to   '''0'''. + + +;Related tasks: +*   [[Loop over multiple arrays simultaneously]] +*   [[Loops/Break]] +*   [[Loops/Continue]] +*   [[Loops/Do-while]] +*   [[Loops/Downward for]] +*   [[Loops/For]] +*   [[Loops/For with a specified step]] +*   [[Loops/Foreach]] +*   [[Loops/Increment loop index within loop body]] +*   [[Loops/Infinite]] +*   [[Loops/N plus one half]] +*   [[Loops/Nested]] +*   [[Loops/While]]

diff --git a/Task/Loops-Downward-for/GW-BASIC/loops-downward-for.gw-basic b/Task/Loops-Downward-for/GW-BASIC/loops-downward-for.gw-basic new file mode 100644 index 0000000000..268153d083 --- /dev/null +++ b/Task/Loops-Downward-for/GW-BASIC/loops-downward-for.gw-basic @@ -0,0 +1,3 @@ +10 FOR I% = 10 TO 0 STEP -1 +20 PRINT I% +30 NEXT I% diff --git a/Task/Loops-For-with-a-specified-step/00DESCRIPTION b/Task/Loops-For-with-a-specified-step/00DESCRIPTION index 9fece5f7c2..798bd1ed49 100644 --- a/Task/Loops-For-with-a-specified-step/00DESCRIPTION +++ b/Task/Loops-For-with-a-specified-step/00DESCRIPTION @@ -1,2 +1,18 @@ Demonstrate a for-loop where the step-value is greater than one. + + +;Related tasks: +*   [[Loop over multiple arrays simultaneously]] +*   [[Loops/Break]] +*   [[Loops/Continue]] +*   [[Loops/Do-while]] +*   [[Loops/Downward for]] +*   [[Loops/For]] +*   [[Loops/For with a specified step]] +*   [[Loops/Foreach]] +*   [[Loops/Increment loop index within loop body]] +*   [[Loops/Infinite]] +*   [[Loops/N plus one half]] +*   [[Loops/Nested]] +*   [[Loops/While]]

diff --git a/Task/Loops-For-with-a-specified-step/Simula/loops-for-with-a-specified-step.simula b/Task/Loops-For-with-a-specified-step/Simula/loops-for-with-a-specified-step.simula index 8160f33e91..a156632a0b 100644 --- a/Task/Loops-For-with-a-specified-step/Simula/loops-for-with-a-specified-step.simula +++ b/Task/Loops-For-with-a-specified-step/Simula/loops-for-with-a-specified-step.simula @@ -1,4 +1,4 @@ begin - integer i; - for i:=5 step 5 until 25 do outint(i,5) - end + integer i; + for i:=5 step 5 until 25 do outint(i, 5) +end diff --git a/Task/Loops-For/00DESCRIPTION b/Task/Loops-For/00DESCRIPTION index 8b0ffcc121..8ac3f2476b 100644 --- a/Task/Loops-For/00DESCRIPTION +++ b/Task/Loops-For/00DESCRIPTION @@ -16,6 +16,23 @@ Specifically print out the following pattern by using one for loop nested in ano ***** +;Related tasks: +*   [[Loop over multiple arrays simultaneously]] +*   [[Loops/Break]] +*   [[Loops/Continue]] +*   [[Loops/Do-while]] +*   [[Loops/Downward for]] +*   [[Loops/For]] +*   [[Loops/For with a specified step]] +*   [[Loops/Foreach]] +*   [[Loops/Increment loop index within loop body]] +*   [[Loops/Infinite]] +*   [[Loops/N plus one half]] +*   [[Loops/Nested]] +*   [[Loops/While]] +

+ + ;Reference: * [[wp:For loop|For loop]] Wikipedia.

diff --git a/Task/Loops-For/BASIC/loops-for-10.basic b/Task/Loops-For/BASIC/loops-for-10.basic index 4274287f65..6a349b11fd 100644 --- a/Task/Loops-For/BASIC/loops-for-10.basic +++ b/Task/Loops-For/BASIC/loops-for-10.basic @@ -1,11 +1,6 @@ -If OpenConsole() - Define i, j - For i=1 To 5 - For j=1 To i - Print("*") - Next j - PrintN("") - Next i - Print(#LFCR$+"Press ENTER to quit"): Input() - CloseConsole() -EndIf +For i = 1 TO 5 + For j = 1 To i + TextWindow.Write("*") + EndFor + TextWindow.WriteLine("") +EndFor diff --git a/Task/Loops-For/BASIC/loops-for-11.basic b/Task/Loops-For/BASIC/loops-for-11.basic index 5ceebe6ca5..4274287f65 100644 --- a/Task/Loops-For/BASIC/loops-for-11.basic +++ b/Task/Loops-For/BASIC/loops-for-11.basic @@ -1,6 +1,11 @@ -FOR i = 1 TO 5 - FOR j = 1 TO i - PRINT "*"; - NEXT j - PRINT -NEXT i +If OpenConsole() + Define i, j + For i=1 To 5 + For j=1 To i + Print("*") + Next j + PrintN("") + Next i + Print(#LFCR$+"Press ENTER to quit"): Input() + CloseConsole() +EndIf diff --git a/Task/Loops-For/BASIC/loops-for-12.basic b/Task/Loops-For/BASIC/loops-for-12.basic index 00e37cdeaf..5ceebe6ca5 100644 --- a/Task/Loops-For/BASIC/loops-for-12.basic +++ b/Task/Loops-For/BASIC/loops-for-12.basic @@ -1,6 +1,6 @@ -for n = 1 to 5 - for m = 1 to n - print "*"; - next m - print -next n +FOR i = 1 TO 5 + FOR j = 1 TO i + PRINT "*"; + NEXT j + PRINT +NEXT i diff --git a/Task/Loops-For/BASIC/loops-for-13.basic b/Task/Loops-For/BASIC/loops-for-13.basic index 92571e13cc..00e37cdeaf 100644 --- a/Task/Loops-For/BASIC/loops-for-13.basic +++ b/Task/Loops-For/BASIC/loops-for-13.basic @@ -1,7 +1,6 @@ -Public OutConsole As Scripting.TextStream -For i = 0 To 4 - For j = 0 To i - OutConsole.Write "*" - Next j - OutConsole.WriteLine -Next i +for n = 1 to 5 + for m = 1 to n + print "*"; + next m + print +next n diff --git a/Task/Loops-For/BASIC/loops-for-14.basic b/Task/Loops-For/BASIC/loops-for-14.basic index a38aab1aa9..92571e13cc 100644 --- a/Task/Loops-For/BASIC/loops-for-14.basic +++ b/Task/Loops-For/BASIC/loops-for-14.basic @@ -1,6 +1,7 @@ -For x As Integer = 0 To 4 - For y As Integer = 0 To x - Console.Write("*") - Next - Console.WriteLine() -Next +Public OutConsole As Scripting.TextStream +For i = 0 To 4 + For j = 0 To i + OutConsole.Write "*" + Next j + OutConsole.WriteLine +Next i diff --git a/Task/Loops-For/BASIC/loops-for-15.basic b/Task/Loops-For/BASIC/loops-for-15.basic index f47f2192b5..a38aab1aa9 100644 --- a/Task/Loops-For/BASIC/loops-for-15.basic +++ b/Task/Loops-For/BASIC/loops-for-15.basic @@ -1,6 +1,6 @@ -10 FOR i = 1 TO 5 -20 FOR j = 1 TO i -30 PRINT "*"; -40 NEXT j -50 PRINT -60 NEXT i +For x As Integer = 0 To 4 + For y As Integer = 0 To x + Console.Write("*") + Next + Console.WriteLine() +Next diff --git a/Task/Loops-For/BASIC/loops-for-16.basic b/Task/Loops-For/BASIC/loops-for-16.basic index a648453b8f..f47f2192b5 100644 --- a/Task/Loops-For/BASIC/loops-for-16.basic +++ b/Task/Loops-For/BASIC/loops-for-16.basic @@ -1,6 +1,6 @@ -10 FOR I = 1 TO 5 -20 FOR J = 1 TO I +10 FOR i = 1 TO 5 +20 FOR j = 1 TO i 30 PRINT "*"; -40 NEXT +40 NEXT j 50 PRINT -60 NEXT +60 NEXT i diff --git a/Task/Loops-For/BASIC/loops-for-17.basic b/Task/Loops-For/BASIC/loops-for-17.basic new file mode 100644 index 0000000000..a648453b8f --- /dev/null +++ b/Task/Loops-For/BASIC/loops-for-17.basic @@ -0,0 +1,6 @@ +10 FOR I = 1 TO 5 +20 FOR J = 1 TO I +30 PRINT "*"; +40 NEXT +50 PRINT +60 NEXT diff --git a/Task/Loops-For/C++/loops-for.cpp b/Task/Loops-For/C++/loops-for.cpp index afcd4752bc..8e405b18d3 100644 --- a/Task/Loops-For/C++/loops-for.cpp +++ b/Task/Loops-For/C++/loops-for.cpp @@ -1,5 +1,6 @@ -for(int i = 1; i <= 5; ++i) { - for(int j = 1; j <= i; j++) - std::cout << "*"; - std::cout << std::endl; +for(int i = 0; i < 5; ++i) { + for(int j = 0; j < i; ++j) + std::cout.put('*'); + + std::cout.put('\n'); } diff --git a/Task/Loops-For/Klong/loops-for.klong b/Task/Loops-For/Klong/loops-for.klong new file mode 100644 index 0000000000..64b8685fde --- /dev/null +++ b/Task/Loops-For/Klong/loops-for.klong @@ -0,0 +1,10 @@ +:" x{p}:*y means repeat {p} x times starting at y " + +5{x{.d(0c*);x}:*0;.p("");x+1}:*1 + +:" But you would not do it like this! " +:" You would reshape 0c* to the desired length " +:" in a function and then iterate that function " +:" over a vector of numbers: " + +{.p(x:^0c*)}'1+!5 diff --git a/Task/Loops-For/PHP/loops-for-3.php b/Task/Loops-For/PHP/loops-for-3.php new file mode 100644 index 0000000000..6c8a3ee906 --- /dev/null +++ b/Task/Loops-For/PHP/loops-for-3.php @@ -0,0 +1,2 @@ +foreach (range(1, 5) as $i) + echo str_repeat('*', $i) , PHP_EOL; diff --git a/Task/Loops-For/Perl/loops-for-1.pl b/Task/Loops-For/Perl/loops-for-1.pl index 33d76039e0..b023d302fe 100644 --- a/Task/Loops-For/Perl/loops-for-1.pl +++ b/Task/Loops-For/Perl/loops-for-1.pl @@ -1,5 +1,5 @@ -for ($x = 1; $x <= 5; $x++) { - for ($y = 1; $y <= $x; $y++) { +for(my $x = 1; $x <= 5; $x++) { + for(my $y = 1; $y <= $x; $y++) { print "*"; } print "\n"; diff --git a/Task/Loops-For/Perl/loops-for-3.pl b/Task/Loops-For/Perl/loops-for-3.pl index e7464336af..8bea32704c 100644 --- a/Task/Loops-For/Perl/loops-for-3.pl +++ b/Task/Loops-For/Perl/loops-for-3.pl @@ -1 +1 @@ -print ('*' x $_ . "\n") for 1..5 +print ('*' x $_ . "\n") for 1..5; diff --git a/Task/Loops-For/Perl/loops-for-4.pl b/Task/Loops-For/Perl/loops-for-4.pl new file mode 100644 index 0000000000..ad93b645d7 --- /dev/null +++ b/Task/Loops-For/Perl/loops-for-4.pl @@ -0,0 +1 @@ +map {print '*' x $_ . "\n"} 1..5; diff --git a/Task/Loops-For/Python/loops-for-3.py b/Task/Loops-For/Python/loops-for-3.py new file mode 100644 index 0000000000..a1bbe01f50 --- /dev/null +++ b/Task/Loops-For/Python/loops-for-3.py @@ -0,0 +1 @@ +print('\n'.join('*' * i for i in range(1, 6))) diff --git a/Task/Loops-For/Rust/loops-for.rust b/Task/Loops-For/Rust/loops-for.rust index f1aa7c0f6d..abc7e37ddf 100644 --- a/Task/Loops-For/Rust/loops-for.rust +++ b/Task/Loops-For/Rust/loops-for.rust @@ -1,7 +1,9 @@ -for i in 0..5 { - for _ in 0..(i + 1) { - print!("*"); - } +fn main() { + for i in 0..5 { + for _ in 0..(i + 1) { + print!("*"); + } - print!("\n"); + println!(); + } } diff --git a/Task/Loops-For/Stata/loops-for.stata b/Task/Loops-For/Stata/loops-for-1.stata similarity index 100% rename from Task/Loops-For/Stata/loops-for.stata rename to Task/Loops-For/Stata/loops-for-1.stata diff --git a/Task/Loops-For/Stata/loops-for-2.stata b/Task/Loops-For/Stata/loops-for-2.stata new file mode 100644 index 0000000000..602868182f --- /dev/null +++ b/Task/Loops-For/Stata/loops-for-2.stata @@ -0,0 +1,4 @@ +for (i=1; i<=5; i++) { + for (j=1; j<=i; j++) printf("*") + printf("\n") +} diff --git a/Task/Loops-Foreach/00DESCRIPTION b/Task/Loops-Foreach/00DESCRIPTION index a7821a45cf..7247beb750 100644 --- a/Task/Loops-Foreach/00DESCRIPTION +++ b/Task/Loops-Foreach/00DESCRIPTION @@ -1,4 +1,20 @@ Loop through and print each element in a collection in order. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. + + +;Related tasks: +*   [[Loop over multiple arrays simultaneously]] +*   [[Loops/Break]] +*   [[Loops/Continue]] +*   [[Loops/Do-while]] +*   [[Loops/Downward for]] +*   [[Loops/For]] +*   [[Loops/For with a specified step]] +*   [[Loops/Foreach]] +*   [[Loops/Increment loop index within loop body]] +*   [[Loops/Infinite]] +*   [[Loops/N plus one half]] +*   [[Loops/Nested]] +*   [[Loops/While]]

diff --git a/Task/Loops-Foreach/Aime/loops-foreach.aime b/Task/Loops-Foreach/Aime/loops-foreach.aime new file mode 100644 index 0000000000..77c0ca4a4d --- /dev/null +++ b/Task/Loops-Foreach/Aime/loops-foreach.aime @@ -0,0 +1,5 @@ +# iterate over a list of integers +integer i, v; + +for (i, v in list(2, 3, 5, 7, 11, 13, 17, 18)) { +} diff --git a/Task/Loops-Foreach/Red/loops-foreach.red b/Task/Loops-Foreach/Red/loops-foreach.red new file mode 100644 index 0000000000..1ebab00b29 --- /dev/null +++ b/Task/Loops-Foreach/Red/loops-foreach.red @@ -0,0 +1,25 @@ +>> blk: ["John" 23 "dave" 30 "bob" 20 "Jeff" 40] +>> foreach item blk [print item] +John +23 +dave +30 +bob +20 +Jeff +40 +>> foreach [name age] blk [print [name "is" age "years old"]] +John is 23 years old +dave is 30 years old +bob is 20 years old +Jeff is 40 years old + +>> forall blk [print blk] +John 23 dave 30 bob 20 Jeff 40 +23 dave 30 bob 20 Jeff 40 +dave 30 bob 20 Jeff 40 +30 bob 20 Jeff 40 +bob 20 Jeff 40 +20 Jeff 40 +Jeff 40 +40 diff --git a/Task/Loops-Infinite/00DESCRIPTION b/Task/Loops-Infinite/00DESCRIPTION index 9b3cf917d2..50421327d2 100644 --- a/Task/Loops-Infinite/00DESCRIPTION +++ b/Task/Loops-Infinite/00DESCRIPTION @@ -1,3 +1,19 @@ ;Task: Print out       '''SPAM'''       followed by a   ''newline''   in an infinite loop. + + +;Related tasks: +*   [[Loop over multiple arrays simultaneously]] +*   [[Loops/Break]] +*   [[Loops/Continue]] +*   [[Loops/Do-while]] +*   [[Loops/Downward for]] +*   [[Loops/For]] +*   [[Loops/For with a specified step]] +*   [[Loops/Foreach]] +*   [[Loops/Increment loop index within loop body]] +*   [[Loops/Infinite]] +*   [[Loops/N plus one half]] +*   [[Loops/Nested]] +*   [[Loops/While]]

diff --git a/Task/Loops-Infinite/C/loops-infinite-5.c b/Task/Loops-Infinite/C/loops-infinite-5.c new file mode 100644 index 0000000000..f29685d222 --- /dev/null +++ b/Task/Loops-Infinite/C/loops-infinite-5.c @@ -0,0 +1,3 @@ +/*Abhishek Ghosh, 24th October 2017*/ +spam: puts("SPAM"); +goto spam; diff --git a/Task/Loops-Infinite/Emacs-Lisp/loops-infinite.l b/Task/Loops-Infinite/Emacs-Lisp/loops-infinite.l new file mode 100644 index 0000000000..f104c5c335 --- /dev/null +++ b/Task/Loops-Infinite/Emacs-Lisp/loops-infinite.l @@ -0,0 +1,3 @@ +#!/usr/bin/env emacs --script + +(while (princ "SPAM\n")) diff --git a/Task/Loops-Infinite/Fortress/loops-infinite.fortress b/Task/Loops-Infinite/Fortress/loops-infinite.fortress new file mode 100644 index 0000000000..e9f9ed132b --- /dev/null +++ b/Task/Loops-Infinite/Fortress/loops-infinite.fortress @@ -0,0 +1,6 @@ +component loops_infinite + export Executable + run() = while true do + println("SPAM") + end +end diff --git a/Task/Loops-Infinite/Perl/loops-infinite-1.pl b/Task/Loops-Infinite/Perl/loops-infinite-1.pl new file mode 100644 index 0000000000..ceceec1af8 --- /dev/null +++ b/Task/Loops-Infinite/Perl/loops-infinite-1.pl @@ -0,0 +1,3 @@ +while(1){ + print "SPAM\n"; +} diff --git a/Task/Loops-Infinite/Perl/loops-infinite.pl b/Task/Loops-Infinite/Perl/loops-infinite-2.pl similarity index 100% rename from Task/Loops-Infinite/Perl/loops-infinite.pl rename to Task/Loops-Infinite/Perl/loops-infinite-2.pl diff --git a/Task/Loops-Infinite/Red/loops-infinite.red b/Task/Loops-Infinite/Red/loops-infinite.red new file mode 100644 index 0000000000..6661748882 --- /dev/null +++ b/Task/Loops-Infinite/Red/loops-infinite.red @@ -0,0 +1,3 @@ +forever [ +print "SPAM" +] diff --git a/Task/Loops-N-plus-one-half/00DESCRIPTION b/Task/Loops-N-plus-one-half/00DESCRIPTION index 7f17c8b675..b0a9d39d0c 100644 --- a/Task/Loops-N-plus-one-half/00DESCRIPTION +++ b/Task/Loops-N-plus-one-half/00DESCRIPTION @@ -12,6 +12,18 @@ using separate output statements for the number and the comma from within the body of the loop. -;Related task: -*   [[Loop/Break]] +;Related tasks: +*   [[Loop over multiple arrays simultaneously]] +*   [[Loops/Break]] +*   [[Loops/Continue]] +*   [[Loops/Do-while]] +*   [[Loops/Downward for]] +*   [[Loops/For]] +*   [[Loops/For with a specified step]] +*   [[Loops/Foreach]] +*   [[Loops/Increment loop index within loop body]] +*   [[Loops/Infinite]] +*   [[Loops/N plus one half]] +*   [[Loops/Nested]] +*   [[Loops/While]]

diff --git a/Task/Loops-N-plus-one-half/ALGOL-60/loops-n-plus-one-half.alg b/Task/Loops-N-plus-one-half/ALGOL-60/loops-n-plus-one-half.alg new file mode 100644 index 0000000000..450e1117db --- /dev/null +++ b/Task/Loops-N-plus-one-half/ALGOL-60/loops-n-plus-one-half.alg @@ -0,0 +1,8 @@ +'BEGIN' + 'COMMENT' Loops N plus one half - Algol60 - 20/06/2018; + 'INTEGER' I; + 'FOR' I:=1 'STEP' 1 'UNTIL' 10 'DO' 'BEGIN' + OUTINTEGER(1,I); + 'IF' I 'NOTEQUAL' 10 'THEN' OUTSTRING(1,'(', ')') + 'END' +'END' diff --git a/Task/Loops-N-plus-one-half/Ada/loops-n-plus-one-half.ada b/Task/Loops-N-plus-one-half/Ada/loops-n-plus-one-half.ada index 6f4fc999b3..0a257ca3a2 100644 --- a/Task/Loops-N-plus-one-half/Ada/loops-n-plus-one-half.ada +++ b/Task/Loops-N-plus-one-half/Ada/loops-n-plus-one-half.ada @@ -1,14 +1,11 @@ -with Ada.Text_Io; use Ada.Text_Io; -with Ada.Integer_Text_Io; use Ada.Integer_Text_Io; +with Ada.Text_IO; -procedure Loop_And_Half is - I : Positive := 1; +procedure LoopsAndHalf is begin - loop - Put(Item => I, Width => 1); - exit when I = 10; - Put(", "); - I := I + 1; - end loop; - New_Line; -end Loop_And_Half; + for i in 1 .. 10 loop + Ada.Text_IO.put (i'Img); + exit when i = 10; + Ada.Text_IO.put (","); + end loop; + Ada.Text_IO.new_line; +end LoopsAndHalf; diff --git a/Task/Loops-N-plus-one-half/Fortran/loops-n-plus-one-half-1.f b/Task/Loops-N-plus-one-half/Fortran/loops-n-plus-one-half-1.f index d253d1f31d..1616782793 100644 --- a/Task/Loops-N-plus-one-half/Fortran/loops-n-plus-one-half-1.f +++ b/Task/Loops-N-plus-one-half/Fortran/loops-n-plus-one-half-1.f @@ -1,49 +1,5 @@ -C WARNING: This program is not valid ANSI FORTRAN 77 code. It uses -C two nonstandard characters on the lines labelled 5001 and 5002. -C Many F77 compilers should be okay with it, but it is *not* -C standard. - PROGRAM LOOPPLUSONEHALF - INTEGER I, TEN -C I'm setting a parameter to distinguish from the label 10. - PARAMETER (TEN = 10) - - DO 10 I = 1, TEN -C Write the number only. - WRITE (*,5001) I - -C If we are on the last one, stop here. This will make this test -C every iteration, which can slow your program down a little. If -C you want to speed this up at the cost of your own convenience, -C you could loop only to nine, and handle ten on its own after -C the loop is finished. If you don't care, power to you. - IF (I .EQ. TEN) GOTO 10 - -C Append a comma to the number. - WRITE (*,5002) ',' - 10 CONTINUE - -C Always finish with a newline. This programmer hates it when a -C program does not end its output with a newline. - WRITE (*,5000) '' - STOP - - 5000 FORMAT (A) - -C Standard FORTRAN 77 is completely incapable of completing a -C WRITE statement without printing a newline. This program would -C be much more difficult (i.e. impossible) to write in the ANSI -C standard, without cheating and saying something like: -C -C WRITE (*,*) '1, 2, 3, 4, 5, 6, 7, 8, 9, 10' -C -C The dollar sign at the end of the format is a nonstandard -C character. It tells the compiler not to print a newline. If you -C are actually using FORTRAN 77, you should figure out what your -C particular compiler accepts. If you are actually using Fortran -C 90 or later, you should replace this line with the commented -C line that follows it. - 5001 FORMAT (I3, $) - 5002 FORMAT (A, $) -C5001 FORMAT (T3, ADVANCE='NO') -C5001 FORMAT (A, ADVANCE='NO') +C Loops N plus one half - Fortran IV (1964) + INTEGER I + WRITE(6,301) (I,I=1,10) + 301 FORMAT((I3,',')) END diff --git a/Task/Loops-N-plus-one-half/Fortran/loops-n-plus-one-half-2.f b/Task/Loops-N-plus-one-half/Fortran/loops-n-plus-one-half-2.f index ee92125863..d253d1f31d 100644 --- a/Task/Loops-N-plus-one-half/Fortran/loops-n-plus-one-half-2.f +++ b/Task/Loops-N-plus-one-half/Fortran/loops-n-plus-one-half-2.f @@ -1,8 +1,49 @@ -i = 1 -do - write(*, '(I0)', advance='no') i - if ( i == 10 ) exit - write(*, '(A)', advance='no') ', ' - i = i + 1 -end do -write(*,*) +C WARNING: This program is not valid ANSI FORTRAN 77 code. It uses +C two nonstandard characters on the lines labelled 5001 and 5002. +C Many F77 compilers should be okay with it, but it is *not* +C standard. + PROGRAM LOOPPLUSONEHALF + INTEGER I, TEN +C I'm setting a parameter to distinguish from the label 10. + PARAMETER (TEN = 10) + + DO 10 I = 1, TEN +C Write the number only. + WRITE (*,5001) I + +C If we are on the last one, stop here. This will make this test +C every iteration, which can slow your program down a little. If +C you want to speed this up at the cost of your own convenience, +C you could loop only to nine, and handle ten on its own after +C the loop is finished. If you don't care, power to you. + IF (I .EQ. TEN) GOTO 10 + +C Append a comma to the number. + WRITE (*,5002) ',' + 10 CONTINUE + +C Always finish with a newline. This programmer hates it when a +C program does not end its output with a newline. + WRITE (*,5000) '' + STOP + + 5000 FORMAT (A) + +C Standard FORTRAN 77 is completely incapable of completing a +C WRITE statement without printing a newline. This program would +C be much more difficult (i.e. impossible) to write in the ANSI +C standard, without cheating and saying something like: +C +C WRITE (*,*) '1, 2, 3, 4, 5, 6, 7, 8, 9, 10' +C +C The dollar sign at the end of the format is a nonstandard +C character. It tells the compiler not to print a newline. If you +C are actually using FORTRAN 77, you should figure out what your +C particular compiler accepts. If you are actually using Fortran +C 90 or later, you should replace this line with the commented +C line that follows it. + 5001 FORMAT (I3, $) + 5002 FORMAT (A, $) +C5001 FORMAT (T3, ADVANCE='NO') +C5001 FORMAT (A, ADVANCE='NO') + END diff --git a/Task/Loops-N-plus-one-half/Fortran/loops-n-plus-one-half-3.f b/Task/Loops-N-plus-one-half/Fortran/loops-n-plus-one-half-3.f new file mode 100644 index 0000000000..ee92125863 --- /dev/null +++ b/Task/Loops-N-plus-one-half/Fortran/loops-n-plus-one-half-3.f @@ -0,0 +1,8 @@ +i = 1 +do + write(*, '(I0)', advance='no') i + if ( i == 10 ) exit + write(*, '(A)', advance='no') ', ' + i = i + 1 +end do +write(*,*) diff --git a/Task/Loops-N-plus-one-half/Haskell/loops-n-plus-one-half.hs b/Task/Loops-N-plus-one-half/Haskell/loops-n-plus-one-half-1.hs similarity index 54% rename from Task/Loops-N-plus-one-half/Haskell/loops-n-plus-one-half.hs rename to Task/Loops-N-plus-one-half/Haskell/loops-n-plus-one-half-1.hs index c9454eccda..84ba8e2e51 100644 --- a/Task/Loops-N-plus-one-half/Haskell/loops-n-plus-one-half.hs +++ b/Task/Loops-N-plus-one-half/Haskell/loops-n-plus-one-half-1.hs @@ -1,5 +1,4 @@ -loop :: IO () -loop = mapM_ action [1 .. 10] - where action n = do +main :: IO () +main = forM_ [1 .. 10] $ \n -> do putStr $ show n putStr $ if n == 10 then "\n" else ", " diff --git a/Task/Loops-N-plus-one-half/Haskell/loops-n-plus-one-half-2.hs b/Task/Loops-N-plus-one-half/Haskell/loops-n-plus-one-half-2.hs new file mode 100644 index 0000000000..9544bc3657 --- /dev/null +++ b/Task/Loops-N-plus-one-half/Haskell/loops-n-plus-one-half-2.hs @@ -0,0 +1 @@ +intercalate ", " (map show [1..10]) diff --git a/Task/Loops-N-plus-one-half/Perl/loops-n-plus-one-half.pl b/Task/Loops-N-plus-one-half/Perl/loops-n-plus-one-half-1.pl similarity index 73% rename from Task/Loops-N-plus-one-half/Perl/loops-n-plus-one-half.pl rename to Task/Loops-N-plus-one-half/Perl/loops-n-plus-one-half-1.pl index b0ba9cfca0..a3a3c21b10 100644 --- a/Task/Loops-N-plus-one-half/Perl/loops-n-plus-one-half.pl +++ b/Task/Loops-N-plus-one-half/Perl/loops-n-plus-one-half-1.pl @@ -1,4 +1,4 @@ -foreach my $i (1..10) { +for my $i(1..10) { print $i; last if $i == 10; print ', '; diff --git a/Task/Loops-N-plus-one-half/Perl/loops-n-plus-one-half-2.pl b/Task/Loops-N-plus-one-half/Perl/loops-n-plus-one-half-2.pl new file mode 100644 index 0000000000..4b25bc4e74 --- /dev/null +++ b/Task/Loops-N-plus-one-half/Perl/loops-n-plus-one-half-2.pl @@ -0,0 +1 @@ +print join(', ', 1..10), "\n"; diff --git a/Task/Loops-Nested/00DESCRIPTION b/Task/Loops-Nested/00DESCRIPTION index 3f91e09e08..45f81b4296 100644 --- a/Task/Loops-Nested/00DESCRIPTION +++ b/Task/Loops-Nested/00DESCRIPTION @@ -3,4 +3,20 @@ Show a nested loop which searches a two-dimensional array filled with random num The loops iterate rows and columns of the array printing the elements until the value 20 is met. Specifically, this task also shows how to [[Loop/Break|break]] out of nested loops. + + +;Related tasks: +*   [[Loop over multiple arrays simultaneously]] +*   [[Loops/Break]] +*   [[Loops/Continue]] +*   [[Loops/Do-while]] +*   [[Loops/Downward for]] +*   [[Loops/For]] +*   [[Loops/For with a specified step]] +*   [[Loops/Foreach]] +*   [[Loops/Increment loop index within loop body]] +*   [[Loops/Infinite]] +*   [[Loops/N plus one half]] +*   [[Loops/Nested]] +*   [[Loops/While]]

diff --git a/Task/Loops-Nested/ALGOL-60/loops-nested.alg b/Task/Loops-Nested/ALGOL-60/loops-nested.alg new file mode 100644 index 0000000000..19eaa21d18 --- /dev/null +++ b/Task/Loops-Nested/ALGOL-60/loops-nested.alg @@ -0,0 +1,22 @@ +'BEGIN' 'COMMENT' Loops/Nested - ALGOL60 - 19/06/2018; + 'INTEGER' SEED; + 'INTEGER' 'PROCEDURE' RANDOM(N); + 'VALUE' N; 'INTEGER' N; + 'BEGIN' + SEED:=(SEED*19157+12347) '/' 21647; + RANDOM:=SEED-(SEED '/' N)*N+1 + 'END' RANDOM; + 'INTEGER' 'ARRAY' A(/1:10,1:10/); + 'INTEGER' I,J; + SEED:=31569; + 'FOR' I:=1 'STEP' 1 'UNTIL' 10 'DO' + 'FOR' J:=1 'STEP' 1 'UNTIL' 10 'DO' + A(/I,J/):=RANDOM(20); + SYSACT(1,6,120);SYSACT(1,8,60);SYSACT(1,12,1);'COMMENT' open print; + 'FOR' I:=1 'STEP' 1 'UNTIL' 10 'DO' + 'FOR' J:=1 'STEP' 1 'UNTIL' 10 'DO' 'BEGIN' + OUTINTEGER(1,A(/I,J/)); + 'IF' A(/I,J/)=20 'THEN' 'GOTO' LAB; + 'END'; +LAB: +'END' diff --git a/Task/Loops-Nested/Factor/loops-nested.factor b/Task/Loops-Nested/Factor/loops-nested.factor new file mode 100644 index 0000000000..c9b2ef4edf --- /dev/null +++ b/Task/Loops-Nested/Factor/loops-nested.factor @@ -0,0 +1,10 @@ +USING: continuations formatting io kernel math.ranges +prettyprint random sequences ; +IN: rosetta-code.loops-nested + +: rand-table ( -- seq ) + 10 [ 20 [ 20 [1,b] random ] replicate ] replicate ; + +rand-table [ + [ [ dup "%4d" printf 20 = [ return ] when ] each nl ] each +] with-return drop diff --git a/Task/Loops-Nested/Haskell/loops-nested-1.hs b/Task/Loops-Nested/Haskell/loops-nested-1.hs index 27c3b76862..2f3bbb1c09 100644 --- a/Task/Loops-Nested/Haskell/loops-nested-1.hs +++ b/Task/Loops-Nested/Haskell/loops-nested-1.hs @@ -1,5 +1,5 @@ import Data.List - +breakIncl :: (a -> Bool) -> [a] -> [a] breakIncl p = uncurry ((. take 1). (++)). break p -taskLLB k = map (breakIncl (==k)). breakIncl (k`elem`) +taskLLB k = map (breakIncl (==k)). breakIncl (k `elem`) diff --git a/Task/Loops-Nested/Haskell/loops-nested-2.hs b/Task/Loops-Nested/Haskell/loops-nested-2.hs index 8facfc84c6..1fbced0e65 100644 --- a/Task/Loops-Nested/Haskell/loops-nested-2.hs +++ b/Task/Loops-Nested/Haskell/loops-nested-2.hs @@ -1,8 +1,4 @@ -mij :: [[Int]] -mij = takeWhile(not.null). unfoldr (Just. splitAt 5) $ - [2, 6, 17, 5, 14, 1, 9, 11, 18, 10, 13, 20, 8, 7, 4, 16, 15, 19, 3, 12] - -*Main> mapM_ (mapM_ print) $ taskLLB 20 mij +*Main> mapM_ (mapM_ print) $ taskLLB 20 [[2,6,17,5,14],[1,9,11,18,10],[13,20,8,7,4],[16,15,19,3,12]] 2 6 17 diff --git a/Task/Loops-While/00DESCRIPTION b/Task/Loops-While/00DESCRIPTION index b60a826415..2185b8d4f1 100644 --- a/Task/Loops-While/00DESCRIPTION +++ b/Task/Loops-While/00DESCRIPTION @@ -6,4 +6,20 @@ Start an integer value at   '''1024'''. Loop while it is greater than zero. Print the value (with a newline) and divide it by two each time through the loop. + + +;Related tasks: +*   [[Loop over multiple arrays simultaneously]] +*   [[Loops/Break]] +*   [[Loops/Continue]] +*   [[Loops/Do-while]] +*   [[Loops/Downward for]] +*   [[Loops/For]] +*   [[Loops/For with a specified step]] +*   [[Loops/Foreach]] +*   [[Loops/Increment loop index within loop body]] +*   [[Loops/Infinite]] +*   [[Loops/N plus one half]] +*   [[Loops/Nested]] +*   [[Loops/While]]

diff --git a/Task/Loops-While/BASIC/loops-while-3.basic b/Task/Loops-While/BASIC/loops-while-3.basic new file mode 100644 index 0000000000..664103a117 --- /dev/null +++ b/Task/Loops-While/BASIC/loops-while-3.basic @@ -0,0 +1,6 @@ +10 N% = 1024 +20 IF N% = 0 THEN 60 +30 PRINT N% +40 N% = N%/2 +50 GOTO 20 +60 END diff --git a/Task/Loops-While/C++/loops-while-1.cpp b/Task/Loops-While/C++/loops-while-1.cpp index a2f7358bd2..614e6a184e 100644 --- a/Task/Loops-While/C++/loops-while-1.cpp +++ b/Task/Loops-While/C++/loops-while-1.cpp @@ -1,5 +1,5 @@ int i = 1024; -while(i > 0) { +while(i > 0){ std::cout << i << std::endl; i /= 2; } diff --git a/Task/Loops-While/C++/loops-while-2.cpp b/Task/Loops-While/C++/loops-while-2.cpp index f12482795b..4ab1ef9979 100644 --- a/Task/Loops-While/C++/loops-while-2.cpp +++ b/Task/Loops-While/C++/loops-while-2.cpp @@ -1,2 +1,2 @@ -for (int i = 1024; i>0; i /= 2) +for(int i = 1024; i > 0; i /= 2) std::cout << i << std::endl; diff --git a/Task/Loops-While/C++/loops-while-3.cpp b/Task/Loops-While/C++/loops-while-3.cpp index 36e36f1ac6..d3a55bbf25 100644 --- a/Task/Loops-While/C++/loops-while-3.cpp +++ b/Task/Loops-While/C++/loops-while-3.cpp @@ -1,2 +1,3 @@ -for (init; cond; update) +for(init; cond; update){ statement; +} diff --git a/Task/Loops-While/C++/loops-while-4.cpp b/Task/Loops-While/C++/loops-while-4.cpp index ccc9c75fbc..e7b3f4682a 100644 --- a/Task/Loops-While/C++/loops-while-4.cpp +++ b/Task/Loops-While/C++/loops-while-4.cpp @@ -1,7 +1,6 @@ { init; - while (cond) - { + while(cond){ statement; update; } diff --git a/Task/Loops-While/Fortress/loops-while.fortress b/Task/Loops-While/Fortress/loops-while.fortress new file mode 100644 index 0000000000..8c5b9396b6 --- /dev/null +++ b/Task/Loops-While/Fortress/loops-while.fortress @@ -0,0 +1,9 @@ +component loops_while + export Executable + + var i:ZZ32 = 1024 + run() = while i > 0 do + println(i) + i := i DIV 2 + end +end diff --git a/Task/Loops-While/Haskell/loops-while-1.hs b/Task/Loops-While/Haskell/loops-while-1.hs index c5fee550cc..6f05262bea 100644 --- a/Task/Loops-While/Haskell/loops-while-1.hs +++ b/Task/Loops-While/Haskell/loops-while-1.hs @@ -1,4 +1,5 @@ import Control.Monad (when) + main = loop 1024 where loop n = when (n > 0) (do print n diff --git a/Task/Loops-While/Haskell/loops-while-2.hs b/Task/Loops-While/Haskell/loops-while-2.hs index d99489321a..87b1c5107b 100644 --- a/Task/Loops-While/Haskell/loops-while-2.hs +++ b/Task/Loops-While/Haskell/loops-while-2.hs @@ -1,5 +1,10 @@ -import Control.Monad (when) +import Data.IORef +import Control.Monad.Loops -whileM :: (Monad m) => m Bool -> m a -> m () -whileM cond body = do c <- cond - when c (body >> whileM cond body) +main :: IO () +main = do r <- newIORef 1024 + whileM_ (do n <- readIORef r + return (n > 0)) + (do n <- readIORef r + print n + modifyIORef r (`div` 2)) diff --git a/Task/Loops-While/Haskell/loops-while-3.hs b/Task/Loops-While/Haskell/loops-while-3.hs index d84185bd89..5017aa84fe 100644 --- a/Task/Loops-While/Haskell/loops-while-3.hs +++ b/Task/Loops-While/Haskell/loops-while-3.hs @@ -1,9 +1,11 @@ +{-# LANGUAGE MonadComprehensions #-} import Data.IORef +import Control.Monad.Loops main :: IO () -main = do r <- newIORef 1024 - whileM (do n <- readIORef r - return (n > 0)) - (do n <- readIORef r - print n - modifyIORef r (`div` 2)) +main = do + r <- newIORef 1024 + whileM_ [n > 0 | n <- readIORef r] $ do + n <- readIORef r + print n + modifyIORef r (`div` 2) diff --git a/Task/Loops-While/PL-SQL/loops-while.sql b/Task/Loops-While/PL-SQL/loops-while.sql new file mode 100644 index 0000000000..2f01c60862 --- /dev/null +++ b/Task/Loops-While/PL-SQL/loops-while.sql @@ -0,0 +1,10 @@ +set serveroutput on +declare + n number := 1024; +begin + while n > 0 loop + dbms_output.put_line(n); + n := trunc(n / 2); + end loop; +end; +/ diff --git a/Task/Loops-While/Perl/loops-while-1.pl b/Task/Loops-While/Perl/loops-while-1.pl index 69386c3a3d..264122d875 100644 --- a/Task/Loops-While/Perl/loops-while-1.pl +++ b/Task/Loops-While/Perl/loops-while-1.pl @@ -1,5 +1,5 @@ my $n = 1024; -while ($n) { +while($n){ print "$n\n"; $n = int $n / 2; } diff --git a/Task/Loops-While/Perl/loops-while-2.pl b/Task/Loops-While/Perl/loops-while-2.pl index 629d3dcf69..5fafb3f2fd 100644 --- a/Task/Loops-While/Perl/loops-while-2.pl +++ b/Task/Loops-While/Perl/loops-while-2.pl @@ -1,5 +1,3 @@ -my $n = 1024; -until ($n <= 0) { +for(my $n = 1024; $n > 0; $n >>= 1){ print "$n\n"; - $n = int $n / 2; } diff --git a/Task/Loops-While/Perl/loops-while-3.pl b/Task/Loops-While/Perl/loops-while-3.pl new file mode 100644 index 0000000000..91bf97ca31 --- /dev/null +++ b/Task/Loops-While/Perl/loops-while-3.pl @@ -0,0 +1,5 @@ +my $n = 1024; +until($n == 0){ + print "$n\n"; + $n = int $n / 2; +} diff --git a/Task/Loops-While/X86-Assembly/loops-while.x86 b/Task/Loops-While/X86-Assembly/loops-while.x86 new file mode 100644 index 0000000000..2b4579da4f --- /dev/null +++ b/Task/Loops-While/X86-Assembly/loops-while.x86 @@ -0,0 +1,40 @@ +; NASM 64 bit X86-64 assembly on Linux + +global main +extern printf + +segment .data + +printffmt db `%ld\n`,0 + +segment .text + +main: + push rbp + mov rbp,rsp + +; used rbx and r12 because printf preserves these values + + mov rbx,1024 ; start with 1024 + mov r12,2 ; load 2 as divisor + +.toploop ; top of while loop + cmp rbx,0 ; compare to 0 + jle .done ; exit 0 or less + + lea rdi,[printffmt] ; print number in rsi + mov rsi,rbx ; mov to rsi as argument + call printf + +; calculate n/2 and save + xor rdx,rdx ; clear rdx for division + mov rax,rbx ; mov number to rax for division + idiv r12 ; divide by 2 + mov rbx,rax ; save n/2 + + jmp .toploop ; next loop + +.done + xor rax,rax ; return code 0 + leave ; fix stack + ret ; return diff --git a/Task/Lucas-Lehmer-test/00DESCRIPTION b/Task/Lucas-Lehmer-test/00DESCRIPTION index 36c874b895..a10d9ca560 100644 --- a/Task/Lucas-Lehmer-test/00DESCRIPTION +++ b/Task/Lucas-Lehmer-test/00DESCRIPTION @@ -3,5 +3,5 @@ Lucas-Lehmer Test: for p an odd prime, the Mersenne number 2^ ;Task: Calculate all Mersenne primes up to the implementation's -maximum precision, or the 47th Mersenne prime   (whichever comes first). +maximum precision, or the 47th Mersenne prime   (whichever comes first).

diff --git a/Task/Lucas-Lehmer-test/Forth/lucas-lehmer-test.fth b/Task/Lucas-Lehmer-test/Forth/lucas-lehmer-test.fth new file mode 100644 index 0000000000..b6896de617 --- /dev/null +++ b/Task/Lucas-Lehmer-test/Forth/lucas-lehmer-test.fth @@ -0,0 +1,8 @@ +: lucas-lehmer + 1+ 2 do + 4 i 2 <> * abs swap 1+ dup + 1- swap + i 1- 1 ?do dup * 2 - over mod loop 0= if ." M" i . then + loop cr +; + +1 15 lucas-lehmer diff --git a/Task/Lucas-Lehmer-test/Julia/lucas-lehmer-test.julia b/Task/Lucas-Lehmer-test/Julia/lucas-lehmer-test.julia new file mode 100644 index 0000000000..9b924b27a1 --- /dev/null +++ b/Task/Lucas-Lehmer-test/Julia/lucas-lehmer-test.julia @@ -0,0 +1,16 @@ +using Primes + +function getmersenneprimes(n) + t1 = time() + count = 0 + i = 2 + while(n > count) + if(isprime(i) && ismersenneprime(2^BigInt(i) - 1)) + println("M$i, cumulative time elapsed: $(time() - t1) seconds") + count += 1 + end + i += 1 + end +end + +getmersenneprimes(50) diff --git a/Task/Lucas-Lehmer-test/R/lucas-lehmer-test.r b/Task/Lucas-Lehmer-test/R/lucas-lehmer-test.r new file mode 100644 index 0000000000..a95ce0cee3 --- /dev/null +++ b/Task/Lucas-Lehmer-test/R/lucas-lehmer-test.r @@ -0,0 +1,33 @@ +# vectorized approach based on scalar code from primeSieve and mersenne in CRAN package `numbers` +require(gmp) +n <- 4423 # note that the sieve below assumes n > 9 + +# sieve the set of primes up to n +p <- seq(1, n, by = 2) +q <- length(p) +p[1] <- 2 +for (k in seq(3, sqrt(n), by = 2)) + if (p[(k + 1)/2] != 0) + p[seq((k * k + 1)/2, q, by = k)] <- 0 +p <- p[p > 0] +cat(p[1]," special case M2 == 3\n") +p <- p[-1] + +z2 <- gmp::as.bigz(2) +z4 <- z2 * z2 +zp <- gmp::as.bigz(p) +zmp <- z2^zp - 1 +S <- rep(z4, length(p)) + +for (i in 1:(p[length(p)] - 2)){ + S <- gmp::mod.bigz(S * S - z2, zmp) + if( i+2 == p[1] ){ + if( S[1] == 0 ){ + cat( p[1], "\n") + flush.console() + } + p <- p[-1] + zmp <- zmp[-1] + S <- S[-1] + } +} diff --git a/Task/Lucas-Lehmer-test/REXX/lucas-lehmer-test.rexx b/Task/Lucas-Lehmer-test/REXX/lucas-lehmer-test.rexx index 1c8b4c6363..84a0b33b6b 100644 --- a/Task/Lucas-Lehmer-test/REXX/lucas-lehmer-test.rexx +++ b/Task/Lucas-Lehmer-test/REXX/lucas-lehmer-test.rexx @@ -1,58 +1,54 @@ -/*REXX program uses the Lucas─Lehmer primality test for prime powers of two.*/ -trace i -parse arg limit . /*get optional arguments from the C.L. */ -if limit=='' then limit=1000 /*No argument? Then assume the default*/ -list= /*placeholder for the results. */ - /* [↓] only process up to the LIMIT, */ - do j=1 by 2 to limit /*there're only so many hours in a day.*/ - power=j + (j==1) /*POWER ≡ J except for when J=1. */ - if \isPrime(power) then iterate /*if POWER isn't prime, then ignore it.*/ - $=Lucas_Lehmer2(power) /*did it pass the Lucas─Lehmer2 test? */ - if $\=='' then list=list $ /*Did the # pass? Then add to the list.*/ - end /*j*/ - -list=space(list) /*elide all extraneous blanks from list*/ -say; say center('list',60-3,"═") /*show a fancy─dancy header (title). */ -say - do k=1 for words(list) /*show entries in list, one per line. */ - say right(word(list,k),30) /*right─justify 'em to look pretty&nice*/ - end /*k*/ -exit /*stick a fork in it, we're all done. */ -/*──────────────────────────────────ISPRIME subroutine────────────────────────*/ -isPrime: procedure; parse arg x /*get number to be tested.*/ -if x<17 then return wordpos(x,'2 3 5 7 11 13')\==0 /*test for special cases. */ -if x//2==0 then return 0 /*is it even? Then not prime.*/ -if x//3==0 then return 0 /*divisible by three? " " " */ -if right(x,1)==5 then return 0 /*right-most dig ≡ 5? " " " */ -if x//7==0 then return 0 /*divisible by seven? " " " */ - - do j=11 by 6 until j*j>x /*ensures that J isn't divisible by 3. */ - if x// j ==0 then return 0 /*is it divisible by J ? */ - if x//(j+2)==0 then return 0 /* " " " " J+2 ? ___ */ - end /*j*/ /* [↑] perform loop through √ x */ -return 1 /*indicate the number X is prime. */ -/*──────────────────────────────────LUCAS_LEHMER2 subroutine──────────────────*/ -Lucas_Lehmer2: procedure; parse arg ? /*Lucas─Lehmer test on 2**? - 1 */ -numeric form /*ensure the correct REXX number form. */ -if ?==2 then s=0 /*handle special case for an even prime*/ - else s=4 -q=2**? /*╔═══════════════════════════════════════════════════════════════╗ - ║ Compute a power of two, using only 9 decimal digits. DIGITs ║ - ║ of 1 million could be used, but that really gums up the whole ║ - ║ works. So, we start with the default of 9 digits, find the ║ - ║ ten's exponent in the product (2**?), double it, and then add ║ - ║ 6. 2 is all that's needed, but 6 is a lot safer. ║ - ║ The doubling is for the squaring of S (below, for s*s). ║ - ╚═══════════════════════════════════════════════════════════════╝*/ -if pos('E',q)\==0 then do /*the number in exponential notation? */ - parse var q 'E' tenpow - numeric digits tenpow*2 + 6 - end - else numeric digits digits()*2 + 6 /* 9*2 + 6 */ -q=2**?-1 - do ?-2 /*apply, rinse, repeat ··· */ - s=(s*s-2) // q /*remainder in REXX is: // */ - end /* [↑] compute the real McCoy. */ - -if s\==0 then return '' /*return nuttin' if number isn't prime.*/ - return 'M'? /*return a "modified" (prime) number. */ +/*REXX pgm uses the Lucas─Lehmer primality test for prime powers of 2 (Mersenne primes)*/ +@.=0; @.2=1; @.3=1; @.5=1; @.7=1; @.11=1; @.13=1 /*a partial list of some low primes. */ +!.=@.; !.0=1; !.2=1; !.4=1; !.5=1; !.6=1; !.8=1 /*#'s with these last digs aren't prime*/ +parse arg limit . /*obtain optional arguments from the CL*/ +if limit=='' then limit= 200 /*Not specified? Then use the default.*/ +say center('Mersenne prime index list',70-3,"═") /*show a fancy─dancy header (or title).*/ +say right('M'2, 25) " [1 decimal digit]" /*left─justify them to align&look nice.*/ + /* [►] note that J==1 is a special case*/ + do j=1 by 2 to limit /*there're only so many hours in a day.*/ + power=j + (j==1) /*POWER ≡ J except for when J=1. */ + if \isPrime(power) then iterate /*if POWER isn't prime, then ignore it.*/ + $=LL2(power) /*perform the Lucas─Lehmer 2 (LL2) test*/ + if $=='' then iterate /*Did it flunk LL2? Then skip this #.*/ + say right($, 25) MPsize /*left─justify them to align&look nice.*/ + end /*j*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +isPrime: procedure expose !. @.; parse arg x '' -1 z /*get # to be tested & last digit*/ + if @.x then return 1 /*is X already found to be prime? */ + if !.z then return 0 /*is last decimal digit even or a five?*/ + if x//3==0 then return 0 /*divisible by three? " " " */ + if x//7==0 then return 0 /*divisible by seven? " " " */ + do j=11 by 6 until j*j > x /*ensures that J isn't divisible by 3. */ + if x// j ==0 then return 0 /*is it divisible by J ? */ + if x// (j+2)==0 then return 0 /* " " " " J+2 ? ___ */ + end /*j*/ /* [↑] perform loop through √ x */ + @.j=1; return 1 /*indicate number X and J are prime.*/ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +LL2: procedure expose MPsize; parse arg ? /*Lucas─Lehmer test on 2**? - 1 */ + if ?==2 then s=0 /*handle special case for an even prime*/ + else s=4 + numeric form; q= 2**? /*ensure correct form for REXX numbers.*/ + /*╔══════════════════════════════════════════════════════════════════════════════════╗ + ║ Compute a power of two, using only 9 decimal digits. DIGITs of 1 million could ║ + ║ be used, but that really slows up computations. So, we start with the default ║ + ║ of 9 digits, and then find the ten's exponent in the product (2**?), double ║ + ║ it, and then add six. {Two is all that's needed, but six is a lot safer.} ║ + ║ The doubling is for the squaring of S (below, for s*s). ║ + ╚══════════════════════════════════════════════════════════════════════════════════╝*/ + if pos('E', q)\==0 then do /*is number in exponential notation ? */ + parse var q 'E' tenPow /*get the exponent.*/ + numeric digits tenPow * 2 + 6 /*expand precision.*/ + end /*REXX used dec FP.*/ + else numeric digits digits() * 2 + 6 /*use 9*2 + 6 digs.*/ + q=2**? - 1; r=q//8 /*obtain Q modulus eight. */ + if r==1 | r==7 then nop; else return '' /*before crunching, do a simple test. */ + do ?-2; s= (s*s -2) // q /*lather, rinse, repeat ··· */ + end /* [↑] compute and test for a MP. */ + if s\==0 then return '' /*Not a Mersenne prime? Return a null.*/ + sz=length(q) /*obtain number of decimal digs in MP. */ + MPsize=' ['sz "decimal digit"s(sz)']' /*define a literal to display after MP.*/ + return 'M'? /*return "modified" # (Mersenne index).*/ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +s: if arg(1)==1 then return arg(3); return word(arg(2) 's', 1) /*simple pluralizer*/ diff --git a/Task/Lucas-Lehmer-test/Rust/lucas-lehmer-test.rust b/Task/Lucas-Lehmer-test/Rust/lucas-lehmer-test.rust new file mode 100644 index 0000000000..9c0ee6f2cb --- /dev/null +++ b/Task/Lucas-Lehmer-test/Rust/lucas-lehmer-test.rust @@ -0,0 +1,53 @@ +extern crate rug; +extern crate primal; + +use rug::Integer; +use rug::ops::Pow; +use std::thread::spawn; + +fn is_mersenne (p : usize) { + let p = p as u32; + let mut m = Integer::from(1); + m = m << p; + m = Integer::from(&m - 1); + let mut flag1 = false; + for k in 1..10_000 { + let mut flag2 = false; + let mut div : u32 = 2*k*p + 1; + if &div >= &m {break; } + for j in [3,5,7,11,13,17,19,23,29,31,37].iter() { + if div % j == 0 { + flag2 = true; + break; + } + } + if flag2 == true {continue;} + if div % 8 != 1 && div % 8 != 7 { continue; } + if m.is_divisible_u(div) { + flag1 = true; + break; + } + } + if flag1 == true {return ()} + let mut s = Integer::from(4); + let two = Integer::from(2); + for _i in 2..p { + let mut sqr = s.pow(2); + s = Integer::from(&Integer::from(&sqr & &m) + &Integer::from(&sqr >> p)); + if &s >= &m {s = s - &m} + s = Integer::from(&s - &two); + } + if s == 0 {println!("Mersenne : {}",p);} +} + +fn main () { + println!("Mersenne : 2"); + let limit = 11_214; + let mut thread_handles = vec![]; + for p in primal::Primes::all().take_while(|p| *p < limit) { + thread_handles.push(spawn(move || is_mersenne(p))); + } + for handle in thread_handles { + handle.join().unwrap(); + } +} diff --git a/Task/Ludic-numbers/Ring/ludic-numbers.ring b/Task/Ludic-numbers/Ring/ludic-numbers.ring new file mode 100644 index 0000000000..da6eb298e8 --- /dev/null +++ b/Task/Ludic-numbers/Ring/ludic-numbers.ring @@ -0,0 +1,75 @@ +# Project : Ludic numbers +# Date : 2017/11/07 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : + +ludic = list(300) +resludic = [] +nr = 1 +for n = 1 to len(ludic) + ludic[n] = n+1 +next +see "the first 25 Ludic numbers are:" + nl +ludicnumbers(ludic) +showarray(resludic) +see nl + +see "Ludic numbers below 1000: " +ludic = list(3000) +resludic = [] +for n = 1 to len(ludic) + ludic[n] = n+1 +next +ludicnumbers(ludic) +showarray2(resludic) +see nr +see nl + nl + +see "the 2000..2005th Ludic numbers are:" + nl +ludic = list(60000) +resludic = [] +for n = 1 to len(ludic) + ludic[n] = n+1 +next +ludicnumbers(ludic) +showarray3(resludic) + +func ludicnumbers(ludic) + for n = 1 to len(ludic) + delludic = [] + for m = 1 to len(ludic) step ludic[1] + add(delludic, m) + next + add(resludic, ludic[1]) + for p = len(delludic) to 1 step -1 + del(ludic, delludic[p]) + next + next + +func showarray(vect) + see "[1, " + svect = "" + for n = 1 to 24 + svect = svect + vect[n] + ", " + next + svect = left(svect, len(svect) - 2) + see svect + see "]" + nl + +func showarray2(vect) + for n = 1 to len(vect) + if vect[n] <= 1000 + nr = nr + 1 + ok + next + return nr + +func showarray3(vect) + see "[" + svect = "" + for n = 1999 to 2004 + svect = svect + vect[n] + ", " + next + svect = left(svect, len(svect) - 2) + see svect + see "]" + nl diff --git a/Task/Luhn-test-of-credit-card-numbers/8th/luhn-test-of-credit-card-numbers.8th b/Task/Luhn-test-of-credit-card-numbers/8th/luhn-test-of-credit-card-numbers.8th new file mode 100644 index 0000000000..57aa146483 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/8th/luhn-test-of-credit-card-numbers.8th @@ -0,0 +1,25 @@ +\ Adapted from the C version: +: remap \ n1 -- n2 + [0,2,4,6,8,1,3,5,7,9] + swap caseof ; + +: luhn \ s -- f + 0 swap + s:rev + ( + '0 n:- + swap 2 n:mod if remap then + n:+ + ) s:each + 10 n:mod not ; + +: test-luhn \ s -- + dup . space + luhn if "OK" else "FAIL" then . cr ; + +"49927398716" test-luhn +"49927398717" test-luhn +"1234567812345678" test-luhn +"1234567812345670" test-luhn + +bye diff --git a/Task/Luhn-test-of-credit-card-numbers/AWK/luhn-test-of-credit-card-numbers.awk b/Task/Luhn-test-of-credit-card-numbers/AWK/luhn-test-of-credit-card-numbers.awk index 3c8a1ac433..0a30930aac 100644 --- a/Task/Luhn-test-of-credit-card-numbers/AWK/luhn-test-of-credit-card-numbers.awk +++ b/Task/Luhn-test-of-credit-card-numbers/AWK/luhn-test-of-credit-card-numbers.awk @@ -4,17 +4,21 @@ BEGIN { A[2] = 49927398717; A[3] = 1234567812345678; A[4] = 1234567812345670; + A[5] = "01234567897"; + A[6] = "01234567890"; + A[7] = "00000000000"; for (k in A) print "isLuhn("A[k]"): ",isLuhn(A[k]); } function isLuhn(cardno) { - m = "246813579"; + s = 0; + m = "0246813579"; n = length(cardno); for (k = n; 0 < k; k -= 2) { s += substr(cardno, k, 1); } for (k = n-1; 0 < k; k -= 2) { - s += substr(m, substr(cardno, k, 1), 1); + s += substr(m, substr(cardno, k, 1)+1, 1); } return ((s%10)==0); } diff --git a/Task/Luhn-test-of-credit-card-numbers/Befunge/luhn-test-of-credit-card-numbers.bf b/Task/Luhn-test-of-credit-card-numbers/Befunge/luhn-test-of-credit-card-numbers.bf new file mode 100644 index 0000000000..fbd6bace72 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Befunge/luhn-test-of-credit-card-numbers.bf @@ -0,0 +1,9 @@ +v 1 >$0 v v < +>&:19+`|v < >v 5 6 7 8 +^ \ <>09p19p>09g+09p:|>2*:19+%19g+19p19+/19g+19p:| + 2 3 4 > v + v"invalid"<10 9 + |%+91+g91g90< + v "valid"< + >:#,_@ + 11 diff --git a/Task/Luhn-test-of-credit-card-numbers/JavaScript/luhn-test-of-credit-card-numbers-3.js b/Task/Luhn-test-of-credit-card-numbers/JavaScript/luhn-test-of-credit-card-numbers-3.js index d5f77db23e..1551f70682 100644 --- a/Task/Luhn-test-of-credit-card-numbers/JavaScript/luhn-test-of-credit-card-numbers-3.js +++ b/Task/Luhn-test-of-credit-card-numbers/JavaScript/luhn-test-of-credit-card-numbers-3.js @@ -1,9 +1,11 @@ -function luhn(str){ - return str.split('').reduceRight(function(prev, curr, idx){ - prev = parseInt(prev, 10); - if ((idx + 1) % 2 !== 0) { - curr = (curr * 2).toString().split('').reduce(function(p, c){ return parseInt(p, 10) + parseInt(c, 10)}); - } - return prev + parseInt(curr, 10); - }) % 10 === 0; -} +var luhn10 = function(a,b,c,d,e) { + for(d = +a[b = a.length-1], e=0; b--;) + c = +a[b], d += ++e % 2 ? 2 * c % 10 + (c > 4) : c; + return !(d%10) +}; + +// returns true +luhn10('4111111111111111') + +// returns false +luhn10('4111111111111112') diff --git a/Task/Luhn-test-of-credit-card-numbers/Julia/luhn-test-of-credit-card-numbers-1.julia b/Task/Luhn-test-of-credit-card-numbers/Julia/luhn-test-of-credit-card-numbers-1.julia new file mode 100644 index 0000000000..aa29b61013 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Julia/luhn-test-of-credit-card-numbers-1.julia @@ -0,0 +1 @@ +luhntest(x::Integer) = (sum(digits(x)[1:2:end]) + sum(map(x -> sum(digits(x)), 2 * digits(x)[2:2:end]))) % 10 == 0 diff --git a/Task/Luhn-test-of-credit-card-numbers/Julia/luhn-test-of-credit-card-numbers-2.julia b/Task/Luhn-test-of-credit-card-numbers/Julia/luhn-test-of-credit-card-numbers-2.julia new file mode 100644 index 0000000000..2f59f715de --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Julia/luhn-test-of-credit-card-numbers-2.julia @@ -0,0 +1,10 @@ +function luhntest(x::Integer) + d = reverse(digits(x)) + s = sum(d[1:2:end]) + s += sum(sum.(digits.(2d[2:2:end]))) + return s % 10 == 0 +end + +for card in [49927398716, 49927398717, 1234567812345678, 1234567812345670] + println(luhntest(card) ? "PASS " : "FAIL ", card) +end diff --git a/Task/Luhn-test-of-credit-card-numbers/Julia/luhn-test-of-credit-card-numbers.julia b/Task/Luhn-test-of-credit-card-numbers/Julia/luhn-test-of-credit-card-numbers.julia deleted file mode 100644 index ea6594a4dc..0000000000 --- a/Task/Luhn-test-of-credit-card-numbers/Julia/luhn-test-of-credit-card-numbers.julia +++ /dev/null @@ -1,5 +0,0 @@ -luhntest(x::Int) = (sum(digits(x)[1:2:end]) + sum(map(x -> sum(digits(x)), 2 * digits(x)[2:2:end]))) % 10 == 0 - -for card in [49927398716, 49927398717, 1234567812345678, 1234567812345670] - println(luhntest(card) ? "PASS " : "FAIL ", card) -end diff --git a/Task/Luhn-test-of-credit-card-numbers/Perl-6/luhn-test-of-credit-card-numbers.pl6 b/Task/Luhn-test-of-credit-card-numbers/Perl-6/luhn-test-of-credit-card-numbers.pl6 new file mode 100644 index 0000000000..bf9973b531 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Perl-6/luhn-test-of-credit-card-numbers.pl6 @@ -0,0 +1,23 @@ +sub luhn-test ($number --> Bool) { + my @digits = $number.comb.reverse; + my $sum = @digits[0,2...*].sum + + @digits[1,3...*].map({ |($_ * 2).comb }).sum; + return $sum %% 10; +} + +# And we can test it like this: + +use Test; + +my @cc-numbers = + '49927398716' => True, + '49927398717' => False, + '1234567812345678' => False, + '1234567812345670' => True; + +plan @cc-numbers.elems; + +for @cc-numbers».kv -> ($cc, $expected-result) { + is luhn-test(+$cc), $expected-result, + "$cc {$expected-result ?? 'passes' !! 'does not pass'} the Luhn test."; +} diff --git a/Task/Luhn-test-of-credit-card-numbers/Ring/luhn-test-of-credit-card-numbers.ring b/Task/Luhn-test-of-credit-card-numbers/Ring/luhn-test-of-credit-card-numbers.ring index 62c783a5dc..2bbe523d09 100644 --- a/Task/Luhn-test-of-credit-card-numbers/Ring/luhn-test-of-credit-card-numbers.ring +++ b/Task/Luhn-test-of-credit-card-numbers/Ring/luhn-test-of-credit-card-numbers.ring @@ -1,19 +1,58 @@ -cardnumber = [49927398716, 49927398717] decimals(0) -for cards = 1 to len(cardnumber) - if luhn(cardnumber[cards]) - see "card number " + cardnumber[cards] + " is valid" + nl - else see "card number " + cardnumber[cards] + " is invalid" + nl ok +test = ["49927398716", "49927398717", "1234567812345678", "1234567812345670"] +for n = 1 to len(test) + see test[n] + " -> " + cardtest(test[n]) + nl next -func luhn card - s = 0 - ln = len(string(card)) - for i = 1 to ln - n = number(substr(string(card), ln-i+1, 1)) - if (i & 1) s += n + nl - else n *= 2 - s += (n % 10) + floor(n/ 10) ok - next - return (s % 10) = 0 +func cardtest(numstr) + revstring = revstr(numstr) + s1 = revodd(revstring) + s2 = reveven(revstring) + s3 =right(string(s1+s2), 1) + if s3 = "0" + return "Valid" + else + return "Invalid" + ok + +func revstr(str) + strnew = "" + for nr = len(str) to 1 step -1 + strnew = strnew + str[nr] + next + return strnew + +func revodd(str) + strnew = "" + for nr = 1 to len(str) step 2 + strnew = strnew + str[nr] + next + sumodd = 0 + for p = 1 to len(strnew) + sumodd = sumodd + number(strnew[p]) + next + return sumodd + +func reveven(str) + strnew = "" + for nr = 2 to len(str) step 2 + strnew = strnew + str[nr] + next + lsteven = [] + for p = 1 to len(strnew) + add(lsteven, string(2*number(strnew[p]))) + next + arreven = list(len(lsteven)) + for q = 1 to len(lsteven) + sum = 0 + for w = 1 to len(lsteven[q]) + sum = sum + lsteven[q][w] + next + arreven[q] = sum + next + sumarr = 0 + for x = 1 to len(arreven) + sumarr = sumarr + arreven[x] + next + return sumarr diff --git a/Task/Luhn-test-of-credit-card-numbers/Rust/luhn-test-of-credit-card-numbers.rust b/Task/Luhn-test-of-credit-card-numbers/Rust/luhn-test-of-credit-card-numbers.rust index 032a320f80..044da18f04 100644 --- a/Task/Luhn-test-of-credit-card-numbers/Rust/luhn-test-of-credit-card-numbers.rust +++ b/Task/Luhn-test-of-credit-card-numbers/Rust/luhn-test-of-credit-card-numbers.rust @@ -1,33 +1,22 @@ -fn get_digits(mut num: u64) -> Vec { - let mut digits = vec![]; - while num != 0 { - digits.push(num % 10); - num /= 10; +struct Digits(u64); +impl Iterator for Digits { + type Item = u64; + fn next(&mut self) -> Option { + let next = if self.0 == 0 { None } else { Some(self.0 % 10) }; + self.0 /= 10; + next } - digits } -fn digit_sum(num: u64) -> u64 { - get_digits(num).into_iter().fold(0,|sum, dig| sum + dig) -} - -fn luhn_test(n: u64) -> bool { - let mut sum = 0; - for (i,digit) in get_digits(n).into_iter().enumerate() { - sum += match i % 2 == 0 { - true => digit, - false => digit_sum(2*digit), - } - } - sum % 10 == 0 +fn luhn_test(num: u64) -> bool { + Digits(num).enumerate() + .map(|(i, digit)| if (i % 2) == 0 { digit } else { Digits(digit*2).sum() }) + .sum::() % 10 == 0 } fn main() { let nums = [49927398716, 49927398717, 1234567812345678, 1234567812345670]; for &n in &nums { - match luhn_test(n) { - true => println!("{} passes.", n), - false => println!("{} fails.", n), - } + println!("{}: {:?}", n, luhn_test(n)); } } diff --git a/Task/Luhn-test-of-credit-card-numbers/Scala/luhn-test-of-credit-card-numbers-1.scala b/Task/Luhn-test-of-credit-card-numbers/Scala/luhn-test-of-credit-card-numbers-1.scala index 7864bc804e..6b0cb7348f 100644 --- a/Task/Luhn-test-of-credit-card-numbers/Scala/luhn-test-of-credit-card-numbers-1.scala +++ b/Task/Luhn-test-of-credit-card-numbers/Scala/luhn-test-of-credit-card-numbers-1.scala @@ -1,35 +1,26 @@ -object LuhnTest extends App { - - object Luhn { - - // pre calculate even digits - private val evenDigits = Vector(0, 2, 4, 6, 8, 1, 3, 5, 7, 9) - - private def compute(number: String): Int = { - number.foreach(d => require(d >= '0' && d <= '9', "must be a number")) - - // we don't need to process the number in reverse because we determine if the digit is in a even position or not - number.foldLeft((number.length & 1) == 0, 0) { (sum, d) => - if (sum._1) (!sum._1, sum._2 + evenDigits(d - '0')) - else (!sum._1, sum._2 + d - '0') - }._2 - } - - // Validate a number using Luhn checksum - def validate(number: String): Boolean = compute(number) % 10 == 0 - - // Compute check digit using Luhn (not used for this task) - def computeCheckDigit(number: String): Int = { - compute(number + '0') % 10 match { - case 0 => 0 - case x => 10 - x - } - } +object Luhn { + private def parse(s: String): Seq[Int] = s.map{c => + assert(c.isDigit) + c.asDigit } + def checksum(digits: Seq[Int]): Int = { + digits.reverse.zipWithIndex.foldLeft(0){case (sum,(digit,i))=> + if (i%2 == 0) sum + digit + else sum + (digit*2)/10 + (digit*2)%10 + } % 10 + } + def validate(digits: Seq[Int]): Boolean = checksum(digits) == 0 + def checksum(number: String): Int = checksum(parse(number)) + def validate(number: String): Boolean = validate(parse(number)) +} - val numbers = Seq("49927398716", "49927398717", "1234567812345678", "1234567812345670") - - numbers.foreach { n => +object LuhnTest extends App { + Seq(("49927398716", true), + ("49927398717", false), + ("1234567812345678", false), + ("1234567812345670", true) + ).foreach { case (n, expected) => println(s"$n ${Luhn.validate(n)}") + assert(Luhn.validate(n) == expected) } } diff --git a/Task/Luhn-test-of-credit-card-numbers/VBA/luhn-test-of-credit-card-numbers.vba b/Task/Luhn-test-of-credit-card-numbers/VBA/luhn-test-of-credit-card-numbers.vba new file mode 100644 index 0000000000..93f155f6e2 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/VBA/luhn-test-of-credit-card-numbers.vba @@ -0,0 +1,27 @@ +Option Explicit + +Sub Main() + Debug.Print "Number 49927398716 is "; Luhn("49927398716") + Debug.Print "Number 49927398717 is "; Luhn("49927398717") + Debug.Print "Number 1234567812345678 is "; Luhn("1234567812345678") + Debug.Print "Number 1234567812345670 is "; Luhn("1234567812345670") +End Sub +Private Function Luhn(Nb As String) As String +Dim t$, i&, Summ&, s& + t = StrReverse(Nb) + For i = 1 To Len(t) Step 2 + Summ = Summ + CInt(Mid(t, i, 1)) + Next i + For i = 2 To Len(t) Step 2 + s = 2 * (CInt(Mid(t, i, 1))) + If s >= 10 Then + Summ = Summ - 9 + End If + Summ = Summ + s + Next i + If Summ Mod 10 = 0 Then + Luhn = "valid" + Else + Luhn = "invalid" + End If +End Function diff --git a/Task/MD5-Implementation/Lingo/md5-implementation-1.lingo b/Task/MD5-Implementation/Lingo/md5-implementation-1.lingo new file mode 100644 index 0000000000..2877be4175 --- /dev/null +++ b/Task/MD5-Implementation/Lingo/md5-implementation-1.lingo @@ -0,0 +1,275 @@ +---------------------------------------- +-- Calculates MD5 hash of string or bytearray +-- @param {bytearray|string} input +-- @return {bytearray} (16 bytes) +---------------------------------------- +on md5 (input) + if stringP(input) then input = bytearray(input) + + -- Convert string to list of little-endian words... + t_iLen = input.length * 8 + t_iCnt = (t_iLen + 64) / 512 * 16 + 16 + + -- Create list, fill with zeros... + x = [] + x[t_iCnt] = 0 + + t_fArr = [1, 256, 65536, 16777216] + i = 0 + j = 0 + repeat while i < t_iLen + j = j + 1 + t_iNext = i / 32 + 1 + t_iTemp = bitAnd(input[i/8+1], 255) * t_fArr[j] + x[t_iNext] = bitOr(x[t_iNext], t_iTemp) + i = i + 8 + j = j mod 4 + end repeat + + -- Append padding... + t_iNext = t_iLen / 32 + 1 + x[t_iNext] = bitOr(x[t_iNext], 128 * t_fArr[j + 1]) + x[(t_iLen + 64) / 512 * 16 + 15] = t_iLen + + -- Actual algorithm starts here... + a = 1732584193 + b = -271733879 + c = -1732584194 + d = 271733878 + i = 1 + t_iWrap = the maxInteger + 1 + t_iCount = x.count + 1 + repeat while i < t_iCount + olda = a + oldb = b + oldc = c + oldd = d + + -- Round(1) -- + n = bitOr(bitAnd(b, c), bitAnd(bitNot(b), d)) + a + x[i] - 680876936 + if(n < 0) then a = bitOr(n * 128, bitOr((n + t_iWrap) / 33554432, 64)) + b + else a = bitOr(n * 128, n / 33554432) + b + n = bitOr(bitAnd(a, b), bitAnd(bitNot(a), c)) + d + x[i + 1] - 389564586 + if(n < 0) then d = bitOr(n * 4096, bitOr((n + t_iWrap) / 1048576, 2048)) + a + else d = bitOr(n * 4096, n / 1048576) + a + n = bitOr(bitAnd(d, a), bitAnd(bitNot(d), b)) + c + x[i + 2] + 606105819 + if(n < 0) then c = bitOr(n * 131072, bitOr((n + t_iWrap) / 32768, 65536)) + d + else c = bitOr(n * 131072, n / 32768) + d + n = bitOr(bitAnd(c, d), bitAnd(bitNot(c), a)) + b + x[i + 3] - 1044525330 + if(n < 0) then b = bitOr(n * 4194304, bitOr((n + t_iWrap) / 1024, 2097152)) + c + else b = bitOr(n * 4194304, n / 1024) + c + n = bitOr(bitAnd(b, c), bitAnd(bitNot(b), d)) + a + x[i + 4] - 176418897 + if(n < 0) then a = bitOr(n * 128, bitOr((n + t_iWrap) / 33554432, 64)) + b + else a = bitOr(n * 128, n / 33554432) + b + n = bitOr(bitAnd(a, b), bitAnd(bitNot(a), c)) + d + x[i + 5] + 1200080426 + if(n < 0) then d = bitOr(n * 4096, bitOr((n + t_iWrap) / 1048576, 2048)) + a + else d = bitOr(n * 4096, n / 1048576) + a + n = bitOr(bitAnd(d, a), bitAnd(bitNot(d), b)) + c + x[i + 6] - 1473231341 + if(n < 0) then c = bitOr(n * 131072, bitOr((n + t_iWrap) / 32768, 65536)) + d + else c = bitOr(n * 131072, n / 32768) + d + n = bitOr(bitAnd(c, d), bitAnd(bitNot(c), a)) + b + x[i + 7] - 45705983 + if(n < 0) then b = bitOr(n * 4194304, bitOr((n + t_iWrap) / 1024, 2097152)) + c + else b = bitOr(n * 4194304, n / 1024) + c + n = bitOr(bitAnd(b, c), bitAnd(bitNot(b), d)) + a + x[i + 8] + 1770035416 + if(n < 0) then a = bitOr(n * 128, bitOr((n + t_iWrap) / 33554432, 64)) + b + else a = bitOr(n * 128, n / 33554432) + b + n = bitOr(bitAnd(a, b), bitAnd(bitNot(a), c)) + d + x[i + 9] - 1958414417 + if(n < 0) then d = bitOr(n * 4096, bitOr((n + t_iWrap) / 1048576, 2048)) + a + else d = bitOr(n * 4096, n / 1048576) + a + n = bitOr(bitAnd(d, a), bitAnd(bitNot(d), b)) + c + x[i + 10] - 42063 + if(n < 0) then c = bitOr(n * 131072, bitOr((n + t_iWrap) / 32768, 65536)) + d + else c = bitOr(n * 131072, n / 32768) + d + n = bitOr(bitAnd(c, d), bitAnd(bitNot(c), a)) + b + x[i + 11] - 1990404162 + if(n < 0) then b = bitOr(n * 4194304, bitOr((n + t_iWrap) / 1024, 2097152)) + c + else b = bitOr(n * 4194304, n / 1024) + c + n = bitOr(bitAnd(b, c), bitAnd(bitNot(b), d)) + a + x[i + 12] + 1804603682 + if(n < 0) then a = bitOr(n * 128, bitOr((n + t_iWrap) / 33554432, 64)) + b + else a = bitOr(n * 128, n / 33554432) + b + n = bitOr(bitAnd(a, b), bitAnd(bitNot(a), c)) + d + x[i + 13] - 40341101 + if(n < 0) then d = bitOr(n * 4096, bitOr((n + t_iWrap) / 1048576, 2048)) + a + else d = bitOr(n * 4096, n / 1048576) + a + n = bitOr(bitAnd(d, a), bitAnd(bitNot(d), b)) + c + x[i + 14] - 1502002290 + if(n < 0) then c = bitOr(n * 131072, bitOr((n + t_iWrap) / 32768, 65536)) + d + else c = bitOr(n * 131072, n / 32768) + d + n = bitOr(bitAnd(c, d), bitAnd(bitNot(c), a)) + b + x[i + 15] + 1236535329 + if(n < 0) then b = bitOr(n * 4194304, bitOr((n + t_iWrap) / 1024, 2097152)) + c + else b = bitOr(n * 4194304, n / 1024) + c + + -- Round(2) -- + n = bitOr(bitAnd(b, d), bitAnd(c, bitNot(d))) + a + x[i + 1] - 165796510 + if(n < 0) then a = bitOr(n * 32, bitOr((n + t_iWrap) / 134217728, 16)) + b + else a = bitOr(n * 32, n / 134217728) + b + n = bitOr(bitAnd(a, c), bitAnd(b, bitNot(c))) + d + x[i + 6] - 1069501632 + if(n < 0) then d = bitOr(n * 512, bitOr((n + t_iWrap) / 8388608, 256)) + a + else d = bitOr(n * 512, n / 8388608) + a + n = bitOr(bitAnd(d, b), bitAnd(a, bitNot(b))) + c + x[i + 11] + 643717713 + if(n < 0) then c = bitOr(n * 16384, bitOr((n + t_iWrap) / 262144, 8192)) + d + else c = bitOr(n * 16384, n / 262144) + d + n = bitOr(bitAnd(c, a), bitAnd(d, bitNot(a))) + b + x[i] - 373897302 + if(n < 0) then b = bitOr(n * 1048576, bitOr((n + t_iWrap) / 4096, 524288)) + c + else b = bitOr(n * 1048576, n / 4096) + c + n = bitOr(bitAnd(b, d), bitAnd(c, bitNot(d))) + a + x[i + 5] - 701558691 + if(n < 0) then a = bitOr(n * 32, bitOr((n + t_iWrap) / 134217728, 16)) + b + else a = bitOr(n * 32, n / 134217728) + b + n = bitOr(bitAnd(a, c), bitAnd(b, bitNot(c))) + d + x[i + 10] + 38016083 + if(n < 0) then d = bitOr(n * 512, bitOr((n + t_iWrap) / 8388608, 256)) + a + else d = bitOr(n * 512, n / 8388608) + a + n = bitOr(bitAnd(d, b), bitAnd(a, bitNot(b))) + c + x[i + 15] - 660478335 + if(n < 0) then c = bitOr(n * 16384, bitOr((n + t_iWrap) / 262144, 8192)) + d + else c = bitOr(n * 16384, n / 262144) + d + n = bitOr(bitAnd(c, a), bitAnd(d, bitNot(a))) + b + x[i + 4] - 405537848 + if(n < 0) then b = bitOr(n * 1048576, bitOr((n + t_iWrap) / 4096, 524288)) + c + else b = bitOr(n * 1048576, n / 4096) + c + n = bitOr(bitAnd(b, d), bitAnd(c, bitNot(d))) + a + x[i + 9] + 568446438 + if(n < 0) then a = bitOr(n * 32, bitOr((n + t_iWrap) / 134217728, 16)) + b + else a = bitOr(n * 32, n / 134217728) + b + n = bitOr(bitAnd(a, c), bitAnd(b, bitNot(c))) + d + x[i + 14] - 1019803690 + if(n < 0) then d = bitOr(n * 512, bitOr((n + t_iWrap) / 8388608, 256)) + a + else d = bitOr(n * 512, n / 8388608) + a + n = bitOr(bitAnd(d, b), bitAnd(a, bitNot(b))) + c + x[i + 3] - 187363961 + if(n < 0) then c = bitOr(n * 16384, bitOr((n + t_iWrap) / 262144, 8192)) + d + else c = bitOr(n * 16384, n / 262144) + d + n = bitOr(bitAnd(c, a), bitAnd(d, bitNot(a))) + b + x[i + 8] + 1163531501 + if(n < 0) then b = bitOr(n * 1048576, bitOr((n + t_iWrap) / 4096, 524288)) + c + else b = bitOr(n * 1048576, n / 4096) + c + n = bitOr(bitAnd(b, d), bitAnd(c, bitNot(d))) + a + x[i + 13] - 1444681467 + if(n < 0) then a = bitOr(n * 32, bitOr((n + t_iWrap) / 134217728, 16)) + b + else a = bitOr(n * 32, n / 134217728) + b + n = bitOr(bitAnd(a, c), bitAnd(b, bitNot(c))) + d + x[i + 2] - 51403784 + if(n < 0) then d = bitOr(n * 512, bitOr((n + t_iWrap) / 8388608, 256)) + a + else d = bitOr(n * 512, n / 8388608) + a + n = bitOr(bitAnd(d, b), bitAnd(a, bitNot(b))) + c + x[i + 7] + 1735328473 + if(n < 0) then c = bitOr(n * 16384, bitOr((n + t_iWrap) / 262144, 8192)) + d + else c = bitOr(n * 16384, n / 262144) + d + n = bitOr(bitAnd(c, a), bitAnd(d, bitNot(a))) + b + x[i + 12] - 1926607734 + if(n < 0) then b = bitOr(n * 1048576, bitOr((n + t_iWrap) / 4096, 524288)) + c + else b = bitOr(n * 1048576, n / 4096) + c + + -- Round(3) -- + n = bitXor(bitXor(b, c), d) + a + x[i + 5] - 378558 + if(n < 0) then a = bitOr(n * 16, bitOr((n + t_iWrap) / 268435456, 8)) + b + else a = bitOr(n * 16, n / 268435456) + b + n = bitXor(bitXor(a, b), c) + d + x[i + 8] - 2022574463 + if(n < 0) then d = bitOr(n * 2048, bitOr((n + t_iWrap) / 2097152, 1024)) + a + else d = bitOr(n * 2048, n / 2097152) + a + n = bitXor(bitXor(d, a), b) + c + x[i + 11] + 1839030562 + if(n < 0) then c = bitOr(n * 65536, bitOr((n + t_iWrap) / 65536, 32768)) + d + else c = bitOr(n * 65536, n / 65536) + d + n = bitXor(bitXor(c, d), a) + b + x[i + 14] - 35309556 + if(n < 0) then b = bitOr(n * 8388608, bitOr((n + t_iWrap) / 512, 4194304)) + c + else b = bitOr(n * 8388608, n / 512) + c + n = bitXor(bitXor(b, c), d) + a + x[i + 1] - 1530992060 + if(n < 0) then a = bitOr(n * 16, bitOr((n + t_iWrap) / 268435456, 8)) + b + else a = bitOr(n * 16, n / 268435456) + b + n = bitXor(bitXor(a, b), c) + d + x[i + 4] + 1272893353 + if(n < 0) then d = bitOr(n * 2048, bitOr((n + t_iWrap) / 2097152, 1024)) + a + else d = bitOr(n * 2048, n / 2097152) + a + n = bitXor(bitXor(d, a), b) + c + x[i + 7] - 155497632 + if(n < 0) then c = bitOr(n * 65536, bitOr((n + t_iWrap) / 65536, 32768)) + d + else c = bitOr(n * 65536, n / 65536) + d + n = bitXor(bitXor(c, d), a) + b + x[i + 10] - 1094730640 + if(n < 0) then b = bitOr(n * 8388608, bitOr((n + t_iWrap) / 512, 4194304)) + c + else b = bitOr(n * 8388608, n / 512) + c + n = bitXor(bitXor(b, c), d) + a + x[i + 13] + 681279174 + if(n < 0) then a = bitOr(n * 16, bitOr((n + t_iWrap) / 268435456, 8)) + b + else a = bitOr(n * 16, n / 268435456) + b + n = bitXor(bitXor(a, b), c) + d + x[i] - 358537222 + if(n < 0) then d = bitOr(n * 2048, bitOr((n + t_iWrap) / 2097152, 1024)) + a + else d = bitOr(n * 2048, n / 2097152) + a + n = bitXor(bitXor(d, a), b) + c + x[i + 3] - 722521979 + if(n < 0) then c = bitOr(n * 65536, bitOr((n + t_iWrap) / 65536, 32768)) + d + else c = bitOr(n * 65536, n / 65536) + d + n = bitXor(bitXor(c, d), a) + b + x[i + 6] + 76029189 + if(n < 0) then b = bitOr(n * 8388608, bitOr((n + t_iWrap) / 512, 4194304)) + c + else b = bitOr(n * 8388608, n / 512) + c + n = bitXor(bitXor(b, c), d) + a + x[i + 9] - 640364487 + if(n < 0) then a = bitOr(n * 16, bitOr((n + t_iWrap) / 268435456, 8)) + b + else a = bitOr(n * 16, n / 268435456) + b + n = bitXor(bitXor(a, b), c) + d + x[i + 12] - 421815835 + if(n < 0) then d = bitOr(n * 2048, bitOr((n + t_iWrap) / 2097152, 1024)) + a + else d = bitOr(n * 2048, n / 2097152) + a + n = bitXor(bitXor(d, a), b) + c + x[i + 15] + 530742520 + if(n < 0) then c = bitOr(n * 65536, bitOr((n + t_iWrap) / 65536, 32768)) + d + else c = bitOr(n * 65536, n / 65536) + d + n = bitXor(bitXor(c, d), a) + b + x[i + 2] - 995338651 + if(n < 0) then b = bitOr(n * 8388608, bitOr((n + t_iWrap) / 512, 4194304)) + c + else b = bitOr(n * 8388608, n / 512) + c + + -- Round(4) -- + n = bitXor(c, bitOr(b, bitNot(d))) + a + x[i] - 198630844 + if(n < 0) then a = bitOr(n * 64, bitOr((n + t_iWrap) / 67108864, 32)) + b + else a = bitOr(n * 64, n / 67108864) + b + n = bitXor(b, bitOr(a, bitNot(c))) + d + x[i + 7] + 1126891415 + if(n < 0) then d = bitOr(n * 1024, bitOr((n + t_iWrap) / 4194304, 512)) + a + else d = bitOr(n * 1024, n / 4194304) + a + n = bitXor(a, bitOr(d, bitNot(b))) + c + x[i + 14] - 1416354905 + if(n < 0) then c = bitOr(n * 32768, bitOr((n + t_iWrap) / 131072, 16384)) + d + else c = bitOr(n * 32768, n / 131072) + d + n = bitXor(d, bitOr(c, bitNot(a))) + b + x[i + 5] - 57434055 + if(n < 0) then b = bitOr(n * 2097152, bitOr((n + t_iWrap) / 2048, 1048576)) + c + else b = bitOr(n * 2097152, n / 2048) + c + n = bitXor(c, bitOr(b, bitNot(d))) + a + x[i + 12] + 1700485571 + if(n < 0) then a = bitOr(n * 64, bitOr((n + t_iWrap) / 67108864, 32)) + b + else a = bitOr(n * 64, n / 67108864) + b + n = bitXor(b, bitOr(a, bitNot(c))) + d + x[i + 3] - 1894986606 + if(n < 0) then d = bitOr(n * 1024, bitOr((n + t_iWrap) / 4194304, 512)) + a + else d = bitOr(n * 1024, n / 4194304) + a + n = bitXor(a, bitOr(d, bitNot(b))) + c + x[i + 10] - 1051523 + if(n < 0) then c = bitOr(n * 32768, bitOr((n + t_iWrap) / 131072, 16384)) + d + else c = bitOr(n * 32768, n / 131072) + d + n = bitXor(d, bitOr(c, bitNot(a))) + b + x[i + 1] - 2054922799 + if(n < 0) then b = bitOr(n * 2097152, bitOr((n + t_iWrap) / 2048, 1048576)) + c + else b = bitOr(n * 2097152, n / 2048) + c + n = bitXor(c, bitOr(b, bitNot(d))) + a + x[i + 8] + 1873313359 + if(n < 0) then a = bitOr(n * 64, bitOr((n + t_iWrap) / 67108864, 32)) + b + else a = bitOr(n * 64, n / 67108864) + b + n = bitXor(b, bitOr(a, bitNot(c))) + d + x[i + 15] - 30611744 + if(n < 0) then d = bitOr(n * 1024, bitOr((n + t_iWrap) / 4194304, 512)) + a + else d = bitOr(n * 1024, n / 4194304) + a + n = bitXor(a, bitOr(d, bitNot(b))) + c + x[i + 6] - 1560198380 + if(n < 0) then c = bitOr(n * 32768, bitOr((n + t_iWrap) / 131072, 16384)) + d + else c = bitOr(n * 32768, n / 131072) + d + n = bitXor(d, bitOr(c, bitNot(a))) + b + x[i + 13] + 1309151649 + if(n < 0) then b = bitOr(n * 2097152, bitOr((n + t_iWrap) / 2048, 1048576)) + c + else b = bitOr(n * 2097152, n / 2048) + c + n = bitXor(c, bitOr(b, bitNot(d))) + a + x[i + 4] - 145523070 + if(n < 0) then a = bitOr(n * 64, bitOr((n + t_iWrap) / 67108864, 32)) + b + else a = bitOr(n * 64, n / 67108864) + b + n = bitXor(b, bitOr(a, bitNot(c))) + d + x[i + 11] - 1120210379 + if(n < 0) then d = bitOr(n * 1024, bitOr((n + t_iWrap) / 4194304, 512)) + a + else d = bitOr(n * 1024, n / 4194304) + a + n = bitXor(a, bitOr(d, bitNot(b))) + c + x[i + 2] + 718787259 + if(n < 0) then c = bitOr(n * 32768, bitOr((n + t_iWrap) / 131072, 16384)) + d + else c = bitOr(n * 32768, n / 131072) + d + n = bitXor(d, bitOr(c, bitNot(a))) + b + x[i + 9] - 343485551 + if(n < 0) then b = bitOr(n * 2097152, bitOr((n + t_iWrap) / 2048, 1048576)) + c + else b = bitOr(n * 2097152, n / 2048) + c + a = a + olda + b = b + oldb + c = c + oldc + d = d + oldd + i = i + 16 + end repeat + + t_iArr = [a, b, c, d] + ba = bytearray() + p = 1 + repeat with i in t_iArr + if(i > 0) then + repeat with n = 1 to 4 + ba[p] = (i mod 256) + i = i / 256 + p = p+1 + end repeat + else + i = bitNot(i) + repeat with n = 1 to 4 + ba[p] = 255-(i mod 256) + i = i / 256 + p = p+1 + end repeat + end if + end repeat + ba.position = 1 + return ba +end diff --git a/Task/MD5-Implementation/Lingo/md5-implementation-2.lingo b/Task/MD5-Implementation/Lingo/md5-implementation-2.lingo new file mode 100644 index 0000000000..7fe399cc0a --- /dev/null +++ b/Task/MD5-Implementation/Lingo/md5-implementation-2.lingo @@ -0,0 +1,12 @@ +tests = [] +tests.add("") +tests.add("a") +tests.add("abc") +tests.add("message digest") +tests.add("abcdefghijklmnopqrstuvwxyz") +tests.add("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") +tests.add("12345678901234567890123456789012345678901234567890123456789012345678901234567890") +repeat with t in tests + ba = md5(t) + put ba.toHexString(1, ba.length) +end repeat diff --git a/Task/MD5-Implementation/Perl-6/md5-implementation.pl6 b/Task/MD5-Implementation/Perl-6/md5-implementation.pl6 index a438619de1..f944a20cd1 100644 --- a/Task/MD5-Implementation/Perl-6/md5-implementation.pl6 +++ b/Task/MD5-Implementation/Perl-6/md5-implementation.pl6 @@ -19,16 +19,16 @@ constant k = flat ( $_ for ^16), ((7*$_ ) % 16 for ^16); sub little-endian($w, $n, *@v) { - my \step1 = ($w X* ^$n).eager; # temporary bug workaround - my \step2 = (@v X+> step1); - step2 X% (2 ** $w); + my \step1 = $w X* ^$n; + my \step2 = @v X+> step1; + step2 X% 2**$w; } sub md5-pad(Blob $msg) { - my \bits = 8 * $msg.elems; - my @padded = flat $msg.list, 0x80, 0x00 xx (-(bits div 8 + 1 + 8) % 64); - flat @padded.map({ :256[$^d,$^c,$^b,$^a] }), little-endian(32, 2, bits); + my $bits = 8 * $msg.elems; + my @padded = flat $msg.list, 0x80, 0x00 xx -($bits div 8 + 1 + 8) % 64; + flat @padded.map({ :256[$^d,$^c,$^b,$^a] }), little-endian(32, 2, $bits); } sub md5-block(@H, @X) diff --git a/Task/MD5-Implementation/Scala/md5-implementation.scala b/Task/MD5-Implementation/Scala/md5-implementation.scala new file mode 100644 index 0000000000..6fb43f4de3 --- /dev/null +++ b/Task/MD5-Implementation/Scala/md5-implementation.scala @@ -0,0 +1,20 @@ +object MD5 extends App { + + def hash(s: String) = { + def b = s.getBytes("UTF-8") + + def m = java.security.MessageDigest.getInstance("MD5").digest(b) + + BigInt(1, m).toString(16).reverse.padTo(32, "0").reverse.mkString + } + + assert("d41d8cd98f00b204e9800998ecf8427e" == hash("")) + assert("0000045c5e2b3911eb937d9d8c574f09" == hash("iwrupvqb346386")) + assert("0cc175b9c0f1b6a831c399e269772661" == hash("a")) + assert("900150983cd24fb0d6963f7d28e17f72" == hash("abc")) + assert("f96b697d7cb7938d525a2f31aaf161d0" == hash("message digest")) + assert("c3fcd3d76192e4007dfb496cca67e13b" == hash("abcdefghijklmnopqrstuvwxyz")) + assert("d174ab98d277d9f5a5611c2c9f419d9f" == hash("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")) + assert("57edf4a22be3c955ac49da2e2107b67a" == hash("12345678901234567890123456789012345678901234567890123456789012345678901234567890")) + +} diff --git a/Task/MD5/Julia/md5.julia b/Task/MD5/Julia/md5.julia index 4d6c3c39aa..f0696e4bb3 100644 --- a/Task/MD5/Julia/md5.julia +++ b/Task/MD5/Julia/md5.julia @@ -1,19 +1,15 @@ using Nettle -function md5sum(s::String) - bytes2hex(md5_hash(s)) +function Base.trunc(s::AbstractString, n::Integer) + n > 0 || throw(DomainError()) + l = length(s) + l > n || return s + n > 3 || return s[1:n] + return s[1:n-3] * "..." end -function Base.trunc(s::String, n::Integer) - 0 < n || throw(DomainError()) - len = length(s) - len > n || return s - 3 < n || return s[1:n] - return s[1:n-3]*"..." -end - -tests = ["" => "d41d8cd98f00b204e9800998ecf8427e", - "a" => "0cc175b9c0f1b6a831c399e269772661", +tests = ["" => "d41d8cd98f00b204e9800998ecf8427e", + "a" => "0cc175b9c0f1b6a831c399e269772661", "abc" => "900150983cd24fb0d6963f7d28e17f72", "message digest" => "f96b697d7cb7938d525a2f31aaf161d0", "abcdefghijklmnopqrstuvwxyz" => "c3fcd3d76192e4007dfb496cca67e13b", @@ -23,15 +19,14 @@ tests = ["" => "d41d8cd98f00b204e9800998ecf8427e", "57edf4a22be3c955ac49da2e2107b67a", "foobad" => "3858f62230ac3c915f300c664312c63f"] - println("Testing Julia's MD5 hash against RFC 1321.") -for k in sort(collect(keys(tests)), by=(x)->length(x)) - mysum = md5sum(k) - print(@sprintf(" %15s => ", trunc(k, 15)), mysum) - if mysum == tests[k] - println(" MD5 OK") +for (k, h) in sort(tests, by = length ∘ first) + md5sum = hexdigest("md5", k) + @printf("%20s → %s ", trunc(k, 15), md5sum) + if md5sum == h + println("MD5 OK") else - println(" MD5 Bad") - println(" The sum should be ", tests[k]) + println("MD5 Bad") + println("* The sum should be ", h) end end diff --git a/Task/MD5/Lingo/md5-2.lingo b/Task/MD5/Lingo/md5-2.lingo index fe35ad7dc8..bc2ec8dcdc 100644 --- a/Task/MD5/Lingo/md5-2.lingo +++ b/Task/MD5/Lingo/md5-2.lingo @@ -12,7 +12,7 @@ on md5 (input) -- Create list, fill with zeros... x = [] - x.SetAt(t_iCnt, 0) + x[t_iCnt] = 0 t_fArr = [1, 256, 65536, 16777216] i = 0 @@ -32,18 +32,15 @@ on md5 (input) x[(t_iLen + 64) / 512 * 16 + 15] = t_iLen -- Actual algorithm starts here... - a = 1732584193 b = -271733879 c = -1732584194 d = 271733878 i = 1 - t_iWrap = the maxInteger + 1 t_iCount = x.count + 1 repeat while i < t_iCount - olda = a oldb = b oldc = c @@ -248,17 +245,14 @@ on md5 (input) n = bitXor(d, bitOr(c, bitNot(a))) + b + x[i + 9] - 343485551 if(n < 0) then b = bitOr(n * 2097152, bitOr((n + t_iWrap) / 2048, 1048576)) + c else b = bitOr(n * 2097152, n / 2048) + c - a = a + olda b = b + oldb c = c + oldc d = d + oldd i = i + 16 - end repeat t_iArr = [a, b, c, d] - ba = bytearray() p = 1 repeat with i in t_iArr diff --git a/Task/Mad-Libs/00DESCRIPTION b/Task/Mad-Libs/00DESCRIPTION index 6e74702f2a..0678a9395b 100644 --- a/Task/Mad-Libs/00DESCRIPTION +++ b/Task/Mad-Libs/00DESCRIPTION @@ -22,6 +22,11 @@ The input should be an arbitrary story in the form: found a . decided to take it home. Given this example, it should then ask for a name, a he or she and a noun ( gets replaced both times with the same value). + + +;Related tasks: +*   [[Old_lady_swallowed_a_fly]] +*   [[The Twelve Days of Christmas]]

== {{header|Ada}} == diff --git a/Task/Mad-Libs/Aime/mad-libs.aime b/Task/Mad-Libs/Aime/mad-libs.aime index 0236a5b865..08e53a36d7 100644 --- a/Task/Mad-Libs/Aime/mad-libs.aime +++ b/Task/Mad-Libs/Aime/mad-libs.aime @@ -1,43 +1,33 @@ -integer i; file f; data b; list l; record r; -f_affix(f, "/dev/stdin"); +f.stdin; o_text("Enter the blank line terminated story:\n"); -while (0 < f_b_line(f, b)) { - l_append(l, b); +while (0 < f.b_line(b)) { + l.append(b); } -i = 0; -while (i < l_length(l)) { +for (, b in l) { integer p, q; text s, t; - b = l_q_data(l, i); - - while ((p = b_index(b, '<')) ^ -1) { - q = b_probe(b, p, '>'); + while ((p = b.place('<')) ^ -1) { + q = b.probe(p, '>'); if (q ^ -1) { - s = cut(b_string(b), p + 1, q - p - 1); - b_erase(b, p, q); - if (!r_key(r, s)) { - o_text(cat3("Replacement for `", s, ":'\n")); - f_line(f, t); - r_put(r, s, t); + s = bq_string(b, p + 1, q - 1); + b.erase(p, q); + if (!r.key(s)) { + o_("Replacement for `", s, "':\n"); + f.line(t); + r.put(s, t); } - b_paste(b, p, r_query(r, s)); + b.paste(p, r[s]); } } - - i += 1; } -while (l_length(l)) { - o_text(b_string(l_head(l))); - o_newline(); - l_delete(l, 0); -} +l.ucall(o_, 0, "\n"); diff --git a/Task/Mad-Libs/AppleScript/mad-libs.applescript b/Task/Mad-Libs/AppleScript/mad-libs.applescript new file mode 100644 index 0000000000..feab5cf428 --- /dev/null +++ b/Task/Mad-Libs/AppleScript/mad-libs.applescript @@ -0,0 +1,7 @@ +set theNoun to the text returned of (display dialog "What is your noun?" default answer "") + +set thePerson to the text returned of (display dialog "What is the person's name?" default answer "") + +set theGender to the text returned of (display dialog "He or she? Please capitalize." default answer "") + +display dialog thePerson & " went for a walk in the park. " & theGender & " found a " & theNoun & ". " & thePerson & " decided to take it home." diff --git a/Task/Mad-Libs/Julia/mad-libs.julia b/Task/Mad-Libs/Julia/mad-libs.julia new file mode 100644 index 0000000000..4324a587b2 --- /dev/null +++ b/Task/Mad-Libs/Julia/mad-libs.julia @@ -0,0 +1,18 @@ +function madlibs(template) + println("The story template is:\n", template) + fields = Set(getfield.(collect(eachmatch(r"<[^>]+>", template)), :match)) + print("\nInput a comma-separated list of words to replace the following items:", + join(fields, ", "), "\n -> ") + values = split(readline(STDIN), ",") + for (m, v) in zip(fields, values) + template = replace(template, m, v) + end + println("\nThe story becomes:\n", template) +end + +const template = """ + went for a walk in the park. +found a . decided to take it home. +""" + +madlibs(template) diff --git a/Task/Magic-squares-of-odd-order/BASIC/magic-squares-of-odd-order.basic b/Task/Magic-squares-of-odd-order/BASIC/magic-squares-of-odd-order.basic new file mode 100644 index 0000000000..d9c750a554 --- /dev/null +++ b/Task/Magic-squares-of-odd-order/BASIC/magic-squares-of-odd-order.basic @@ -0,0 +1,13 @@ + 100 : + 110 REM MAGIC SQUARE OF ODD ORDER + 120 : + 130 DEF FN MOD(A) = A - INT (A / N) * N + 140 DEF FN NR(J) = FN MOD((J + 2 * I + 1)) + 200 INPUT "ENTER N: ";N + 210 IF N < 3 OR (N - INT (N / 2) * 2) = 0 GOTO 200 + 220 FOR I = 0 TO (N - 1) + 230 FOR J = 0 TO (N - 1): HTAB 4 * (J + 1) + 240 PRINT N * FN NR(N - J - 1) + FN NR(J) + 1; + 250 NEXT J: PRINT + 260 NEXT I + 270 PRINT "MAGIC CONSTANT: ";N * (N * N + 1) / 2 diff --git a/Task/Main-step-of-GOST-28147-89/00DESCRIPTION b/Task/Main-step-of-GOST-28147-89/00DESCRIPTION index c23ad81b66..5bfd4ee8a0 100644 --- a/Task/Main-step-of-GOST-28147-89/00DESCRIPTION +++ b/Task/Main-step-of-GOST-28147-89/00DESCRIPTION @@ -1,7 +1,12 @@ -[[wp:GOST (block cipher)|GOST 28147-89]] is a standard symmetric encryption based on a [[wp:Feistel cipher|Feistel network]]. Structure of the algorithm consists of three levels: +[[wp:GOST (block cipher)|GOST 28147-89]] is a standard symmetric encryption based on a [[wp:Feistel cipher|Feistel network]]. -# encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation; -# cycles - 32-З, 32-Р and 16-З, is a repetition of the main step; -# ''main step'', a function that takes a 64-bit block of text and one of the eight 32-bit encryption key elements, and uses the replacement table (8x16 matrix of 4-bit values), and returns encrypted block. +The structure of the algorithm consists of three levels: +#   encryption modes - simple replacement, application range, imposing a range of feedback and authentication code generation; +#   cycles - 32-З, 32-Р and 16-З, is a repetition of the main step; +#   ''main step'', a function that takes a 64-bit block of text and one of the eight 32-bit encryption key elements, and uses the replacement table (8x16 matrix of 4-bit values), and returns encrypted block. + + +;Task: Implement the main step of this encryption algorithm. +

diff --git a/Task/Main-step-of-GOST-28147-89/Julia/main-step-of-gost-28147-89.julia b/Task/Main-step-of-GOST-28147-89/Julia/main-step-of-gost-28147-89.julia new file mode 100644 index 0000000000..7afa767444 --- /dev/null +++ b/Task/Main-step-of-GOST-28147-89/Julia/main-step-of-gost-28147-89.julia @@ -0,0 +1,41 @@ +const k8 = [ 4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3] +const k7 = [14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9] +const k6 = [ 5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11] +const k5 = [ 7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3] +const k4 = [ 6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2] +const k3 = [ 4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14] +const k2 = [13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12] +const k1 = [ 1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12] +const k87 = zeros(UInt32,256) +const k65 = zeros(UInt32,256) +const k43 = zeros(UInt32,256) +const k21 = zeros(UInt32,256) +for i in 1:256 + j = (i-1) >> 4 + 1 + k = (i-1) & 15 + 1 + k87[i] = (k1[j] << 4) | k2[k] + k65[i] = (k3[j] << 4) | k4[k] + k43[i] = (k5[j] << 4) | k6[k] + k21[i] = (k7[j] << 4) | k8[k] +end + +function f(x) + y = (k87[(x>>24) & 0xff + 1] << 24) | (k65[(x>>16) & 0xff + 1] << 16) | + (k43[(x>> 8) & 0xff + 1] << 8) | k21[x & 0xff + 1] + (y << 11) | (y >> (32-11)) +end + +bytes2int(arr) = arr[1] + (UInt32(arr[2]) << 8) + (UInt32(arr[3]) << 16) + (UInt32(arr[4])) << 24 +int2bytes(x) = [UInt8(x&0xff), UInt8((x&0xff00)>>8), UInt8((x&0xff0000)>>16), UInt8(x>>24)] + +function mainstep(inputbytes, keybytes) + intkey = bytes2int(keybytes) + lowint = bytes2int(inputbytes[1:4]) + topint = bytes2int(inputbytes[5:8]) + xorbytes = f(UInt32(intkey) + UInt32(lowint)) ⊻ topint + vcat(int2bytes(xorbytes), inputbytes[1:4]) +end + +const input = [0x21, 0x04, 0x3B, 0x04, 0x30, 0x04, 0x32, 0x04] +const key = [0xF9, 0x04, 0xC1, 0xE2] +println("The encoded bytes are $(mainstep(input, key))") diff --git a/Task/Main-step-of-GOST-28147-89/Kotlin/main-step-of-gost-28147-89.kotlin b/Task/Main-step-of-GOST-28147-89/Kotlin/main-step-of-gost-28147-89.kotlin new file mode 100644 index 0000000000..b99f035cda --- /dev/null +++ b/Task/Main-step-of-GOST-28147-89/Kotlin/main-step-of-gost-28147-89.kotlin @@ -0,0 +1,77 @@ +// version 1.1.4-3 + +fun Byte.toUInt() = java.lang.Byte.toUnsignedInt(this) + +fun Byte.toULong() = java.lang.Byte.toUnsignedLong(this) + +fun Int.toULong() = java.lang.Integer.toUnsignedLong(this) + +val s = arrayOf( + byteArrayOf( 4, 10, 9, 2, 13, 8, 0, 14, 6, 11, 1, 12, 7, 15, 5, 3), + byteArrayOf(14, 11, 4, 12, 6, 13, 15, 10, 2, 3, 8, 1, 0, 7, 5, 9), + byteArrayOf( 5, 8, 1, 13, 10, 3, 4, 2, 14, 15, 12, 7, 6, 0, 9, 11), + byteArrayOf( 7, 13, 10, 1, 0, 8, 9, 15, 14, 4, 6, 12, 11, 2, 5, 3), + byteArrayOf( 6, 12, 7, 1, 5, 15, 13, 8, 4, 10, 9, 14, 0, 3, 11, 2), + byteArrayOf( 4, 11, 10, 0, 7, 2, 1, 13, 3, 6, 8, 5, 9, 12, 15, 14), + byteArrayOf(13, 11, 4, 1, 3, 15, 5, 9, 0, 10, 14, 7, 6, 8, 2, 12), + byteArrayOf( 1, 15, 13, 0, 5, 7, 10, 4, 9, 2, 3, 14, 6, 11, 8, 12) +) + +class Gost(val sBox: Array) { + + val k87 = ByteArray(256) + val k65 = ByteArray(256) + val k43 = ByteArray(256) + val k21 = ByteArray(256) + val enc = ByteArray(8) + + init { + for (i in 0 until 256) { + val j = i ushr 4 + val k = i and 15 + k87[i] = ((sBox[7][j].toUInt() shl 4) or sBox[6][k].toUInt()).toByte() + k65[i] = ((sBox[5][j].toUInt() shl 4) or sBox[4][k].toUInt()).toByte() + k43[i] = ((sBox[3][j].toUInt() shl 4) or sBox[2][k].toUInt()).toByte() + k21[i] = ((sBox[1][j].toUInt() shl 4) or sBox[0][k].toUInt()).toByte() + } + } + + fun f(x: Int): Int { + val y = (k87[(x ushr 24) and 255].toULong() shl 24) or + (k65[(x ushr 16) and 255].toULong() shl 16) or + (k43[(x ushr 8) and 255].toULong() shl 8) or + (k21[ x and 255].toULong()) + return ((y shl 11) or (y ushr 21)).toInt() + } + + fun u32(ba: ByteArray): Int = + (ba[0].toULong() or + (ba[1].toULong() shl 8) or + (ba[2].toULong() shl 16) or + (ba[3].toULong() shl 24)).toInt() + + fun b4(u: Int) { + enc[0] = u.toByte() + enc[1] = (u ushr 8).toByte() + enc[2] = (u ushr 16).toByte() + enc[3] = (u ushr 24).toByte() + } + + fun mainStep(input: ByteArray, key: ByteArray) { + val key32 = u32(key) + val input1 = u32(input.sliceArray(0..3)) + val input2 = u32(input.sliceArray(4..7)) + val temp = (key32.toULong() + input1.toULong()).toInt() + b4(f(temp) xor input2) + for (i in 0..3) enc[4 + i] = input[i] + } +} + +fun main(args: Array) { + val input = byteArrayOf(0x21, 0x04, 0x3B, 0x04, 0x30, 0x04, 0x32, 0x04) + val key = byteArrayOf(0xF9.toByte(), 0x04, 0xC1.toByte(), 0xE2.toByte()) + val g = Gost(s) + g.mainStep(input, key) + for (b in g.enc) print("[%02X]".format(b)) + println() +} diff --git a/Task/Main-step-of-GOST-28147-89/REXX/main-step-of-gost-28147-89.rexx b/Task/Main-step-of-GOST-28147-89/REXX/main-step-of-gost-28147-89.rexx index 9403afceb1..087caa53ff 100644 --- a/Task/Main-step-of-GOST-28147-89/REXX/main-step-of-gost-28147-89.rexx +++ b/Task/Main-step-of-GOST-28147-89/REXX/main-step-of-gost-28147-89.rexx @@ -1,28 +1,26 @@ -/*REXX pgm implements main step GOST 28147-89 based on a Feistel network*/ -numeric digits 12 /* ┌── a list of 4─bit S─box values used by */ - /* ↓ the Central Bank of Russian Federation.*/ -_.0 = 4 10 9 2 13 8 0 14 6 11 1 12 7 15 5 3 -_.1 = 14 11 4 12 6 13 15 10 2 3 8 1 0 7 5 9 -_.2 = 5 8 1 13 10 3 4 2 14 15 12 7 6 0 9 11 -_.3 = 7 13 10 1 0 8 9 15 14 4 6 12 11 2 5 3 -_.4 = 6 12 7 1 5 15 13 8 4 10 9 14 0 3 11 2 -_.5 = 4 11 10 0 7 2 1 13 3 6 8 5 9 12 15 14 -_.6 = 13 11 4 1 3 15 5 9 0 10 14 7 6 8 2 12 -_.7 = 1 15 13 0 5 7 10 4 9 2 3 14 6 11 8 12 - /* [↑] build the sub-keys array.*/ - do r=0 for 8; do c=0 for 16; !.r.c = word(_.r, c+1); end; end +/*REXX program implements main step GOST 28147-89 based on a Feistel network. */ +numeric digits 12 /* ┌── a list of 4─bit S─box values used by */ + /* ↓ the Central Bank of Russian Federation.*/ + @.0 = 4 10 9 2 13 8 0 14 6 11 1 12 7 15 5 3 + @.1 = 14 11 4 12 6 13 15 10 2 3 8 1 0 7 5 9 + @.2 = 5 8 1 13 10 3 4 2 14 15 12 7 6 0 9 11 + @.3 = 7 13 10 1 0 8 9 15 14 4 6 12 11 2 5 3 + @.4 = 6 12 7 1 5 15 13 8 4 10 9 14 0 3 11 2 + @.5 = 4 11 10 0 7 2 1 13 3 6 8 5 9 12 15 14 + @.6 = 13 11 4 1 3 15 5 9 0 10 14 7 6 8 2 12 + @.7 = 1 15 13 0 5 7 10 4 9 2 3 14 6 11 8 12 + /* [↓] build the sub-keys array from above. */ + do r=0 for 8; do c=0 for 16; !.r.c=word(@.r, c + 1); end; end +z=0 +#1=x2d( 43b0421 ); #2=x2d( 4320430 ); k=#1 + x2d( 0e2c104f9 ) + do while k > x2d( 7ffFFffF ); k=k - 2**32; end + do while k < x2d( 80000000 ); k=k + 2**32; end -#.1=x2d(43b0421); #.2=x2d(4320430); key=x2d(0e2c104f9); z=0 -k=#.1+key; p=2**32 - do while k>2147483647; k = k - p; end - do while k<2147483648; k = k + p; end - - do i=0 for 4; $=x2d(right(d2x(k%2**(i*8)), 2)) - ii=i+i ; iip=ii+1 /*calculate array "subscripts". */ - cm=$//16 ; cd=$%16 /*perform modulus and integer div*/ - z=z + (!.ii.cm + 16*!.iip.cd) * 2**(i*8) - end /*i*/ /* [↑] encryption algorithm S-box*/ - /* [↓] encryption algorithm round*/ -k = c2d( bitxor( bitor( d2c(z* 2**11, 4), d2c(z% 2**21, 4)), d2c(#.2, 4))) -say center(d2x(k) d2x(#.1), 79) /*display the (centered) result.*/ - /*stick a fork in it, we're done.*/ + do j=0 for 4; jj=j + j; jjp=jj + 1 /*calculate the array'a "subscripts". */ + $=x2d( right( d2x( k % 2 ** (j * 8) ), 2) ) + cm=$ // 16; cd=$ % 16 /*perform modulus and integer division.*/ + z=z + (!.jj.cm + 16 * !.jjp.cd) * 2**(j*8) + end /*i*/ /* [↑] encryption algorithm for S-box.*/ + /* [↓] encryption algorithm round. */ +k = c2d( bitxor( bitor( d2c(z * 2**11, 4), d2c(z % 2**21, 4) ), d2c(#2, 4) ) ) +say center(d2x(k) ' ' d2x(#1), 79) /*stick a fork in it, we're all done. */ diff --git a/Task/Make-directory-path/Aime/make-directory-path.aime b/Task/Make-directory-path/Aime/make-directory-path.aime new file mode 100644 index 0000000000..d14ee4f63d --- /dev/null +++ b/Task/Make-directory-path/Aime/make-directory-path.aime @@ -0,0 +1,21 @@ +void +mkdirp(text path) +{ + list l; + text p, s; + + file().b_affix(path).news(l, 0, 0, "/"); + + for (, s in l) { + p = p + s + "/"; + trap_q(mkdir, p, 00755); + } +} + +integer +main(void) +{ + mkdirp("./path/to/dir"); + + 0; +} diff --git a/Task/Make-directory-path/AppleScript/make-directory-path.applescript b/Task/Make-directory-path/AppleScript/make-directory-path.applescript new file mode 100644 index 0000000000..78d978ab27 --- /dev/null +++ b/Task/Make-directory-path/AppleScript/make-directory-path.applescript @@ -0,0 +1,58 @@ +use framework "Foundation" +use scripting additions + + +-- createOrFindDirectoryMay :: Bool -> FilePath -> Maybe IO () +on createOrFindDirectoryMay(fp) + createDirectoryIfMissingMay(true, fp) +end createOrFindDirectoryMay + + +-- createDirectoryIfMissingMay :: Bool -> FilePath -> Maybe IO () +on createDirectoryIfMissingMay(blnParents, fp) + if doesPathExist(fp) then + nothing("Directory already exists: " & fp) + else + set e to reference + set ca to current application + set oPath to (ca's NSString's stringWithString:(fp))'s ¬ + stringByStandardizingPath + set {bool, nse} to ca's NSFileManager's ¬ + defaultManager's createDirectoryAtPath:(oPath) ¬ + withIntermediateDirectories:(blnParents) ¬ + attributes:(missing value) |error|:(e) + if bool then + just(fp) + else + nothing((localizedDescription of nse) as string) + end if + end if +end createDirectoryIfMissingMay + +-- TEST ---------------------------------------------------------------------- +on run + + createOrFindDirectoryMay("~/Desktop/Notes/today") + +end run + +-- GENERIC FUNCTIONS --------------------------------------------------------- + +-- doesPathExist :: FilePath -> IO Bool +on doesPathExist(strPath) + set ca to current application + ca's NSFileManager's defaultManager's ¬ + fileExistsAtPath:((ca's NSString's ¬ + stringWithString:strPath)'s ¬ + stringByStandardizingPath) +end doesPathExist + +-- just :: a -> Just a +on just(x) + {nothing:false, just:x} +end just + +-- nothing :: () -> Nothing +on nothing(msg) + {nothing:true, msg:msg} +end nothing diff --git a/Task/Make-directory-path/D/make-directory-path.d b/Task/Make-directory-path/D/make-directory-path.d new file mode 100644 index 0000000000..c2b3c14b54 --- /dev/null +++ b/Task/Make-directory-path/D/make-directory-path.d @@ -0,0 +1,29 @@ +import std.stdio; + +void main() { + makeDir("parent/test"); +} + +/// Manual implementation of what mkdirRecurse in std.file does. +void makeDir(string path) out { + import std.exception : enforce; + import std.file : exists; + enforce(path.exists, "Failed to create the requested directory."); +} body { + import std.array : array; + import std.file; + import std.path : pathSplitter, chainPath; + + auto workdir = ""; + foreach (dir; path.pathSplitter) { + workdir = chainPath(workdir, dir).array; + if (workdir.exists) { + if (!workdir.isDir) { + import std.conv : text; + throw new FileException(text("The file ", workdir, " in the path ", path, " is not a directory.")); + } + } else { + workdir.mkdir(); + } + } +} diff --git a/Task/Make-directory-path/Julia/make-directory-path.julia b/Task/Make-directory-path/Julia/make-directory-path.julia new file mode 100644 index 0000000000..a0df316732 --- /dev/null +++ b/Task/Make-directory-path/Julia/make-directory-path.julia @@ -0,0 +1 @@ +mkpath("/tmp/unusefuldir/helloworld.d/test123") diff --git a/Task/Make-directory-path/Lua/make-directory-path.lua b/Task/Make-directory-path/Lua/make-directory-path.lua new file mode 100644 index 0000000000..8c295abd56 --- /dev/null +++ b/Task/Make-directory-path/Lua/make-directory-path.lua @@ -0,0 +1,11 @@ +require("lfs") + +function mkdir (path) + local sep, pStr = package.config:sub(1, 1), "" + for dir in path:gmatch("[^" .. sep .. "]+") do + pStr = pStr .. dir .. sep + lfs.mkdir(pStr) + end +end + +mkdir("C:\\path\\to\\dir") -- Quoting backslashes requires escape sequence diff --git a/Task/Make-directory-path/Objeck/make-directory-path.objeck b/Task/Make-directory-path/Objeck/make-directory-path.objeck new file mode 100644 index 0000000000..9f1cf45240 --- /dev/null +++ b/Task/Make-directory-path/Objeck/make-directory-path.objeck @@ -0,0 +1,5 @@ +class Program { + function : Main(args : String[]) ~ Nil { + System.IO.File.Directory->CreatePath("your/path/name")->PrintLine(); + } +} diff --git a/Task/Man-or-boy-test/00DESCRIPTION b/Task/Man-or-boy-test/00DESCRIPTION index 65b56fe36d..ac864a13e9 100644 --- a/Task/Man-or-boy-test/00DESCRIPTION +++ b/Task/Man-or-boy-test/00DESCRIPTION @@ -112,9 +112,9 @@ The table below shows the result, call depths, and total calls for a range of '' |align="right"| 6,100,852 |align="right"| 13,172,239 |align="right"| 28,499,827 -|  -|  -|  +|align="right"| 61,786,266 +|align="right"| 134,202,509 +|align="right"| 292,011,464 |  |  |  @@ -218,4 +218,7 @@ The table below shows the result, call depths, and total calls for a range of '' |  |  |} -

+
+;Related tasks: +*   [[Jensen's Device]] +
diff --git a/Task/Man-or-boy-test/Aime/man-or-boy-test.aime b/Task/Man-or-boy-test/Aime/man-or-boy-test.aime index 64c7a7fcc2..2a2d9d87d6 100644 --- a/Task/Man-or-boy-test/Aime/man-or-boy-test.aime +++ b/Task/Man-or-boy-test/Aime/man-or-boy-test.aime @@ -1,13 +1,13 @@ integer F(list l) { - return l[1]; + l[1]; } integer eval(list l) { - return call(l[0], l); + l[0](l); } integer A(list); @@ -15,7 +15,7 @@ integer A(list); integer B(list l) { - return A(l_assemble(B, l[1] = __integer(l[1]) - 1, l, l[-5], l[-4], l[-3], l[-2])); + A(list(B, l[1] = l[1] - 1, l, l[-5], l[-4], l[-3], l[-2])); } integer @@ -29,7 +29,7 @@ A(list l) x = B(l); } - return x; + x; } integer @@ -46,7 +46,7 @@ main(void) l_append(fn1, F); l_append(fn1, -1); - o_(A(l_assemble(B, 10, f1, fn1, fn1, f1, f0)), "\n"); + o_(A(list(B, 10, f1, fn1, fn1, f1, f0)), "\n"); - return 0; + 0; } diff --git a/Task/Man-or-boy-test/Rust/man-or-boy-test.rust b/Task/Man-or-boy-test/Rust/man-or-boy-test.rust new file mode 100644 index 0000000000..12679fb8a0 --- /dev/null +++ b/Task/Man-or-boy-test/Rust/man-or-boy-test.rust @@ -0,0 +1,39 @@ +use std::cell::Cell; + +trait Arg { + fn run(&self) -> i32; +} + +impl Arg for i32 { + fn run(&self) -> i32 { *self } +} + +struct B<'a> { + k: &'a Cell, + x1: &'a Arg, + x2: &'a Arg, + x3: &'a Arg, + x4: &'a Arg, +} + +impl<'a> Arg for B<'a> { + fn run(&self) -> i32 { + self.k.set(self.k.get() - 1); + a(self.k.get(), self, self.x1, self.x2, self.x3, self.x4) + } +} + +fn a(k: i32, x1: &Arg, x2: &Arg, x3: &Arg, x4: &Arg, x5: &Arg) -> i32 { + if k <= 0 { + x4.run() + x5.run() + } else { + B{ + k: &Cell::new(k), + x1, x2, x3, x4 + }.run() + } +} + +pub fn main() { + println!("{}", a(10, &1, &-1, &-1, &1, &0)); +} diff --git a/Task/Man-or-boy-test/Swift/man-or-boy-test-1.swift b/Task/Man-or-boy-test/Swift/man-or-boy-test-1.swift index 3b524dc0df..66e38330cd 100644 --- a/Task/Man-or-boy-test/Swift/man-or-boy-test-1.swift +++ b/Task/Man-or-boy-test/Swift/man-or-boy-test-1.swift @@ -1,9 +1,16 @@ -func A(k: Int, _ x1: () -> Int, _ x2: () -> Int, _ x3: () -> Int, _ x4: () -> Int, _ x5: () -> Int) -> Int { +func A(_ k: Int, + _ x1: @escaping () -> Int, + _ x2: @escaping () -> Int, + _ x3: @escaping () -> Int, + _ x4: @escaping () -> Int, + _ x5: @escaping () -> Int) -> Int { var k1 = k + func B() -> Int { - k1-=1 + k1 -= 1 return A(k1, B, x1, x2, x3, x4) } + if k1 <= 0 { return x4() + x5() } else { diff --git a/Task/Man-or-boy-test/Swift/man-or-boy-test-2.swift b/Task/Man-or-boy-test/Swift/man-or-boy-test-2.swift index 89aabe3c7e..3b524dc0df 100644 --- a/Task/Man-or-boy-test/Swift/man-or-boy-test-2.swift +++ b/Task/Man-or-boy-test/Swift/man-or-boy-test-2.swift @@ -1,14 +1,14 @@ -func A(var k: Int, x1: () -> Int, x2: () -> Int, x3: () -> Int, x4: () -> Int, x5: () -> Int) -> Int { - var B: (() -> Int)! - B = { - k-- - return A(k, B, x1, x2, x3, x4) - } - if k <= 0 { - return x4() + x5() - } else { - return B() - } +func A(k: Int, _ x1: () -> Int, _ x2: () -> Int, _ x3: () -> Int, _ x4: () -> Int, _ x5: () -> Int) -> Int { + var k1 = k + func B() -> Int { + k1-=1 + return A(k1, B, x1, x2, x3, x4) + } + if k1 <= 0 { + return x4() + x5() + } else { + return B() + } } -println(A(10, {1}, {-1}, {-1}, {1}, {0})) +print(A(10, {1}, {-1}, {-1}, {1}, {0})) diff --git a/Task/Man-or-boy-test/Swift/man-or-boy-test-3.swift b/Task/Man-or-boy-test/Swift/man-or-boy-test-3.swift new file mode 100644 index 0000000000..89aabe3c7e --- /dev/null +++ b/Task/Man-or-boy-test/Swift/man-or-boy-test-3.swift @@ -0,0 +1,14 @@ +func A(var k: Int, x1: () -> Int, x2: () -> Int, x3: () -> Int, x4: () -> Int, x5: () -> Int) -> Int { + var B: (() -> Int)! + B = { + k-- + return A(k, B, x1, x2, x3, x4) + } + if k <= 0 { + return x4() + x5() + } else { + return B() + } +} + +println(A(10, {1}, {-1}, {-1}, {1}, {0})) diff --git a/Task/Mandelbrot-set/BASIC/mandelbrot-set-10.basic b/Task/Mandelbrot-set/BASIC/mandelbrot-set-10.basic new file mode 100644 index 0000000000..168460a577 --- /dev/null +++ b/Task/Mandelbrot-set/BASIC/mandelbrot-set-10.basic @@ -0,0 +1,15 @@ +Function mandel(xi As Double, yi As Double) + +maxiter = 256 +x = 0 +y = 0 + +For i = 1 To maxiter + If ((x * x) + (y * y)) > 4 Then Exit For + xt = xi + ((x * x) - (y * y)) + y = yi + (2 * x * y) + x = xt + Next + +mandel = i +End Function diff --git a/Task/Mandelbrot-set/BASIC/mandelbrot-set-11.basic b/Task/Mandelbrot-set/BASIC/mandelbrot-set-11.basic new file mode 100644 index 0000000000..a5ce972b0a --- /dev/null +++ b/Task/Mandelbrot-set/BASIC/mandelbrot-set-11.basic @@ -0,0 +1,20 @@ +1 REM MANDELBROT SET - TANDY COCO 3 +2 POKE 65497,1 +10 HSCREEN 2 +20 HCLS +30 X1=319:Y1=191 +40 I1=-1.0:I2=1.0:R1=-2:R2=1.0 +50 S1=(R2-R1)/X1:S2=(I2-I1)/Y1 +60 FOR Y=0 TO Y1 +70 I3=I1+S2*Y +80 FOR X=0 TO X1 +90 R3=R1+S1*X:Z1=R3:Z2=I3 +100 FOR N=0 TO 30 +110 A=Z1*Z1:B=Z2*Z2 +120 IF A+B>4.0 GOTO 150 +130 Z2=2*Z1*Z2+I3:Z1=A-B+R3 +140 NEXT N +150 HSET(X,Y,N-16*INT(N/16)) +160 NEXT X +170 NEXT Y +180 GOTO 180 diff --git a/Task/Mandelbrot-set/BASIC/mandelbrot-set-2.basic b/Task/Mandelbrot-set/BASIC/mandelbrot-set-2.basic index 0169237ea2..57733f59ff 100644 --- a/Task/Mandelbrot-set/BASIC/mandelbrot-set-2.basic +++ b/Task/Mandelbrot-set/BASIC/mandelbrot-set-2.basic @@ -2,32 +2,32 @@ fastgraphics graphsize 384,384 refresh -kt=319 : m = 4.0 -xmin=2.1 : xmax=-0.6 : ymin=-1.35 : ymax=1.35 -dx=(xmax-xmin)/graphwidth : dy=(ymax-ymin)/graphheight +kt = 319 : m = 4.0 +xmin = -2.1 : xmax = 0.6 : ymin = -1.35 : ymax = 1.35 +dx = (xmax - xmin) / graphwidth : dy = (ymax - ymin) / graphheight -for x=0 to graphwidth - jx = xmin+x*dx - for y=0 to graphheight - jy = ymin+y*dy +for x = 0 to graphwidth + jx = xmin + x * dx + for y = 0 to graphheight + jy = ymin + y * dy k = 0 : wx = 0.0 : wy = 0.0 do - tx = wx*wx-(wy*wy+jx) - ty = 2.0*wx*wy+jy + tx = wx * wx - wy * wy + jx + ty = 2.0 * wx * wy + jy wx = tx wy = ty - r = wx*wx+wy*wy - k = k+1 - until r>m or k>kt + r = wx * wx + wy * wy + k = k + 1 + until r > m or k > kt - if k>kt then + if k > kt then color black else - if k<16 then color k*8,k*8,128+k*4 - if k>=16 and k<64 then color 128+k-16,128+k-16,192+k-16 - if k>=64 then color kt-k,128+(kt-k)/2,kt-k + if k < 16 then color k * 8, k * 8, 128 + k * 4 + if k >= 16 and k < 64 then color 128 + k - 16, 128 + k - 16, 192 + k - 16 + if k >= 64 then color kt - k, 128 + (kt - k) / 2, kt - k end if - plot x,y + plot x, y next y refresh next x diff --git a/Task/Mandelbrot-set/BASIC/mandelbrot-set-6.basic b/Task/Mandelbrot-set/BASIC/mandelbrot-set-6.basic index 5e57b1a33a..d111bbc34b 100644 --- a/Task/Mandelbrot-set/BASIC/mandelbrot-set-6.basic +++ b/Task/Mandelbrot-set/BASIC/mandelbrot-set-6.basic @@ -1,85 +1,44 @@ -'Mandelbrot V4 for RunBasic -'Based on LibertyBasic solution -'copy the code and go to runbasic.com -'http://rosettacode.org/wiki/Mandelbrot_set#Liberty_BASIC -'May 2015 -' -WindowWidth = 320 'RunBasic max size 800 x 600 -WindowHeight = 320 -'print zone -2 to 1 (X) -'print zone -1.5 to 1.5 (Y) -a = -1.5 'graph -1.5 to -0.75, first "loop" -b = -0.75 'adjust for max processor time (y0 for loop below) - -'open "Mandelbrot Set" for graphics_nsb_nf as #w not used in RunBasic - -graphic #w, WindowWidth, WindowHeight -'#w "trapclose [quit]" not used in RunBasic -'#w "down" not used in RunBasic - -cls -'#w flush() -#w cls("black") -render #w - '#w flush() -input "OK, hit enter to continue"; guess -cls - -[man_calc] -'3/screen size 3/800 = 0.00375 ** 3/790 = 0.0037974 -'3/screen size (y) 3/600 = .005 ** 3/590 = 0.0050847 -'3/215 = .0139 .0068 = 3/440 -cc = 3/299 -' - for x0 = -2 to 1 step cc - for y0 = a to b step cc - x = 0 - y = 0 - - iteration = 0 - maxIteration = 255 - - while ( ( x *x +y *y) <=4) and ( iteration maxIteration then - c =iteration - else - c =0 - end if - - call pSet x0, y0, c - 'scan why scan? (wait for user input) with RunBasic ? - next -next - -'#w flush() 'what is flush? RunBasic uses the render command. -render #w - -input "OK, hit enter to continue"; guess -cls -a = a + 0.75 -b = b + 0.75 -if b > 1.6 then goto[quit] else goto[man_calc] - -sub pSet x, y, c - xScreen = 5+(x +2) /3 * 300 'need positive screen number - yScreen = 5+(y +1.5) /3 * 300 'and 5x5 boarder - if c =0 then - col$ ="red" - else - if c mod 2 =1 then col$ ="lightgray" else col$ ="white" - end if - #w "color "; col$ - #w "set "; xScreen; " "; yScreen -end sub - -[quit] -cls -render #w -print "All done, good bye." -end +1000 REM Mandelbrot Set Project +1010 REM Quite BASIC Math Project +1015 REM 'http://www.quitebasic.com/prj/math/mandelbrot/ +1020 REM ------------------------ +1030 CLS +1040 PRINT "This program plots a graphical representation of the famous Mandelbrot set. It takes a while to finish so have patience and don't have too high expectations; the graphics resolution is not very high on our canvas." +2000 REM Initialize the color palette +2010 GOSUB 3000 +2020 REM L is the maximum iterations to try +2030 LET L = 100 +2040 FOR I = 0 TO 100 +2050 FOR J = 0 TO 100 +2060 REM Map from pixel coordinates (I,J) to math (U,V) +2060 LET U = I / 50 - 1.5 +2070 LET V = J / 50 - 1 +2080 LET X = U +2090 LET Y = V +2100 LET N = 0 +2110 REM Inner iteration loop starts here +2120 LET R = X * X +2130 LET Q = Y * Y +2140 IF R + Q > 4 OR N >= L THEN GOTO 2190 +2150 LET Y = 2 * X * Y + V +2160 LET X = R - Q + U +2170 LET N = N + 1 +2180 GOTO 2120 +2190 REM Compute the color to plot +2200 IF N < 10 THEN LET C = "black" ELSE LET C = P[ROUND(8 * (N-10) / (L-10))] +2210 PLOT I, J, C +2220 NEXT J +2230 NEXT I +2240 END +3000 REM Subroutine -- Set up Palette +3010 ARRAY P +3020 LET P[0] = "black" +3030 LET P[1] = "magenta" +3040 LET P[2] = "blue" +3050 LET P[3] = "green" +3060 LET P[4] = "cyan" +3070 LET P[5] = "red" +3080 LET P[6] = "orange" +3090 LET P[7] = "yellow" +3090 LET P[8] = "white" +3100 RETURN diff --git a/Task/Mandelbrot-set/BASIC/mandelbrot-set-7.basic b/Task/Mandelbrot-set/BASIC/mandelbrot-set-7.basic index cabf53a96d..e42910ee38 100644 --- a/Task/Mandelbrot-set/BASIC/mandelbrot-set-7.basic +++ b/Task/Mandelbrot-set/BASIC/mandelbrot-set-7.basic @@ -1,13 +1,90 @@ - 10 FOR X=-2 TO 2 STEP 0.1 - 20 FOR Y=-2 TO 2 STEP 0.1 - 30 LET XA=0 - 40 LET YA=0 - 50 LET ITER=0 - 60 LET XTEMP=XA*XA-YA*YA+X - 70 LET YA=2*XA*YA+Y - 80 LET XA=XTEMP - 90 LET ITER=ITER+1 -100 IF XA*XA+YA*YA<=4 AND ITER<200 THEN GOTO 60 -110 IF ITER<200 THEN PLOT X*10+20,Y*10+20 -120 NEXT Y -130 NEXT X +'Mandelbrot V4 for RunBasic +'Based on LibertyBasic solution +'copy the code and go to runbasic.com +'http://rosettacode.org/wiki/Mandelbrot_set#Liberty_BASIC +'May 2015 (updated 29 Apr 2018) +' +'Note - we only get so much processing time on the server, so the +'graph is computed in three or four pieces +' +WindowWidth = 320 'RunBasic max size 800 x 600 +WindowHeight = 320 +'print zone -2 to 1 (X) +'print zone -1.5 to 1.5 (Y) +a = -1.5 'graph -1.5 to -0.75, first "loop" +b = -0.75 'adjust for max processor time (y0 for loop below) + +'open "Mandelbrot Set" for graphics_nsb_nf as #w not used in RunBasic + +graphic #w, WindowWidth, WindowHeight +'#w "trapclose [quit]" not used in RunBasic +'#w "down" not used in RunBasic + +cls +'#w flush() +#w cls("black") +render #w + '#w flush() +input "OK, hit enter to continue"; guess +cls + +[man_calc] +'3/screen size 3/800 = 0.00375 ** 3/790 = 0.0037974 +'3/screen size (y) 3/600 = .005 ** 3/590 = 0.0050847 +'3/215 = .0139 .0068 = 3/440 +cc = 3/299 +' + for x0 = -2 to 1 step cc + for y0 = a to b step cc + x = 0 + y = 0 + + iteration = 0 + maxIteration = 255 + + while ( ( x *x +y *y) <=4) and ( iteration maxIteration then + c =iteration + else + c =0 + end if + + call pSet x0, y0, c + 'scan why scan? (wait for user input) with RunBasic ? + next +next + +'#w flush() 'what is flush? RunBasic uses the render command. +render #w + +input "OK, hit enter to continue"; guess +cls +a = a + 0.75 +b = b + 0.75 +if b > 1.6 then goto[quit] else goto[man_calc] + +sub pSet x, y, c + xScreen = 5+(x +2) /3 * 300 'need positive screen number + yScreen = 5+(y +1.5) /3 * 300 'and 5x5 boarder + if c =0 then + col$ ="red" + else + if c mod 2 =1 then col$ ="lightgray" else col$ ="white" + end if + #w "color "; col$ + #w "set "; xScreen; " "; yScreen +end sub + +[quit] +'cls +print +print "This is a Mandelbrot Graph output from www.runbasic.com" +render #w +print "All done, good bye." +end diff --git a/Task/Mandelbrot-set/BASIC/mandelbrot-set-8.basic b/Task/Mandelbrot-set/BASIC/mandelbrot-set-8.basic index 9080950f17..ff02c4bd34 100644 --- a/Task/Mandelbrot-set/BASIC/mandelbrot-set-8.basic +++ b/Task/Mandelbrot-set/BASIC/mandelbrot-set-8.basic @@ -1,29 +1,15 @@ -GraphicsWindow.Show() -size = 500 -half = 250 -GraphicsWindow.Width = size * 1.5 -GraphicsWindow.Height = size -GraphicsWindow.Title = "Mandelbrot" -For px = 1 To size * 1.5 - x_0 = px/half - 2 - For py = 1 To size - y_0 = py/half - 1 - x = x_0 - y = y_0 - i = 0 - While(c <= 2 AND i<100) - x_1 = Math.Power(x, 2) - Math.Power(y, 2) + x_0 - y_1 = 2 * x * y + y_0 - c = Math.Power(Math.Power(x_1, 2) + Math.Power(y_1, 2), 0.5) - x = x_1 - y = y_1 - i = i + 1 - EndWhile - If i < 99 Then - GraphicsWindow.SetPixel(px, py, GraphicsWindow.GetColorFromRGB((255/25)*i, (255/25)*i, (255/5)*i)) - Else - GraphicsWindow.SetPixel(px, py, "black") - EndIf - c=0 - EndFor -EndFor + 10 FOR I=0 TO 63 + 20 FOR J=43 TO 0 STEP -1 + 30 LET X=(I-52)/31 + 40 LET Y=(J-22)/31 + 50 LET XA=0 + 60 LET YA=0 + 70 LET ITER=0 + 80 LET XTEMP=XA*XA-YA*YA+X + 90 LET YA=2*XA*YA+Y +100 LET XA=XTEMP +110 LET ITER=ITER+1 +120 IF XA*XA+YA*YA<=4 AND ITER<200 THEN GOTO 80 +130 IF ITER=200 THEN PLOT I, J +140 NEXT J +150 NEXT I diff --git a/Task/Mandelbrot-set/BASIC/mandelbrot-set-9.basic b/Task/Mandelbrot-set/BASIC/mandelbrot-set-9.basic index 168460a577..9080950f17 100644 --- a/Task/Mandelbrot-set/BASIC/mandelbrot-set-9.basic +++ b/Task/Mandelbrot-set/BASIC/mandelbrot-set-9.basic @@ -1,15 +1,29 @@ -Function mandel(xi As Double, yi As Double) - -maxiter = 256 -x = 0 -y = 0 - -For i = 1 To maxiter - If ((x * x) + (y * y)) > 4 Then Exit For - xt = xi + ((x * x) - (y * y)) - y = yi + (2 * x * y) - x = xt - Next - -mandel = i -End Function +GraphicsWindow.Show() +size = 500 +half = 250 +GraphicsWindow.Width = size * 1.5 +GraphicsWindow.Height = size +GraphicsWindow.Title = "Mandelbrot" +For px = 1 To size * 1.5 + x_0 = px/half - 2 + For py = 1 To size + y_0 = py/half - 1 + x = x_0 + y = y_0 + i = 0 + While(c <= 2 AND i<100) + x_1 = Math.Power(x, 2) - Math.Power(y, 2) + x_0 + y_1 = 2 * x * y + y_0 + c = Math.Power(Math.Power(x_1, 2) + Math.Power(y_1, 2), 0.5) + x = x_1 + y = y_1 + i = i + 1 + EndWhile + If i < 99 Then + GraphicsWindow.SetPixel(px, py, GraphicsWindow.GetColorFromRGB((255/25)*i, (255/25)*i, (255/5)*i)) + Else + GraphicsWindow.SetPixel(px, py, "black") + EndIf + c=0 + EndFor +EndFor diff --git a/Task/Mandelbrot-set/C/mandelbrot-set-3.c b/Task/Mandelbrot-set/C/mandelbrot-set-3.c new file mode 100644 index 0000000000..621c7573be --- /dev/null +++ b/Task/Mandelbrot-set/C/mandelbrot-set-3.c @@ -0,0 +1,3 @@ +main(k){float i,j,r,x,y=-16;while(puts(""),y++<15)for(x +=0;x++<84;putchar(" .:-;!/>)|&IH%*#"[k&15]))for(i=k=r=0; +j=r*r-i*i-2+x/25,i=2*r*i+y/10,j*j+i*i<11&&k++<111;r=j);} diff --git a/Task/Mandelbrot-set/J/mandelbrot-set-2.j b/Task/Mandelbrot-set/J/mandelbrot-set-2.j index f04c92191d..50f99bad99 100644 --- a/Task/Mandelbrot-set/J/mandelbrot-set-2.j +++ b/Task/Mandelbrot-set/J/mandelbrot-set-2.j @@ -1,4 +1,4 @@ domain=. |.@|:@({.@[ + ] *~ j./&i.&>/@+.@(1j1 + ] %~ -~/@[))&>/ -load'graph' +load 'viewmat' viewmat mcf "0 @ domain (_2j_1 1j1) ; 0.01 NB. Complex interval and resolution diff --git a/Task/Mandelbrot-set/Maple/mandelbrot-set.maple b/Task/Mandelbrot-set/Maple/mandelbrot-set.maple new file mode 100644 index 0000000000..898431315c --- /dev/null +++ b/Task/Mandelbrot-set/Maple/mandelbrot-set.maple @@ -0,0 +1 @@ +ImageTools:-Embed(Fractals[EscapeTime]:-Mandelbrot(500, -2.0-1.35*I, .7+1.35*I, output = layer1)); diff --git a/Task/Mandelbrot-set/Metapost/mandelbrot-set-1.metapost b/Task/Mandelbrot-set/Metapost/mandelbrot-set-1.metapost new file mode 100644 index 0000000000..9681397160 --- /dev/null +++ b/Task/Mandelbrot-set/Metapost/mandelbrot-set-1.metapost @@ -0,0 +1,44 @@ +prologues:=3; +outputtemplate:="%j-%c.svg"; +outputformat:="svg"; + + +def mandelbrot(expr maxX, maxY) = + max_iteration := 500; + + color col[]; + for i := 0 upto max_iteration: + t := i / max_iteration; + col[i] = (t,t,t); + endfor; + + + for px := 0 upto maxX: + for py := 0 upto maxY: + xz := px * 3.5 / maxX - 2.5; % (-2.5,1) + yz := py * 2 / maxY - 1; % (-1,1) + + x := 0; + y := 0; + + iteration := 0; + + forever: exitunless ((x*x + y*y < 4) and (iteration < max_iteration)); + xtemp := x*x - y*y + xz; + y := 2*x*y + yz; + x := xtemp; + iteration := iteration + 1; + endfor; + + draw (px,py) withpen pencircle withcolor col[iteration]; + + endfor; + endfor; +enddef; + + +beginfig(1); + mandelbrot(200, 150); +endfig; + +end diff --git a/Task/Mandelbrot-set/Metapost/mandelbrot-set-2.metapost b/Task/Mandelbrot-set/Metapost/mandelbrot-set-2.metapost new file mode 100644 index 0000000000..7d9bb517e8 --- /dev/null +++ b/Task/Mandelbrot-set/Metapost/mandelbrot-set-2.metapost @@ -0,0 +1 @@ +mpost -numbersystem="double" mandelbrot.mp diff --git a/Task/Mandelbrot-set/Processing/mandelbrot-set b/Task/Mandelbrot-set/Processing/mandelbrot-set new file mode 100644 index 0000000000..c6e2499047 --- /dev/null +++ b/Task/Mandelbrot-set/Processing/mandelbrot-set @@ -0,0 +1,64 @@ +// Following code is a zoomable Mandelbrot. +// Of course, you want to click on an interesting area +// with contrast and more colors to zoom in. + +double x, y, zr, zi, zr2, zi2, cr, ci, n; +double zmx1, zmx2, zmy1, zmy2, f, di, dj; +double fn1, fn2, fn3, re, gr, bl, xt, yt, i, j; + +void setup() { + size(500, 500); + di = 0; + dj = 0; + f = 10; + fn1 = random(20); + fn2 = random(20); + fn3 = random(20); + zmx1 = int(width / 4); + zmx2 = 2; + zmy1 = int(height / 4); + zmy2 = 2; +} + +void draw() { + if (i <= width) i++; + x = (i + di)/ zmx1 - zmx2; + for ( j = 0; j <= height; j++) { + y = zmy2 - (j + dj) / zmy1; + zr = 0; + zi = 0; + zr2 = 0; + zi2 = 0; + cr = x; + ci = y; + n = 1; + while (n < 200 && (zr2 + zi2) < 4) { + zi2 = zi * zi; + zr2 = zr * zr; + zi = 2 * zi * zr + ci; + zr = zr2 - zi2 + cr; + n++; + } + re = (n * fn1) % 255; + gr = (n * fn2) % 255; + bl = (n * fn3) % 255; + stroke((float)re, (float)gr, (float)bl); + point((float)i, (float)j); + } +} + +void mousePressed() { + background(200); + xt = mouseX; + yt = mouseY; + di = di + xt - float(width / 2); + dj = dj + yt - float(height / 2); + zmx1 = zmx1 * f; + zmx2 = zmx2 * (1 / f); + zmy1 = zmy1 * f; + zmy2 = zmy2 * (1 / f); + di = di * f; + dj = dj * f; + i = 0; + j = 0; +} diff --git a/Task/Mandelbrot-set/Ring/mandelbrot-set.ring b/Task/Mandelbrot-set/Ring/mandelbrot-set.ring index 268a6f07c8..318eb5023a 100644 --- a/Task/Mandelbrot-set/Ring/mandelbrot-set.ring +++ b/Task/Mandelbrot-set/Ring/mandelbrot-set.ring @@ -3,7 +3,7 @@ load "guilib.ring" new qapp { win1 = new qwidget() { - setwindowtitle("drawing using qpainter") + setwindowtitle("Mandelbrot set") setgeometry(100,100,500,500) label1 = new qlabel(win1) { setgeometry(10,10,400,400) diff --git a/Task/Mandelbrot-set/Rust/mandelbrot-set.rust b/Task/Mandelbrot-set/Rust/mandelbrot-set.rust new file mode 100644 index 0000000000..005f881d16 --- /dev/null +++ b/Task/Mandelbrot-set/Rust/mandelbrot-set.rust @@ -0,0 +1,43 @@ +extern crate image; +extern crate num_complex; + +use std::fs::File; +use num_complex::Complex; + +fn main() { + let max_iterations = 256u16; + let img_side = 800u32; + let cxmin = -2f32; + let cxmax = 1f32; + let cymin = -1.5f32; + let cymax = 1.5f32; + let scalex = (cxmax - cxmin) / img_side as f32; + let scaley = (cymax - cymin) / img_side as f32; + + // Create a new ImgBuf + let mut imgbuf = image::ImageBuffer::new(img_side, img_side); + + // Calculate for each pixel + for (x, y, pixel) in imgbuf.enumerate_pixels_mut() { + let cx = cxmin + x as f32 * scalex; + let cy = cymin + y as f32 * scaley; + + let c = Complex::new(cx, cy); + let mut z = Complex::new(0f32, 0f32); + + let mut i = 0; + for t in 0..max_iterations { + if z.norm() > 2.0 { + break; + } + z = z * z + c; + i = t; + } + + *pixel = image::Luma([i as u8]); + } + + // Save image + let fout = &mut File::create("fractal.png").unwrap(); + image::ImageLuma8(imgbuf).save(fout, image::PNG).unwrap(); +} diff --git a/Task/Map-range/Julia/map-range.julia b/Task/Map-range/Julia/map-range.julia index 35c8707e3f..167738e164 100644 --- a/Task/Map-range/Julia/map-range.julia +++ b/Task/Map-range/Julia/map-range.julia @@ -1,3 +1,8 @@ -maprange(s, a, b) = let a1 = minimum(a), a2 = maximum(a), b1 = minimum(b), b2 = maximum(b) - b1 + (s-a1) * (b2-b1) / (a2-a1) +function maprange(s, a, b) + a₁, a₂ = minimum(a), maximum(a) + b₁, b₂ = minimum(b), maximum(b) + return b₁ + (s - a₁) * (b₂ - b₁) / (a₂ - a₁) end + +@show maprange(6, 1:10, -1:0) +@show maprange(0:10, 0:10, -1:0) diff --git a/Task/Map-range/Maple/map-range.maple b/Task/Map-range/Maple/map-range.maple new file mode 100644 index 0000000000..9ef7a983fb --- /dev/null +++ b/Task/Map-range/Maple/map-range.maple @@ -0,0 +1,8 @@ +Map:=proc(a1,a2,b1,b2,s); + return (b1+((s-a1)*(b2-b1)/(a2-a1))); +end proc; + +for i from 0 to 10 do + printf("%a maps to ",i); + printf("%a\n",Map(0,10,-1,0,i)); +end do; diff --git a/Task/Map-range/REXX/map-range-1.rexx b/Task/Map-range/REXX/map-range-1.rexx index a30668c427..4f001df3d8 100644 --- a/Task/Map-range/REXX/map-range-1.rexx +++ b/Task/Map-range/REXX/map-range-1.rexx @@ -1,11 +1,11 @@ /*REXX program maps and displays a range of numbers from one range to another range.*/ -rangeA = 0 10 /*or: rangeA = ' 0 10 ' */ -rangeB = -1 0 /*or: rangeB = " -1 0 " */ -parse var RangeA L H -inc=1 +rangeA = 0 10 /*or: rangeA = ' 0 10 ' */ +rangeB = -1 0 /*or: rangeB = " -1 0 " */ +parse var rangeA L H +inc= 1 do j=L to H by inc * (1 - 2 * sign(H=0)$ diff --git a/Task/Map-range/REXX/map-range-2.rexx b/Task/Map-range/REXX/map-range-2.rexx index d2261d306b..f47a89babc 100644 --- a/Task/Map-range/REXX/map-range-2.rexx +++ b/Task/Map-range/REXX/map-range-2.rexx @@ -1,11 +1,11 @@ /*REXX program maps and displays a range of numbers from one range to another range.*/ -rangeA = 10 0 /*or: rangeA = ' 10 0 ' */ -rangeB = -1 0 /*or: rangeB = " -1 0 " */ -parse var RangeA L H /*note the LOW & HIGH values in A*/ -inc= 1/2 /*use a different step size (inc)*/ - do j=L to H by inc * (1 - 2 * sign(H=0)$ diff --git a/Task/Map-range/REXX/map-range-3.rexx b/Task/Map-range/REXX/map-range-3.rexx index 62f6b0fa6b..bfd07dda50 100644 --- a/Task/Map-range/REXX/map-range-3.rexx +++ b/Task/Map-range/REXX/map-range-3.rexx @@ -1,12 +1,13 @@ /*REXX program maps and displays a range of numbers from one range to another range.*/ -rangeA = 0 10 -rangeB = -1 0 - inc = 1 -call mapRange rangeA, RangeB, inc -exit /*stick a fork in it, we're done.*/ +rangeA = 0 10 +rangeB = -1 0 +inc = 1 +call mapR rangeA, rangeB, inc +exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -mapRange: procedure; parse arg a1 a2, b1 b2, inc /* [↓] BY: either +inc or -inc*/ - do s=a1 to a2 by inc * (1 - 2 * sign(a2 < a1) ) - say right(s,digits()) ' maps to ' b1 + (s-a1) * (b2-b1) / (a2-a1) - end /*s*/ /*↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑*/ - return /*═══════════════t═══════════════*/ +mapR: procedure; parse arg a1 a2, b1 b2, inc /* [↓] BY is either +inc or -inc.*/ + do s=a1 to a2 by inc * (1 - 2 * sign(a2 < a1) ) + t= b1 + (s-a1) * (b2-b1) / (a2-a1) + say right(s, 9) ' maps to' left('', t>=0) t + end /*s*/ + return /* [↑] LEFT··· aligns non─negative #'s*/ diff --git a/Task/Map-range/REXX/map-range-4.rexx b/Task/Map-range/REXX/map-range-4.rexx index 3406abb3ef..2989410657 100644 --- a/Task/Map-range/REXX/map-range-4.rexx +++ b/Task/Map-range/REXX/map-range-4.rexx @@ -1,6 +1,6 @@ /*REXX program maps a number from one range to another range. */ /* 31.10.2013 Walter Pachl */ -/* 'translated' from version 1 without using Procedure */ +/* 'translated' from an older version 1 without using Procedure */ do j=0 to 10 say right(j,3) ' maps to ' mapRange(0,10,-1,0,j) end diff --git a/Task/Map-range/Ring/map-range.ring b/Task/Map-range/Ring/map-range.ring index 59ea9128ea..280bcede95 100644 --- a/Task/Map-range/Ring/map-range.ring +++ b/Task/Map-range/Ring/map-range.ring @@ -3,13 +3,14 @@ # Author : Gal Zsolt (~ CalmoSoft ~) # Email : +decimals(1) al = 0 ah = 10 bl = -1 bh = 0 for n = 0 to 10 - see " maps to " + maprange(al, bl, n) + nl + see "" + n + " maps to " + maprange(al, bl, n) + nl next func maprange(al, bl, s) - return bl + (s - al) * (bh - bl) / (ah - al) + return bl + (s - al) * (bh - bl) / (ah - al) diff --git a/Task/Map-range/Stata/map-range-1.stata b/Task/Map-range/Stata/map-range-1.stata new file mode 100644 index 0000000000..e947e7e4c9 --- /dev/null +++ b/Task/Map-range/Stata/map-range-1.stata @@ -0,0 +1,22 @@ +program define maprange + version 15.1 + syntax varname(numeric) [if] [in], /// + from(numlist min=2 max=2) to(numlist min=2 max=2) /// + GENerate(name) [REPLACE] + tempname a b c d h + sca `a'=`:word 1 of `from'' + sca `b'=`:word 2 of `from'' + sca `c'=`:word 1 of `to'' + sca `d'=`:word 2 of `to'' + sca `h'=(`d'-`c')/(`b'-`a') + cap confirm variable `generate' + if "`replace'"=="replace" & !_rc { + qui replace `generate'=(`varlist'-`a')*`h'+`c' `if' `in' + } + else { + if "`replace'"=="replace" { + di in gr `"(note: variable `generate' not found)"' + } + qui gen `generate'=(`varlist'-`a')*`h'+`c' `if' `in' + } +end diff --git a/Task/Map-range/Stata/map-range-2.stata b/Task/Map-range/Stata/map-range-2.stata new file mode 100644 index 0000000000..4321d4c93b --- /dev/null +++ b/Task/Map-range/Stata/map-range-2.stata @@ -0,0 +1,6 @@ +clear +set obs 11 +gen x=_n-1 +maprange x if mod(x,2)==0, gen(y) from(0 10) to(-10 10) +maprange x if mod(x,2)!=0, gen(y) from(0 10) to(-100 100) replace +list diff --git a/Task/Matrix-arithmetic/00DESCRIPTION b/Task/Matrix-arithmetic/00DESCRIPTION index f9e65c2b76..3a71d86cf8 100644 --- a/Task/Matrix-arithmetic/00DESCRIPTION +++ b/Task/Matrix-arithmetic/00DESCRIPTION @@ -8,6 +8,7 @@ In both cases the sum is over the permutations \sigma of the permut More efficient algorithms for the determinant are known: [[LU decomposition]], see for example [[wp:LU decomposition#Computing the determinant]]. Efficient methods for calculating the permanent are not known. -;Cf.: + +;Related task: * [[Permutations by swapping]]

diff --git a/Task/Matrix-arithmetic/Go/matrix-arithmetic-4.go b/Task/Matrix-arithmetic/Go/matrix-arithmetic-4.go index 5b087d874d..8963166cb0 100644 --- a/Task/Matrix-arithmetic/Go/matrix-arithmetic-4.go +++ b/Task/Matrix-arithmetic/Go/matrix-arithmetic-4.go @@ -3,14 +3,14 @@ package main import ( "fmt" - "github.com/gonum/matrix/mat64" + "gonum.org/v1/gonum/mat" ) func main() { - fmt.Println(mat64.Det(mat64.NewDense(2, 2, []float64{ + fmt.Println(mat.Det(mat.NewDense(2, 2, []float64{ 1, 2, 3, 4}))) - fmt.Println(mat64.Det(mat64.NewDense(3, 3, []float64{ + fmt.Println(mat.Det(mat.NewDense(3, 3, []float64{ 2, 9, 4, 7, 5, 3, 6, 1, 8}))) diff --git a/Task/Matrix-arithmetic/Perl/matrix-arithmetic.pl b/Task/Matrix-arithmetic/Perl/matrix-arithmetic.pl new file mode 100644 index 0000000000..c6feeebd7b --- /dev/null +++ b/Task/Matrix-arithmetic/Perl/matrix-arithmetic.pl @@ -0,0 +1,27 @@ +#!/usr/bin/perl +use strict; +use warnings; +use PDL; +use PDL::NiceSlice; + +sub permanent{ + my $mat = shift; + my $n = shift // $mat->dim(0); + return undef if $mat->dim(0) != $mat->dim(1); + return $mat(0,0) if $n == 1; + my $sum = 0; + --$n; + my $m = $mat(1:,1:)->copy; + for(my $i = 0; $i <= $n; ++$i){ + $sum += $mat($i,0) * permanent($m, $n); + last if $i == $n; + $m($i,:) .= $mat($i,1:); + } + return sclr($sum); +} + +my $M = pdl([[2,9,4], [7,5,3], [6,1,8]]); +print "M = $M\n"; +print "det(M) = " . $M->determinant . ".\n"; +print "det(M) = " . $M->det . ".\n"; +print "perm(M) = " . permanent($M) . ".\n"; diff --git a/Task/Matrix-arithmetic/Sidef/matrix-arithmetic.sidef b/Task/Matrix-arithmetic/Sidef/matrix-arithmetic.sidef new file mode 100644 index 0000000000..5c9b4bd80b --- /dev/null +++ b/Task/Matrix-arithmetic/Sidef/matrix-arithmetic.sidef @@ -0,0 +1,31 @@ +class Array { + method permanent { + var r = @^self.len + + var sum = 0 + r.permutations { |*a| + var prod = 1 + [a,r].zip {|row,col| prod *= self[row][col] } + sum += prod + } + + return sum + } +} + +var m1 = [[1,2],[3,4]] + +var m2 = [[1, 2, 3, 4], + [4, 5, 6, 7], + [7, 8, 9, 10], + [10, 11, 12, 13]] + +var m3 = [[0, 1, 2, 3, 4], + [5, 6, 7, 8, 9], + [10, 11, 12, 13, 14], + [15, 16, 17, 18, 19], + [20, 21, 22, 23, 24]] + +[m1, m2, m3].each { |m| + say "determinant:\t #{m.determinant}\npermanent:\t #{m.permanent}\n" +} diff --git a/Task/Matrix-arithmetic/Simula/matrix-arithmetic.simula b/Task/Matrix-arithmetic/Simula/matrix-arithmetic.simula index 2ae5bd68ee..dfdeb2adcb 100644 --- a/Task/Matrix-arithmetic/Simula/matrix-arithmetic.simula +++ b/Task/Matrix-arithmetic/Simula/matrix-arithmetic.simula @@ -1,24 +1,18 @@ ! MATRIX ARITHMETIC ; BEGIN - INTEGER PROCEDURE LENGTH(A); REAL ARRAY A; + INTEGER PROCEDURE LENGTH(A); ARRAY A; LENGTH := UPPERBOUND(A, 1) - LOWERBOUND(A, 1) + 1; - PROCEDURE MINOR(A, X, Y, MAT); REAL ARRAY A, MAT; INTEGER X, Y; + ! Set MAT to the first minor of A dropping row X and column Y ; + PROCEDURE MINOR(A, X, Y, MAT); ARRAY A, MAT; INTEGER X, Y; BEGIN - INTEGER I, J, M; M := LENGTH(A) - 1; - FOR I := 1 STEP 1 UNTIL M DO + INTEGER I, J, rowA, M; M := LENGTH(A) - 1; ! not a constant; + FOR I := 1 STEP 1 UNTIL M DO BEGIN + rowA := IF I < X THEN I ELSE I + 1; FOR J := 1 STEP 1 UNTIL M DO - BEGIN - IF I < X AND J < Y THEN - MAT(I, J) := A(I, J) - ELSE IF I >= X AND J < Y THEN - MAT(I, J) := A(I + 1, J) - ELSE IF I < X AND J >= Y THEN - MAT(I, J) := A(I, J + 1) - ELSE ! I > X AND J > Y ; - MAT(I, J) := A(I + 1, J + 1) - END + MAT(I, J) := A(rowA, IF J < Y THEN J else J + 1); + END END MINOR; REAL PROCEDURE DET(A); REAL ARRAY A; @@ -68,18 +62,17 @@ BEGIN REAL ARRAY A(1:SIZE, 1:SIZE); INTEGER I, J; - FOR I := 1 STEP 1 UNTIL SIZE DO + FOR I := 1 STEP 1 UNTIL SIZE DO BEGIN + ! may be need here: INIMAGE; FOR J := 1 STEP 1 UNTIL SIZE DO - A(I, J) := INREAL; - + A(I, J) := INREAL + END; OUTTEXT("DETERMINANT ... : "); OUTREAL(DET (A), 10, 20); OUTIMAGE; OUTTEXT("PERMANENT ..... : "); OUTREAL(PERM(A), 10, 20); OUTIMAGE; END - ! NOTE THAT THE FIRST INPUT IS THE SIZE OF THE MATRIX. - ! FOR EXAMPLE: + COMMENT THE FIRST INPUT IS THE SIZE OF THE MATRIX, FOR EXAMPLE: - COMMENT ! 2 ! 1 2 ! 3 4 diff --git a/Task/Matrix-arithmetic/Stata/matrix-arithmetic-1.stata b/Task/Matrix-arithmetic/Stata/matrix-arithmetic-1.stata new file mode 100644 index 0000000000..bcfde5b790 --- /dev/null +++ b/Task/Matrix-arithmetic/Stata/matrix-arithmetic-1.stata @@ -0,0 +1,28 @@ +real vector range1(real scalar n, real scalar i) { + if (i < 1 | i > n) { + return(1::n) + } else if (i == 1) { + return(2::n) + } else if (i == n) { + return(1::n-1) + } else { + return(1::i-1\i+1::n) + } +} + +real matrix submat(real matrix a, real scalar i, real scalar j) { + return(a[range1(rows(a), i), range1(cols(a), j)]) +} + +real scalar sumrec(real matrix a, real scalar x) { + real scalar n, s, p + n = rows(a) + if (n==1) return(a[1,1]) + s = 0 + p = 1 + for (i=1; i<=n; i++) { + s = s+p*a[i,1]*sumrec(submat(a, i, 1), x) + p = p*x + } + return(s) +} diff --git a/Task/Matrix-arithmetic/Stata/matrix-arithmetic-2.stata b/Task/Matrix-arithmetic/Stata/matrix-arithmetic-2.stata new file mode 100644 index 0000000000..182c0233e6 --- /dev/null +++ b/Task/Matrix-arithmetic/Stata/matrix-arithmetic-2.stata @@ -0,0 +1,19 @@ +: a=1,1,1,0\1,1,0,1\1,0,1,1\0,1,1,1 +: a +[symmetric] + 1 2 3 4 + +-----------------+ + 1 | 1 | + 2 | 1 1 | + 3 | 1 0 1 | + 4 | 0 1 1 1 | + +-----------------+ + +: det(a) + -3 + +: sumrec(a,-1) + -3 + +: sumrec(a,1) + 9 diff --git a/Task/Matrix-exponentiation-operator/Sidef/matrix-exponentiation-operator.sidef b/Task/Matrix-exponentiation-operator/Sidef/matrix-exponentiation-operator.sidef new file mode 100644 index 0000000000..6070cb636a --- /dev/null +++ b/Task/Matrix-exponentiation-operator/Sidef/matrix-exponentiation-operator.sidef @@ -0,0 +1,22 @@ +class Array { + method ** (Number n { .>= 0 }) { + var tmp = self + var out = self.len.of {|i| self.len.of {|j| i == j ? 1 : 0 }} + loop { + out = (out `mmul` tmp) if n.is_odd + n >>= 1 || break + tmp = (tmp `mmul` tmp) + } + return out + } +} + +var m = [[1, 2, 0], + [0, 3, 1], + [1, 0, 0]] + +for order in (0..5) { + say "### Order #{order}" + var t = (m ** order) + say (' ', t.join("\n ")) +} diff --git a/Task/Matrix-exponentiation-operator/Stata/matrix-exponentiation-operator-1.stata b/Task/Matrix-exponentiation-operator/Stata/matrix-exponentiation-operator-1.stata new file mode 100644 index 0000000000..b343755f22 --- /dev/null +++ b/Task/Matrix-exponentiation-operator/Stata/matrix-exponentiation-operator-1.stata @@ -0,0 +1,13 @@ +real matrix matpow(real matrix a, real scalar n) { + real matrix p, x + real scalar i, s + s = n<0 + n = abs(n) + x = a + p = I(rows(a)) + for (i=n; i>0; i=floor(i/2)) { + if (mod(i,2)==1) p = p*x + x = x*x + } + return(s?luinv(p):p) +} diff --git a/Task/Matrix-exponentiation-operator/Stata/matrix-exponentiation-operator-2.stata b/Task/Matrix-exponentiation-operator/Stata/matrix-exponentiation-operator-2.stata new file mode 100644 index 0000000000..dc723f25b0 --- /dev/null +++ b/Task/Matrix-exponentiation-operator/Stata/matrix-exponentiation-operator-2.stata @@ -0,0 +1,7 @@ +: matpow((0,1\1,1),10) +[symmetric] + 1 2 + +-----------+ + 1 | 34 | + 2 | 55 89 | + +-----------+ diff --git a/Task/Matrix-multiplication/Fortran/matrix-multiplication-1.f b/Task/Matrix-multiplication/Fortran/matrix-multiplication-1.f index d6cf3f2542..f2c0d858c5 100644 --- a/Task/Matrix-multiplication/Fortran/matrix-multiplication-1.f +++ b/Task/Matrix-multiplication/Fortran/matrix-multiplication-1.f @@ -1,5 +1,5 @@ -real, dimension(n,m) :: a = reshape( (/ (i, i=1, n*m) /), (/ n, m /) ) -real, dimension(m,k) :: b = reshape( (/ (i, i=1, m*k) /), (/ m, k /) ) +real, dimension(n,m) :: a = reshape( [ (i, i=1, n*m) ], [ n, m ] ) +real, dimension(m,k) :: b = reshape( [ (i, i=1, m*k) ], [ m, k ] ) real, dimension(size(a,1), size(b,2)) :: c ! C is an array whose first dimension (row) size ! is the same as A's first dimension size, and ! whose second dimension (column) size is the same diff --git a/Task/Matrix-multiplication/Go/matrix-multiplication-1.go b/Task/Matrix-multiplication/Go/matrix-multiplication-1.go index e8ae47efdb..8e6135baef 100644 --- a/Task/Matrix-multiplication/Go/matrix-multiplication-1.go +++ b/Task/Matrix-multiplication/Go/matrix-multiplication-1.go @@ -3,21 +3,21 @@ package main import ( "fmt" - "github.com/gonum/matrix/mat64" + "gonum.org/v1/gonum/mat" ) func main() { - a := mat64.NewDense(2, 4, []float64{ + a := mat.NewDense(2, 4, []float64{ 1, 2, 3, 4, 5, 6, 7, 8, }) - b := mat64.NewDense(4, 3, []float64{ + b := mat.NewDense(4, 3, []float64{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, }) - var m mat64.Dense + var m mat.Dense m.Mul(a, b) - fmt.Println(mat64.Formatted(&m)) + fmt.Println(mat.Formatted(&m)) } diff --git a/Task/Matrix-multiplication/Klong/matrix-multiplication.klong b/Task/Matrix-multiplication/Klong/matrix-multiplication.klong new file mode 100644 index 0000000000..cffed65918 --- /dev/null +++ b/Task/Matrix-multiplication/Klong/matrix-multiplication.klong @@ -0,0 +1,4 @@ + mul::{[a b];b::+y;{a::x;+/'{a*x}'b}'x} + [[1 2] [3 4]] mul [[5 6] [7 8]] +[[19 22] + [43 50]] diff --git a/Task/Matrix-multiplication/Stata/matrix-multiplication-1.stata b/Task/Matrix-multiplication/Stata/matrix-multiplication-1.stata new file mode 100644 index 0000000000..a1a393fc31 --- /dev/null +++ b/Task/Matrix-multiplication/Stata/matrix-multiplication-1.stata @@ -0,0 +1,9 @@ +. mat a=1,2,3\4,5,6 +. mat b=1,1,0,0\1,0,0,1\0,0,1,1 +. mat c=a*b +. mat list c + +c[2,4] + c1 c2 c3 c4 +r1 3 1 3 5 +r2 9 4 6 11 diff --git a/Task/Matrix-multiplication/Stata/matrix-multiplication-2.stata b/Task/Matrix-multiplication/Stata/matrix-multiplication-2.stata new file mode 100644 index 0000000000..6e41464744 --- /dev/null +++ b/Task/Matrix-multiplication/Stata/matrix-multiplication-2.stata @@ -0,0 +1,8 @@ +: a=1,2,3\4,5,6 +: b=1,1,0,0\1,0,0,1\0,0,1,1 +: a*b + 1 2 3 4 + +---------------------+ + 1 | 3 1 3 5 | + 2 | 9 4 6 11 | + +---------------------+ diff --git a/Task/Matrix-transposition/Go/matrix-transposition-1.go b/Task/Matrix-transposition/Go/matrix-transposition-1.go index ef2acadb3e..f77d59bf24 100644 --- a/Task/Matrix-transposition/Go/matrix-transposition-1.go +++ b/Task/Matrix-transposition/Go/matrix-transposition-1.go @@ -3,15 +3,15 @@ package main import ( "fmt" - "github.com/gonum/matrix/mat64" + "gonum.org/v1/gonum/mat" ) func main() { - m := mat64.NewDense(2, 3, []float64{ + m := mat.NewDense(2, 3, []float64{ 1, 2, 3, 4, 5, 6, }) - fmt.Println(mat64.Formatted(m)) + fmt.Println(mat.Formatted(m)) fmt.Println() - fmt.Println(mat64.Formatted(m.T())) + fmt.Println(mat.Formatted(m.T())) } diff --git a/Task/Matrix-transposition/JavaScript/matrix-transposition-3.js b/Task/Matrix-transposition/JavaScript/matrix-transposition-3.js index 11d3cd289c..a27a0b8d7c 100644 --- a/Task/Matrix-transposition/JavaScript/matrix-transposition-3.js +++ b/Task/Matrix-transposition/JavaScript/matrix-transposition-3.js @@ -2,11 +2,9 @@ 'use strict'; // transpose :: [[a]] -> [[a]] - let transpose = xs => + const transpose = xs => xs[0].map((_, iCol) => xs.map((row) => row[iCol])); - - // TEST return transpose([ [1, 2], diff --git a/Task/Matrix-transposition/Perl-6/matrix-transposition.pl6 b/Task/Matrix-transposition/Perl-6/matrix-transposition.pl6 index 731ade278f..381ecd7e2f 100644 --- a/Task/Matrix-transposition/Perl-6/matrix-transposition.pl6 +++ b/Task/Matrix-transposition/Perl-6/matrix-transposition.pl6 @@ -1 +1,22 @@ -say [Z] (
,,) +# Transposition can be done with the reduced zip meta-operator +# on list-of-lists data structures + +say [Z] (, , ); + +# For native shaped arrays, a more traditional procedure of copying item-by-item +# Here the resulting matrix is also a native shaped array + +my @a[3;4] = + [ + [], + [], + [], + ]; + +(my $n, my $m) = @a.shape; +my @b[$m;$n]; +for ^$m X ^$n -> (\i, \j) { + @b[i;j] = @a[j;i]; +} + +say @b; diff --git a/Task/Matrix-transposition/REXX/matrix-transposition.rexx b/Task/Matrix-transposition/REXX/matrix-transposition.rexx new file mode 100644 index 0000000000..c6496085c0 --- /dev/null +++ b/Task/Matrix-transposition/REXX/matrix-transposition.rexx @@ -0,0 +1,25 @@ +/*REXX program transposes any sized rectangular matrix, displays before & after matrices*/ +@.=; @.1 = 1.02 2.03 3.04 4.05 5.06 6.07 7.08 + @.2 = 111 2222 33333 444444 5555555 66666666 777777777 +w=0 + do row=1 while @.row\=='' + do col=1 until @.row==''; parse var @.row A.row.col @.row + w=max(w, length(A.row.col) ) /*max width for elements*/ + end /*col*/ /*(used to align ouput).*/ + end /*row*/ /* [↑] build matrix A from the @ lists*/ +row= row-1 /*adjust for DO loop index increment.*/ + do j=1 for row /*process each row of the matrix.*/ + do k=1 for col /* " " column " " " */ + B.k.j= A.j.k /*transpose the A matrix (into B). */ + end /*k*/ + end /*j*/ +call showMat 'A', row, col /*display the A matrix to terminal.*/ +call showMat 'B', col, row /* " " B " " " */ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +showMat: arg mat,rows,cols; say; say center( mat 'matrix', (w+1)*cols +4, "─") + do r=1 for rows; _= /*newLine*/ + do c=1 for cols; _=_ right( value( mat'.'r"."c), w) /*append.*/ + end /*c*/ + say _ /*1 line.*/ + end /*r*/; return diff --git a/Task/Matrix-transposition/Stata/matrix-transposition-1.stata b/Task/Matrix-transposition/Stata/matrix-transposition-1.stata new file mode 100644 index 0000000000..9c3c0ec001 --- /dev/null +++ b/Task/Matrix-transposition/Stata/matrix-transposition-1.stata @@ -0,0 +1,16 @@ +. mat a=1,2,3\4,5,6 +. mat b=a' +. mat list a + +a[2,3] + c1 c2 c3 +r1 1 2 3 +r2 4 5 6 + +. mat list b + +b[3,2] + r1 r2 +c1 1 4 +c2 2 5 +c3 3 6 diff --git a/Task/Matrix-transposition/Stata/matrix-transposition-2.stata b/Task/Matrix-transposition/Stata/matrix-transposition-2.stata new file mode 100644 index 0000000000..f99bcafdeb --- /dev/null +++ b/Task/Matrix-transposition/Stata/matrix-transposition-2.stata @@ -0,0 +1,21 @@ +: a=1,1i + +: a + 1 2 + +-----------+ + 1 | 1 1i | + +-----------+ + +: a' + 1 + +-------+ + 1 | 1 | + 2 | -1i | + +-------+ + +: transposeonly(a) + 1 + +------+ + 1 | 1 | + 2 | 1i | + +------+ diff --git a/Task/Maximum-triangle-path-sum/Astro/maximum-triangle-path-sum.astro b/Task/Maximum-triangle-path-sum/Astro/maximum-triangle-path-sum.astro index 442873227e..e5e1bfde2d 100644 --- a/Task/Maximum-triangle-path-sum/Astro/maximum-triangle-path-sum.astro +++ b/Task/Maximum-triangle-path-sum/Astro/maximum-triangle-path-sum.astro @@ -1,9 +1,10 @@ -fun solve(!tri): - while tri.size > 1: +fun solve(tri): + var tri = tri + while tri.len > 1: let t0 = tri.pop() - for (i, t) in enumerate(tri[!0]): - tri[!0, i] = max(t0[i], t0[i+1]) + t - tri[0, 0] + for i, t in enumerate(tri[!1]): + tri[!1, i] = max(t0[i], t0[i]) + t + tri[1, 1] let data = """ 55 @@ -23,6 +24,7 @@ let data = """ 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 -27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93""" +27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93 +""" -print solve data.lines.map |x| -> x.trim().split().map(int) +print solve data.lines.map|x| => x.split().map(int) diff --git a/Task/Maximum-triangle-path-sum/C++/maximum-triangle-path-sum.cpp b/Task/Maximum-triangle-path-sum/C++/maximum-triangle-path-sum.cpp index c4206cd013..1afa4f2a03 100644 --- a/Task/Maximum-triangle-path-sum/C++/maximum-triangle-path-sum.cpp +++ b/Task/Maximum-triangle-path-sum/C++/maximum-triangle-path-sum.cpp @@ -1,3 +1,4 @@ +/* Algorithm complexity: n*log(n) */ #include int main( int argc, char* argv[] ) @@ -30,7 +31,7 @@ int main( int argc, char* argv[] ) // walk backward by rows, replacing each element with max attainable therefrom for (int n = tn - 1; n > 0; --n) // n is size of row, note we do not process last row - for (int k = (n * (n-1)) / 2; k < (n * (n+2)) / 2; ++k) + for (int k = (n * (n-1)) / 2; k < (n * (n+1)) / 2; ++k) // from the start to the end of row triangle[k] += std::max(triangle[k + n], triangle[k + n + 1]); std::cout << "Maximum total: " << triangle[0] << "\n\n"; diff --git a/Task/Maximum-triangle-path-sum/Elena/maximum-triangle-path-sum.elena b/Task/Maximum-triangle-path-sum/Elena/maximum-triangle-path-sum.elena new file mode 100644 index 0000000000..b3193a1a49 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Elena/maximum-triangle-path-sum.elena @@ -0,0 +1,52 @@ +import system'routines. +import extensions. +import extensions'math. + +literal input = "55 + 94 48 + 95 30 96 + 77 71 26 67 + 97 13 76 38 45 + 07 36 79 16 37 68 + 48 07 09 18 70 26 06 + 18 72 79 46 59 79 29 90 + 20 76 87 11 32 07 07 49 18 + 27 83 58 35 71 11 25 57 29 85 + 14 64 36 96 27 11 58 56 92 18 55 + 02 90 03 60 48 49 41 46 33 36 47 23 + 92 50 48 02 36 59 42 79 72 20 82 77 42 + 56 78 38 80 39 75 02 71 66 66 01 03 55 72 + 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 + 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 + 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 + 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93". + +program = +[ + var list := IntMatrix new(18,19). + + int i := 0. + int j := 0. + input split('newLine); forEach(:line) + [ + j := 0. + line trim; split(" "); forEach(:num) + [ + list[i][j] := num toInt. + + j += 1 + ]. + + i += 1. + ]. + + 16 to:0 do(:i) + [ + 0 till:18 do(:j) + [ + list[i][j] := mathControl max(list[i][j] + list[i+1][j], list[i][j] + list[i+1][j+1]). + ]. + ]. + + console printLine("Maximum total: ", list[0][0]). +]. diff --git a/Task/Maximum-triangle-path-sum/Julia/maximum-triangle-path-sum.julia b/Task/Maximum-triangle-path-sum/Julia/maximum-triangle-path-sum.julia new file mode 100644 index 0000000000..0f8f8a0bc9 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Julia/maximum-triangle-path-sum.julia @@ -0,0 +1,31 @@ +# dynamic solution +function maxpathsum(t::Array{Array{I, 1}, 1}) where I + T = deepcopy(t) + for r in length(T)-1:-1:1 + for c in linearindices(T[r]) + T[r][c] += max(T[r+1][c], T[r+1][c+1]) + end + end + return T[1][1] +end + +test = [[55], + [94, 48], + [95, 30, 96], + [77, 71, 26, 67], + [97, 13, 76, 38, 45], + [07, 36, 79, 16, 37, 68], + [48, 07, 09, 18, 70, 26, 06], + [18, 72, 79, 46, 59, 79, 29, 90], + [20, 76, 87, 11, 32, 07, 07, 49, 18], + [27, 83, 58, 35, 71, 11, 25, 57, 29, 85], + [14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55], + [02, 90, 03, 60, 48, 49, 41, 46, 33, 36, 47, 23], + [92, 50, 48, 02, 36, 59, 42, 79, 72, 20, 82, 77, 42], + [56, 78, 38, 80, 39, 75, 02, 71, 66, 66, 01, 03, 55, 72], + [44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36], + [85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 01, 01, 99, 89, 52], + [06, 71, 28, 75, 94, 48, 37, 10, 23, 51, 06, 48, 53, 18, 74, 98, 15], + [27, 02, 92, 23, 08, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93]] + +@show maxpathsum(test) diff --git a/Task/Maximum-triangle-path-sum/Perl-6/maximum-triangle-path-sum.pl6 b/Task/Maximum-triangle-path-sum/Perl-6/maximum-triangle-path-sum.pl6 new file mode 100644 index 0000000000..3b2d5bd5e9 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Perl-6/maximum-triangle-path-sum.pl6 @@ -0,0 +1,36 @@ +my $triangle = q| 55 + 94 48 + 95 30 96 + 77 71 26 67 + 97 13 76 38 45 + 07 36 79 16 37 68 + 48 07 09 18 70 26 06 + 18 72 79 46 59 79 29 90 + 20 76 87 11 32 07 07 49 18 + 27 83 58 35 71 11 25 57 29 85 + 14 64 36 96 27 11 58 56 92 18 55 + 02 90 03 60 48 49 41 46 33 36 47 23 + 92 50 48 02 36 59 42 79 72 20 82 77 42 + 56 78 38 80 39 75 02 71 66 66 01 03 55 72 + 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36 + 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52 + 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15 +27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93|; + + +my @rows = $triangle.lines.map: { [.words] } +while @rows > 1 { + my @last := @rows.pop; + @rows[*-1] = (@rows[*-1][] Z+ (@last Zmax @last[1..*])).List; +} +put @rows; + + +# Here's a more FPish version. We define our own operator and the use it in the reduction metaoperator form, [op], which turns any infix into a list operator. +sub infix:(@a,@b) { (@a Zmax @a[1..*]) Z+ @b } +put [op] $triangle.lines.reverse.map: { [.words] } + + +# Or, instead of using reverse, one could also define the op as right-associative. +sub infix:(@a,@b) is assoc('right') { @a Z+ (@b Zmax @b[1..*]) } +put [rop] $triangle.lines.map: { [.words] } diff --git a/Task/Maximum-triangle-path-sum/Ring/maximum-triangle-path-sum.ring b/Task/Maximum-triangle-path-sum/Ring/maximum-triangle-path-sum.ring new file mode 100644 index 0000000000..0d9bf6d299 --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Ring/maximum-triangle-path-sum.ring @@ -0,0 +1,57 @@ +# Project : Maximum triangle path sum +# Date : 2018/02/06 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : + +load "stdlib.ring" +ln = list(19) +ln[1] = " 55" +ln[2] = " 94 48" +ln[3] = " 95 30 96" +ln[4] = " 77 71 26 67" +ln[5] = " 97 13 76 38 45" +ln[6] = " 07 36 79 16 37 68" +ln[7] = " 48 07 09 18 70 26 06" +ln[8] = " 18 72 79 46 59 79 29 90" +ln[9] = " 20 76 87 11 32 07 07 49 18" +ln[10] = " 27 83 58 35 71 11 25 57 29 85" +ln[11] = " 14 64 36 96 27 11 58 56 92 18 55" +ln[12] = " 02 90 03 60 48 49 41 46 33 36 47 23" +ln[13] = " 92 50 48 02 36 59 42 79 72 20 82 77 42" +ln[14] = " 56 78 38 80 39 75 02 71 66 66 01 03 55 72" +ln[15] = " 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36" +ln[16] = " 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52" +ln[17] = " 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15" +ln[18] = " 27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93" +ln[19] = "end" + +matrix = newlist(20,20) +x = 1 +size = 0 + +for n = 1 to len(ln) - 1 + ln2 = ln[n] + ln2 = trim(ln2) + for y = 1 to x + matrix[x][y] = number(left(ln2,2)) + if len(ln2) > 4 + ln2 = substr(ln2,4,len(ln2)-4) + ok + next + x = x + 1 + size = size + 1 +next + +for x = size - 1 to 1 step - 1 + for y = 1 to x + s1 = matrix[x+1][y] + s2 = matrix[x+1][y+1] + if s1 > s2 + matrix[x][y] = matrix[x][y] + s1 + else + matrix[x][y] = matrix[x][y] + s2 + ok + next +next + +see "maximum triangle path sum = " + matrix[1][1] diff --git a/Task/Maximum-triangle-path-sum/Stata/maximum-triangle-path-sum.stata b/Task/Maximum-triangle-path-sum/Stata/maximum-triangle-path-sum.stata new file mode 100644 index 0000000000..4aad39016f --- /dev/null +++ b/Task/Maximum-triangle-path-sum/Stata/maximum-triangle-path-sum.stata @@ -0,0 +1,11 @@ +import delimited triangle.txt, delim(" ") clear +mata +a = st_data(.,.) +n = rows(a) +for (i=n-1; i>=1; i--) { + for (j=1; j<=i; j++) { + a[i,j] = a[i,j]+max((a[i+1,j],a[i+1,j+1])) + } +} +a[1,1] +end diff --git a/Task/Maze-generation/BASIC/maze-generation.basic b/Task/Maze-generation/BASIC/maze-generation.basic new file mode 100644 index 0000000000..1b3b6f2d52 --- /dev/null +++ b/Task/Maze-generation/BASIC/maze-generation.basic @@ -0,0 +1,68 @@ +OPTION BASE 0 +RANDOMIZE TIMER + +REM must be even +width% = 40 +height% = 20 + +REM make array and fill +DIM maze$(width%, height%) +FOR x% = 0 TO width% + FOR y% = 0 TO height% + maze$(x%, y%) = "#" + NEXT y% +NEXT x% + +REM initial start location +currentx% = INT(RND * (width% - 1)) +currenty% = INT(RND * (height% - 1)) +REM value must be odd +IF currentx% MOD 2 = 0 THEN currentx% = currentx% + 1 +IF currenty% MOD 2 = 0 THEN currenty% = currenty% + 1 +maze$(currentx%, currenty%) = " " + +REM generate maze +done% = 0 +DO WHILE done% = 0 + FOR i% = 0 TO 99 + oldx% = currentx% + oldy% = currenty% + + REM move in random direction + SELECT CASE INT(RND * 4) + CASE 0 + IF currentx% + 2 < width% THEN currentx% = currentx% + 2 + CASE 1 + IF currenty% + 2 < height% THEN currenty% = currenty% + 2 + CASE 2 + IF currentx% - 2 > 0 THEN currentx% = currentx% - 2 + CASE 3 + IF currenty% - 2 > 0 THEN currenty% = currenty% - 2 + END SELECT + + REM if cell is unvisited then connect it + IF maze$(currentx%, currenty%) = "#" THEN + maze$(currentx%, currenty%) = " " + maze$(INT((currentx% + oldx%) / 2), ((currenty% + oldy%) / 2)) = " " + END IF + NEXT i% + + REM check if all cells are visited + done% = 1 + FOR x% = 1 TO width% - 1 STEP 2 + FOR y% = 1 TO height% - 1 STEP 2 + IF maze$(x%, y%) = "#" THEN done% = 0 + NEXT y% + NEXT x% +LOOP + +REM draw maze +FOR y% = 0 TO height% + FOR x% = 0 TO width% + PRINT maze$(x%, y%); + NEXT x% + PRINT +NEXT y% + +REM wait +DO: LOOP WHILE INKEY$ = "" diff --git a/Task/Maze-generation/Batch-File/maze-generation.bat b/Task/Maze-generation/Batch-File/maze-generation.bat new file mode 100644 index 0000000000..ffa1b7ae7b --- /dev/null +++ b/Task/Maze-generation/Batch-File/maze-generation.bat @@ -0,0 +1,94 @@ +:amaze Rows Cols [wall char] +:: A stack-less, iterative, depth-first maze generator in native WinNT batch. +:: Rows and Cols must each be >1 and Rows*Cols cannot exceed 2096. +:: Default wall character is #, [wall char] is used if provided. + +@ECHO OFF +SETLOCAL EnableDelayedExpansion + +:: check for valid input, else GOTO :help +IF /I "%~2" EQU "" GOTO :amaze_help +FOR /F "tokens=* delims=0123456789" %%A IN ("%~1%~2") DO IF "%%~A" NEQ "" GOTO :amaze_help +SET /A "rows=%~1, cols=%~2, mTmp=rows*cols" +IF !rows! LSS 2 GOTO :amaze_help +IF !cols! LSS 2 GOTO :amaze_help +IF !mTmp! GTR 2096 GOTO :amaze_help + +:: set map characters and use 1st character of %3 for wall, if defined +SET "wall=#" +SET "hall= " +SET "crumb=." +IF "%~3" NEQ "" SET "wall=%~3" +SET "wall=!wall:~0,1!" + +:: assign width, height, cursor position, loop count, and offsets for NSEW +SET /A "cnt=0, wide=cols*2-1, high=rows*2-1, size=wide*high, N=wide*-2, S=wide*2, E=2, W=-2" + +:: different random entrance points +:: ...on top +:: SET /A "start=(!RANDOM! %% cols)*2" +:: ...on bottom +:: SET /A "start=size-(!RANDOM! %% cols)*2-1" +:: ...on top or bottom +:: SET /A ch=cols*2, ch=!RANDOM! %% ch +:: IF !ch! GEQ !cols! ( SET /A "start=size-(ch-cols)*2-1" +:: ) ELSE SET /A start=ch*2 +:: random entrance inside maze +SET /A "start=(!RANDOM! %% cols*2)+(!RANDOM! %% rows*2)*wide" +SET /A "curPos=start, cTmp=curPos+1, loops=cols*rows*2+1" + +:: fill the maze with 8186 wall characters, clip to size, and open 1st cell +SET "mz=!wall!" +FOR /L %%A IN (1,1,6) DO SET mz=!mz!!mz!!mz!!mz! +SET bdr=!mz:~-%wide%! +SET mz=!mz:~3!!mz:~3! +SET mz=!mz:~-%size%! +SET mz=!mz:~0,%curPos%!!hall!!mz:~%cTmp%! + +:: iterate #cells*2+1 steps of random depth-first search +FOR /L %%@ IN (1,1,%loops%) DO ( + SET "rand=" & SET "crmPos=" + REM set values for NSEW cell and wall positions + SET /A "rCnt=rTmp=0, cTmp=curPos+1, np=curPos+N, sp=curPos+S, ep=curPos+E, wp=curPos+W, wChk=curPos/wide*wide, eChk=wChk+wide, nw=curPos-wide, sw=curPos+wide, ew=curPos+1, ww=curPos-1" + REM examine adjacent cells, build direction list, and find last crumb position + FOR /F "tokens=1-8" %%A IN ("!np! !sp! !ep! !wp! !nw! !sw! !ew! !ww!") DO ( + IF !np! GEQ 0 IF "!mz:~%%A,1!" EQU "!wall!" ( SET /A rCnt+=1 & SET "rand=n !rand!" + ) ELSE IF "!mz:~%%E,1!" EQU "!crumb!" SET /A crmPos=np, cw=nw + IF !sp! LEQ !size! IF "!mz:~%%B,1!" EQU "!wall!" ( SET /A rCnt+=1 & SET "rand=s !rand!" + ) ELSE IF "!mz:~%%F,1!" EQU "!crumb!" SET /A crmPos=sp, cw=sw + IF !ep! LEQ !eChk! IF "!mz:~%%C,1!" EQU "!wall!" ( SET /A rCnt+=1 & SET "rand=e !rand!" + ) ELSE IF "!mz:~%%G,1!" EQU "!crumb!" SET /A crmPos=ep, cw=ew + IF !wp! GEQ !wChk! IF "!mz:~%%D,1!" EQU "!wall!" ( SET /A rCnt+=1 & SET "rand=w !rand!" + ) ELSE IF "!mz:~%%H,1!" EQU "!crumb!" SET /A crmPos=wp, cw=ww + ) + IF DEFINED rand ( REM adjacent unvisited cell is available + SET /A rCnt=!RANDOM! %% rCnt + FOR %%A IN (!rand!) DO ( REM pick random cell + wall + IF !rTmp! EQU !rCnt! SET /A "curPos=!%%Ap!, cTmp=curPos+1, mw=!%%Aw!, mTmp=mw+1" + SET /A rTmp+=1 + ) + REM write the 2 new characters into the maze + FOR /F "tokens=1-4" %%A IN ("!mw! !mTmp! !curPos! !cTmp!") DO ( + SET "mz=!mz:~0,%%A!!crumb!!mz:~%%B!" + SET "mz=!mz:~0,%%C!!hall!!mz:~%%D!" + ) + ) ELSE IF DEFINED crmPos ( REM follow the crumbs backward + SET /A mTmp=cw+1 + REM erase the crumb character and set new cursor position + FOR /F "tokens=1-2" %%A IN ("!cw! !mTmp!") DO SET "mz=!mz:~0,%%A!!hall!!mz:~%%B!" + SET "curPos=!crmPos!" + ) +) +SET /A open=cols/2*2, mTmp=open+1 +ECHO !wall!!bdr:~0,%open%!!hall!!bdr:~%mTmp%!!wall! +FOR /L %%A IN (0,!wide!,!size!) DO IF %%A LSS !size! ECHO !wall!!mz:~%%A,%wide%!!wall! +ECHO !wall!!bdr:~0,%open%!!hall!!bdr:~%mTmp%!!wall! +ENDLOCAL +EXIT /B 0 + +:amaze_help +ECHO Usage: %~0 Rows Cols [wall char] +ECHO Rows^>1, Cols^>1, and Rows*Cols^<=2096 +ECHO Example: %~0 11 39 @ +ENDLOCAL +EXIT /B 0 diff --git a/Task/Maze-generation/Julia/maze-generation-1.julia b/Task/Maze-generation/Julia/maze-generation-1.julia new file mode 100644 index 0000000000..f6fd849151 --- /dev/null +++ b/Task/Maze-generation/Julia/maze-generation-1.julia @@ -0,0 +1,19 @@ +check(bound::Vector) = cell -> all([1, 1] .≤ cell .≤ bound) +neighbors(cell::Vector, bound::Vector, step::Int=2) = + filter(check(bound), map(dir -> cell + step * dir, [[0, 1], [-1, 0], [0, -1], [1, 0]])) + +function walk(maze::Matrix, nxtcell::Vector, visited::Vector=[]) + push!(visited, nxtcell) + for neigh in shuffle(neighbors(nxtcell, size(maze))) + if neigh ∉ visited + maze[round.(Int, (nxtcell + neigh) / 2)...] = 0 + walk(maze, neigh, visited) + end + end + maze +end +function maze(w::Int, h::Int) + maze = collect(i % 2 | j % 2 for i in 1:2w+1, j in 1:2h+1) + firstcell = 2 * [rand(1:w), rand(1:h)] + return walk(maze, firstcell) +end diff --git a/Task/Maze-generation/Julia/maze-generation-2.julia b/Task/Maze-generation/Julia/maze-generation-2.julia new file mode 100644 index 0000000000..1659037041 --- /dev/null +++ b/Task/Maze-generation/Julia/maze-generation-2.julia @@ -0,0 +1,13 @@ +pprint(matrix) = for i = 1:size(matrix, 1) println(join(matrix[i, :])) end +function printmaze(maze) + walls = split("╹ ╸ ┛ ╺ ┗ ━ ┻ ╻ ┃ ┓ ┫ ┏ ┣ ┳ ╋") + h, w = size(maze) + f = cell -> 2 ^ ((3cell[1] + cell[2] + 3) / 2) + wall(i, j) = if maze[i,j] == 0 " " else + walls[Int(sum(f, filter(x -> maze[x...] != 0, neighbors([i, j], [h, w], 1)) .- [[i, j]]))] + end + mazewalls = collect(wall(i, j) for i in 1:2:h, j in 1:w) + pprint(mazewalls) +end + +printmaze(maze(10, 10)) diff --git a/Task/Maze-generation/Julia/maze-generation.julia b/Task/Maze-generation/Julia/maze-generation.julia deleted file mode 100644 index 1a20b49c8f..0000000000 --- a/Task/Maze-generation/Julia/maze-generation.julia +++ /dev/null @@ -1,27 +0,0 @@ -function walk(maze, cell, visited = Any[]) - push!(visited, cell) - for neigh in shuffle(neighbors(cell, size(maze))) - if !(neigh in visited) - maze[round.(Int,(cell+neigh)/2)...] = 0 - walk(maze, neigh, visited) - end - end - maze -end - -neighbors(c,b,d=2)=filter(check(b),map(m->c+d*m, Any[[0,1],[-1,0],[0,-1],[1,0]])) - -check(bound) = cell -> all([1,1] .<= cell .<= [bound...]) - -maze(w, h) = walk([i%2|j%2 for i=1:2w+1,j=1:2h+1], 2*[rand(1:w),rand(1:h)]) - -pprint(matrix) = for i = 1:size(matrix,1) println(join(matrix[i,:])) end - -function printmaze(maze, wall = split("╹ ╸ ┛ ╺ ┗ ━ ┻ ╻ ┃ ┓ ┫ ┏ ┣ ┳ ╋")) - h,w = size(maze) - pprint([ maze[i,j] == 0 ? ' ' : - wall[Int(sum(c-> 2.0^.5(3c[1]+c[2]+3), - filter(x -> maze[x...] != 0, - neighbors([i,j],[h,w],1)) .- Any[[i,j]]))] - for i = 1:2:h, j = 1:w]) -end diff --git a/Task/Maze-generation/OCaml/maze-generation.ocaml b/Task/Maze-generation/OCaml/maze-generation.ocaml index 2a45c994aa..85158983fb 100644 --- a/Task/Maze-generation/OCaml/maze-generation.ocaml +++ b/Task/Maze-generation/OCaml/maze-generation.ocaml @@ -11,14 +11,9 @@ let () = let nx = int_of_string Sys.argv.(1) in let ny = int_of_string Sys.argv.(2) in - let rec random_order = function - | [] -> [] - | [a] -> [a] - | x -> let i = Random.int (List.length x) in - let rec del i = function - | [] -> failwith "del" - | h::t -> if i = 0 then t else h :: del (i-1) t in - (List.nth x i) :: random_order (del i x) in + let shuffle lst = + let nl = List.map (fun c -> (Random.bits (), c)) lst in + List.map snd (List.sort compare nl) in let get_neighbours (x,y) = let lim n k = (0 <= k) && (k < n) in @@ -29,7 +24,7 @@ let () = mark cell; let check k = if not (marked k) then (join cell k; visit k) in - List.iter check (random_order (get_neighbours cell)) in + List.iter check (shuffle (get_neighbours cell)) in let print_maze () = begin diff --git a/Task/Maze-generation/Swift/maze-generation.swift b/Task/Maze-generation/Swift/maze-generation.swift index 8685271d6a..28e467413a 100644 --- a/Task/Maze-generation/Swift/maze-generation.swift +++ b/Task/Maze-generation/Swift/maze-generation.swift @@ -1,17 +1,13 @@ import Foundation extension Array { - mutating func swap(_ index1:Int, _ index2:Int) { - let temp = self[index1] - self[index1] = self[index2] - self[index2] = temp - } - mutating func shuffle() { - for _ in 0.. 1 else { return } + + for i in 0.. const graph = [ + 0 1 0 0 0 0; + 1 0 1 0 1 0; + 0 1 0 0 0 1; + 0 0 0 0 1 0; + 0 1 0 1 0 0; + 0 0 1 0 0 0] + + julia> dist, path = dijkstra(graph, 1) + (Dict(4=>3,2=>1,3=>2,5=>2,6=>3,1=>0), Dict(4=>5,2=>1,3=>2,5=>2,6=>3,1=>0)) + + julia> printpath(path, 6) # Display solution of the maze + 1 -> 2 -> 3 -> 6 + +""" +function dijkstra(graph, source::Int=1) + # ensure that the adjacency matrix is squared + @assert size(graph, 1) == size(graph, 2) + inf = typemax(Int64) + n = size(graph, 1) + + Q = IntSet(1:n) # Set of unvisited nodes + dist = Dict(n => inf for n in Q) # Unknown distance function from source to v + prev = Dict(n => 0 for n in Q) # Previous node in optimal path from source + dist[source] = 0 # Distance from source to source + + function _minimumdist(nodes) # Find the less distant node among nodes + kmin, vmin = nothing, inf + for (k, v) in dist + if k ∈ nodes && v ≤ vmin + kmin, vmin = k, v + end + end + return kmin + end + # Until all nodes are visited... + while !isempty(Q) + u = _minimumdist(Q) # Vertex in Q with smallest dist[] + pop!(Q, u) + if dist[u] == inf break end # All remaining vertices are inaccessible from source + for v in 1:n # Each neighbor v of u + if graph[u, v] != 0 && v ∈ Q # where v has not yet been visited + alt = dist[u] + graph[u, v] + if alt < dist[v] # Relax (u, v, a) + dist[v] = alt + prev[v] = u + end + end + end + end + + return dist, prev +end + +function printpath(prev::Dict, target::Int) + path = "$target" + while prev[target] != 0 + target = prev[target] + path = "$target -> " * path + end + println(path) +end + +const graph = [ + 0 1 0 0 0 0; + 1 0 1 0 1 0; + 0 1 0 0 0 1; + 0 0 0 0 1 0; + 0 1 0 1 0 0; + 0 0 1 0 0 0] + +dist, path = dijkstra(graph) +printpath(path, 6) diff --git a/Task/Maze-solving/Kotlin/maze-solving.kotlin b/Task/Maze-solving/Kotlin/maze-solving.kotlin new file mode 100644 index 0000000000..28de54cb0d --- /dev/null +++ b/Task/Maze-solving/Kotlin/maze-solving.kotlin @@ -0,0 +1,117 @@ +// Version 1.2.31 + +import java.io.File + +typealias Maze = List + +/** + * Makes the maze half as wide (i. e. "+---+" becomes "+-+"), so that + * each cell in the maze is the same size horizontally as vertically. + * (Versus the expanded version, which looks better visually.) + * Also, converts each line of the maze from a String to a + * char[], because we'll want mutability when drawing the solution later. + */ +fun decimateHorizontally(lines: List): Maze { + val width = (lines[0].length + 1) / 2 + val c = List(lines.size) { CharArray(width) } + for (i in 0 until lines.size) { + for (j in 0 until width) c[i][j] = lines[i][j * 2] + } + return c +} + +/** + * Given the maze, the x and y coordinates (which must be odd), + * and the direction we came from, return true if the maze is + * solvable, and draw the solution if so. + */ +fun solveMazeRecursively(maze: Maze, x: Int, y: Int, d: Int): Boolean { + var ok = false + var i = 0 + while (i < 4 && !ok) { + if (i != d) { + // 0 = up, 1 = right, 2 = down, 3 = left + when(i) { + 0 -> if (maze[y - 1][x] == ' ') ok = solveMazeRecursively (maze, x, y - 2, 2) + 1 -> if (maze[y][x + 1] == ' ') ok = solveMazeRecursively (maze, x + 2, y, 3) + 2 -> if (maze[y + 1][x] == ' ') ok = solveMazeRecursively (maze, x, y + 2, 0) + 3 -> if (maze[y][x - 1] == ' ') ok = solveMazeRecursively (maze, x - 2, y, 1) + else -> {} + } + } + i++ + } + + // check for end condition + if (x == 1 && y == 1) ok = true + + // once we have found a solution, draw it as we unwind the recursion + if (ok) { + maze[y][x] = '*' + when (d) { + 0 -> maze[y - 1][x] = '*' + 1 -> maze[y][x + 1] = '*' + 2 -> maze[y + 1][x] = '*' + 3 -> maze[y][x - 1] = '*' + else -> {} + } + } + return ok +} + +/** + * Solve the maze and draw the solution. For simplicity, + * assumes the starting point is the lower right, and the + * ending point is the upper left. + */ +fun solveMaze(maze: Maze) = + solveMazeRecursively(maze, maze[0].size - 2, maze.size - 2, -1) + +/** + * Opposite of decimateHorizontally(). Adds extra characters to make + * the maze "look right", and converts each line from char[] to + * String at the same time. + */ +fun expandHorizontally(maze: Maze): Array { + val tmp = CharArray(3) + val lines = Array(maze.size) { "" } + for (i in 0 until maze.size) { + val sb = StringBuilder(maze[i].size * 2) + for (j in 0 until maze[i].size) { + if (j % 2 == 0) + sb.append(maze[i][j]) + else { + for (k in 0..2) tmp[k] = maze[i][j] + if (tmp[1] == '*') { + tmp[0] = ' ' + tmp[2] = ' ' + } + sb.append(tmp) + } + } + lines[i] = sb.toString() + } + return lines +} + +/** + * Accepts a maze as generated by: + * http://rosettacode.org/wiki/Maze_generation#Kotlin + * in a file whose name is specified as a command-line argument. + */ +fun main(args: Array) { + if (args.size != 1) { + println("The maze file to be read should be passed as a single command line argument.") + return + } + val f = File(args[0]) + if (!f.exists()) { + println("Sorry ${args[0]} does not exist.") + return + } + val lines = f.readLines(Charsets.US_ASCII) + val maze = decimateHorizontally(lines) + solveMaze(maze) + val solvedLines = expandHorizontally(maze) + println(solvedLines.joinToString("\n")) +} diff --git a/Task/Median-filter/Julia/median-filter.julia b/Task/Median-filter/Julia/median-filter.julia new file mode 100644 index 0000000000..35debe2bbd --- /dev/null +++ b/Task/Median-filter/Julia/median-filter.julia @@ -0,0 +1,7 @@ +using Images, ImageFiltering, FileIO +Base.isless(a::RGB{T}, b::RGB{T}) where T = + red(a) < red(b) || green(a) < green(b) || blue(a) < blue(b) +Base.middle(x::RGB) = x + +img = load("data/lenna100.jpg") +mapwindow(median!, img, (3, 3)) diff --git a/Task/Median-filter/Kotlin/median-filter.kotlin b/Task/Median-filter/Kotlin/median-filter.kotlin new file mode 100644 index 0000000000..92cabff107 --- /dev/null +++ b/Task/Median-filter/Kotlin/median-filter.kotlin @@ -0,0 +1,57 @@ +// Version 1.2.41 +import java.awt.Color +import java.awt.Graphics +import java.awt.image.BufferedImage +import java.io.File +import javax.imageio.ImageIO + +class BasicBitmapStorage(width: Int, height: Int) { + val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR) + + fun fill(c: Color) { + val g = image.graphics + g.color = c + g.fillRect(0, 0, image.width, image.height) + } + + fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB()) + + fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y)) + + fun medianFilter(windowWidth: Int, windowHeight: Int) { + val window = Array(windowWidth * windowHeight) { Color.black } + val edgeX = windowWidth / 2 + val edgeY = windowHeight / 2 + val compareByLuminance = { + c: Color -> 0.2126 * c.red + 0.7152 * c.green + 0.0722 * c.blue + } + for (x in edgeX until image.width - edgeX) { + for (y in edgeY until image.height - edgeY) { + var i = 0 + for (fx in 0 until windowWidth) { + for (fy in 0 until windowHeight) { + window[i] = getPixel(x + fx - edgeX, y + fy - edgeY) + i++ + } + } + window.sortBy(compareByLuminance) + setPixel(x, y, window[windowWidth * windowHeight / 2]) + } + } + } +} + +fun main(args: Array) { + val img = ImageIO.read(File("Medianfilterp.png")) + val bbs = BasicBitmapStorage(img.width / 2, img.height) + with (bbs) { + for (y in 0 until img.height) { + for (x in 0 until img.width / 2) { + setPixel(x, y, Color(img.getRGB(x, y))) + } + } + medianFilter(3, 3) + val mfFile = File("Medianfilterp2.png") + ImageIO.write(image, "png", mfFile) + } +} diff --git a/Task/Memory-allocation/Julia/memory-allocation.julia b/Task/Memory-allocation/Julia/memory-allocation.julia new file mode 100644 index 0000000000..1b2b6361c5 --- /dev/null +++ b/Task/Memory-allocation/Julia/memory-allocation.julia @@ -0,0 +1,2 @@ +matrix = Array{Float64,2}(100,100) +matrix[31,42] = pi diff --git a/Task/Memory-layout-of-a-data-structure/Julia/memory-layout-of-a-data-structure.julia b/Task/Memory-layout-of-a-data-structure/Julia/memory-layout-of-a-data-structure.julia new file mode 100644 index 0000000000..d6f600069b --- /dev/null +++ b/Task/Memory-layout-of-a-data-structure/Julia/memory-layout-of-a-data-structure.julia @@ -0,0 +1,23 @@ +mutable struct NinePinSerialPort + pins::BitArray + function NinePinSerialPort() + this = new() + this.pins = BitArray(9) + end +end + +const CD = 1 +const RD = 2 +const TD = 3 +const SG = 5 +const DSR = 6 +const RTS = 7 +const CTS = 8 + +# Here we test the type's code. +port = NinePinSerialPort() +println("Port is now at defaults, which are $port") +port[CTS] = true +println("CD pin of port, which is pin $CD, is now $(port[CD])") +println("CTS pin of port, which is pin $CTS, is now $(port[CTS])") +println("port is now: $port") diff --git a/Task/Memory-layout-of-a-data-structure/Scala/memory-layout-of-a-data-structure.scala b/Task/Memory-layout-of-a-data-structure/Scala/memory-layout-of-a-data-structure.scala new file mode 100644 index 0000000000..001b8c41ee --- /dev/null +++ b/Task/Memory-layout-of-a-data-structure/Scala/memory-layout-of-a-data-structure.scala @@ -0,0 +1,40 @@ +object Rs232Pins9 extends App { + + val (off: Boolean, on: Boolean) = (false, true) + val plug = new Rs232Pins9(carrierDetect = on, receivedData = on) // set first two pins, say + + def toOnOff(b: Boolean) = if (b) "on" else "off" + + class Rs232Pins9( + var carrierDetect: Boolean = off, + var receivedData: Boolean = off, + var transmittedData: Boolean = off, + var dataTerminalReady: Boolean = off, + var signalGround: Boolean = off, + var dataSetReady: Boolean = off, + var requestToSend: Boolean = off, + var clearToSend: Boolean = off, + var ringIndicator: Boolean = off + ) { + def setPin(n: Int, v: Boolean) { + (n) match { + case 1 => carrierDetect = v + case 2 => receivedData = v + case 3 => transmittedData = v + case 4 => dataTerminalReady = v + case 5 => signalGround = v + case 6 => dataSetReady = v + case 7 => requestToSend = v + case 8 => clearToSend = v + case 9 => ringIndicator = v + } + } + } + + // println(toOnOff(plug.component2())) // print value of pin 2 by number + plug.transmittedData = on // set pin 3 by name + plug.setPin(4, on) // set pin 4 by number + // println(toOnOff(plug.component3())) // print value of pin 3 by number + println(toOnOff(plug.dataTerminalReady)) // print value of pin 4 by name + println(toOnOff(plug.ringIndicator)) // print value of pin 9 by name +} diff --git a/Task/Menu/00DESCRIPTION b/Task/Menu/00DESCRIPTION index c3bb84415d..0b1a18ceac 100644 --- a/Task/Menu/00DESCRIPTION +++ b/Task/Menu/00DESCRIPTION @@ -16,4 +16,3 @@ For test purposes use the following four phrases in a list: ;Note: This task is fashioned after the action of the [http://www.softpanorama.org/Scripting/Shellorama/Control_structures/select_statements.shtml Bash select statement]. -

diff --git a/Task/Menu/Julia/menu.julia b/Task/Menu/Julia/menu.julia new file mode 100644 index 0000000000..b4fbd93a2c --- /dev/null +++ b/Task/Menu/Julia/menu.julia @@ -0,0 +1,28 @@ +function _menu(items) + for (ind, item) in enumerate(items) + @printf " %2i) %s\n" ind item + end +end + +_ok(::Any,::Any) = false +function _ok(reply::AbstractString, itemcount) + n = tryparse(Int, reply) + return isnull(n) || 0 ≤ get(n) ≤ itemcount +end + +"Prompt to select an item from the items" +function _selector(items, prompt::AbstractString) + isempty(items) && return "" + reply = -1 + itemcount = length(items) + while !_ok(reply, itemcount) + _menu(items) + print(prompt) + reply = strip(readline(STDIN)) + end + return items[parse(Int, reply)] +end + +items = ["fee fie", "huff and puff", "mirror mirror", "tick tock"] +item = _selector(items, "Which is from the three pigs: ") +println("You chose: ", item) diff --git a/Task/Menu/Rust/menu.rust b/Task/Menu/Rust/menu.rust new file mode 100644 index 0000000000..00ef428a0a --- /dev/null +++ b/Task/Menu/Rust/menu.rust @@ -0,0 +1,47 @@ +fn menu_select<'a>(items: &'a [&'a str]) -> &'a str { + if items.len() == 0 { + return ""; + } + + let stdin = std::io::stdin(); + let mut buffer = String::new(); + + loop { + for (i, item) in items.iter().enumerate() { + println!("{}) {}", i + 1, item); + } + print!("Pick a number from 1 to {}: ", items.len()); + + // Read the user input: + stdin.read_line(&mut buffer).unwrap(); + println!(); + + if let Ok(selected_index) = buffer.trim().parse::() { + if 0 < selected_index { + if let Some(selected_item) = items.get(selected_index - 1) { + return selected_item; + } + } + } + + // The buffer will contain the old input, so we need to clear it before we can reuse it. + buffer.clear(); + } +} + +fn main() { + // Empty list: + let selection = menu_select(&[]); + println!("No choice: {:?}", selection); + + // List with items: + let items = [ + "fee fie", + "huff and puff", + "mirror mirror", + "tick tock", + ]; + + let selection = menu_select(&items); + println!("You chose: {}", selection); +} diff --git a/Task/Menu/Scala/menu.scala b/Task/Menu/Scala/menu.scala new file mode 100644 index 0000000000..be12c0e5a8 --- /dev/null +++ b/Task/Menu/Scala/menu.scala @@ -0,0 +1,28 @@ +import scala.util.Try + +object Menu extends App { + val choice = menu(list) + + def menu(menuList: Seq[String]): String = { + if (menuList.isEmpty) "" else { + val n = menuList.size + + def getChoice: Try[Int] = { + println("\n M E N U\n") + menuList.zipWithIndex.map { case (text, index) => s"${index + 1}: $text" }.foreach(println(_)) + print(s"\nEnter your choice 1 - $n : ") + Try { + io.StdIn.readInt() + } + } + + menuList(Iterator.continually(getChoice) + .dropWhile(p => p.isFailure || !(1 to n).contains(p.get)) + .next.get - 1) + } + } + + def list = Seq("fee fie", "huff and puff", "mirror mirror", "tick tock") + + println(s"\nYou chose : $choice") +} diff --git a/Task/Metaprogramming/Nim/metaprogramming-1.nim b/Task/Metaprogramming/Nim/metaprogramming-1.nim index 474335b20a..92c63debc5 100644 --- a/Task/Metaprogramming/Nim/metaprogramming-1.nim +++ b/Task/Metaprogramming/Nim/metaprogramming-1.nim @@ -1,4 +1,4 @@ -proc `^`*[T: SomeInteger](base: T, exp: T): T = +proc `^`*[T: SomeInteger](base, exp: T): T = var (base, exp) = (base, exp) result = 1 diff --git a/Task/Metaprogramming/Nim/metaprogramming-7.nim b/Task/Metaprogramming/Nim/metaprogramming-7.nim index d5fcd84467..c04435c549 100644 --- a/Task/Metaprogramming/Nim/metaprogramming-7.nim +++ b/Task/Metaprogramming/Nim/metaprogramming-7.nim @@ -1,7 +1,7 @@ -template times(x: expr, y: stmt): stmt = +template times(x, y: untyped): untyped = for i in 1..x: y -10.times: # or times 10: +10.times: # or times 10: or times(10): echo "hi" echo "bye" diff --git a/Task/Metaprogramming/Scala/metaprogramming.scala b/Task/Metaprogramming/Scala/metaprogramming.scala new file mode 100644 index 0000000000..9a3fcbacd4 --- /dev/null +++ b/Task/Metaprogramming/Scala/metaprogramming.scala @@ -0,0 +1,11 @@ +import scala.language.experimental.macros +import scala.reflect.macros.Context + +object Macros { + def impl(c: Context) = { + import c.universe._ + c.Expr[Unit](q"""println("Hello World")""") + } + + def hello: Unit = macro impl +} diff --git a/Task/Metered-concurrency/Kotlin/metered-concurrency.kotlin b/Task/Metered-concurrency/Kotlin/metered-concurrency.kotlin new file mode 100644 index 0000000000..93f3f8c95a --- /dev/null +++ b/Task/Metered-concurrency/Kotlin/metered-concurrency.kotlin @@ -0,0 +1,20 @@ +// version 1.1.51 + +import java.util.concurrent.Semaphore +import kotlin.concurrent.thread + +fun main(args: Array) { + val numPermits = 4 + val numThreads = 9 + val semaphore = Semaphore(numPermits) + for (i in 1..numThreads) { + thread { + val name = "Unit #$i" + semaphore.acquire() + println("$name has acquired the semaphore") + Thread.sleep(2000) + semaphore.release() + println("$name has released the semaphore") + } + } +} diff --git a/Task/Metered-concurrency/Scala/metered-concurrency.scala b/Task/Metered-concurrency/Scala/metered-concurrency.scala new file mode 100644 index 0000000000..3b2ad9096e --- /dev/null +++ b/Task/Metered-concurrency/Scala/metered-concurrency.scala @@ -0,0 +1,30 @@ +class CountingSemaphore(var maxCount: Int) { + private var lockCount = 0 + + def acquire(): Unit = { + while ( { + lockCount >= maxCount + }) wait() + lockCount += 1 + } + + def release(): Unit = { + if (lockCount > 0) { + lockCount -= 1 + notifyAll() + } + } + + def getCount: Int = lockCount +} + +object Worker { + def main(args: Array[String]): Unit = { + val (lock, crew) = (new CountingSemaphore(3), new Array[Worker](5)) + + for { i <- 0 until 5} { + crew(i) = new Worker(lock, i) + crew(i).start() + } + } +} diff --git a/Task/Metronome/Julia/metronome.julia b/Task/Metronome/Julia/metronome.julia new file mode 100644 index 0000000000..cbc7f300f5 --- /dev/null +++ b/Task/Metronome/Julia/metronome.julia @@ -0,0 +1,13 @@ +function metronome(bpm::Real=72, bpb::Int=4) + s = 60.0 / bpm + counter = 0 + while true + counter += 1 + if counter % bpb != 0 + println("tick") + else + println("TICK") + end + sleep(s) + end +end diff --git a/Task/Metronome/Scala/metronome.scala b/Task/Metronome/Scala/metronome.scala new file mode 100644 index 0000000000..c797f06db2 --- /dev/null +++ b/Task/Metronome/Scala/metronome.scala @@ -0,0 +1,14 @@ +def metronome(bpm: Int, bpb: Int, maxBeats: Int = Int.MaxValue) { + val delay = 60000L / bpm + var beats = 0 + do { + Thread.sleep(delay) + if (beats % bpb == 0) print("\nTICK ") + else print("tick ") + beats+=1 + } + while (beats < maxBeats) + println() +} + +metronome(120, 4, 20) // limit to 20 diff --git a/Task/Middle-three-digits/Aime/middle-three-digits.aime b/Task/Middle-three-digits/Aime/middle-three-digits.aime index 345d8389e4..357cdb27a7 100644 --- a/Task/Middle-three-digits/Aime/middle-three-digits.aime +++ b/Task/Middle-three-digits/Aime/middle-three-digits.aime @@ -4,18 +4,15 @@ m3(integer i) text s; s = itoa(i); - if (character(s, 0) == '-') { + if (s[0] == '-') { s = delete(s, 0); } - if (length(s) < 3) { + if (~s < 3) { v_integer(i); v_text(" has not enough digits\n"); - } elif (length(s) & 1) { - o_winteger(9, i); - o_text(": "); - o_text(cut(s, length(s) - 3 >> 1, 3)); - o_byte('\n'); + } elif (~s & 1) { + o_form("/w9/: ~\n", i, cut(s, ~s - 3 >> 1, 3)); } else { v_integer(i); v_text(" has an even number of digits\n"); diff --git a/Task/Middle-three-digits/Elena/middle-three-digits.elena b/Task/Middle-three-digits/Elena/middle-three-digits.elena new file mode 100644 index 0000000000..6e66e54ce6 --- /dev/null +++ b/Task/Middle-three-digits/Elena/middle-three-digits.elena @@ -0,0 +1,29 @@ +import system'routines. +import extensions. + +middleThreeDigits = (:n) +[ + literal s := n absolute; literal. + int len := s length. + if(len<3) + [ + InvalidArgumentException new:"n must have 3 digits or more"; raise + ]; + if(len isEven) + [ + InvalidArgumentException new:"n must have an odd number of digits"; raise + ]. + + int mid := len / 2. + + ^ s Substring(mid-1,3). +]. + +program = +[ + (123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0) + forEach(:n) + [ + console printLine("middleThreeDigits(",n,"):",middleThreeDigits eval(n) | if(:e)(e message)) + ] +]. diff --git a/Task/Middle-three-digits/Factor/middle-three-digits.factor b/Task/Middle-three-digits/Factor/middle-three-digits.factor new file mode 100644 index 0000000000..9ef9a5b989 --- /dev/null +++ b/Task/Middle-three-digits/Factor/middle-three-digits.factor @@ -0,0 +1,26 @@ +USING: combinators formatting io kernel math math.parser +sequences ; +IN: rosetta-code.middle-three-digits + +CONSTANT: test-values { 123 12345 1234567 987654321 10001 -10001 + -123 -100 100 -12345 1 2 -1 -10 2002 -2002 0 } + +: middle-three ( str -- str' ) [ midpoint@ ] keep + [ [ 1 - ] [ 2 + ] bi ] dip subseq ; + +: too-short ( -- ) "Number must have at least three digits." + print ; + +: number-even ( -- ) "Number must have an odd number of digits." + print ; + +: process ( n -- ) + abs number>string { + { [ dup length 3 < ] [ drop too-short ] } + { [ dup length even? ] [ drop number-even ] } + [ middle-three print ] + } cond ; + +: main ( -- ) test-values [ dup "%9d : " printf process ] each ; + +MAIN: main diff --git a/Task/Middle-three-digits/Julia/middle-three-digits.julia b/Task/Middle-three-digits/Julia/middle-three-digits.julia index 979bb3028a..f8a5b52f95 100644 --- a/Task/Middle-three-digits/Julia/middle-three-digits.julia +++ b/Task/Middle-three-digits/Julia/middle-three-digits.julia @@ -1,17 +1,16 @@ -function middle(i) - s = string(abs(i)) +function middle3(n::Integer) + s = dec(abs(n)) l = length(s) - mid = round(Int,(l+1)/2) - l < 3 ? - "error: not enough digits" : - iseven(l) ? - "error: number of digits is even" : - s[mid-1:mid+1] + if iseven(l) + throw(ArgumentError("n must have an odd number of digits")) + elseif l < 3 + throw(ArgumentError("n must have 3 digits or more")) + end + mid = (l + 1) ÷ 2 + return s[mid-1:mid+1] end -julia> - for n = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0] - println (@sprintf("%10d : ", n), middle(n)) + @printf("%10d -> %s\n", n, try middle3(n) catch e e.msg end) end diff --git a/Task/Middle-three-digits/Kotlin/middle-three-digits.kotlin b/Task/Middle-three-digits/Kotlin/middle-three-digits.kotlin index 51f712ca77..7d8af5708e 100644 --- a/Task/Middle-three-digits/Kotlin/middle-three-digits.kotlin +++ b/Task/Middle-three-digits/Kotlin/middle-three-digits.kotlin @@ -1,14 +1,16 @@ fun middleThree(x: Int): Int? { val s = Math.abs(x).toString() - when { - s.length < 3 -> return null // throw Exception("too short!") - s.length % 2 == 0 -> return null // throw Exception("even number of digits") - else -> return ((s.length / 2) - 1).let { s.substring(it, it + 3) }.toInt() + return when { + s.length < 3 -> null // throw Exception("too short!") + s.length % 2 == 0 -> null // throw Exception("even number of digits") + else -> ((s.length / 2) - 1).let { s.substring(it, it + 3) }.toInt() } } -println(middleThree(12345)) // 234 -println(middleThree(1234)) // null -println(middleThree(1234567)) // 345 -println(middleThree(123))// 123 -println(middleThree(123555)) //null +fun main(args: Array) { + println(middleThree(12345)) // 234 + println(middleThree(1234)) // null + println(middleThree(1234567)) // 345 + println(middleThree(123))// 123 + println(middleThree(123555)) //null +} diff --git a/Task/Middle-three-digits/VBA/middle-three-digits.vba b/Task/Middle-three-digits/VBA/middle-three-digits.vba new file mode 100644 index 0000000000..370436327b --- /dev/null +++ b/Task/Middle-three-digits/VBA/middle-three-digits.vba @@ -0,0 +1,21 @@ +Option Explicit + +Sub Main_Middle_three_digits() +Dim Numbers, i& + Numbers = Array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, _ + 100, -12345, 1, 2, -1, -10, 2002, -2002, 0) + For i = 0 To 16 + Debug.Print Numbers(i) & " Return : " & Middle3digits(CStr(Numbers(i))) + Next +End Sub + +Function Middle3digits(strNb As String) As String + If Left(strNb, 1) = "-" Then strNb = Right(strNb, Len(strNb) - 1) + If Len(strNb) < 3 Then + Middle3digits = "Error ! Number of digits must be >= 3" + ElseIf Len(strNb) Mod 2 = 0 Then + Middle3digits = "Error ! Number of digits must be odd" + Else + Middle3digits = Mid(strNb, 1 + (Len(strNb) - 3) / 2, 3) + End If +End Function diff --git a/Task/Minesweeper-game/Ceylon/minesweeper-game.ceylon b/Task/Minesweeper-game/Ceylon/minesweeper-game.ceylon new file mode 100644 index 0000000000..191e6fb846 --- /dev/null +++ b/Task/Minesweeper-game/Ceylon/minesweeper-game.ceylon @@ -0,0 +1,134 @@ +import ceylon.random { + + DefaultRandom +} + +class Cell() { + + shared variable Boolean covered = true; + shared variable Boolean flagged = false; + shared variable Boolean mined = false; + shared variable Integer adjacentMines = 0; + + string => + if (covered && !flagged) + then "." + else if (covered && flagged) + then "?" + else if (!covered && mined) + then "X" + else if (!covered && adjacentMines > 0) + then adjacentMines.string + else " "; +} + +"The main function of the module. Run this one." +shared void run() { + + value random = DefaultRandom(); + value chanceOfBomb = 0.2; + + value width = 6; + value height = 4; + + value grid = Array { for (j in 1..height) Array { for (i in 1..width) Cell() } }; + + function getCell(Integer x, Integer y) => grid[y]?.get(x); + + void initializeGrid() { + + for (row in grid) { + for (cell in row) { + cell.covered = true; + cell.flagged = false; + cell.mined = random.nextFloat() < chanceOfBomb; + } + } + + function countAdjacentMines(Integer x, Integer y) => count { + for (j in y - 1 .. y + 1) + for (i in x - 1 .. x + 1) + if (exists cell = getCell(i, j)) + cell.mined + }; + + for (j->row in grid.indexed) { + for (i->cell in row.indexed) { + cell.adjacentMines = countAdjacentMines(i, j); + } + } + } + + void displayGrid() { + print(" " + "".join(1..width)); + print(" " + "-".repeat(width)); + for (j->row in grid.indexed) { + print("``j + 1``|``"".join(row)``|``j + 1``"); + } + print(" " + "-".repeat(width)); + print(" " + "".join(1..width)); + } + + Boolean won() => + expand(grid).every((cell) => (cell.flagged && cell.mined) || (!cell.flagged && !cell.mined)); + + void uncoverNeighbours(Integer x, Integer y) { + for (j in y - 1 .. y + 1) { + for (i in x - 1 .. x + 1) { + if (exists cell = getCell(i, j), cell.covered, !cell.flagged, !cell.mined) { + cell.covered = false; + if (cell.adjacentMines == 0) { + uncoverNeighbours(i, j); + } + } + } + } + } + + while (true) { + print("Welcome to minesweeper! + -----------------------"); + initializeGrid(); + while (true) { + displayGrid(); + print(" + The number of mines to find is ``count(expand(grid)*.mined)``. + What would you like to do? + [1] reveal a free space (or blow yourself up) + [2] mark (or unmark) a mine"); + assert (exists instruction = process.readLine()); + print("Please enter the coordinates. eg 2 4"); + assert (exists line2 = process.readLine()); + value coords = line2.split().map(Integer.parse).narrow().sequence(); + if (exists x = coords[0], exists y = coords[1], exists cell = getCell(x - 1, y - 1)) { + switch (instruction) + case ("1") { + if (cell.mined) { + print("================= + === You lose! === + ================="); + expand(grid).each((cell) => cell.covered = false); + displayGrid(); + break; + } + else if (cell.covered) { + cell.covered = false; + uncoverNeighbours(x - 1, y - 1); + } + } + case ("2") { + if (cell.covered) { + cell.flagged = !cell.flagged; + } + } + else { print("bad choice"); } + if (won()) { + print("**************** + *** You win! *** + ****************"); + break; + } + } + } + } +} diff --git a/Task/Minesweeper-game/Rust/minesweeper-game.rust b/Task/Minesweeper-game/Rust/minesweeper-game.rust new file mode 100644 index 0000000000..6909f831f3 --- /dev/null +++ b/Task/Minesweeper-game/Rust/minesweeper-game.rust @@ -0,0 +1,316 @@ +extern crate rand; + +use std::io; +use std::io::Write; + +fn main() { + + use minesweeper::{MineSweeper, GameStatus}; + + let mut width = 6; + let mut height = 4; + let mut mine_perctg = 10; + let mut game = MineSweeper::new(width, height, mine_perctg); + + loop { + let mut command = String::new(); + + println!( + "\n\ + M I N E S W E E P E R\n\ + \n\ + Commands: \n\ + line col - reveal line,col \n\ + m line col - mark line,col \n\ + q - quit\n\ + n - new game\n\ + n width height perc - new game size and mine percentage\n" + ); + + game.print(); + print!("> "); + io::stdout().flush().unwrap(); + while let Ok(_) = io::stdin().read_line(&mut command) { + let mut command_ok = false; + { + let values: Vec<&str> = command.trim().split(' ').collect(); + if values.len() == 1 { + if values[0] == "q" { + println!("Goodbye"); + return; + } else if values[0] == "n" { + println!("New game"); + game = MineSweeper::new(width, height, mine_perctg); + command_ok = true; + } + } else if values.len() == 2 { + if let (Ok(x), Ok(y)) = ( + values[0].parse::(), + values[1].parse::(), + ) + { + game.play(x - 1, y - 1); + + match game.game_status { + GameStatus::Won => println!("You won!"), + GameStatus::Lost => println!("You lost!"), + _ => (), + } + command_ok = true; + } + } else if values.len() == 3 { + if values[0] == "m" { + if let (Ok(x), Ok(y)) = ( + values[1].parse::(), + values[2].parse::(), + ) + { + game.mark(x - 1, y - 1); + command_ok = true; + } + } + } else if values.len() == 4 { + if values[0] == "n" { + if let (Ok(new_width), Ok(new_height), Ok(new_mines_perctg)) = + ( + values[1].parse::(), + values[2].parse::(), + values[3].parse::(), + ) + { + width = new_width; + height = new_height; + mine_perctg = new_mines_perctg; + game = MineSweeper::new(width, height, mine_perctg); + command_ok = true; + } + } + } + } + + if command_ok { + game.print(); + } else { + println!("Invalid command"); + } + + print!("> "); + io::stdout().flush().unwrap(); + command.clear(); + } + } +} + +pub mod minesweeper { + + pub struct MineSweeper { + cell: [[Cell; 100]; 100], + pub game_status: GameStatus, + mines: usize, + width: usize, + height: usize, + revealed_count: usize, + } + + #[derive(Copy, Clone)] + struct Cell { + content: CellContent, + mark: Mark, + revealed: bool, + } + + #[derive(Copy, Clone)] + enum CellContent { + Empty, + Mine, + MineNeighbour { count: u8 }, + } + + #[derive(Copy, Clone)] + enum Mark { + None, + Mine, + } + + pub enum GameStatus { + InGame, + Won, + Lost, + } + + extern crate rand; + + use std::cmp::max; + use std::cmp::min; + use self::rand::Rng; + use self::CellContent::*; + use self::GameStatus::*; + + impl MineSweeper { + pub fn new(width: usize, height: usize, percentage_of_mines: usize) -> MineSweeper { + let mut game = MineSweeper { + cell: [[Cell { + content: Empty, + mark: Mark::None, + revealed: false, + }; 100]; 100], + game_status: InGame, + mines: (width * height * percentage_of_mines) / 100, + width: width, + height: height, + revealed_count: 0, + }; + game.put_mines(); + game.calc_neighbours(); + game + } + + pub fn play(&mut self, x: usize, y: usize) { + match self.game_status { + InGame => { + if !self.cell[x][y].revealed { + match self.cell[x][y].content { + Mine => { + self.cell[x][y].revealed = true; + self.revealed_count += 1; + self.game_status = Lost; + } + Empty => { + self.flood_fill_reveal(x, y); + if self.revealed_count + self.mines == self.width * self.height { + self.game_status = Won; + } + } + MineNeighbour { .. } => { + self.cell[x][y].revealed = true; + self.revealed_count += 1; + if self.revealed_count + self.mines == self.width * self.height { + self.game_status = Won; + } + } + } + } + } + _ => println!("Game has ended"), + } + } + + pub fn mark(&mut self, x: usize, y: usize) { + self.cell[x][y].mark = match self.cell[x][y].mark { + Mark::None => Mark::Mine, + Mark::Mine => Mark::None, + } + } + + pub fn print(&self) { + print!("┌"); + for _ in 0..self.width { + print!("─"); + } + println!("┐"); + for y in 0..self.height { + print!("│"); + for x in 0..self.width { + self.cell[x][y].print(); + } + println!("│"); + } + print!("└"); + for _ in 0..self.width { + print!("─"); + } + println!("┘"); + } + + fn put_mines(&mut self) { + let mut rng = rand::thread_rng(); + for _ in 0..self.mines { + while let (x, y, true) = ( + rng.gen::() % self.width, + rng.gen::() % self.height, + true, + ) + { + match self.cell[x][y].content { + Mine => continue, + _ => { + self.cell[x][y].content = Mine; + break; + } + } + } + } + } + + fn calc_neighbours(&mut self) { + for x in 0..self.width { + for y in 0..self.height { + if !self.cell[x][y].is_bomb() { + let mut adjacent_bombs = 0; + + for i in max(x as isize - 1, 0) as usize..min(x + 2, self.width) { + for j in max(y as isize - 1, 0) as usize..min(y + 2, self.height) { + adjacent_bombs += if self.cell[i][j].is_bomb() { 1 } else { 0 }; + } + } + + if adjacent_bombs == 0 { + self.cell[x][y].content = Empty; + } else { + self.cell[x][y].content = MineNeighbour { count: adjacent_bombs }; + } + } + } + } + } + + fn flood_fill_reveal(&mut self, x: usize, y: usize) { + let mut stack = Vec::<(usize, usize)>::new(); + stack.push((x, y)); + + while let Some((i, j)) = stack.pop() { + if self.cell[i][j].revealed { + continue; + } + self.cell[i][j].revealed = true; + self.revealed_count += 1; + if let Empty = self.cell[i][j].content { + for m in max(i as isize - 1, 0) as usize..min(i + 2, self.width) { + for n in max(j as isize - 1, 0) as usize..min(j + 2, self.height) { + if !self.cell[m][n].is_bomb() && !self.cell[m][n].revealed { + stack.push((m, n)); + } + } + } + } + } + } + } + + impl Cell { + pub fn print(&self) { + print!( + "{}", + if self.revealed { + match self.content { + Empty => ' ', + Mine => '*', + MineNeighbour { count } => char::from(count + b'0'), + } + } else { + match self.mark { + Mark::Mine => '?', + Mark::None => '.', + } + } + ); + } + + pub fn is_bomb(&self) -> bool { + match self.content { + Mine => true, + _ => false, + } + } + } +} diff --git a/Task/Minesweeper-game/VBA/minesweeper-game-1.vba b/Task/Minesweeper-game/VBA/minesweeper-game-1.vba new file mode 100644 index 0000000000..b3f0613c0d --- /dev/null +++ b/Task/Minesweeper-game/VBA/minesweeper-game-1.vba @@ -0,0 +1,12 @@ +Option Explicit + +Public vTime As Single +Public PlaysCount As Long + +Sub Main_MineSweeper() +Dim Userf As New cMinesweeper +'Arguments : + 'First arg is level : 0 = easy, 1 = middle, 2 = difficult + 'Second arg is Cheat Mode : True if you want to cheat... + Userf.Show 0, True +End Sub diff --git a/Task/Minesweeper-game/VBA/minesweeper-game-2.vba b/Task/Minesweeper-game/VBA/minesweeper-game-2.vba new file mode 100644 index 0000000000..6e534db409 --- /dev/null +++ b/Task/Minesweeper-game/VBA/minesweeper-game-2.vba @@ -0,0 +1,241 @@ +Option Explicit + +Public myForm As Object +Public Fram As MSForms.Frame +Public Dico As Object +Public DicoParent As Object +Public TypeObjet As String +Public Mine As Boolean +Public boolFind As Boolean +Private strName As String +Private cNeighbours() As cMinesweeper +Public WithEvents myButton As MSForms.CommandButton +Private Const WIDTH_BUTT As Byte = 18 +Private Const MIN_OF_LINES As Byte = 7 +Private Const MAX_OF_LINES As Byte = 30 - MIN_OF_LINES +Private Const MIN_COL As Byte = 7 +Private Const MAX_COL As Byte = 40 - MIN_COL +Private Const POURCENT_SIMPLE As Byte = 10 +Private Const POURCENT_MEDIUM As Byte = 2 * POURCENT_SIMPLE +Private Const POURCENT_HARD As Byte = 3 * POURCENT_SIMPLE +Private Const COLOR_MINE As Long = &H188B0 +Private Const COLOR_BOUTON As Long = &H8000000F +Private Const COLOR_MINE_POSSIBLE As Long = &H80FF& +Private Const COLOR_MINE_PROB As Long = &H8080FF + +Property Get Neighbours() As cMinesweeper() + Neighbours = cNeighbours +End Property + +Property Let Neighbours(ByRef nouvNeighbours() As cMinesweeper) + cNeighbours = nouvNeighbours +End Property + +Private Sub Class_Initialize() + Set Dico = CreateObject("Scripting.dictionary") +End Sub + +Public Sub Show(ByRef Difficult As Long, Optional CheatMode As Boolean = False) + On Error GoTo ErrorParametresMacros + With ThisWorkbook.VBProject: End With + + Dim Lin As Long, Col As Long, NbLines As Long, NbColumns As Long + Dim NbMines As Long, MineAdress() As String, CptMine As Long + Randomize Timer + NbLines = Int(MAX_OF_LINES * Rnd) + MIN_OF_LINES + NbColumns = Int(MAX_COL * Rnd) + MIN_COL + Select Case Difficult + Case 0: Difficult = POURCENT_SIMPLE + Case 1: Difficult = POURCENT_MEDIUM + Case 2: Difficult = POURCENT_HARD + End Select + PlaysCount = 0 + NbMines = (NbLines * NbColumns) * Difficult \ 100 + ReDim MineAdress(NbMines) + For CptMine = 1 To NbMines + MineAdress(CptMine) = Int(NbColumns * Rnd) + 1 & "-" & Int(NbLines * Rnd) + 1 + Next + Call Create_Usf("Minesweeper", (NbColumns * WIDTH_BUTT) + 5, (NbLines * WIDTH_BUTT) + 22) + Call New_Frame("Fram1", "", NbColumns * WIDTH_BUTT, NbLines * WIDTH_BUTT) + For Lin = 1 To NbLines + For Col = 1 To NbColumns + Call Dico("Fram1").New_Button(Col & "-" & Lin, "", WIDTH_BUTT * (Col - 1), WIDTH_BUTT * (Lin - 1), IsIn(Col & "-" & Lin, MineAdress), CheatMode) + Set Dico("Fram1").Dico(Col & "-" & Lin).DicoParent = Dico("Fram1").Dico + Next Col + Next Lin + MsgBox "Start With " & NbMines & " mines." & vbCrLf & "Good luck !" + myForm.Show + Exit Sub +ErrorParametresMacros: + MsgBox "Programmatic Access to Visual Basic Project is not trusted. See it in Macro's security!" +End Sub + +Private Sub Create_Usf(strTitle As String, dblWidth As Double, dblHeight As Double) + TypeObjet = "UserForm" + Set myForm = ThisWorkbook.VBProject.VBComponents.Add(3) + strName = myForm.Name + VBA.UserForms.Add (strName) + Set myForm = UserForms(UserForms.Count - 1) + With myForm + .Caption = strTitle + .Width = dblWidth + .Height = dblHeight + End With +End Sub + +Public Sub New_Frame(myStringName As String, strTitle As String, dblWidth As Double, dblHeight As Double) + If Dico.Exists(myStringName) = True Then Exit Sub + Dim myClass As New cMinesweeper + Select Case TypeObjet + Case "UserForm": Set myClass.Fram = myForm.Controls.Add("forms.frame.1") + Case "Frame": Set myClass.Fram = Fram.Controls.Add("forms.frm.1") + End Select + myClass.TypeObjet = "Frame" + Set myClass.myForm = myForm + With myClass.Fram + .Name = myStringName + .Caption = strTitle + .Move 0, 0, dblWidth, dblHeight + End With + Dico.Add myStringName, myClass + Set myClass = Nothing +End Sub + +Public Sub New_Button(myStringName As String, strTitle As String, dblLeft As Double, dblTop As Double, boolMine As Boolean, Optional CheatMode As Boolean) + If Dico.Exists(myStringName) = True Then Exit Sub + Dim myClass As New cMinesweeper + Select Case TypeObjet + Case "UserForm": Set myClass.myButton = myForm.Controls.Add("forms.CommandButton.1") + Case "Frame": Set myClass.myButton = Fram.Controls.Add("forms.CommandButton.1") + End Select + Set myClass.myForm = myForm + myClass.Mine = boolMine + With myClass.myButton + .Name = myStringName + .Caption = strTitle + .Move dblLeft, dblTop, WIDTH_BUTT, WIDTH_BUTT + If CheatMode Then + If boolMine Then .BackColor = COLOR_MINE Else .BackColor = COLOR_BOUTON + Else + .BackColor = COLOR_BOUTON + End If + End With + Dico.Add myStringName, myClass + Set myClass = Nothing +End Sub + +Private Function IsIn(strAddress As String, Tb) As Boolean + Dim i As Long + For i = 0 To UBound(Tb) + If Tb(i) = strAddress Then IsIn = True: Exit Function + Next i +End Function + +Private Sub myButton_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal x As Single, ByVal y As Single) + If Button = XlMouseButton.xlSecondaryButton Then + Select Case myButton.Caption + Case "": myButton.Caption = "!": myButton.BackColor = COLOR_MINE_PROB + Case "!": myButton.Caption = "?": myButton.BackColor = COLOR_MINE_POSSIBLE + Case "?": myButton.Caption = "": myButton.BackColor = COLOR_BOUTON + Case Else: + End Select + ElseIf Button = XlMouseButton.xlPrimaryButton Then + PlaysCount = PlaysCount + 1 + If PlaysCount = 1 Then vTime = Timer + If DicoParent.Item(myButton.Name).Mine Then + Call Show_Mines + MsgBox "Game over!" + myForm.Hide + Else + myButton.BackColor = COLOR_BOUTON + Dim myClass As cMinesweeper + Set myClass = DicoParent.Item(myButton.Name) + Call Demine(myClass) + End If + End If + If IsVictoriousGame Then + Call Show_Mines + MsgBox "You win." & vbCrLf & "in : " & PlaysCount & " clicks, and in : " & Timer - vTime & " seconds." + Erase Neighbours + myForm.Hide + End If +End Sub + +Private Sub Show_Mines() +Dim cle As Variant + For Each cle In DicoParent.Keys + If DicoParent.Item(cle).Mine Then DicoParent.Item(cle).myButton.BackColor = COLOR_MINE + Next +End Sub + +Private Sub Demine(Cl As cMinesweeper) +Dim NbMines As Integer + NbMines = Count_Of_Mines(Cl.myButton.Name) + If NbMines > 0 Then + Cl.myButton.Caption = NbMines + Cl.boolFind = True + Cl.myButton.BackColor = COLOR_BOUTON + Else + If Cl.boolFind = False Then + Cl.boolFind = True + Cl.myButton.Visible = False + What_Neighbours Cl + Dim Tb() As cMinesweeper, i As Integer + Tb = Cl.Neighbours + For i = 0 To UBound(Tb) + Demine Tb(i) + Next + End If + End If +End Sub + +Private Function Count_Of_Mines(Bout As String) As Integer +Dim i As Integer, j As Integer, Col As Integer, Lin As Integer +Dim myClass As cMinesweeper + For i = -1 To 1 + For j = -1 To 1 + Col = CInt(Split(Bout, "-")(0)) + i + Lin = CInt(Split(Bout, "-")(1)) + j + If DicoParent.Exists(Col & "-" & Lin) Then + Set myClass = DicoParent.Item(Col & "-" & Lin) + If myClass.Mine Then Count_Of_Mines = Count_Of_Mines + 1 + End If + Next j + Next i +End Function + +Private Sub What_Neighbours(Cl As cMinesweeper) +Dim i As Integer, j As Integer, Col As Integer, Lin As Integer +Dim myClass As cMinesweeper, ListNeighbours() As cMinesweeper, cpt As Byte + For i = -1 To 1 + For j = -1 To 1 + Col = CInt(Split(Cl.myButton.Name, "-")(0)) + i + Lin = CInt(Split(Cl.myButton.Name, "-")(1)) + j + If DicoParent.Exists(Col & "-" & Lin) And Cl.myButton.Name <> Col & "-" & Lin Then + Set myClass = DicoParent.Item(Col & "-" & Lin) + ReDim Preserve ListNeighbours(cpt) + Set ListNeighbours(cpt) = myClass + cpt = cpt + 1 + End If + Next j + Next i + Cl.Neighbours = ListNeighbours +End Sub + +Private Function IsVictoriousGame() As Boolean +Dim cle As Variant + For Each cle In DicoParent.Keys + If DicoParent.Item(cle).boolFind = False And DicoParent.Item(cle).Mine = False Then IsVictoriousGame = False: Exit Function + Next + IsVictoriousGame = True +End Function + +Private Sub Class_Terminate() + Dim VBComp + Set Dico = Nothing + Set DicoParent = Nothing + If strName <> "" Then + Set VBComp = ThisWorkbook.VBProject.VBComponents(strName) + ThisWorkbook.VBProject.VBComponents.Remove VBComp + End If +End Sub diff --git a/Task/Modular-exponentiation/Julia/modular-exponentiation.julia b/Task/Modular-exponentiation/Julia/modular-exponentiation.julia index 906850648a..01cc4bf140 100644 --- a/Task/Modular-exponentiation/Julia/modular-exponentiation.julia +++ b/Task/Modular-exponentiation/Julia/modular-exponentiation.julia @@ -1,5 +1,4 @@ -julia> a = BigInt("2988348162058574136915891421498819466320163312926952423791023078876139") - b = BigInt("2351399303373464486466122544523690094744975233415544072992656881240319") - m = BigInt(10)^40 - powermod(a, b, m) -1527229998585248450016808958343740453059 +a = 2988348162058574136915891421498819466320163312926952423791023078876139 +b = 2351399303373464486466122544523690094744975233415544072992656881240319 +m = big(10) ^ 40 +@show powermod(a, b, m) diff --git a/Task/Modular-inverse/C-sharp/modular-inverse.cs b/Task/Modular-inverse/C-sharp/modular-inverse.cs new file mode 100644 index 0000000000..4253a1b7f9 --- /dev/null +++ b/Task/Modular-inverse/C-sharp/modular-inverse.cs @@ -0,0 +1,24 @@ +public class Program +{ + static void Main() + { + System.Console.WriteLine(42.ModInverse(2017)); + } +} + +public static class IntExtensions +{ + public static int ModInverse(this int a, int m) + { + if (m == 1) return 0; + int m0 = m; + (int x, int y) = (1, 0); + + while (a > 1) { + int q = a / m; + (a, m) = (m, a % m); + (x, y) = (y, x - q * y); + } + return x < 0 ? x + m0 : x; + } +} diff --git a/Task/Modular-inverse/Factor/modular-inverse.factor b/Task/Modular-inverse/Factor/modular-inverse.factor new file mode 100644 index 0000000000..a7d36f70a8 --- /dev/null +++ b/Task/Modular-inverse/Factor/modular-inverse.factor @@ -0,0 +1,2 @@ +USE: math.functions +42 2017 mod-inv diff --git a/Task/Modular-inverse/GW-BASIC/modular-inverse.gw-basic b/Task/Modular-inverse/GW-BASIC/modular-inverse.gw-basic new file mode 100644 index 0000000000..0aad60ca9a --- /dev/null +++ b/Task/Modular-inverse/GW-BASIC/modular-inverse.gw-basic @@ -0,0 +1,27 @@ +10 ' Modular inverse +20 LET E% = 42 +30 LET T% = 2017 +40 GOSUB 1000 +50 PRINT MODINV% +60 END + +990 ' increments e stp (step) times until bal is greater than t +992 ' repeats until bal = 1 (mod = 1) and returns count +994 ' bal will not be greater than t + e +1000 LET D% = 0 +1010 IF E% >= T% THEN GOTO 1140 +1020 LET BAL% = E% +1025 ' At least one iteration is necessary +1030 LET STP% = ((T% - BAL%) \ E%) + 1 +1040 LET BAL% = BAL% + STP% * E% +1050 LET COUNT% = 1 + STP% +1060 LET BAL% = BAL% - T% +1070 WHILE BAL% <> 1 +1080 LET STP% = ((T% - BAL%) \ E%) + 1 +1090 LET BAL% = BAL% + STP% * E% +1100 LET COUNT% = COUNT% + STP% +1110 LET BAL% = BAL% - T% +1120 WEND +1130 LET D% = COUNT% +1140 LET MODINV% = D% +1150 RETURN diff --git a/Task/Modular-inverse/Modula-2/modular-inverse.mod2 b/Task/Modular-inverse/Modula-2/modular-inverse.mod2 new file mode 100644 index 0000000000..7efc1952b8 --- /dev/null +++ b/Task/Modular-inverse/Modula-2/modular-inverse.mod2 @@ -0,0 +1,43 @@ +MODULE ModularInverse; + FROM InOut IMPORT WriteString, WriteInt, WriteLn; + + TYPE Data = RECORD x : INTEGER; + y : INTEGER + END; + + VAR c : INTEGER; + ab : ARRAY [1..5] OF Data; + +PROCEDURE mi(VAR a, b : INTEGER): INTEGER; + VAR t, nt, r, nr, q, tmp : INTEGER; + +BEGIN + b := ABS(b); + IF a < 0 THEN a := b - (-a MOD b) END; + t := 0; nt := 1; r := b; nr := a MOD b; + WHILE (nr # 0) DO + q := r / nr; + tmp := nt; nt := t - q * nt; t := tmp; + tmp := nr; nr := r - q * nr; r := tmp; + END; + IF (r > 1) THEN RETURN -1 END; + IF (t < 0) THEN RETURN t + b END; + RETURN t; +END mi; + +BEGIN + ab[1].x := 42; ab[1].y := 2017; + ab[2].x := 40; ab[2].y := 1; + ab[3].x := 52; ab[3].y := -217; + ab[4].x := -486; ab[4].y := 217; + ab[5].x := 40; ab[5].y := 2018; + WriteLn; + WriteString("Modular inverse"); + WriteLn; + FOR c := 1 TO 5 DO + WriteInt(ab[c].x, 6); WriteString(", "); + WriteInt(ab[c].y, 6); WriteString(" = "); + WriteInt(mi(ab[c].x, ab[c].y),6); + WriteLn; + END; +END ModularInverse. diff --git a/Task/Modular-inverse/PureBasic/modular-inverse.purebasic b/Task/Modular-inverse/PureBasic/modular-inverse.purebasic new file mode 100644 index 0000000000..5c2a88aa55 --- /dev/null +++ b/Task/Modular-inverse/PureBasic/modular-inverse.purebasic @@ -0,0 +1,37 @@ +EnableExplicit +Declare main() +Declare.i mi(a.i, b.i) + +If OpenConsole("MODULAR-INVERSE") + main() : Input() : End +EndIf + +Macro ModularInverse(a, b) + PrintN(~"\tMODULAR-INVERSE(" + RSet(Str(a),5) + "," + + RSet(Str(b),5)+") = " + + RSet(Str(mi(a, b)),5)) +EndMacro + +Procedure main() + ModularInverse(42, 2017) ; = 1969 + ModularInverse(40, 1) ; = 0 + ModularInverse(52, -217) ; = 96 + ModularInverse(-486, 217) ; = 121 + ModularInverse(40, 2018) ; = -1 +EndProcedure + +Procedure.i mi(a.i, b.i) + Define x.i = 1, + y.i = Int(Abs(b)), + r.i = 0 + If y = 1 : ProcedureReturn 0 : EndIf + While x < y + r = (a * x) % b + If r = 1 Or (y + r) = 1 + Break + EndIf + x + 1 + Wend + If x > y - 1 : x = -1 : EndIf + ProcedureReturn x +EndProcedure diff --git a/Task/Monte-Carlo-methods/Go/monte-carlo-methods.go b/Task/Monte-Carlo-methods/Go/monte-carlo-methods-1.go similarity index 100% rename from Task/Monte-Carlo-methods/Go/monte-carlo-methods.go rename to Task/Monte-Carlo-methods/Go/monte-carlo-methods-1.go diff --git a/Task/Monte-Carlo-methods/Go/monte-carlo-methods-2.go b/Task/Monte-Carlo-methods/Go/monte-carlo-methods-2.go new file mode 100644 index 0000000000..8067b31b5c --- /dev/null +++ b/Task/Monte-Carlo-methods/Go/monte-carlo-methods-2.go @@ -0,0 +1,34 @@ +package main + +import ( + "fmt" + "math" + "time" + + "golang.org/x/exp/rand" +) + +func getPi(numThrows int) float64 { + inCircle := 0 + for i := 0; i < numThrows; i++ { + //a square with a side of length 2 centered at 0 has + //x and y range of -1 to 1 + randX := rand.Float64()*2 - 1 //range -1 to 1 + randY := rand.Float64()*2 - 1 //range -1 to 1 + //distance from (0,0) = sqrt((x-0)^2+(y-0)^2) + dist := math.Hypot(randX, randY) + if dist < 1 { //circle with diameter of 2 has radius of 1 + inCircle++ + } + } + return 4 * float64(inCircle) / float64(numThrows) +} + +func main() { + rand.Seed(uint64(time.Now().UnixNano())) + fmt.Println(getPi(10000)) + fmt.Println(getPi(100000)) + fmt.Println(getPi(1000000)) + fmt.Println(getPi(10000000)) + fmt.Println(getPi(100000000)) +} diff --git a/Task/Monte-Carlo-methods/Julia/monte-carlo-methods.julia b/Task/Monte-Carlo-methods/Julia/monte-carlo-methods.julia index 1520b0edf5..5e94d30a39 100644 --- a/Task/Monte-Carlo-methods/Julia/monte-carlo-methods.julia +++ b/Task/Monte-Carlo-methods/Julia/monte-carlo-methods.julia @@ -1,7 +1,9 @@ -function montepi(n) - s = 0 - for i = 1:n - s += rand()^2 + rand()^2 < 1 - end - return 4*s/n +function monteπ(n) + s = count(rand() ^ 2 + rand() ^ 2 < 1 for _ in 1:n) + return 4s / n +end + +for n in 10 .^ (3:8) + p = monteπ(n) + println("$(lpad(n, 9)): π ≈ $(lpad(p, 10)), pct.err = ", @sprintf("%2.5f%%", abs(p - π) / π)) end diff --git a/Task/Monte-Carlo-methods/Ruby/monte-carlo-methods.rb b/Task/Monte-Carlo-methods/Ruby/monte-carlo-methods.rb index 29d0f7740e..806a00a4f8 100644 --- a/Task/Monte-Carlo-methods/Ruby/monte-carlo-methods.rb +++ b/Task/Monte-Carlo-methods/Ruby/monte-carlo-methods.rb @@ -1,9 +1,8 @@ def approx_pi(throws) times_inside = throws.times.count {Math.hypot(rand, rand) <= 1.0} - # in pre-Ruby-1.8.7: times_inside = throws.times.select {Math.hypot(rand, rand) <= 1.0}.length 4.0 * times_inside / throws end [1000, 10_000, 100_000, 1_000_000, 10_000_000].each do |n| - puts "%8d samples: PI = %s" % [n, approx_pi(n)] + puts "%8d samples: PI = %s" % [n, approx_pi(n)] end diff --git a/Task/Monte-Carlo-methods/Rust/monte-carlo-methods.rust b/Task/Monte-Carlo-methods/Rust/monte-carlo-methods.rust new file mode 100644 index 0000000000..a24cfd45d0 --- /dev/null +++ b/Task/Monte-Carlo-methods/Rust/monte-carlo-methods.rust @@ -0,0 +1,33 @@ +extern crate rand; + +use rand::Rng; +use std::f64::consts::PI; + +// `(f32, f32)` would be faster for some RNGs (including `rand::thread_rng` on 32-bit platforms +// and `rand::weak_rng` as of rand v0.4) as `next_u64` combines two `next_u32`s if not natively +// supported by the RNG. It would less accurate however. +fn is_inside_circle((x, y): (f64, f64)) -> bool { + x * x + y * y <= 1.0 +} + +fn simulate(rng: &mut R, samples: usize) -> f64 { + let mut count = 0; + for _ in 0..samples { + if is_inside_circle(rng.gen()) { + count += 1; + } + } + (count as f64) / (samples as f64) +} + +fn main() { + let mut rng = rand::weak_rng(); + + println!("Real pi: {}", PI); + + for samples in (3..9).map(|e| 10_usize.pow(e)) { + let estimate = 4.0 * simulate(&mut rng, samples); + let deviation = 100.0 * (1.0 - estimate / PI).abs(); + println!("{:9}: {:<11} dev: {:.5}%", samples, estimate, deviation); + } +} diff --git a/Task/Morse-code/ABAP/morse-code.abap b/Task/Morse-code/ABAP/morse-code.abap new file mode 100644 index 0000000000..ff83f9cf1e --- /dev/null +++ b/Task/Morse-code/ABAP/morse-code.abap @@ -0,0 +1,72 @@ +REPORT morse_code. +TYPES: BEGIN OF y_morse_code, + letter TYPE string, + code TYPE string, + END OF y_morse_code, + ty_morse_code TYPE STANDARD TABLE OF y_morse_code WITH EMPTY KEY. + +cl_demo_output=>new( + )->begin_section( |Morse Code| + )->write( REDUCE stringtab( LET words = VALUE stringtab( ( |sos| ) + ( | Hello World!| ) + ( |Rosetta Code| ) ) + morse_code = VALUE ty_morse_code( ( letter = 'A' code = '.- ' ) + ( letter = 'B' code = '-... ' ) + ( letter = 'C' code = '-.-. ' ) + ( letter = 'D' code = '-.. ' ) + ( letter = 'E' code = '. ' ) + ( letter = 'F' code = '..-. ' ) + ( letter = 'G' code = '--. ' ) + ( letter = 'H' code = '.... ' ) + ( letter = 'I' code = '.. ' ) + ( letter = 'J' code = '.--- ' ) + ( letter = 'K' code = '-.- ' ) + ( letter = 'L' code = '.-.. ' ) + ( letter = 'M' code = '-- ' ) + ( letter = 'N' code = '-. ' ) + ( letter = 'O' code = '--- ' ) + ( letter = 'P' code = '.--. ' ) + ( letter = 'Q' code = '--.- ' ) + ( letter = 'R' code = '.-. ' ) + ( letter = 'S' code = '... ' ) + ( letter = 'T' code = '- ' ) + ( letter = 'U' code = '..- ' ) + ( letter = 'V' code = '...- ' ) + ( letter = 'W' code = '.- - ' ) + ( letter = 'X' code = '-..- ' ) + ( letter = 'Y' code = '-.-- ' ) + ( letter = 'Z' code = '--.. ' ) + ( letter = '0' code = '----- ' ) + ( letter = '1' code = '.---- ' ) + ( letter = '2' code = '..--- ' ) + ( letter = '3' code = '...-- ' ) + ( letter = '4' code = '....- ' ) + ( letter = '5' code = '..... ' ) + ( letter = '6' code = '-.... ' ) + ( letter = '7' code = '--... ' ) + ( letter = '8' code = '---.. ' ) + ( letter = '9' code = '----. ' ) + ( letter = '''' code = '.----. ' ) + ( letter = ':' code = '---... ' ) + ( letter = ',' code = '--..-- ' ) + ( letter = '-' code = '-....- ' ) + ( letter = '(' code = '-.--.- ' ) + ( letter = '.' code = '.-.-.- ' ) + ( letter = '?' code = '..--.. ' ) + ( letter = ';' code = '-.-.-. ' ) + ( letter = '/' code = '-..-. ' ) + ( letter = '_' code = '..--.- ' ) + ( letter = ')' code = '---.. ' ) + ( letter = '=' code = '-...- ' ) + ( letter = '@' code = '.--.-. ' ) + ( letter = '\' code = '.-..-. ' ) + ( letter = '+' code = '.-.-. ' ) + ( letter = ' ' code = '/' ) ) + IN INIT word_coded_tab TYPE stringtab + FOR word IN words + NEXT word_coded_tab = VALUE #( BASE word_coded_tab ( REDUCE string( INIT word_coded TYPE string + FOR index = 1 UNTIL index > strlen( word ) + LET _morse_code = VALUE #( morse_code[ letter = COND #( WHEN index = 1 THEN to_upper( word(index) ) + ELSE LET prev = index - 1 IN to_upper( word+prev(1) ) ) ]-code OPTIONAL ) + IN NEXT word_coded = |{ word_coded } { _morse_code }| ) ) ) ) + )->display( ). diff --git a/Task/Morse-code/Modula-2/morse-code.mod2 b/Task/Morse-code/Modula-2/morse-code.mod2 new file mode 100644 index 0000000000..66f2e6c567 --- /dev/null +++ b/Task/Morse-code/Modula-2/morse-code.mod2 @@ -0,0 +1,62 @@ +MODULE MorseCode; +FROM Terminal IMPORT WriteString,WriteLn,ReadChar; + +PROCEDURE WriteMorseCode(str : ARRAY OF CHAR); +VAR i : CARDINAL; +BEGIN + WriteString(str); + WriteLn; + FOR i:=0 TO HIGH(str) DO + CASE CAP(str[i]) OF + 'A': WriteString(".-"); + | 'B': WriteString("-..."); + | 'C': WriteString("-.-"); + | 'D': WriteString("-.."); + | 'E': WriteString("."); + | 'F': WriteString("..-."); + | 'G': WriteString("--."); + | 'H': WriteString("...."); + | 'I': WriteString(".."); + | 'J': WriteString(".---"); + | 'K': WriteString("-.-"); + | 'L': WriteString(".-.."); + | 'M': WriteString("--"); + | 'N': WriteString("-."); + | 'O': WriteString("---"); + | 'P': WriteString(".--."); + | 'Q': WriteString("--.-"); + | 'R': WriteString(".-."); + | 'S': WriteString("..."); + | 'T': WriteString("-"); + | 'U': WriteString("..-"); + | 'V': WriteString("...-"); + | 'W': WriteString(".--"); + | 'X': WriteString("-..-"); + | 'Y': WriteString("-.--"); + | 'Z': WriteString("--.."); + | '0': WriteString("-----"); + | '1': WriteString(".----"); + | '2': WriteString("..---"); + | '3': WriteString("...--"); + | '4': WriteString("....-"); + | '5': WriteString("....."); + | '6': WriteString("-...."); + | '7': WriteString("--..."); + | '8': WriteString("---.."); + | '9': WriteString("----."); + | ' ': WriteString(" "); + ELSE + IF (str[i] # 0C) THEN + WriteString("?"); + END + END; + WriteString(" "); + END; +END WriteMorseCode; + +BEGIN + WriteMorseCode("hello world"); + WriteLn; + + ReadChar; +END MorseCode. diff --git a/Task/Morse-code/Red/morse-code-1.red b/Task/Morse-code/Red/morse-code-1.red new file mode 100644 index 0000000000..6f07cb7c51 --- /dev/null +++ b/Task/Morse-code/Red/morse-code-1.red @@ -0,0 +1,60 @@ +Red [ + file: %morse.red ;; filename, could be ommited +] +; ";" is character for comment, i use double ones for better readability + +DIT: 100 ;; constant : 100 ms for short Beep +FREQ: 700 ;; frequency for Beep + +;; exported code for red/system win api calls to Beep / Sleep: +#include %api.reds + +;; string with morse codes for alphabet: +;; ( caution, u must use "str: copy ..." if code ist to be executed multiple times ! ) +str: "A.-B-...C-.-.D-..E.F..-.G--.H....I..J.---K-.-L.-..M--N-." +append str "O---P.--.Q--.-R.-.S...T-U..-V...-W.--X-..-Y-.--Z--.." + + delim: charset [#"A" - #"Z"] + + ;; use of parse to generate "mc" morse code series / array containing codes for A - Z + ;; use characters only as delimiter for each code + mc: parse str [ thru "A" collect some [ keep copy result to [delim | end ] skip ] ] + + ;;-------------------------------------------- + send-code: func ["function to play morse code for character " + ;;-------------------------------------------- + chr [char!] ;; character A .. Z + ][ + sleep 500 ;; short break so u can read the character first + ind: to-integer chr - 64 ;; calculate index for morse array + foreach sym mc/:ind [ ;; foreach symbol of code for character ... + prin sym ;; prin(t) "." or "-" + either sym = #"." [ ;; short beep + beep FREQ DIT + ][ + beep FREQ 3 * DIT ;; or long beep = 3 x short + ] + sleep DIT ;; short break after each character + ] +] + ;;---------------------------------------------- + morse-text: func ["extract valid characters from sentence" + ;;---------------------------------------------- + msg [string!] +][ + foreach chr uppercase msg [ + prin chr prin " " ;; print character + ;; valid character A-Z ? + either (chr >= #"A") and (chr <= #"Z") [ + send-code chr + ] [ ;; ... "else" word gap or unknown + sleep 6 * DIT ;; pause after word + ] + prin newline ;; equal to : print """ ,( prin prints without crlf ) + ] + sleep 6 * DIT ;; pause after sentence + ] + ;;---------------------------------- + +morse-text "rosetta code" +morse-text "hello world" diff --git a/Task/Morse-code/Red/morse-code-2.red b/Task/Morse-code/Red/morse-code-2.red new file mode 100644 index 0000000000..0b71508121 --- /dev/null +++ b/Task/Morse-code/Red/morse-code-2.red @@ -0,0 +1,25 @@ +Red/System [ + file: %api.reds ;; filename, could be ommited +] + +; --- lib import ----- +;; for winapi functions "Beep" and "Sleep" +#system [ #import [ "kernel32.dll" stdcall [ + wbeep: "Beep" [ + frequ [integer!] + dur [integer!] + return: [integer!] + ] + wsleep: "Sleep" [ dur [integer!] ] +] ] ] + +beep: routine [ + freq [integer!] + duration [integer!] + return: [integer!] + ] [ wbeep freq duration ] + +sleep: routine [ + duration [integer!] + ] [ wsleep duration ] +;;---------------------------------------------- diff --git a/Task/Morse-code/Ring/morse-code.ring b/Task/Morse-code/Ring/morse-code.ring new file mode 100644 index 0000000000..3dbe182950 --- /dev/null +++ b/Task/Morse-code/Ring/morse-code.ring @@ -0,0 +1,55 @@ + morsecode = [["a", ".-"], + ["b", "-..."], + ["c", "-.-."], + ["d", "-.."], + ["e", "."], + ["f", "..-."], + ["g", "--."], + ["h", "...."], + ["i", ".."], + ["j", ".---"], + ["k", "-.-"], + ["l", ".-.."], + ["m", "--"], + ["n", "-."], + ["o", "---"], + ["p", ".--."], + ["q", "--.-"], + ["r", ".-."], + ["s", "..."], + ["t", "-"], + ["u", "..-"], + ["v", "...-"], + ["w", ".--"], + ["x", "-..-"], + ["y", "-.--"], + ["z", "--.."], + ["0", "-----"], + ["1", ".----"], + ["2", "..---"], + ["3", "...--"], + ["4", "....-"], + ["5", "....."], + ["6", "-...."], + ["7", "--..."], + ["8", "---.."], + ["9", "----."]] +strmorse = "" +str = "this is a test text" +for n = 1 to len(str) + pos = 0 + for m = 1 to len(morsecode) + if morsecode[m][1] = str[n] + pos = m + ok + next + if str[n] = " " + strmorse = strmorse + " " + else + if pos > 0 + strmorse = strmorse + morsecode[pos][2] + "|" + ok + ok +next +strmorse = left(strmorse,len(strmorse)-1) +see strmorse + nl diff --git a/Task/Morse-code/VBA/morse-code.vba b/Task/Morse-code/VBA/morse-code.vba new file mode 100644 index 0000000000..0a2c996a95 --- /dev/null +++ b/Task/Morse-code/VBA/morse-code.vba @@ -0,0 +1,60 @@ +Option Explicit + +Private Declare Function Beep Lib "kernel32" (ByVal dwFreq As Long, ByVal dwDuration As Long) As Long +Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) + +Private Const MORSE_ALPHA As String = ".-,-...,-.-.,-..,.,..-.,--.,....,..,.---,-.-,.-..,--,-.,---,.--.,--.-,.-.,...,-,..-,...-,.--,-..-,-.--,--.." +Private Const MORSE_NUMERIC As String = "-----,.----,..---,...--,....-,.....,-....,--...,---..,----." + +Private Const ONE_UNIT As Integer = 100 + +Private Const BEEP_DOT As Integer = ONE_UNIT +Private Const BEEP_DASH As Integer = 3 * ONE_UNIT +Private Const BEEP_OTHER As Integer = 7 * ONE_UNIT +Private Const DELAY As Integer = ONE_UNIT +Private Const LETTERS_DELAY As Integer = 3 * ONE_UNIT +Private Const SPACE_DELAY As Integer = 7 * ONE_UNIT + +Private Const FREQUENCY_CHARS As Integer = 1200 +Private Const FREQUENCY_OTHERCHARS As Integer = 400 + +Sub Main() +Dim p$, temp$ + p = ToMorse("Hel/lo 123 world") + temp = Replace(p, "+", "") + Debug.Print Replace(temp, "_", "") + PlayMorse p +End Sub + +Private Function ToMorse(s As String) As String +Dim i&, t$, j& + s = UCase(s) + For i = 1 To Len(s) + j = Asc(Mid(s, i, 1)) + Select Case j + Case 65 To 90 'alpha + t = t & Split(MORSE_ALPHA, ",")(j - 65) & "+" ' "+" ==> separate each characters + Case 48 To 57 'numerics + t = t & Split(MORSE_NUMERIC, ",")(j - 48) & "+" + Case 32 'space + t = t & " " & "+" + Case Else 'others + t = t & "_" & "+" + End Select + Next i + ToMorse = t +End Function + +Private Sub PlayMorse(s As String) +Dim i& + For i = 1 To Len(s) + Select Case Mid(s, i, 1) + Case ".": Beep FREQUENCY_CHARS, BEEP_DOT + Case "-": Beep FREQUENCY_CHARS, BEEP_DASH + Case "_": Beep FREQUENCY_OTHERCHARS, BEEP_OTHER + Case "+": Sleep LETTERS_DELAY + Case " ": Sleep SPACE_DELAY + End Select + Sleep DELAY + Next i +End Sub diff --git a/Task/Mouse-position/00DESCRIPTION b/Task/Mouse-position/00DESCRIPTION index e33ba5ada7..6424786598 100644 --- a/Task/Mouse-position/00DESCRIPTION +++ b/Task/Mouse-position/00DESCRIPTION @@ -12,6 +12,7 @@ {{omit from|PHP}} {{omit from|PostScript}} {{omit from|R}} +{{omit from|SQL PL|It does not handle GUI}} {{omit from|TI-83 BASIC|Does not have a pointing device.}} {{omit from|TI-89 BASIC|Does not have a pointing device.}} {{omit from|UNIX Shell}} diff --git a/Task/Move-to-front-algorithm/Aime/move-to-front-algorithm.aime b/Task/Move-to-front-algorithm/Aime/move-to-front-algorithm.aime new file mode 100644 index 0000000000..d3dbd04f42 --- /dev/null +++ b/Task/Move-to-front-algorithm/Aime/move-to-front-algorithm.aime @@ -0,0 +1,48 @@ +text +decode(list l) +{ + integer c, e, i; + text al, s; + + al = "abcdefghijklmnopqrstuvwxyz"; + for (i, e in l) { + s = insert(s, -1, c = al[e]); + al = insert(delete(al, e), 0, c); + } + + s; +} + +list +encode(text s) +{ + integer c, e; + text al; + list l; + + al = "abcdefghijklmnopqrstuvwxyz"; + while (c = initial(s)) { + s = delete(s, 0); + l.append(e = place(al, c)); + al = insert(delete(al, e), 0, c); + } + + l; +} + +integer +main(void) +{ + integer i; + text s; + + for (i, s in list("broood", "bananaaa", "hiphophiphop")) { + list l; + + l = encode(s); + l.ucall(o_, 1, " "); + o_(": ", decode(l), "\n"); + } + + 0; +} diff --git a/Task/Move-to-front-algorithm/Bracmat/move-to-front-algorithm.bracmat b/Task/Move-to-front-algorithm/Bracmat/move-to-front-algorithm.bracmat new file mode 100644 index 0000000000..99886eefd2 --- /dev/null +++ b/Task/Move-to-front-algorithm/Bracmat/move-to-front-algorithm.bracmat @@ -0,0 +1,46 @@ + ( encode + = string symboltable + . !arg:(?string.?symboltable) + & vap + $ ( ( + = A Z i + . !symboltable:?A [?i !arg ?Z + & !arg !A !Z:?symboltable + & !i + ) + . !string + ) + ) +& ( decode + = indices symboltable + . !arg:(?indices.?symboltable) + & str + $ ( map + $ ( ( + = A Z symbol + . !symboltable:?A [!arg %?symbol ?Z + & !symbol !A !Z:?symboltable + & !symbol + ) + . !indices + ) + ) + ) +& ( test + = string symboltable encoded decoded + . !arg:(?string.?symboltable) + & put$str$("input:" !string ", ") + & encode$(!string.!symboltable):?encoded + & put$("encoded:" !encoded ", ") + & decode$(!encoded.!symboltable):?decoded + & put$str$("decoded:" !decoded ", ") + & ( !string:!decoded + & out$OK + | out$WRONG + ) + ) +& a b c d e f g h i j k l m n o p q r s t y v w x y z + : ?symboltable +& test$(broood.!symboltable) +& test$(bananaaa.!symboltable) +& test$(hiphophiphop.!symboltable) diff --git a/Task/Move-to-front-algorithm/Go/move-to-front-algorithm.go b/Task/Move-to-front-algorithm/Go/move-to-front-algorithm.go index 38ed986b0b..5a2cf3acc0 100644 --- a/Task/Move-to-front-algorithm/Go/move-to-front-algorithm.go +++ b/Task/Move-to-front-algorithm/Go/move-to-front-algorithm.go @@ -10,12 +10,9 @@ type symbolTable string func (symbols symbolTable) encode(s string) []byte { seq := make([]byte, len(s)) pad := []byte(symbols) - c1 := []byte{0} - for i := 0; i < len(s); i++ { - c := s[i] - c1[0] = c - x := byte(bytes.Index(pad, c1)) - seq[i] = x + for i, c := range []byte(s) { + x := bytes.IndexByte(pad, c) + seq[i] = byte(x) copy(pad[1:], pad[:x]) pad[0] = c } diff --git a/Task/Move-to-front-algorithm/Julia/move-to-front-algorithm.julia b/Task/Move-to-front-algorithm/Julia/move-to-front-algorithm.julia new file mode 100644 index 0000000000..1206cf3bf1 --- /dev/null +++ b/Task/Move-to-front-algorithm/Julia/move-to-front-algorithm.julia @@ -0,0 +1,33 @@ +function encodeMTF(str::AbstractString, symtable::Vector{Char}=collect('a':'z')) + function encode(ch::Char) + r = findfirst(symtable, ch) + deleteat!(symtable, r) + prepend!(symtable, ch) + return r + end + collect(encode(ch) for ch in str) +end + +function decodeMTF(arr::Vector{Int}, symtable::Vector{Char}=collect('a':'z')) + function decode(i::Int) + r = symtable[i] + deleteat!(symtable, i) + prepend!(symtable, r) + return r + end + join(decode(i) for i in arr) +end + +testset = ["broood", "bananaaa", "hiphophiphop"] +encoded = encodeMTF.(testset) +decoded = decodeMTF.(encoded) +for (str, enc, dec) in zip(testset, encoded, decoded) + println("Test string: $str\n -> Encoded: $enc\n -> Decoded: $dec") +end + +using Base.Test +@testset "Decoded string equal to original" begin + for (str, dec) in zip(testset, decoded) + @test str == dec + end +end diff --git a/Task/Move-to-front-algorithm/REXX/move-to-front-algorithm-2.rexx b/Task/Move-to-front-algorithm/REXX/move-to-front-algorithm-2.rexx index fe60f1375d..85aeb6286a 100644 --- a/Task/Move-to-front-algorithm/REXX/move-to-front-algorithm-2.rexx +++ b/Task/Move-to-front-algorithm/REXX/move-to-front-algorithm-2.rexx @@ -1,17 +1,17 @@ /*REXX program demonstrates the move─to─front algorithm encode/decode symbol table. */ parse arg xxx; if xxx='' then xxx= 'broood bananaaa hiphophiphop' /*use the default?*/ one=1 /*(offset) for this task's requirement.*/ - do j=1 for words(xxx); x=word(xxx, j) /*process a single word at a time. */ + do j=1 for words(xxx); x=word(xxx, j) /*process a single word at a time. */ @= 'abcdefghijklmnopqrstuvwxyz'; @@=@ /*symbol table: the lowercase alphabet */ $= /*set the decode string to a null. */ - do k=1 for length(x); z=substr(x, k, 1) /*encrypt a symbol in the word. */ + do k=1 for length(x); z=substr(x, k, 1) /*encrypt a symbol in the word. */ _=pos(z, @); if _==0 then iterate /*the symbol position in symbol table. */ - $=$ _ - one; @=z || delstr(@, _, 1) /*(re-)adjust the symbol table string. */ + $=$ (_ - one); @=z || delstr(@, _, 1) /*(re─)adjust the symbol table string. */ end /*k*/ /* [↑] the move─to─front encoding. */ != /*set the encode string to a null. */ - do m=1 for words($); n=word($, m) +one /*decode the sequence table string. */ - y=substr(@@, n, 1); !=! || y /*the decode symbol for the N word.*/ + do m=1 for words($); n=word($, m) + one /*decode the sequence table string. */ + y=substr(@@, n, 1); !=! || y /*the decode symbol for the N word.*/ @@=y || delstr(@@, n, 1) /*rebuild the symbol table string. */ end /*m*/ /* [↑] the move─to─front decoding. */ - say ' word: ' left(x, 20) "encoding:" left($, 35) word('wrong OK', 1+(!==x) ) + say ' word: ' left(x, 20) "encoding:" left($, 35) word('wrong OK', 1 + (!==x) ) end /*j*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Move-to-front-algorithm/Ring/move-to-front-algorithm.ring b/Task/Move-to-front-algorithm/Ring/move-to-front-algorithm.ring new file mode 100644 index 0000000000..7822d0bf89 --- /dev/null +++ b/Task/Move-to-front-algorithm/Ring/move-to-front-algorithm.ring @@ -0,0 +1,42 @@ +# Project : Move-to-front algorithm +# Date : 2018/01/13 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +test("broood") +test("bananaaa") +test("hiphophiphop") + +func encode(s) + symtab = "abcdefghijklmnopqrstuvwxyz" + res = "" + for i=1 to len(s) + ch = s[i] + k = substr(symtab, ch) + res = res + " " + (k-1) + for j=k to 2 step -1 + symtab[j] = symtab[j-1] + next + symtab[1] = ch + next + return res + +func decode(s) + s = str2list( substr(s, " ", nl) ) + symtab = "abcdefghijklmnopqrstuvwxyz" + res = "" + for i=1 to len(s) + k = number(s[i]) + 1 + ch = symtab[k] + res = res + " " + ch + for j=k to 2 step -1 + symtab[j] = symtab[j-1] + next + symtab[1] = ch + next + return right(res, len(res)-2) + +func test(s) + e = encode(s) + d = decode(e) + see "" + s + " => " + "(" + right(e, len(e) - 1) + ") " + " => " + substr(d, " ", "") + nl diff --git a/Task/Multifactorial/Aime/multifactorial.aime b/Task/Multifactorial/Aime/multifactorial.aime new file mode 100644 index 0000000000..91970bcc4a --- /dev/null +++ b/Task/Multifactorial/Aime/multifactorial.aime @@ -0,0 +1,30 @@ +integer +mf(integer a, integer n) +{ + integer o; + + o = 1; + do { + o *= a; + } while (0 < (a -= n)); + + return o; +} + +integer +main(void) +{ + integer i, j; + + i = 0; + while ((i += 1) <= 5) { + o_("degree ", i, ":"); + j = 0; + while ((j += 1) <= 10) { + o_("\t", mf(j, i)); + } + o_("\n"); + } + + return 0; +} diff --git a/Task/Multifactorial/BBC-BASIC/multifactorial.bbc b/Task/Multifactorial/BBC-BASIC/multifactorial.bbc new file mode 100644 index 0000000000..ef427393c3 --- /dev/null +++ b/Task/Multifactorial/BBC-BASIC/multifactorial.bbc @@ -0,0 +1,17 @@ +REM >multifact +FOR i% = 1 TO 5 + PRINT "Degree "; i%; ":"; + FOR j% = 1 TO 10 + PRINT " ";FNmultifact(j%, i%); + NEXT + PRINT +NEXT +END +: +DEF FNmultifact(n%, degree%) +LOCAL i%, mfact% +mfact% = 1 +FOR i% = n% TO 1 STEP -degree% + mfact% = mfact% * i% +NEXT += mfact% diff --git a/Task/Multifactorial/Factor/multifactorial.factor b/Task/Multifactorial/Factor/multifactorial.factor new file mode 100644 index 0000000000..1d28079bb5 --- /dev/null +++ b/Task/Multifactorial/Factor/multifactorial.factor @@ -0,0 +1,15 @@ +USING: formatting io kernel math math.ranges prettyprint +sequences ; +IN: rosetta-code.multifactorial + +: multifactorial ( n degree -- m ) + neg 1 swap product ; + +: mf-row ( degree -- ) + dup "Degree %d: " printf + 10 [1,b] [ swap multifactorial pprint bl ] with each ; + +: main ( -- ) + 5 [1,b] [ mf-row nl ] each ; + +MAIN: main diff --git a/Task/Multifactorial/Julia/multifactorial.julia b/Task/Multifactorial/Julia/multifactorial.julia index ede7324527..5f1ac63d35 100644 --- a/Task/Multifactorial/Julia/multifactorial.julia +++ b/Task/Multifactorial/Julia/multifactorial.julia @@ -1,18 +1,14 @@ -function multifact{T<:Integer,U<:Integer}(n::T, k::U) - -1 0 && k > 0 || throw(DomainError()) + k > 1 || factorial(n) + return prod(n:-k:2) end -khi = 5 -nhi = 10 -println("Showing multifactorial for n in [1,", nhi, "] and k in [1,", khi, "].") +const khi = 5 +const nhi = 10 +println("Showing multifactorial for n in [1, $nhi] and k in [1, $khi].") for k = 1:khi - a = Int64[multifact(i, k) for i in 1:nhi] - lab = "n"*"!"^k - println(@sprintf(" %-6s => ", lab), a) + a = multifact.(1:nhi, k) + lab = "n" * "!" ^ k + @printf(" %-6s → %s\n", lab, a) end diff --git a/Task/Multifactorial/Maple/multifactorial.maple b/Task/Multifactorial/Maple/multifactorial.maple new file mode 100644 index 0000000000..84f2454115 --- /dev/null +++ b/Task/Multifactorial/Maple/multifactorial.maple @@ -0,0 +1,16 @@ +f := proc (n, m) + local fac, i; + fac := 1; + for i from n by -m to 1 do + fac := fac*i; + end do; + return fac; +end proc: + +a:=Matrix(5,10): +for i from 1 to 5 do + for j from 1 to 10 do + a[i,j]:=f(j,i); + end do; +end do; +a; diff --git a/Task/Multiple-distinct-objects/AppleScript/multiple-distinct-objects-1.applescript b/Task/Multiple-distinct-objects/AppleScript/multiple-distinct-objects-1.applescript index 9ac8d0e864..f82d0ba57b 100644 --- a/Task/Multiple-distinct-objects/AppleScript/multiple-distinct-objects-1.applescript +++ b/Task/Multiple-distinct-objects/AppleScript/multiple-distinct-objects-1.applescript @@ -1,17 +1,17 @@ +-- MULTIPLE DISTINCT OBJECTS ------------------------------------------------- + -- nObjects Constructor -> Int -> [Object] on nObjects(f, n) - map(f, range(1, n)) + map(f, enumFromTo(1, n)) end nObjects - --- TEST +-- TEST ---------------------------------------------------------------------- on run - -- someConstructor :: a -> Int -> b script someConstructor - on lambda(_, i) + on |λ|(_, i) {index:i} - end lambda + end |λ| end script nObjects(someConstructor, 6) @@ -19,9 +19,21 @@ on run --> {{index:1}, {index:2}, {index:3}, {index:4}, {index:5}, {index:6}} end run +-- GENERIC FUNCTIONS --------------------------------------------------------- - --- GENERIC FUNCTIONS ----------------------------------------------------------- +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if m > n then + set d to -1 + else + set d to 1 + end if + set lst to {} + repeat with i from m to n by d + set end of lst to i + end repeat + return lst +end enumFromTo -- map :: (a -> b) -> [a] -> [b] on map(f, xs) @@ -29,7 +41,7 @@ on map(f, xs) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell @@ -42,21 +54,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn - --- range :: Int -> Int -> [Int] -on range(m, n) - if n < m then - set d to -1 - else - set d to 1 - end if - set lst to {} - repeat with i from m to n by d - set end of lst to i - end repeat - return lst -end range diff --git a/Task/Multiple-distinct-objects/Julia/multiple-distinct-objects-1.julia b/Task/Multiple-distinct-objects/Julia/multiple-distinct-objects-1.julia new file mode 100644 index 0000000000..5a7d4e9c2b --- /dev/null +++ b/Task/Multiple-distinct-objects/Julia/multiple-distinct-objects-1.julia @@ -0,0 +1,2 @@ +foo() = rand() # repeated calls change the result with each call +repeat([foo()], outer=5) # but this only calls foo() once, clones that first value diff --git a/Task/Multiple-distinct-objects/Julia/multiple-distinct-objects-2.julia b/Task/Multiple-distinct-objects/Julia/multiple-distinct-objects-2.julia new file mode 100644 index 0000000000..fe68ce6e30 --- /dev/null +++ b/Task/Multiple-distinct-objects/Julia/multiple-distinct-objects-2.julia @@ -0,0 +1 @@ +[foo() for i in 1:5] # Code this to call the function within each iteration diff --git a/Task/Multiple-regression/00META.yaml b/Task/Multiple-regression/00META.yaml index 1e81690bbc..29aeacfd2a 100644 --- a/Task/Multiple-regression/00META.yaml +++ b/Task/Multiple-regression/00META.yaml @@ -1,2 +1,2 @@ --- -note: Matrices +note: Probability and statistics diff --git a/Task/Multiple-regression/Fortran/multiple-regression.f b/Task/Multiple-regression/Fortran/multiple-regression.f index b7e06c9d48..faabf98ad0 100644 --- a/Task/Multiple-regression/Fortran/multiple-regression.f +++ b/Task/Multiple-regression/Fortran/multiple-regression.f @@ -12,20 +12,20 @@ * * INPUT ARRAYS ARE DESTROYED! * -*___Name_________Type_______________In/Out____Description________________________ -* X(N,K) Double precision In Predictors -* Y(N) Double precision Both On input: N Observations -* On output: K beta weights -* N Integer In Number of observations -* K Integer In Number of predictor variables -* DWORK(3*K) Double precision Neither Workspace -* IWORK(K) Integer Neither Workspace +*___Name___________Type_______________In/Out____Description_____________ +* X(N,K) Double precision In Predictors +* Y(N) Double precision Both On input: N Observations +* On output: K beta weights +* N Integer In Number of observations +* K Integer In Number of predictor variables +* DWORK(N+2*K) Double precision Neither Workspace +* IWORK(K) Integer Neither Workspace *----------------------------------------------------------------------- SUBROUTINE MR (X, Y, N, K, DWORK, IWORK) IMPLICIT NONE INTEGER K, N, IWORK DOUBLE PRECISION X, Y, DWORK - DIMENSION X(N,K), Y(N), DWORK(3*K), IWORK(K) + DIMENSION X(N,K), Y(N), DWORK(N+2*K), IWORK(K) * local variables INTEGER I, J @@ -44,7 +44,7 @@ * call function CALL DHFTI (X, N, N, K, Y, N, 1, TAU, - $ J, DWORK(1), DWORK(K+1), DWORK(2*K+1), IWORK) + $ J, DWORK(1), DWORK(N+1), DWORK(N+K+1), IWORK) IF (J < K) PRINT *, 'mr: solution is rank deficient!' RETURN END ! of MR @@ -55,7 +55,7 @@ INTEGER N, K PARAMETER (N=15, K=3) INTEGER IWORK(K), I, J - DOUBLE PRECISION XIN(N), X(N,K), Y(N), DWORK(3*K) + DOUBLE PRECISION XIN(N), X(N,K), Y(N), DWORK(N+2*K) DATA XIN / 1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, 1.68, $ 1.70, 1.73, 1.75, 1.78, 1.80, 1.83 / diff --git a/Task/Multiple-regression/Kotlin/multiple-regression.kotlin b/Task/Multiple-regression/Kotlin/multiple-regression.kotlin new file mode 100644 index 0000000000..b383cf7670 --- /dev/null +++ b/Task/Multiple-regression/Kotlin/multiple-regression.kotlin @@ -0,0 +1,121 @@ +// Version 1.2.31 + +typealias Vector = DoubleArray +typealias Matrix = Array + +operator fun Matrix.times(other: Matrix): Matrix { + val rows1 = this.size + val cols1 = this[0].size + val rows2 = other.size + val cols2 = other[0].size + require(cols1 == rows2) + val result = Matrix(rows1) { Vector(cols2) } + for (i in 0 until rows1) { + for (j in 0 until cols2) { + for (k in 0 until rows2) { + result[i][j] += this[i][k] * other[k][j] + } + } + } + return result +} + +fun Matrix.transpose(): Matrix { + val rows = this.size + val cols = this[0].size + val trans = Matrix(cols) { Vector(rows) } + for (i in 0 until cols) { + for (j in 0 until rows) trans[i][j] = this[j][i] + } + return trans +} + +fun Matrix.inverse(): Matrix { + val len = this.size + require(this.all { it.size == len }) { "Not a square matrix" } + val aug = Array(len) { DoubleArray(2 * len) } + for (i in 0 until len) { + for (j in 0 until len) aug[i][j] = this[i][j] + // augment by identity matrix to right + aug[i][i + len] = 1.0 + } + aug.toReducedRowEchelonForm() + val inv = Array(len) { DoubleArray(len) } + // remove identity matrix to left + for (i in 0 until len) { + for (j in len until 2 * len) inv[i][j - len] = aug[i][j] + } + return inv +} + +fun Matrix.toReducedRowEchelonForm() { + var lead = 0 + val rowCount = this.size + val colCount = this[0].size + for (r in 0 until rowCount) { + if (colCount <= lead) return + var i = r + + while (this[i][lead] == 0.0) { + i++ + if (rowCount == i) { + i = r + lead++ + if (colCount == lead) return + } + } + + val temp = this[i] + this[i] = this[r] + this[r] = temp + + if (this[r][lead] != 0.0) { + val div = this[r][lead] + for (j in 0 until colCount) this[r][j] /= div + } + + for (k in 0 until rowCount) { + if (k != r) { + val mult = this[k][lead] + for (j in 0 until colCount) this[k][j] -= this[r][j] * mult + } + } + + lead++ + } +} + +fun printVector(v: Vector) { + println(v.asList()) + println() +} + +fun multipleRegression(y: Vector, x: Matrix): Vector { + val cy = (arrayOf(y)).transpose() // convert 'y' to column vector + val cx = x.transpose() // convert 'x' to column vector array + return ((x * cx).inverse() * x * cy).transpose()[0] +} + +fun main(args: Array) { + var y = doubleArrayOf(1.0, 2.0, 3.0, 4.0, 5.0) + var x = arrayOf(doubleArrayOf(2.0, 1.0, 3.0, 4.0, 5.0)) + var v = multipleRegression(y, x) + printVector(v) + + y = doubleArrayOf(3.0, 4.0, 5.0) + x = arrayOf( + doubleArrayOf(1.0, 2.0, 1.0), + doubleArrayOf(1.0, 1.0, 2.0) + ) + v = multipleRegression(y, x) + printVector(v) + + y = doubleArrayOf(52.21, 53.12, 54.48, 55.84, 57.20, 58.57, 59.93, 61.29, + 63.11, 64.47, 66.28, 68.10, 69.92, 72.19, 74.46) + + val a = doubleArrayOf(1.47, 1.50, 1.52, 1.55, 1.57, 1.60, 1.63, 1.65, 1.68, 1.70, + 1.73, 1.75, 1.78, 1.80, 1.83) + x = arrayOf(DoubleArray(a.size) { 1.0 }, a, a.map { it * it }.toDoubleArray()) + v = multipleRegression(y, x) + printVector(v) +} diff --git a/Task/Multiple-regression/Stata/multiple-regression-1.stata b/Task/Multiple-regression/Stata/multiple-regression-1.stata new file mode 100644 index 0000000000..b408af1d5b --- /dev/null +++ b/Task/Multiple-regression/Stata/multiple-regression-1.stata @@ -0,0 +1,7 @@ +clear +set seed 17760704 +set obs 200 +forv i=1/4 { + gen x`i'=rnormal() +} +gen y=1.5+0.8*x1-0.7*x2+1.1*x3-1.7*x4+rnormal() diff --git a/Task/Multiple-regression/Stata/multiple-regression-2.stata b/Task/Multiple-regression/Stata/multiple-regression-2.stata new file mode 100644 index 0000000000..8c08c36cab --- /dev/null +++ b/Task/Multiple-regression/Stata/multiple-regression-2.stata @@ -0,0 +1 @@ +reg y x* diff --git a/Task/Multiple-regression/Stata/multiple-regression-3.stata b/Task/Multiple-regression/Stata/multiple-regression-3.stata new file mode 100644 index 0000000000..89f10978d4 --- /dev/null +++ b/Task/Multiple-regression/Stata/multiple-regression-3.stata @@ -0,0 +1,11 @@ +. di _b[x1] +.75252466 + +. di _b[_cons] +1.3991314 + +. di _se[x1] +.06895593 + +. di _se[_cons] +.06978623 diff --git a/Task/Multiple-regression/Stata/multiple-regression-4.stata b/Task/Multiple-regression/Stata/multiple-regression-4.stata new file mode 100644 index 0000000000..d6c50e1a4b --- /dev/null +++ b/Task/Multiple-regression/Stata/multiple-regression-4.stata @@ -0,0 +1,25 @@ +. estat ic + +Akaike's information criterion and Bayesian information criterion + +----------------------------------------------------------------------------- + Model | Obs ll(null) ll(model) df AIC BIC +-------------+--------------------------------------------------------------- + . | 200 -487.1455 -275.6985 5 561.397 577.8886 +----------------------------------------------------------------------------- + Note: N=Obs used in calculating BIC; see [R] BIC note. + +. estat vce + +Covariance matrix of coefficients of regress model + + e(V) | x1 x2 x3 x4 _cons +-------------+------------------------------------------------------------ + x1 | .00475492 + x2 | -.00040258 .00486445 + x3 | -.00042516 .00017355 .00521125 + x4 | -.00011915 -.0002568 .00054646 .00386583 + _cons | .00030777 -.00031109 -.00023794 .00058926 .00487012 + +. predict yhat, xb +. predict r, r diff --git a/Task/Multiplication-tables/GW-BASIC/multiplication-tables.gw-basic b/Task/Multiplication-tables/GW-BASIC/multiplication-tables.gw-basic new file mode 100644 index 0000000000..de1b0f5f84 --- /dev/null +++ b/Task/Multiplication-tables/GW-BASIC/multiplication-tables.gw-basic @@ -0,0 +1,17 @@ +10 ' Multiplication Tables +20 LET N% = 12 +30 FOR J% = 1 TO N% - 1 +40 PRINT USING "###"; J%; +50 PRINT " "; +60 NEXT J% +70 PRINT USING "###"; N% +80 FOR J% = 0 TO N% - 1 +90 PRINT "----"; +100 NEXT J% +110 PRINT "+" +120 FOR I% = 1 TO N% +130 FOR J% = 1 TO N% +140 IF J% < I% THEN PRINT " "; ELSE PRINT USING "###"; I% * J%;: PRINT " "; +150 NEXT J% +160 PRINT "| "; USING "##"; I% +170 NEXT I% diff --git a/Task/Multiplication-tables/HolyC/multiplication-tables.holyc b/Task/Multiplication-tables/HolyC/multiplication-tables.holyc new file mode 100644 index 0000000000..18a3871174 --- /dev/null +++ b/Task/Multiplication-tables/HolyC/multiplication-tables.holyc @@ -0,0 +1,21 @@ +U8 i, j, n = 12; +for (j = 1; j <= n; j++) + if (j != n) + Print("%3d%c", j, ' '); + else + Print("%3d%c", j, '\n'); + +for (j = 0; j <= n; j++) + if (j != n) + Print("----"); + else + Print("+\n"); + +for (i = 1; i <= n; i++) { + for (j = 1; j <= n; j++) + if (j < i) + Print(" "); + else + Print("%3d ", i * j); + Print("| %d\n", i); +} diff --git a/Task/Multiplication-tables/JavaScript/multiplication-tables-4.js b/Task/Multiplication-tables/JavaScript/multiplication-tables-4.js new file mode 100644 index 0000000000..99dcaf64be --- /dev/null +++ b/Task/Multiplication-tables/JavaScript/multiplication-tables-4.js @@ -0,0 +1,92 @@ +(() => { + + // multTable :: Int -> Int -> [[String]] + const multTable = (m, n) => { + const xs = enumFromToInt(m, n); + return [ + ['x', ...xs], + ...concatMap( + x => [ + [x, ...concatMap( + y => y < x ? [''] : [x * y], + xs + )] + ], + xs + ) + ]; + }; + + // main :: () -> IO String + const main = () => { + return wikiTable( + multTable(1, 12), true, + 'text-align:center;width:33em;height:33em;table-layout:fixed;' + ); + }; + + // GENERIC FUNCTIONS ----------------------------------------------------- + + // Tuple (,) :: a -> b -> (a, b) + const Tuple = (a, b) => ({ + type: 'Tuple', + '0': a, + '1': b + }); + + // Size of space -> filler Char -> String -> Centered String + // center :: Int -> Char -> String -> String + const center = (n, c, s) => { + const + qr = quotRem(n - s.length, 2), + q = qr[0]; + return concat(concat([replicate(q, c), s, replicate(q + qr[1], c)])); + }; + + // concat :: [[a]] -> [a] + // concat :: [String] -> String + const concat = xs => + xs.length > 0 ? (() => { + const unit = typeof xs[0] === 'string' ? '' : []; + return unit.concat.apply(unit, xs); + })() : []; + + // concatMap :: (a -> [b]) -> [a] -> [b] + const concatMap = (f, xs) => [].concat.apply([], xs.map(f)); + + // enumFromToInt :: Int -> Int -> [Int] + const enumFromToInt = (m, n) => + n >= m ? Array.from({ + length: Math.floor(n - m) + 1 + }, (_, i) => m + i) : []; + + // map :: (a -> b) -> [a] -> [b] + const map = (f, xs) => xs.map(f); + + // quotRem :: Int -> Int -> (Int, Int) + const quotRem = (m, n) => Tuple(Math.floor(m / n), m % n); + + // replicate :: Int -> a -> [a] + const replicate = (n, x) => + Array.from({ + length: n + }, () => x); + + // FORMATTING ------------------------------------------------------------- + + // wikiTable :: [[a]] -> Bool -> String -> String + const wikiTable = (rows, blnHeader, style) => + '{| class="wikitable" ' + ( + style ? 'style="' + style + '"' : '' + ) + rows.map((row, i) => { + const dlm = ((blnHeader && !i) ? '!' : '|'); + return '\n|-\n' + dlm + ' ' + row.map(v => + typeof v !== 'undefined' ? v : ' ' + ) + .join(' ' + dlm + dlm + ' '); + }) + .join('') + '\n|}'; + + // MAIN ------------------------------------------------------------------ + return main(); +})(); diff --git a/Task/Multiplication-tables/Modula-2/multiplication-tables.mod2 b/Task/Multiplication-tables/Modula-2/multiplication-tables.mod2 new file mode 100644 index 0000000000..702791fa2b --- /dev/null +++ b/Task/Multiplication-tables/Modula-2/multiplication-tables.mod2 @@ -0,0 +1,39 @@ +MODULE MultiplicationTables; + +FROM SWholeIO IMPORT + WriteInt; +FROM STextIO IMPORT + WriteString, WriteLn; + +CONST + N = 12; + +VAR + I, J: INTEGER; + +BEGIN + FOR J := 1 TO N - 1 DO + WriteInt(J, 3); + WriteString(" "); + END; + WriteInt(N, 3); + WriteLn; + FOR J := 0 TO N - 1 DO + WriteString("----"); + END; + WriteString("+"); + WriteLn; + FOR I := 1 TO N DO + FOR J := 1 TO N DO + IF J < I THEN + WriteString(" "); + ELSE + WriteInt(I * J, 3); + WriteString(" "); + END; + END; + WriteString("| "); + WriteInt(I, 2); + WriteLn; + END; +END MultiplicationTables. diff --git a/Task/Multiplication-tables/VBA/multiplication-tables.vba b/Task/Multiplication-tables/VBA/multiplication-tables.vba new file mode 100644 index 0000000000..893a284d39 --- /dev/null +++ b/Task/Multiplication-tables/VBA/multiplication-tables.vba @@ -0,0 +1,29 @@ +Option Explicit + +Sub Multiplication_Tables() +Dim strTemp As String, strBuff As String +Dim i&, j&, NbDigits As Byte + +'You can adapt the following const : +Const NB_END As Byte = 12 + + Select Case NB_END + Case Is < 10: NbDigits = 3 + Case 10 To 31: NbDigits = 4 + Case 31 To 100: NbDigits = 5 + Case Else: MsgBox "Number too large": Exit Sub + End Select + strBuff = String(NbDigits, " ") + + For i = 1 To NB_END + strTemp = Right(strBuff & i, NbDigits) + For j = 2 To NB_END + If j < i Then + strTemp = strTemp & strBuff + Else + strTemp = strTemp & Right(strBuff & j * i, NbDigits) + End If + Next j + Debug.Print strTemp + Next i +End Sub diff --git a/Task/Multiplicative-order/Clojure/multiplicative-order.clj b/Task/Multiplicative-order/Clojure/multiplicative-order.clj new file mode 100644 index 0000000000..6287cc2152 --- /dev/null +++ b/Task/Multiplicative-order/Clojure/multiplicative-order.clj @@ -0,0 +1,26 @@ +(defn gcd [a b] + (if (zero? b) + a + (recur b (mod a b)))) + +(defn lcm [a b] + (/ (* a b) (gcd a b))) + +(def NaN (Math/log -1)) + +(defn ord' [a [p e]] + (let [m (imath/expt p e) + t (* (quot m p) (dec p))] + (loop [dv (factor/divisors t)] + (let [d (first dv)] + (if (= (mmath/expm a d m) 1) + d + (recur (next dv))))))) + +(defn ord [a n] + (if (not= (gcd a n) 1) + NaN + (->> + (factor/factorize n) + (map (partial ord' a)) + (reduce lcm)))) diff --git a/Task/Multiplicative-order/Java/multiplicative-order.java b/Task/Multiplicative-order/Java/multiplicative-order.java new file mode 100644 index 0000000000..61aa89a9e6 --- /dev/null +++ b/Task/Multiplicative-order/Java/multiplicative-order.java @@ -0,0 +1,106 @@ +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; + +public class MultiplicativeOrder { + private static final BigInteger ONE = BigInteger.ONE; + private static final BigInteger TWO = BigInteger.valueOf(2); + private static final BigInteger THREE = BigInteger.valueOf(3); + private static final BigInteger TEN = BigInteger.TEN; + + private static class PExp { + BigInteger prime; + long exp; + + PExp(BigInteger prime, long exp) { + this.prime = prime; + this.exp = exp; + } + } + + private static void moTest(BigInteger a, BigInteger n) { + if (!n.isProbablePrime(20)) { + System.out.println("Not computed. Modulus must be prime for this algorithm."); + return; + } + if (a.bitLength() < 100) System.out.printf("ord(%s)", a); + else System.out.print("ord([big])"); + if (n.bitLength() < 100) System.out.printf(" mod %s ", n); + else System.out.print(" mod [big] "); + BigInteger mob = moBachShallit58(a, n, factor(n.subtract(ONE))); + System.out.println("= " + mob); + } + + private static BigInteger moBachShallit58(BigInteger a, BigInteger n, List pf) { + BigInteger n1 = n.subtract(ONE); + BigInteger mo = ONE; + for (PExp pe : pf) { + BigInteger y = n1.divide(pe.prime.pow((int) pe.exp)); + long o = 0; + BigInteger x = a.modPow(y, n.abs()); + while (x.compareTo(ONE) > 0) { + x = x.modPow(pe.prime, n.abs()); + o++; + } + BigInteger o1 = BigInteger.valueOf(o); + o1 = pe.prime.pow(o1.intValue()); + o1 = o1.divide(mo.gcd(o1)); + mo = mo.multiply(o1); + } + return mo; + } + + private static List factor(BigInteger n) { + List pf = new ArrayList<>(); + BigInteger nn = n; + Long e = 0L; + while (!nn.testBit(e.intValue())) e++; + if (e > 0L) { + nn = nn.shiftRight(e.intValue()); + pf.add(new PExp(TWO, e)); + } + BigInteger s = sqrt(nn); + BigInteger d = THREE; + while (nn.compareTo(ONE) > 0) { + if (d.compareTo(s) > 0) d = nn; + e = 0L; + while (true) { + BigInteger[] qr = nn.divideAndRemainder(d); + if (qr[1].bitLength() > 0) break; + nn = qr[0]; + e++; + } + if (e > 0L) { + pf.add(new PExp(d, e)); + s = sqrt(nn); + } + d = d.add(TWO); + } + return pf; + } + + private static BigInteger sqrt(BigInteger n) { + BigInteger b = n; + while (true) { + BigInteger a = b; + b = n.divide(a).add(a).shiftRight(1); + if (b.compareTo(a) >= 0) return a; + } + } + + public static void main(String[] args) { + moTest(BigInteger.valueOf(37), BigInteger.valueOf(3343)); + + BigInteger b = TEN.pow(100).add(ONE); + moTest(b, BigInteger.valueOf(7919)); + + b = TEN.pow(1000).add(ONE); + moTest(b, BigInteger.valueOf(15485863)); + + b = TEN.pow(10000).subtract(ONE); + moTest(b, BigInteger.valueOf(22801763489L)); + + moTest(BigInteger.valueOf(1511678068), BigInteger.valueOf(7379191741L)); + moTest(BigInteger.valueOf(3047753288L), BigInteger.valueOf(2257683301L)); + } +} diff --git a/Task/Multiplicative-order/Kotlin/multiplicative-order.kotlin b/Task/Multiplicative-order/Kotlin/multiplicative-order.kotlin new file mode 100644 index 0000000000..b17982fa4e --- /dev/null +++ b/Task/Multiplicative-order/Kotlin/multiplicative-order.kotlin @@ -0,0 +1,94 @@ +// version 1.2.10 + +import java.math.BigInteger + +val bigOne = BigInteger.ONE +val bigTwo = 2.toBigInteger() +val bigThree = 3.toBigInteger() +val bigTen = BigInteger.TEN + +class PExp(val prime: BigInteger, val exp: Long) + +fun moTest(a: BigInteger, n: BigInteger) { + if (!n.isProbablePrime(20)) { + println("Not computed. Modulus must be prime for this algorithm.") + return + } + if (a.bitLength() < 100) print("ord($a)") else print("ord([big])") + if (n.bitLength() < 100) print(" mod $n ") else print(" mod [big] ") + val mob = moBachShallit58(a, n, factor(n - bigOne)) + println("= $mob") +} + +fun moBachShallit58(a: BigInteger, n: BigInteger, pf: List): BigInteger { + val n1 = n - bigOne + var mo = bigOne + for (pe in pf) { + val y = n1 / pe.prime.pow(pe.exp.toInt()) + var o = 0L + var x = a.modPow(y, n.abs()) + while (x > bigOne) { + x = x.modPow(pe.prime, n.abs()) + o++ + } + var o1 = o.toBigInteger() + o1 = pe.prime.pow(o1.toInt()) + o1 /= mo.gcd(o1) + mo *= o1 + } + return mo +} + +fun factor(n: BigInteger): List { + val pf = mutableListOf() + var nn = n + var e = 0L + while (!nn.testBit(e.toInt())) e++ + if (e > 0L) { + nn = nn shr e.toInt() + pf.add(PExp(bigTwo, e)) + } + var s = bigSqrt(nn) + var d = bigThree + while (nn > bigOne) { + if (d > s) d = nn + e = 0L + while (true) { + val (q, r) = nn.divideAndRemainder(d) + if (r.bitLength() > 0) break + nn = q + e++ + } + if (e > 0L) { + pf.add(PExp(d, e)) + s = bigSqrt(nn) + } + d += bigTwo + } + return pf +} + +fun bigSqrt(n: BigInteger): BigInteger { + var b = n + while (true) { + val a = b + b = (n / a + a) shr 1 + if (b >= a) return a + } +} + +fun main(args: Array) { + moTest(37.toBigInteger(), 3343.toBigInteger()) + + var b = bigTen.pow(100) + bigOne + moTest(b, 7919.toBigInteger()) + + b = bigTen.pow(1000) + bigOne + moTest(b, BigInteger("15485863")) + + b = bigTen.pow(10000) - bigOne + moTest(b, BigInteger("22801763489")) + + moTest(BigInteger("1511678068"), BigInteger("7379191741")) + moTest(BigInteger("3047753288"), BigInteger("2257683301")) +} diff --git a/Task/Multiplicative-order/Perl-6/multiplicative-order.pl6 b/Task/Multiplicative-order/Perl-6/multiplicative-order.pl6 index 061f52f1ea..f0842b1a81 100644 --- a/Task/Multiplicative-order/Perl-6/multiplicative-order.pl6 +++ b/Task/Multiplicative-order/Perl-6/multiplicative-order.pl6 @@ -1,4 +1,4 @@ -my @primes := 2, grep *.is-prime, (3,5,7...*); +my @primes := 2, |grep *.is-prime, (3,5,7...*); sub factor($a is copy) { gather { @@ -23,9 +23,8 @@ sub mo-prime($a, $p, $e) { for factor($t) -> $f { @qs = flat @qs.map(-> $q { (0..$f.value).map(-> $j { $q * $f.key ** $j }) }); } - @qs.sort(); - @qs.first(-> $q { expmod( $a, $q, $m ) == 1}); + @qs.sort.first(-> $q { expmod( $a, $q, $m ) == 1}); } sub mo($a, $m) { diff --git a/Task/Multiplicative-order/Sidef/multiplicative-order.sidef b/Task/Multiplicative-order/Sidef/multiplicative-order.sidef new file mode 100644 index 0000000000..d1351726db --- /dev/null +++ b/Task/Multiplicative-order/Sidef/multiplicative-order.sidef @@ -0,0 +1,26 @@ +func mo_prime(a, p, e) { + var m = p**e + var t = (p-1)*(p**(e-1)) + var qs = [1] + + for f in (t.factor_exp) { + qs.map! {|q| + 0..f[1] -> map {|j| q * f[0]**j }... + } + } + + qs.sort.first_by {|q| powmod(a, q, m) == 1 } +} + +func mo(a, m) { + gcd(a, m) == 1 || die "#{a} and #{m} are not relatively prime" + Math.lcm(1, m.factor_exp.map {|r| mo_prime(a, r...) }...) +} + +say mo(37, 1000) +say mo(54, 100001) + +with (10**20 - 1) {|b| + say mo(2, b) + say mo(17, b) +} diff --git a/Task/Multisplit/Haskell/multisplit.hs b/Task/Multisplit/Haskell/multisplit-1.hs similarity index 100% rename from Task/Multisplit/Haskell/multisplit.hs rename to Task/Multisplit/Haskell/multisplit-1.hs diff --git a/Task/Multisplit/Haskell/multisplit-2.hs b/Task/Multisplit/Haskell/multisplit-2.hs new file mode 100644 index 0000000000..7c2188c7b6 --- /dev/null +++ b/Task/Multisplit/Haskell/multisplit-2.hs @@ -0,0 +1,25 @@ +import Data.List (find, isPrefixOf) + +multiSplit :: [String] -> String -> [(String, String, Int)] +multiSplit ds s = + let lng = length s + (ts, ps, o) = + foldl + (\(tokens, parts, offset) (c, i) -> + let inDelim = offset > i + in case (if inDelim + then Nothing + else find (`isPrefixOf` drop i s) ds) of + Just x -> ([], (tokens, x, i) : parts, i + length x) + Nothing -> + ( if inDelim + then tokens + else c : tokens + , parts + , offset)) + ([], [], 0) + (zip s [0 .. lng]) + in reverse $ (ts, [], lng) : ps + +main :: IO () +main = print $ multiSplit ["==", "!=", "="] "a!===b=!=c" diff --git a/Task/Multisplit/JavaScript/multisplit.js b/Task/Multisplit/JavaScript/multisplit-1.js similarity index 100% rename from Task/Multisplit/JavaScript/multisplit.js rename to Task/Multisplit/JavaScript/multisplit-1.js diff --git a/Task/Multisplit/JavaScript/multisplit-2.js b/Task/Multisplit/JavaScript/multisplit-2.js new file mode 100644 index 0000000000..8f5202c02d --- /dev/null +++ b/Task/Multisplit/JavaScript/multisplit-2.js @@ -0,0 +1,119 @@ +(() => { + + /// Delimiter list -> String -> list of parts, delimiters, offsets + + // multiSplit :: [String] -> String -> + // [{part::String, delim::String, offset::Int}] + const multiSplit = (ds, s) => { + const + dcs = map(chars, ds), + xs = chars(s), + dct = foldl( + (a, c, i, s) => { + const + inDelim = a.offset > i, + mb = inDelim ? ( + nothing('') + ) : find(d => isPrefixOf(d, drop(i, xs)), dcs); + return mb.nothing ? { + tokens: a.tokens.concat(inDelim ? ( + [] + ) : [c]), + parts: a.parts, + offset: a.offset + } : { + tokens: [], + parts: append(a.parts, [{ + part: intercalate('', a.tokens), + delim: intercalate('', mb.just), + offset: i + }]), + offset: i + length(mb.just) + }; + }, { + tokens: [], + parts: [], + offset: 0 + }, xs + ); + return append(dct.parts, [{ + part: intercalate('', dct.tokens), + delim: "", + offset: length(s) + }]); + }; + + // GENERIC FUNCTIONS ----------------------------------------------------- + + // append (++) :: [a] -> [a] -> [a] + const append = (xs, ys) => xs.concat(ys); + + // chars :: String -> [Char] + const chars = s => s.split(''); + + // drop :: Int -> [a] -> [a] + // drop :: Int -> String -> String + const drop = (n, xs) => xs.slice(n); + + // find :: (a -> Bool) -> [a] -> Maybe a + const find = (p, xs) => { + for (var i = 0, lng = xs.length; i < lng; i++) { + var x = xs[i]; + if (p(x)) return just(x); + } + return nothing('Not found'); + }; + + // foldl :: (a -> b -> a) -> a -> [b] -> a + const foldl = (f, a, xs) => xs.reduce(f, a); + + // intercalate :: String -> [String] -> String + const intercalate = (s, xs) => xs.join(s); + + // isPrefixOf takes two lists or strings and returns + // true iff the first is a prefix of the second. + // isPrefixOf :: [a] -> [a] -> Bool + // isPrefixOf :: String -> String -> Bool + const isPrefixOf = (xs, ys) => { + const pfx = (xs, ys) => xs.length ? ( + ys.length ? xs[0] === ys[0] && pfx( + xs.slice(1), ys.slice(1) + ) : false + ) : true; + return typeof xs !== 'string' ? pfx(xs, ys) : ys.startsWith(xs); + }; + + // just :: a -> Just a + const just = x => ({ + nothing: false, + just: x + }); + + // length :: [a] -> Int + const length = xs => xs.length; + + // map :: (a -> b) -> [a] -> [b] + const map = (f, xs) => xs.map(f); + + // nothing :: () -> Nothing + const nothing = (optionalMsg) => ({ + nothing: true, + msg: optionalMsg + }); + + // show :: Int -> a -> Indented String + // show :: a -> String + const show = (...x) => + JSON.stringify.apply( + null, x.length > 1 ? [x[1], null, x[0]] : x + ); + + // TEST ------------------------------------------------------------------ + const + strTest = 'a!===b=!=c', + delims = ['==', '!=', '=']; + + return show(2, + multiSplit(delims, strTest) + ); +})(); diff --git a/Task/Multisplit/Ring/multisplit.ring b/Task/Multisplit/Ring/multisplit.ring new file mode 100644 index 0000000000..26ab99fcb3 --- /dev/null +++ b/Task/Multisplit/Ring/multisplit.ring @@ -0,0 +1,12 @@ +# Project : Multisplit +# Date : 2017/12/26 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +str = "a!===b=!=c" +sep = "=== != =! b =!=" +sep = str2list(substr(sep, " ", nl)) +for n = 1 to len(sep) + pos = substr(str, sep[n]) + see "" + n + ": " + substr(str, 1, pos-1) + " Sep By: " + sep[n] + nl +next diff --git a/Task/Munching-squares/AWK/munching-squares.awk b/Task/Munching-squares/AWK/munching-squares.awk new file mode 100644 index 0000000000..e114ad99ba --- /dev/null +++ b/Task/Munching-squares/AWK/munching-squares.awk @@ -0,0 +1,17 @@ +BEGIN { + # square size + s = 256 + # the PPM image header needs 3 lines: + # P3 + # width height + # max colors number (per channel) + print("P3\n", s, s, "\n", s - 1) + # and now we generate pixels as a RGB pair in a relaxed + # form "R G B\n" + for (x = 0; x < s; x++) { + for (y = 0; y < s; y++) { + p = xor(x, y) + print(0, p, p) + } + } +} diff --git a/Task/Munching-squares/Factor/munching-squares.factor b/Task/Munching-squares/Factor/munching-squares.factor new file mode 100644 index 0000000000..d1f3d395f9 --- /dev/null +++ b/Task/Munching-squares/Factor/munching-squares.factor @@ -0,0 +1,21 @@ +USING: accessors images images.loader kernel math sequences ; +IN: rosetta-code.munching-squares + +: img-data ( -- seq ) 256 sq [ B{ 0 0 0 255 } ] replicate ; + +: (munching) ( elt index -- elt' ) + 256 /mod bitxor [ rest ] dip prefix ; + +: munching ( -- seq ) + img-data [ (munching) ] map-index B{ } concat-as ; + +: ( -- img ) + + { 256 256 } >>dim + BGRA >>component-order + ubyte-components >>component-type + munching >>bitmap ; + +: main ( -- ) "munching.png" save-graphic-image ; + +MAIN: main diff --git a/Task/Munching-squares/Kotlin/munching-squares.kotlin b/Task/Munching-squares/Kotlin/munching-squares.kotlin new file mode 100644 index 0000000000..4cfc7f87f3 --- /dev/null +++ b/Task/Munching-squares/Kotlin/munching-squares.kotlin @@ -0,0 +1,47 @@ +// version 1.1.4-3 + +import javax.swing.JFrame +import javax.swing.JPanel +import java.awt.Graphics +import java.awt.Graphics2D +import java.awt.Color +import java.awt.Dimension +import java.awt.BorderLayout +import java.awt.RenderingHints +import javax.swing.SwingUtilities + +class XorPattern : JPanel() { + + init { + preferredSize = Dimension(256, 256) + background = Color.white + } + + override fun paint(gg: Graphics) { + super.paintComponent(gg) + val g = gg as Graphics2D + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON) + for (y in 0 until width) { + for (x in 0 until height) { + g.color = Color(0, (x xor y) % 256, 255) + g.drawLine(x, y, x, y) + } + } + } +} + +fun main(args: Array) { + SwingUtilities.invokeLater { + val f = JFrame() + with (f) { + defaultCloseOperation = JFrame.EXIT_ON_CLOSE + title = "Munching squares" + isResizable = false + add(XorPattern(), BorderLayout.CENTER) + pack() + setLocationRelativeTo(null) + isVisible = true + } + } +} diff --git a/Task/Munching-squares/Perl-6/munching-squares-1.pl6 b/Task/Munching-squares/Perl-6/munching-squares-1.pl6 index 297b951179..4c57eea75f 100644 --- a/Task/Munching-squares/Perl-6/munching-squares-1.pl6 +++ b/Task/Munching-squares/Perl-6/munching-squares-1.pl6 @@ -1,4 +1,4 @@ -my $ppm = open("munching.ppm", :w) or +my $ppm = open("munching0.ppm", :w) or die "Can't create munching.ppm: $!"; $ppm.print(q :to 'EOT'); diff --git a/Task/Munching-squares/Perl-6/munching-squares-2.pl6 b/Task/Munching-squares/Perl-6/munching-squares-2.pl6 index 54a23e89a0..07e76f304c 100644 --- a/Task/Munching-squares/Perl-6/munching-squares-2.pl6 +++ b/Task/Munching-squares/Perl-6/munching-squares-2.pl6 @@ -5,7 +5,7 @@ my @colors = map -> $r, $g, $b { Buf.new: $r, $g, $b }, flat (0,2...254),(254,252...0)); -my $PPM = open "munching.ppm", :w or die "Can't create munching.ppm: $!"; +my $PPM = open "munching1.ppm", :w or die "Can't create munching.ppm: $!"; $PPM.print: qq:to/EOH/; P6 diff --git a/Task/Munching-squares/REXX/munching-squares.rexx b/Task/Munching-squares/REXX/munching-squares.rexx new file mode 100644 index 0000000000..350b03c3f1 --- /dev/null +++ b/Task/Munching-squares/REXX/munching-squares.rexx @@ -0,0 +1,20 @@ +/*REXX program renders a graphical pattern by coloring each pixel with x XOR y */ +/*───────────────────────────────────────── from an arbitrary constructed color table. */ +rows=25 /*the number of rows in the color table*/ +cols=50 /* " " " cols " " " " */ + + do row =0 for rows*3 /*construct a color table, size 25x50.*/ + do col=0 for cols*3 + $= (row+col) // 255 + @.row.col= x2b( d2x($+0, 2) ) ||, /*ensure $ is converted──►2 hex nibbles*/ + x2b( d2x($+1, 2) ) ||, + x2b( d2x($+2, 2) ) + end /*col*/ /* [↑] construct a three-byte pixel. */ + end /*row*/ + + do x=0 for cols /*create a graphical pattern with XORs.*/ + do y=0 for rows + @.x.y=bitxor(@.x, @.y) /*renders 3 bytes (a pixel) at a time. */ + end /*y*/ + end /*x*/ + /*stick a fork in it, we're all done. */ diff --git a/Task/Munching-squares/Ring/munching-squares.ring b/Task/Munching-squares/Ring/munching-squares.ring new file mode 100644 index 0000000000..928f632a92 --- /dev/null +++ b/Task/Munching-squares/Ring/munching-squares.ring @@ -0,0 +1,57 @@ +# Project : Munching squares +# Date : 2018/01/13 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +load "guilib.ring" + +paint = null + +new qapp + { + win1 = new qwidget() { + setwindowtitle("Archimedean spiral") + setgeometry(100,100,500,600) + label1 = new qlabel(win1) { + setgeometry(10,10,400,400) + settext("") + } + new qpushbutton(win1) { + setgeometry(150,500,100,30) + settext("draw") + setclickevent("draw()") + } + show() + } + exec() + } + +func draw + p1 = new qpicture() + color = new qcolor() { + setrgb(0,0,255,255) + } + pen = new qpen() { + setcolor(color) + setwidth(1) + } + paint = new qpainter() { + begin(p1) + setpen(pen) + + w = 100 + for x = 0 to w + for y = 0 to w + b = (x ^ y) + color = new qcolor() + color.setrgb(255 -b,b /2,b,255) + pen.setcolor(color) + setpen(pen) + drawpoint(x,w -y -1) + next + next + + endpaint() + } + label1 { setpicture(p1) show() } + return diff --git a/Task/Mutual-recursion/Elena/mutual-recursion.elena b/Task/Mutual-recursion/Elena/mutual-recursion.elena new file mode 100644 index 0000000000..d7ff3ce39e --- /dev/null +++ b/Task/Mutual-recursion/Elena/mutual-recursion.elena @@ -0,0 +1,20 @@ +import extensions. +import system'collections. + +F = (:n)((n == 0) ifTrue:[^1] ifFalse:[ ^n - (M(F(n-1))) ] ). +M = (:n)((n == 0) ifTrue:[^0] ifFalse:[ ^n - (F(M(n-1))) ] ). + +program = +[ + var ra := ArrayList new. + var rb := ArrayList new. + + 0 to:19 do(:i) + [ + ra append(F eval:i). + rb append(M eval:i). + ]. + + console printLine(ra). + console printLine(rb). +]. diff --git a/Task/Mutual-recursion/Maple/mutual-recursion.maple b/Task/Mutual-recursion/Maple/mutual-recursion.maple new file mode 100644 index 0000000000..feacfd7398 --- /dev/null +++ b/Task/Mutual-recursion/Maple/mutual-recursion.maple @@ -0,0 +1,17 @@ +female_seq := proc(n) + if (n = 0) then + return 1; + else + return n - male_seq(female_seq(n-1)); + end if; +end proc; + +male_seq := proc(n) + if (n = 0) then + return 0; + else + return n - female_seq(male_seq(n-1)); + end if; +end proc; +seq(female_seq(i), i=0..10); +seq(male_seq(i), i=0..10); diff --git a/Task/N-queens-problem/Clojure/n-queens-problem.clj b/Task/N-queens-problem/Clojure/n-queens-problem-1.clj similarity index 100% rename from Task/N-queens-problem/Clojure/n-queens-problem.clj rename to Task/N-queens-problem/Clojure/n-queens-problem-1.clj diff --git a/Task/N-queens-problem/Clojure/n-queens-problem-2.clj b/Task/N-queens-problem/Clojure/n-queens-problem-2.clj new file mode 100644 index 0000000000..173d4a8af6 --- /dev/null +++ b/Task/N-queens-problem/Clojure/n-queens-problem-2.clj @@ -0,0 +1,6 @@ +(ns queens + (:require [clojure.math.combinatorics :as combo] + +(defn queens [n] + (filter (fn [x] (every? #(apply distinct? (map-indexed % x)) [+ -])) + (combo/permutations (range 1 (inc n))))) diff --git a/Task/N-queens-problem/Prolog/n-queens-problem-6.pro b/Task/N-queens-problem/Prolog/n-queens-problem-6.pro new file mode 100644 index 0000000000..3de18373e5 --- /dev/null +++ b/Task/N-queens-problem/Prolog/n-queens-problem-6.pro @@ -0,0 +1,5 @@ +not_diagonal(X, N) :- + maplist(plus, X, N, Z1), maplist(plus, X, Z2, N), is_set(Z1), is_set(Z2). + +queens(N, Qs) :- + numlist(1, N, P), findall(Q, (permutation(P, Q), not_diagonal(Q, P)), Qs). diff --git a/Task/N-queens-problem/REXX/n-queens-problem.rexx b/Task/N-queens-problem/REXX/n-queens-problem.rexx index d9e37abcff..b9af0afbac 100644 --- a/Task/N-queens-problem/REXX/n-queens-problem.rexx +++ b/Task/N-queens-problem/REXX/n-queens-problem.rexx @@ -3,11 +3,11 @@ parse arg N . /*obtain optional argument from if N=='' | N=="," then N=8 /*Not specified: Then use the default.*/ if N<1 then signal nOK /*display a message, the board is bad. */ rank=1; file=1; #=0 /*starting rank&file; #≡number queens.*/ -@.=0; pad=left('', 9* (N<18)) /*define empty board; set indentation.*/ +@.=0; pad=left('', 9* (N<18) ) /*define empty board; set indentation.*/ /* [↓] rank&file ≡ chessboard row&cols*/ do while #>1) { + if (var r = search([i], 1)) { + return r + } + } +} + +for n in (1..15) { + say "#{'%2d' % n}: #{N_queens_solution(n) || 'No solution'}" +} diff --git a/Task/N-queens-problem/Stata/n-queens-problem-1.stata b/Task/N-queens-problem/Stata/n-queens-problem-1.stata index 4271153966..96999bef33 100644 --- a/Task/N-queens-problem/Stata/n-queens-problem-1.stata +++ b/Task/N-queens-problem/Stata/n-queens-problem-1.stata @@ -9,34 +9,32 @@ real matrix queens(real scalar n) { s = J(1, n, 0) u = J(1, 2*n-1, 1) v = J(1, 2*n-1, 1) - i = j = 1 -L1: k = a[j] - a[j] = a[i] - a[i] = k + i = 1 +L1: if (i > n) { + m = m\a + goto L4 + } + j=i +L2: k = a[j] p = i-k+n q = i+k-1 if (u[p] & v[q]) { - s[i++] = j u[p] = v[q] = 0 - if (i > n) { - m = m\a - goto L3 - } - j = i + a[j] = a[i] + a[i] = k + s[i++] = j goto L1 } -L2: if (++j <= n) goto L1 - while (--j > i) { - k = a[i] - a[i] = a[j] - a[j] = k - } -L3: if (--i == 0) return(m) - p = i-a[i]+n - q = i+a[i]-1 +L3: if (++j <= n) goto L2 +L4: if (--i == 0) return(m) j = s[i] + k = a[i] + a[i] = a[j] + a[j] = k + p = i-k+n + q = i+k-1 u[p] = v[q] = 1 - goto L2 + goto L3 } a = queens(8) diff --git a/Task/N-queens-problem/Stata/n-queens-problem-3.stata b/Task/N-queens-problem/Stata/n-queens-problem-3.stata index b7ea6aeb55..c72ea0a795 100644 --- a/Task/N-queens-problem/Stata/n-queens-problem-3.stata +++ b/Task/N-queens-problem/Stata/n-queens-problem-3.stata @@ -1,5 +1,5 @@ mata -real matrix queens(real scalar n) { +real matrix queens_rec(real scalar n) { real rowvector a, u, v real matrix m @@ -13,46 +13,25 @@ real matrix queens(real scalar n) { void queens_aux(real scalar n, real scalar i, real rowvector a, real rowvector u, real rowvector v, real matrix m) { - - real scalar j, k, s + real scalar j, k if (i > n) { m = m\a } else { - for (k = i; k <= n; k++) { - j = a[k] - p = i+j-1 - q = i-j+n + for (j = i; j <= n; j++) { + k = a[j] + p = i-k+n + q = i+k-1 if (u[p] & v[q]) { u[p] = v[q] = 0 - s = a[i] - a[i] = a[k] - a[k] = s + a[j] = a[i] + a[i] = k queens_aux(n, i+1, a, u, v, m) u[p] = v[q] = 1 - s = a[i] - a[i] = a[k] - a[k] = s + a[i] = a[j] + a[j] = k } } } } - -a = queens(8) -e = I(8) -1:/e[a[1,.],.] - 1 2 3 4 5 6 7 8 - +---------------------------------+ - 1 | 1 . . . . . . . | - 2 | . . . . 1 . . . | - 3 | . . . . . . . 1 | - 4 | . . . . . 1 . . | - 5 | . . 1 . . . . . | - 6 | . . . . . . 1 . | - 7 | . 1 . . . . . . | - 8 | . . . 1 . . . . | - +---------------------------------+ - -rows(a) - 92 end diff --git a/Task/N-queens-problem/Stata/n-queens-problem-4.stata b/Task/N-queens-problem/Stata/n-queens-problem-4.stata new file mode 100644 index 0000000000..2885247001 --- /dev/null +++ b/Task/N-queens-problem/Stata/n-queens-problem-4.stata @@ -0,0 +1,2 @@ +queens(8) == queens_rec(8) + 1 diff --git a/Task/N-queens-problem/Wart/n-queens-problem.wart b/Task/N-queens-problem/Wart/n-queens-problem.wart new file mode 100644 index 0000000000..1c84c0a1c6 --- /dev/null +++ b/Task/N-queens-problem/Wart/n-queens-problem.wart @@ -0,0 +1,24 @@ +def (nqueens n queens) + prn "step: " queens # show progress + if (len.queens = n) + prn "solution! " queens + # else + let row (if queens (queens.zero.zero + 1) 0) + for col 0 (col < n) ++col + let new_queens (cons (list row col) queens) + if (no conflicts.new_queens) + (nqueens n new_queens) + +# check if the first queen in 'queens' lies on the same column or diagonal as +# any of the others +def (conflicts queens) + let (curr ... rest) queens + or (let curr_column curr.1 + (some (fn(_) (= _ curr_column)) + (map cadr rest))) # columns + (some (fn(_) (diagonal_match curr _)) + rest) + +def (diagonal_match curr other) + (= (abs (curr.0 - other.0)) + (abs (curr.1 - other.1))) diff --git a/Task/Named-parameters/Go/named-parameters.go b/Task/Named-parameters/Go/named-parameters.go new file mode 100644 index 0000000000..15dea66383 --- /dev/null +++ b/Task/Named-parameters/Go/named-parameters.go @@ -0,0 +1,20 @@ +package main + +import ( + "fmt" +) + +type params struct {x, y, z int} + +func myFunc(p params) int { + return p.x + p.y + p.z +} + +func main() { + r := myFunc(params{x: 1, y: 2, z: 3}) // all fields, same order + fmt.Println("r =", r) + s := myFunc(params{z: 3, y: 2, x: 1}) // all fields, different order + fmt.Println("s =", s) + t := myFunc(params{y: 2}) // only one field, others set to zero + fmt.Println("t =", t) +} diff --git a/Task/Named-parameters/Perl-6/named-parameters-2.pl6 b/Task/Named-parameters/Perl-6/named-parameters-2.pl6 index f31e5a460c..c470b011de 100644 --- a/Task/Named-parameters/Perl-6/named-parameters-2.pl6 +++ b/Task/Named-parameters/Perl-6/named-parameters-2.pl6 @@ -3,3 +3,9 @@ sub funkshun ($a, $b?, :$c = 15, :$d, *@e, *%f) { say join ' ', @e; say join ' ', keys %f; } + +# this particularly thorny call: + +funkshun + 'Alfa', k1 => 'v1', c => 'Charlie', 'Bravo', 'e1', + d => 'Delta', 'e2', k2 => 'v2'; diff --git a/Task/Narcissist/D/narcissist.d b/Task/Narcissist/D/narcissist.d new file mode 100644 index 0000000000..b5401ceca9 --- /dev/null +++ b/Task/Narcissist/D/narcissist.d @@ -0,0 +1 @@ +import std.file; import std.stdio; import std.string; void main() { auto source = readText("narcissist.d").chomp; auto input = readln().chomp(); if (source == input) writeln("accept"); else writeln("reject"); } diff --git a/Task/Narcissist/Julia/narcissist.julia b/Task/Narcissist/Julia/narcissist.julia new file mode 100644 index 0000000000..32750810bf --- /dev/null +++ b/Task/Narcissist/Julia/narcissist.julia @@ -0,0 +1,3 @@ +input = Base.readstring(ARGS[1]) +mysource = Base.readstring(Base.source_path()) +println(input == mysource ? "1" : "0") diff --git a/Task/Narcissist/Scala/narcissist.scala b/Task/Narcissist/Scala/narcissist.scala new file mode 100644 index 0000000000..e22a2de67c --- /dev/null +++ b/Task/Narcissist/Scala/narcissist.scala @@ -0,0 +1,11 @@ +import scala.io.StdIn + +object Narcissist extends App { + val text = scala.io.Source.fromFile("Narcissist.scala", "UTF-8").toStream + println("Enter the number of lines to be input followed by those lines:\n") + val n = StdIn.readInt() + val lines = Stream { + StdIn.readLine() + } + if (lines.mkString("\r\n") == text) println("\naccept") else println("\nreject") +} diff --git a/Task/Narcissistic-decimal-number/00DESCRIPTION b/Task/Narcissistic-decimal-number/00DESCRIPTION index a3d53ad966..2f32f158d6 100644 --- a/Task/Narcissistic-decimal-number/00DESCRIPTION +++ b/Task/Narcissistic-decimal-number/00DESCRIPTION @@ -1,6 +1,8 @@ A   [http://mathworld.wolfram.com/NarcissisticNumber.html Narcissistic decimal number]   is a non-negative integer,   n,   that is equal to the sum of the   m-th   powers of each of the digits in the decimal representation of   n,   where   m   is the number of digits in the decimal representation of   n. + Narcissistic (decimal) numbers are sometimes called   '''Armstrong'''   numbers, named after Michael F. Armstrong. +
They are also known as   '''Plus Perfect'''   numbers. ;An example: @@ -16,4 +18,10 @@ Generate and show here the first   '''25'''   narcissistic decimal num Note:   0^1 = 0,   the first in the series. + + +;See also: +*   the  OEIS entry:     [http://oeis.org/A005188 Armstrong (or Plus Perfect, or narcissistic) numbers]. +*   MathWorld entry:   [http://mathworld.wolfram.com/NarcissisticNumber.html Narcissistic Number]. +*   Wikipedia entry:     [https://en.wikipedia.org/wiki/Narcissistic_number Narcissistic number].

diff --git a/Task/Narcissistic-decimal-number/COBOL/narcissistic-decimal-number.cobol b/Task/Narcissistic-decimal-number/COBOL/narcissistic-decimal-number.cobol new file mode 100644 index 0000000000..927ca64af7 --- /dev/null +++ b/Task/Narcissistic-decimal-number/COBOL/narcissistic-decimal-number.cobol @@ -0,0 +1,57 @@ + PROGRAM-ID. NARCISSIST-NUMS. + DATA DIVISION. + WORKING-STORAGE SECTION. + + 01 num-length PIC 9(2) value 0. + 01 in-sum PIC 9(9) value 0. + 01 counter PIC 9(9) value 0. + 01 current-number PIC 9(9) value 0. + 01 narcissist PIC Z(9). + 01 temp PIC 9(9) value 0. + 01 modulo PIC 9(9) value 0. + 01 answer PIC 9 . + + PROCEDURE DIVISION. + MAIN-PROCEDURE. + DISPLAY "the first 20 narcissist numbers:" . + + MOVE 20 TO counter. + PERFORM UNTIL counter=0 + + PERFORM 000-NARCISSIST-PARA + + IF answer = 1 + SUBTRACT 1 from counter + GIVING counter + MOVE current-number TO narcissist + DISPLAY narcissist + END-IF + + ADD 1 TO current-number + + END-PERFORM + + STOP RUN. + + 000-NARCISSIST-PARA. + + MOVE ZERO TO in-sum. + MOVE current-number TO temp. + COMPUTE num-length =1+ FUNCTION Log10(temp) + + PERFORM UNTIL temp=0 + + DIVIDE temp BY 10 GIVING temp + REMAINDER modulo + + COMPUTE modulo=modulo**num-length + ADD modulo to in-sum GIVING in-sum + + END-PERFORM. + + IF current-number=in-sum + MOVE 1 TO answer + ELSE MOVE 0 TO answer + END-IF. + + END PROGRAM NARCISSIST-NUMS. diff --git a/Task/Narcissistic-decimal-number/Factor/narcissistic-decimal-number.factor b/Task/Narcissistic-decimal-number/Factor/narcissistic-decimal-number.factor new file mode 100644 index 0000000000..5ea124dc6b --- /dev/null +++ b/Task/Narcissistic-decimal-number/Factor/narcissistic-decimal-number.factor @@ -0,0 +1,15 @@ +USING: io kernel lists lists.lazy math math.functions +math.text.utils prettyprint sequences ; +IN: rosetta-code.narcissistic-decimal-number + +: digit-count ( n -- count ) log10 floor >integer 1 + ; + +: narcissist? ( n -- ? ) dup [ 1 digit-groups ] + [ digit-count [ ^ ] curry ] bi map-sum = ; + +: first25 ( -- seq ) 25 0 lfrom [ narcissist? ] lfilter + ltake list>array ; + +: main ( -- ) first25 [ pprint bl ] each ; + +MAIN: main diff --git a/Task/Narcissistic-decimal-number/Maple/narcissistic-decimal-number.maple b/Task/Narcissistic-decimal-number/Maple/narcissistic-decimal-number.maple new file mode 100644 index 0000000000..5304d784e3 --- /dev/null +++ b/Task/Narcissistic-decimal-number/Maple/narcissistic-decimal-number.maple @@ -0,0 +1,22 @@ +Narc:=proc(i) + local num,len,j,sums: + sums:=0: + num := parse~(StringTools:-Explode((convert(i,string)))): + len:=numelems(num): + for j from 1 to len do + sums:=sums+(num[j]^(len)): + end do; + if sums = i then + return i; + else + return NULL; + end if; +end proc: + +i:=0: +NDN:=[]: +while numelems(NDN)<25 do + NDN:=[op(NDN),(Narc(i))]: + i:=i+1: +end do: +NDN; diff --git a/Task/Narcissistic-decimal-number/Perl-6/narcissistic-decimal-number-2.pl6 b/Task/Narcissistic-decimal-number/Perl-6/narcissistic-decimal-number-2.pl6 index 74cbfda7f4..6899b33d06 100644 --- a/Task/Narcissistic-decimal-number/Perl-6/narcissistic-decimal-number-2.pl6 +++ b/Task/Narcissistic-decimal-number/Perl-6/narcissistic-decimal-number-2.pl6 @@ -7,14 +7,12 @@ sub kigits($n) { } } -constant narcissistic = 0, (1..*).map: -> $d { +for (1..*) -> $d { my @t = 0..9 X** $d; my @table = @t X+ @t X+ @t; - sub is-narcissistic(\n) { n == [+] @table[kigits(n)] } - gather take $_ if is-narcissistic($_) for 10**($d-1) ..^ 10**$d; -} - -for narcissistic { - say ++state $n, "\t", $_; - last if $n == 25; -} + sub is-narcissistic(\n) { n == [+] @table[kigits(n)] }; + state $l = 2; + FIRST say "1\t0"; + say $l++, "\t", $_ if .&is-narcissistic for 10**($d-1) ..^ 10**$d; + last if $l > 25 +}; diff --git a/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-1.rexx b/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-1.rexx index 84348d7bbf..9fb41a9606 100644 --- a/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-1.rexx +++ b/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-1.rexx @@ -1,17 +1,17 @@ /*REXX program generates and displays a number of narcissistic (Armstrong) numbers. */ numeric digits 39 /*be able to handle largest Armstrong #*/ -parse arg N .; if N=='' | N=="," then N=25 /*obtain the number of narcissistic #'s*/ +parse arg N . /*obtain optional argument from the CL.*/ +if N=='' | N=="," then N=25 /*Not specified? Then use the default.*/ N=min(N, 89) /*there are only 89 narcissistic #s. */ #=0 /*number of narcissistic numbers so far*/ do j=0 until #==N; L=length(j) /*get length of the J decimal number.*/ - $=left(j,1)**L /*1st digit in J raised to the L pow.*/ + $=left(j, 1) **L /*1st digit in J raised to the L pow.*/ - do k=2 for L-1 until $>j /*perform for each decimal digit in J.*/ - $=$ + substr(j, k, 1) ** L /*add digit raised to power to the sum.*/ - end /*k*/ /* [↑] calculate the rest of the sum. */ + do k=2 for L-1 until $>j /*perform for each decimal digit in J.*/ + $=$ + substr(j, k, 1) ** L /*add digit raised to power to the sum.*/ + end /*k*/ /* [↑] calculate the rest of the sum. */ if $\==j then iterate /*does the sum equal to J? No, skip it*/ - #=#+1 /*bump count of narcissistic numbers. */ + #=# + 1 /*bump count of narcissistic numbers. */ say right(#, 9) ' narcissistic:' j /*display index and narcissistic number*/ - end /*j*/ /* [↑] this list starts at 0 (zero).*/ - /*stick a fork in it, we're all done. */ + end /*j*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-2.rexx b/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-2.rexx index 33e58a8379..f6a3f84107 100644 --- a/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-2.rexx +++ b/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-2.rexx @@ -1,23 +1,23 @@ /*REXX program generates and displays a number of narcissistic (Armstrong) numbers. */ numeric digits 39 /*be able to handle largest Armstrong #*/ -parse arg N .; if N=='' | N=="," then N=25 /*obtain the number of narcissistic #'s*/ +parse arg N . /*obtain optional argument from the CL.*/ +if N=='' | N=="," then N=25 /*Not specified? Then use the default.*/ N=min(N, 89) /*there are only 89 narcissistic #s. */ - do w=1 for 39 /*generate tables: digits ^ L power. */ - do i=0 for 10; @.w.i=i**w /*build table of ten digits ^ L power. */ + do p=1 for 39 /*generate tables: digits ^ P power. */ + do i=0 for 10; @.p.i= i**p /*build table of ten digits ^ P power. */ end /*i*/ end /*w*/ /* [↑] table is a fixed (limited) size*/ #=0 /*number of narcissistic numbers so far*/ do j=0 until #==N; L=length(j) /*get length of the J decimal number.*/ _=left(j, 1) /*select the first decimal digit to sum*/ $=@.L._ /*sum of the J dec. digits ^ L (so far)*/ - do k=2 for L-1 until $>j /*perform for each decimal digit in J.*/ - _=substr(j, k, 1) /*select the next decimal digit to sum.*/ - $=$ + @.L._ /*add dec. digit raised to power to sum*/ - end /*k*/ /* [↑] calculate the rest of the sum. */ + do k=2 for L-1 until $>j /*perform for each decimal digit in J.*/ + _=substr(j, k, 1) /*select the next decimal digit to sum.*/ + $=$ + @.L._ /*add dec. digit raised to power to sum*/ + end /*k*/ /* [↑] calculate the rest of the sum. */ if $\==j then iterate /*does the sum equal to J? No, skip it*/ - #=#+1 /*bump count of narcissistic numbers. */ + #=# + 1 /*bump count of narcissistic numbers. */ say right(#, 9) ' narcissistic:' j /*display index and narcissistic number*/ - end /*j*/ /* [↑] this list starts at 0 (zero).*/ - /*stick a fork in it, we're all done. */ + end /*j*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-3.rexx b/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-3.rexx index 6e4631bd02..2df52905a2 100644 --- a/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-3.rexx +++ b/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-3.rexx @@ -1,28 +1,31 @@ /*REXX program generates and displays a number of narcissistic (Armstrong) numbers. */ numeric digits 39 /*be able to handle largest Armstrong #*/ -parse arg N .; if N=='' | N=="," then N=25 /*obtain the number of narcissistic #'s*/ +parse arg N . /*obtain optional argument from the CL.*/ +if N=='' | N=="," then N=25 /*Not specified? Then use the default.*/ N=min(N, 89) /*there are only 89 narcissistic #s. */ @.=0 /*set default for the @ stemmed array. */ #=0 /*number of narcissistic numbers so far*/ - do w=0 for 39+1; if w<10 then call tell w /*display the 1st 1─digit dec. numbers.*/ - do i=1 for 9; @.w.i=i**w /*build table of ten digits ^ L power. */ + do p=0 for 39+1; if p<10 then call tell p /*display the 1st 1─digit dec. numbers.*/ + do i=1 for 9; @.p.i= i**p /*build table of ten digits ^ P power. */ end /*i*/ - end /*w*/ /* [↑] table is a fixed (limited) size*/ + end /*p*/ /* [↑] table is a fixed (limited) size*/ /* [↓] skip the 2─digit dec. numbers. */ - do j=100; L=length(j) /*get length of the J decimal number.*/ - parse var j _1 2 _2 3 m '' -1 _R /*get 1st, 2nd, middle, last dec. digit*/ + do j=100; L=length(j) /*get length of the J decimal number.*/ + parse var j _1 2 _2 3 m '' -1 _R /*get 1st, 2nd, middle, last dec. digit*/ $=@.L._1 + @.L._2 + @.L._R /*sum of the J decimal digs^L (so far).*/ - do k=3 for L-3 until $>j /*perform for other decimal digits in J*/ - parse var m _ +1 m /*get next dec. dig in J, start at 3rd.*/ - $=$ + @.L._ /*add dec. digit raised to pow to sum. */ - end /*k*/ /* [↑] calculate the rest of the sum. */ + do k=3 for L-3 until $>j /*perform for other decimal digits in J*/ + parse var m _ +1 m /*get next dec. dig in J, start at 3rd.*/ + $=$ + @.L._ /*add dec. digit raised to pow to sum. */ + end /*k*/ /* [↑] calculate the rest of the sum. */ - if $==j then call tell j /*does the sum equal to J? Show the #*/ + if $==j then do; call tell j /*does the sum equal to J? Show the #*/ + if #==n then leave /*does the sum equal to J? Show the #*/ + end end /*j*/ /* [↑] the J loop list starts at 100*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -tell: #=#+1 /*bump the counter for narcissistic #s.*/ +tell: #=# + 1 /*bump the counter for narcissistic #s.*/ say right(#,9) ' narcissistic:' arg(1) /*display index and narcissistic number*/ - if #==N then exit /*stick a fork in it, we're all done. */ + if #==n & n<11 then exit /*finished showing of narcissistic #'s?*/ return /*return to invoker & keep on truckin'.*/ diff --git a/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-4.rexx b/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-4.rexx new file mode 100644 index 0000000000..4d18ffca97 --- /dev/null +++ b/Task/Narcissistic-decimal-number/REXX/narcissistic-decimal-number-4.rexx @@ -0,0 +1,40 @@ +/*REXX program generates and displays a number of narcissistic (Armstrong) numbers. */ +numeric digits 39 /*be able to handle largest Armstrong #*/ +parse arg N . /*obtain optional argument from the CL.*/ +if N=='' | N=="," then N=25 /*Not specified? Then use the default.*/ +N=min(N, 89) /*there are only 89 narcissistic #s. */ +@.=0 /*set default for the @ stemmed array. */ +#=0 /*number of narcissistic numbers so far*/ + do p=0 for 39+1; if p<10 then call tell p /*display the 1st 1─digit dec. numbers.*/ + do i=1 for 9; @.p.i= i**p /*build table of ten digits ^ P power. */ + zzj= '00'j; @.p.zzj= @.p.j /*assign value for a 3-dig number (LZ),*/ + end /*i*/ + + do j=10 to 99; parse var j t 2 u /*obtain 2 decimal digits of J: T U */ + @.p.j = @.p.t + @.p.u /*assign value for a 2─dig number. */ + zj= '0'j; @.p.zj = @.p.j /* " " " " 3─dig " (LZ),*/ + end /*j*/ /* [↑] T≡ tens digit; U≡ units digit.*/ + + do k=100 to 999; parse var k h 2 t 3 u /*obtain 3 decimal digits of J: H T U */ + @.p.k= @.p.h + @.p.t + @.p.u /*assign value for a three-digit number*/ + end /*k*/ /* [↑] H≡ hundreds digit; T≡ tens ···*/ + end /*p*/ /* [↑] table is a fixed (limited) size*/ + /* [↓] skip the 2─digit dec. numbers. */ + do j=100; L=length(j) /*get length of the J decimal number.*/ + parse var j _ +3 m /*get 1st three decimal digits of J. */ + $=@.L._ /*sum of the J decimal digs^L (so far).*/ + do while m\=='' /*do the rest of the dec. digs in J. */ + parse var m _ +3 m /*get the next 3 decimal digits in M. */ + $=$ + @.L._ /*add dec. digit raised to pow to sum. */ + end /*while*/ /* [↑] calculate the rest of the sum. */ + + if $==j then do; call tell j /*does the sum equal to J? Show the #*/ + if #==n then leave /*does the sum equal to J? Show the #*/ + end + end /*j*/ /* [↑] the J loop list starts at 100*/ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +tell: #=# + 1 /*bump the counter for narcissistic #s.*/ + say right(#,9) ' narcissistic:' arg(1) /*display index and narcissistic number*/ + if #==n & n<11 then exit /*finished showing of narcissistic #'s?*/ + return /*return to invoker & keep on truckin'.*/ diff --git a/Task/Narcissistic-decimal-number/Ruby/narcissistic-decimal-number.rb b/Task/Narcissistic-decimal-number/Ruby/narcissistic-decimal-number.rb index 69d2194522..9c716ae27e 100644 --- a/Task/Narcissistic-decimal-number/Ruby/narcissistic-decimal-number.rb +++ b/Task/Narcissistic-decimal-number/Ruby/narcissistic-decimal-number.rb @@ -1,28 +1,10 @@ class Integer def narcissistic? - return false if self < 0 - len = to_s.size - n = self - sum = 0 - while n > 0 - n, r = n.divmod(10) - sum += r ** len - end - sum == self + return false if negative? + digs = self.digits + m = digs.size + digs.map{|d| d**m}.sum == self end end -numbers = [] -n = 0 -while numbers.size < 25 - numbers << n if n.narcissistic? - n += 1 -end - -# or -# numbers = 0.step.lazy.select(&:narcissistic?).first(25) # Ruby ver 2.1 - -max = numbers.max.to_s.size -g = numbers.group_by{|n| n.to_s.size} -g.default = [] -(1..max).each{|n| puts "length #{n} : #{g[n].join(", ")}"} +puts 0.step.lazy.select(&:narcissistic?).first(25) diff --git a/Task/Natural-sorting/Haskell/natural-sorting.hs b/Task/Natural-sorting/Haskell/natural-sorting.hs new file mode 100644 index 0000000000..b81fcd4f1b --- /dev/null +++ b/Task/Natural-sorting/Haskell/natural-sorting.hs @@ -0,0 +1,89 @@ +import Data.List +import Data.Char +import Data.String.Utils +import Data.List.Utils +import Data.Function (on) + + +printOutput = do + putStrLn "# Ignoring leading spaces \n" + printBlockOfMessages sample1Rule ignoringStartEndSpaces + putStrLn "\n # Ignoring multiple adjacent spaces (m.a.s) \n" + printBlockOfMessages sample2Rule ignoringMultipleAdjacentSpaces + putStrLn "\n # Equivalent whitespace characters \n" + printBlockOfMessages sample3Rule ignoringMultipleAdjacentSpaces + putStrLn "\n # Case Indepenent sorts \n" + printBlockOfMessages sample4Rule caseIndependent + putStrLn "\n # Numeric fields as numerics \n" + printBlockOfMessages sample5Rule numericFieldsAsNumbers + putStrLn "\n # Title sorts \n" + printBlockOfMessages sample6Rule removeLeadCommonWords + +printMessage message content = do + putStrLn message + mapM_ print content + +printBlockOfMessages list function = do + printMessage "Text strings:" list + printMessage "Normally sorted:" (sort list) + printMessage "Naturally sorted:" (sortListWith list function) + + +-- samples +sample1Rule = ["ignore leading spaces: 2-2", " ignore leading spaces: 2-1", " ignore leading spaces: 2+0", " ignore leading spaces: 2+1"] +sample2Rule = ["ignore m.a.s spaces: 2-2", "ignore m.a.s spaces: 2-1", "ignore m.a.s spaces: 2+0", "ignore m.a.s spaces: 2+1"] +sample3Rule = ["Equiv. spaces: 3-3", "Equiv.\rspaces: 3-2", "Equiv.\x0cspaces: 3-1", "Equiv.\x0bspaces: 3+0", "Equiv.\nspaces: 3+1", "Equiv.\tspaces: 3+2"] +sample4Rule = ["cASE INDEPENENT: 3-2", "caSE INDEPENENT: 3-1", "casE INDEPENENT: 3+0", "case INDEPENENT: 3+1"] +sample5Rule = ["foo100bar99baz0.txt", "foo100bar10baz0.txt", "foo1000bar99baz10.txt", "foo1000bar99baz9.txt"] +sample6Rule = ["The Wind in the Willows", "The 40th step more", "The 39 steps", "Wanda"] + + +-- function to execute all sorts +sortListWith l f = sort $ f l + +-- 1. Ignore leading, trailing and multiple adjacent spaces + + -- Ignoring leading spaces + +-- receive a String and remove all spaces from the start and end of that String, a String is considered an List os Char +-- ex: " a string " = "a string" +ignoringStartEndSpaces :: [String] -> [String] +ignoringStartEndSpaces = map strip + +-- Ignoring multiple adjacent spaces and Equivalent whitespace characters + +ignoringMultipleAdjacentSpaces :: [String] -> [String] +ignoringMultipleAdjacentSpaces = map (unwords . words) + +-- 2. Equivalent whitespace characters +-- 3. Case independent sort +-- lower case of an entire String +-- ex "SomeCAse" = "somecase" +caseIndependent :: [String] -> [String] +caseIndependent = map (map toLower) + +-- 4. Numeric fields as numerics (deals with up to 20 digits) +numericFieldsAsNumbers :: [String] -> [[Int]] +numericFieldsAsNumbers = map findOnlyNumerics + +findOnlyNumerics :: String -> [Int] +findOnlyNumerics s = convertDigitAsStringToInt $ makeListOfDigitsAsString $ extractDigitsAsString s +extractDigitsAsString :: String -> [String] +extractDigitsAsString s = map (filter isNumber) $ groupBy ((==) `on` isNumber ) s +makeListOfDigitsAsString :: [String] -> [String] +makeListOfDigitsAsString l = tail $ nub l +convertDigitAsStringToInt :: [String] -> [Int] +convertDigitAsStringToInt = map (joiner . map digitToInt) + +-- join a list of numbers into a single number +-- ex [4,2] = 42 +joiner :: [Int] -> Int +joiner = read . concatMap show + +-- 5. Title sort +removeLeadCommonWords l = map removeLeadCommonWord $ splitList l + +splitList = map words +removeLeadCommonWord a = unwords $ if f a commonWords then tail a else a + where f l1 = elem (map toLower (head l1)) + commonWords = ["the","a","an","of"] diff --git a/Task/Natural-sorting/Phix/natural-sorting.phix b/Task/Natural-sorting/Phix/natural-sorting.phix index dfac6abbdd..72d103d2a5 100644 --- a/Task/Natural-sorting/Phix/natural-sorting.phix +++ b/Task/Natural-sorting/Phix/natural-sorting.phix @@ -1,5 +1,5 @@ -- --- demo/rosetta/Natural_sorting.exw +-- demo/rosetta/Natural_sorting2.exw -- function utf32ch(sequence s) for i=1 to length(s) do diff --git a/Task/Natural-sorting/PowerShell/natural-sorting.psh b/Task/Natural-sorting/PowerShell/natural-sorting.psh new file mode 100644 index 0000000000..16d7ef7177 --- /dev/null +++ b/Task/Natural-sorting/PowerShell/natural-sorting.psh @@ -0,0 +1,62 @@ +# six sorting +$Discard = '^a ', '^an ', '^the ' +$List = + 'ignore leading spaces: 2-2<==', + ' ignore leading spaces: 2-1 <==', + ' ignore leading spaces: 2+0 <==', + ' ignore leading spaces: 2+1 <==', + 'ignore m.a.s spaces: 2-2<==', + 'ignore m.a.s spaces: 2-1<==', + 'ignore m.a.s spaces: 2+0<==', + 'ignore m.a.s spaces: 2+1<==', + 'Equiv. spaces: 3-3<==', + "Equiv.`rspaces: 3-2<==", + "Equiv.`fspaces: 3-1<==", + "Equiv.`vspaces: 3+0<==", + "Equiv.`nspaces: 3+1<==", + "Equiv.`tspaces: 3+2<==", + 'cASE INDEPENDENT: 3-2<==', + 'caSE INDEPENDENT: 3-1<==', + 'casE INDEPENDENT: 3+0<==', + 'case INDEPENDENT: 3+1<==', + 'Lâmpada accented characters<==', + 'Lúdico accented characters<==', + ' Lula Free !!! accented characters<==', + 'Amanda accented characters<==', + 'Ágata accented characters<==', + 'Ångström accented characters<==', + 'Ângela accented characters<==', + 'À toa accented characters<==', + 'ânsia accented characters<==', + 'álibi accented characters<==', + 'foo100bar99baz0.txt<==', + 'foo100bar10baz0.txt<==', + 'foo1000bar99baz10.txt<==', + 'foo1000bar99baz9.txt<==', + 'The Wind in the Willows<==', + 'The 40th step more<==', + 'The 39 steps<==', + 'Wanda<==' + +'List index sorting' +$List +' ' +'Lexicographically sorting' +$List | Sort-Object +' ' +'Natural sorting' +$List | Sort-Object -Property { + [Regex]::Replace( + ( + ( + & { + If ($_.Trim() -match ($Discard -join '|')) { + $_ -replace '^\s*[^\s]+\s*' + } Else { + $_.Trim() + } + } + ) -replace '\s+' + ), '\d+', { $args[0].Value.PadLeft(20) } + ) +} diff --git a/Task/Nautical-bell/C/nautical-bell.c b/Task/Nautical-bell/C/nautical-bell.c index e57c58c0c3..69277bcd28 100644 --- a/Task/Nautical-bell/C/nautical-bell.c +++ b/Task/Nautical-bell/C/nautical-bell.c @@ -1,11 +1,14 @@ +/*Abhishek Ghosh, Original : 20th September 2017, Corrected : 25th September 2017*/ + #include #include #include -#define DELAY 3000 +#define SHORTLAG 1000 +#define LONGLAG 2000 int main(){ - int i,times; + int i,times,hour,min,sec,min1,min2; time_t t; struct tm* currentTime; @@ -14,22 +17,39 @@ int main(){ time(&t); currentTime = localtime(&t); - times = (currentTime->tm_hour%12==0)?12:currentTime->tm_hour%12; + hour = currentTime->tm_hour; + min = currentTime->tm_min; + sec = currentTime->tm_sec; - if(currentTime->tm_min==0 && currentTime->tm_sec==0){ - printf("\nIt is now %d:00 %s. Sounding the bell %d times.",times,(currentTime->tm_hour>11)?"PM":"AM",times); + hour = 12; + min = 0; + sec = 0; - for(i=0;i11)?"PM":"AM",times); + + for(i=1;i<=times;i++){ printf("\a"); - sleep(DELAY); + + (i%2==0)?sleep(LONGLAG):sleep(SHORTLAG); } } - - else if(currentTime->tm_min==30 && currentTime->tm_sec==0){ - printf("\nIt is now %d:30 %s. Sounding the bell once.",times,(currentTime->tm_hour>11)?"PM":"AM"); - printf("\a"); - } } - return 0; } diff --git a/Task/Nautical-bell/Mathematica/nautical-bell.math b/Task/Nautical-bell/Mathematica/nautical-bell.math new file mode 100644 index 0000000000..dedc1990fe --- /dev/null +++ b/Task/Nautical-bell/Mathematica/nautical-bell.math @@ -0,0 +1 @@ +SessionSubmit[ScheduledTask[EmitSound[SoundNote["C", 1, "TubularBells"]], "Hourly"]] diff --git a/Task/Nautical-bell/REXX/nautical-bell.rexx b/Task/Nautical-bell/REXX/nautical-bell.rexx index f5aa285b38..e67ad0dff1 100644 --- a/Task/Nautical-bell/REXX/nautical-bell.rexx +++ b/Task/Nautical-bell/REXX/nautical-bell.rexx @@ -1,25 +1,24 @@ /*REXX program sounds "ship's bells" (using PC speaker) when executing (perpetually).*/ -echo= (arg()\==0) /*echo time and bells if any arguments.*/ +echo= ( arg()\==0 ) /*echo time and bells if any arguments.*/ signal on halt /*allow a clean way to stop the program*/ t.1= '00:30 01:00 01:30 02:00 02:30 03:00 03:30 04:00' t.2= '04:30 05:00 05:30 06:00 06:30 07:00 07:30 08:00' t.3= '08:30 09:00 09:30 10:00 10:30 11:00 11:30 12:00' - do forever; t=time(); ss=right(t,2); mn=substr(t,4,2) /*the current time. */ - ct=time('C') /*[↓] maybe add leading zero*/ - hhmmc=left( right( ct, 7, 0), 5) /*HH:MM (with leading zero).*/ - if echo then say center(arg(1) ct, 79) /*echo 1st arg with the time?*/ - if ss\==00 & mn\==00 & mn\==30 then do /*wait for the next minute ? */ - call delay 60-ss; iterate - end /* [↑] delay minute fraction*/ - /* [↓] number bells to peel.*/ - do j=1 for 3 until $\==0; $=wordpos(hhmmc,t.j) - end /*j*/ + do forever; t=time(); ss=right(t, 2); mn=substr(t, 4, 2) /*the current time.*/ + ct=time('C') /*[↓] maybe add leading zero to time. */ + hhmmc=left( right( ct, 7, 0), 5) /*HH:MM (maybe with a leading zero). */ + if echo then say center(arg(1) ct, 79) /*echo the 1st argument with the time? */ + if ss\==00 & mn\==00 & mn\==30 then do; call delay 60-ss; iterate + end /* [↑] delay for fraction of a minute.*/ + /* [↓] the number of bells to peel {$}*/ + do j=1 for 3 until $\==0; $=wordpos(hhmmc, t.j) + end /*j*/ - if $\==0 & echo then say center($ "bells", 79) /*echo the bells ? */ + if $\==0 & echo then say center($ "bells", 79) /*echo the number of bells? */ - do k=1 for $; call sound 650,1; call delay 1 +(k//2==0) - end /*k*/ /*[↑] peel and then pause. */ - call delay 60 /*ensure we don't re-peel. */ + do k=1 for $; call sound 650,1; call delay 1 + (k//2==0) + end /*k*/ /*[↑] peel, and then pause for effect.*/ + call delay 60; if rc\==0 then leave /*ensure we don't re─peel. */ end /*forever*/ halt: /*stick a fork in it, we're all done. */ diff --git a/Task/Nautical-bell/Ring/nautical-bell.ring b/Task/Nautical-bell/Ring/nautical-bell.ring new file mode 100644 index 0000000000..161d24c889 --- /dev/null +++ b/Task/Nautical-bell/Ring/nautical-bell.ring @@ -0,0 +1,23 @@ +# Project : Nautical bell +# Date : 2017/12/26 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +m = 0 +for n = 0 to 23 + if n = 23 + see "23" + ":30" + " = " + "7 bells" + nl + else + m = m + 1 + see "" + n%23 + ":30" + " = " + m + " bells" + nl + ok + if n = 23 + see "00" + ":00" + " = " + "8 bells" + nl + else + m = m + 1 + see "" + (n%23+1) + ":00" + " = " + m + " bells" + nl + if m = 8 + m = 0 + ok + ok +next diff --git a/Task/Non-continuous-subsequences/Julia/non-continuous-subsequences.julia b/Task/Non-continuous-subsequences/Julia/non-continuous-subsequences.julia new file mode 100644 index 0000000000..82dcde50c3 --- /dev/null +++ b/Task/Non-continuous-subsequences/Julia/non-continuous-subsequences.julia @@ -0,0 +1,56 @@ +iscontseq(n::Integer) = count_zeros(n) == leading_zeros(n) + trailing_zeros(n) +iscontseq(n::BigInt) = !ismatch(r"0", rstrip(bin(n), '0')) + +function makeint2seq(n::Integer) + const idex = collect(1:n) + function int2seq(m::Integer) + d = digits(m, 2, n) + idex[d .== 1] + end + return int2seq +end + +struct NCSubSeq{T<:Integer} + n::T +end + +mutable struct NCSubState{T<:Integer} + m::T + m2s::Function +end + +Base.iteratorsize(::NCSubSeq) = Base.HasLength() +Base.length(a::NCSubSeq) = 2 ^ a.n - a.n * (a.n + 1) ÷ 2 - 1 + +Base.start(a::NCSubSeq) = NCSubState(5, makeint2seq(a.n)) +Base.done(a::NCSubSeq, as::NCSubState) = 2 ^ a.n - 3 < as.m +function Base.next(a::NCSubSeq, as::NCSubState) + s = as.m2s(as.m) + as.m += 1 + while iscontseq(as.m) + as.m += 1 + end + return (s, as) +end + +n = 4 +println("Testing NCSubSeq for ", n, " items:\n ", join(NCSubSeq(n), " ")) + +s = "Rosetta" +cs = split(s, "") +m = 10 +n = length(NCSubSeq(length(s))) - m +println("\nThe first and last ", m, " NC sub-sequences of \"", s, "\":") +for (i, a) in enumerate(NCSubSeq(length(cs))) + i <= m || n < i || continue + println(@sprintf "%6d %s" i join(cs[a], "")) + i == m || continue + println(" .. ......") +end + +using IterTools.chain + +println("\nThe first and last ", m, " NC sub-sequences of \"", s, "\"") +for x in IterTools.chain(1:10, 20:10:40, big.(50:50:200)) + @printf "%7d → %d\n" x length(NCSubSeq(x)) +end diff --git a/Task/Non-continuous-subsequences/Ring/non-continuous-subsequences.ring b/Task/Non-continuous-subsequences/Ring/non-continuous-subsequences.ring new file mode 100644 index 0000000000..febd5c24c6 --- /dev/null +++ b/Task/Non-continuous-subsequences/Ring/non-continuous-subsequences.ring @@ -0,0 +1,61 @@ +# Project : Non-continuous subsequences +# Date : 2018/02/03 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : + +load "stdlib.ring" +list = [1,2,3,4] +items = newlist(pow(2,len(list))-1,len(list)) +see "For [1, 2, 3, 4] non-continuous subsequences are:" + nl +powerset(list,4) +showarray(items,4) +see nl + +list = [1,2,3,4,5] +items = newlist(pow(2,len(list))-1,len(list)) +see "For [1, 2, 3, 4, 5] non-continuous subsequences are:" + nl +powerset(list,5) +showarray(items,5) + +func showarray(items,ind) + for n = 1 to len(items) + flag = 0 + for m = 1 to ind - 1 + if items[n][m] = 0 or items[n][m+1] = 0 + exit + ok + if (items[n][m] + 1) != items[n][m+1] + flag = 1 + exit + ok + next + if flag = 1 + see "[" + str = "" + for x = 1 to len(items[n]) + if items[n][x] != 0 + str = str + items[n][x] + " " + ok + next + str = left(str, len(str) - 1) + see str + "]" + nl + ok + next + +func powerset(list,ind) + num = 0 + num2 = 0 + items = newlist(pow(2,len(list))-1,ind) + for i = 2 to (2 << len(list)) - 1 step 2 + num2 = 0 + num = num + 1 + for j = 1 to len(list) + if i & (1 << j) + num2 = num2 + 1 + if list[j] != 0 + items[num][num2] = list[j] + ok + ok + next + next + return items diff --git a/Task/Non-decimal-radices-Convert/AppleScript/non-decimal-radices-convert-1.applescript b/Task/Non-decimal-radices-Convert/AppleScript/non-decimal-radices-convert-1.applescript index dda467e716..714084b95f 100644 --- a/Task/Non-decimal-radices-Convert/AppleScript/non-decimal-radices-convert-1.applescript +++ b/Task/Non-decimal-radices-Convert/AppleScript/non-decimal-radices-convert-1.applescript @@ -7,25 +7,26 @@ on toBase(intBase, n) end if end toBase - -- inBaseDigits :: String -> Int -> [String] on inBaseDigits(strDigits, n) set intBase to length of strDigits script nextDigit - on lambda(residue) + on |λ|(residue) set {divided, remainder} to quotRem(residue, intBase) + if divided > 0 then + {just:(item (remainder + 1) of strDigits), new:divided, nothing:false} + else + {nothing:true} + end if - {valid:divided > 0, value:(item (remainder + 1) of strDigits), new:divided} - end lambda + end |λ| end script reverse of unfoldr(nextDigit, n) as string end inBaseDigits - - --- OTHER FUNCTIONS DERIVABLE FROM inBaseDigits +-- OTHER FUNCTIONS DERIVABLE FROM inBaseDigits ------------------------------- -- inUpperHex :: Int -> String on inUpperHex(n) @@ -37,31 +38,32 @@ on inDevanagariDecimal(n) inBaseDigits("०१२३४५६७८९", n) end inDevanagariDecimal --- TEST +-- TEST ---------------------------------------------------------------------- on run script - on lambda(x) + on |λ|(x) {{binary:toBase(2, x), octal:toBase(8, x), hex:toBase(16, x)}, ¬ {upperHex:inUpperHex(x), dgDecimal:inDevanagariDecimal(x)}} - end lambda + end |λ| end script map(result, [255, 240]) end run --- GENERIC FUNCTIONS +-- GENERIC FUNCTIONS --------------------------------------------------------- -- unfoldr :: (b -> Maybe (a, b)) -> b -> [a] on unfoldr(f, v) - set mf to mReturn(f) set lst to {} - set recM to mf's lambda(v) - repeat while (valid of recM) is true - set end of lst to value of recM - set recM to mf's lambda(new of recM) - end repeat - lst & value of recM + set recM to {nothing:false, new:v} + tell mReturn(f) + repeat while (not (nothing of recM)) + set recM to |λ|(new of recM) + if not nothing of recM then set end of lst to just of recM + end repeat + end tell + lst end unfoldr -- quotRem :: Integral a => a -> a -> (a, a) @@ -75,7 +77,7 @@ on map(f, xs) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell @@ -88,20 +90,7 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn - --- until :: (a -> Bool) -> (a -> a) -> a -> a -on |until|(p, f, x) - set mp to mReturn(p) - set v to x - - tell mReturn(f) - repeat until mp's lambda(v) - set v to lambda(v) - end repeat - end tell - return v -end |until| diff --git a/Task/Non-decimal-radices-Convert/Maple/non-decimal-radices-convert.maple b/Task/Non-decimal-radices-Convert/Maple/non-decimal-radices-convert.maple new file mode 100644 index 0000000000..1ff86fc0c8 --- /dev/null +++ b/Task/Non-decimal-radices-Convert/Maple/non-decimal-radices-convert.maple @@ -0,0 +1,31 @@ +#converts a number to a given based represented by a string +to_base := proc(num, based) + local i; + local chart := "0123456789abcdefghijklmnopqrstuvwxyz"; + local conversion := ListTools:-Reverse((convert(num,base,based))); + local str := StringTools:-StringBuffer(); + for i in conversion do + str:-append(chart[i+1]); + end do; + return str; +end proc: + +#find the location of char in chart +find_digit := proc(char) + if (StringTools:-HasAlpha(char)) then + return (StringTools:-Ord(char) - 87); + else + return (StringTools:-Ord(char) - 48); + end if; +end proc: + +#converts a string with given base to a number +from_base := proc(str, base) + local char; + local result := 0; + for char in str do + result *= base; + result += find_digit(char); + end do; + return result; +end proc: diff --git a/Task/Non-decimal-radices-Convert/R/non-decimal-radices-convert.r b/Task/Non-decimal-radices-Convert/R/non-decimal-radices-convert.r new file mode 100644 index 0000000000..5b09d00536 --- /dev/null +++ b/Task/Non-decimal-radices-Convert/R/non-decimal-radices-convert.r @@ -0,0 +1,26 @@ +int2str <- function(x, b) { + if(x==0) return("0") + if(x<0) return(paste0("-", base(-x,b))) + + map <- c(as.character(0:9), letters) + res <- "" + while (x>0) { + res <- c(map[x %% b + 1], res) + x <- x %/% b + } + return(paste(res, collapse="")) +} + +str2int <- function(s, b) { + map <- c(as.character(0:9), letters) + s <- strsplit(s,"")[[1]] + res <- sapply(s, function(x) which(map==x)) + res <- as.vector((res-1) %*% b^((length(res)-1):0)) + return(res) +} + +## example: convert 255 to hex (ff): +int2str(255, 16) + +## example: convert "1a" in base 16 to integer (26): +str2int("1a", 16) diff --git a/Task/Non-decimal-radices-Convert/Ring/non-decimal-radices-convert.ring b/Task/Non-decimal-radices-Convert/Ring/non-decimal-radices-convert.ring new file mode 100644 index 0000000000..af7e3c688f --- /dev/null +++ b/Task/Non-decimal-radices-Convert/Ring/non-decimal-radices-convert.ring @@ -0,0 +1,32 @@ +# Project : Non-decimal radices/Convert +# Date : 2017/10/20 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +see "0 (decimal) -> " + hex(0) + " (base 16)" + nl +see "26 (decimal) -> " + hex(26) + " (base 16)" + nl +see "383 (decimal) -> " + hex(383) + " (base 16)" + nl +see "26 (decimal) -> " + tobase(26, 2) + " (base 2)" + nl +see "383 (decimal) -> " + tobase(383, 2) + " (base 2)" + nl +see "1a (base 16) -> " + dec("1a") + " (decimal)" + nl +see "1A (base 16) -> " + dec("1A") + " (decimal)" + nl +see "17f (base 16) -> " + dec("17f") + " (decimal)" + nl +see "101111111 (base 2) -> " + bintodec("101111111") + " (decimal)" + nl + +func tobase(nr, base) + binary = 0 + i = 1 + while(nr != 0) + remainder = nr % base + nr = floor(nr/base) + binary= binary + (remainder*i) + i = i*10 + end + return string(binary) + +func bintodec(bin) + binsum = 0 + for n=1 to len(bin) + binsum = binsum + number(bin[n]) *pow(2, len(bin)-n) + next + return binsum diff --git a/Task/Non-decimal-radices-Convert/Scala/non-decimal-radices-convert.scala b/Task/Non-decimal-radices-Convert/Scala/non-decimal-radices-convert.scala new file mode 100644 index 0000000000..83317d4a3e --- /dev/null +++ b/Task/Non-decimal-radices-Convert/Scala/non-decimal-radices-convert.scala @@ -0,0 +1,3 @@ +def backToBig(num: String, oldBase: Int): BigInt = BigInt(num, oldBase) + +def bigToBase(num: BigInt, newBase: Int): String = num.toString(newBase) diff --git a/Task/Non-decimal-radices-Input/Scala/non-decimal-radices-input.scala b/Task/Non-decimal-radices-Input/Scala/non-decimal-radices-input.scala new file mode 100644 index 0000000000..5eb738c1dd --- /dev/null +++ b/Task/Non-decimal-radices-Input/Scala/non-decimal-radices-input.scala @@ -0,0 +1,5 @@ +object Main extends App { + + val (s, bases) = ("100", Seq(2, 8, 10, 16, 19, 36)) + bases.foreach(base => println(f"String $s in base $base%2d is $BigInt(s, base)%5d")) +} diff --git a/Task/Non-decimal-radices-Output/Julia/non-decimal-radices-output.julia b/Task/Non-decimal-radices-Output/Julia/non-decimal-radices-output.julia index 7ccea25bb9..4e42366785 100644 --- a/Task/Non-decimal-radices-Output/Julia/non-decimal-radices-output.julia +++ b/Task/Non-decimal-radices-Output/Julia/non-decimal-radices-output.julia @@ -1,6 +1,6 @@ -hi = 50 -println("Primes \u2264 ", hi, " written in common bases.") -println(" bin oct dec hex") -for i in primes(hi) - println(@sprintf("%8s %4s %2s %2s", bin(i), oct(i), dec(i), hex(i))) +using Primes +println("Primes ≤ $hi written in common bases.") +@printf("%8s%8s%8s%8s", "bin", "oct", "dec", "hex") +for i in primes(50) + @printf("%8s%8s%8s%8s\n", bin(i), oct(i), dec(i), hex(i)) end diff --git a/Task/Non-decimal-radices-Output/Ring/non-decimal-radices-output.ring b/Task/Non-decimal-radices-Output/Ring/non-decimal-radices-output.ring index e35db044f2..f787b31f25 100644 --- a/Task/Non-decimal-radices-Output/Ring/non-decimal-radices-output.ring +++ b/Task/Non-decimal-radices-Output/Ring/non-decimal-radices-output.ring @@ -1,4 +1,4 @@ -# Project : Editing Non Decimal radices/Output +# Project : Non Decimal radices/Output # Date : 2017/09/15 # Author : Gal Zsolt (~ CalmoSoft ~) # Email : diff --git a/Task/Non-decimal-radices-Output/Scala/non-decimal-radices-output.scala b/Task/Non-decimal-radices-Output/Scala/non-decimal-radices-output.scala new file mode 100644 index 0000000000..5b9fba3e17 --- /dev/null +++ b/Task/Non-decimal-radices-Output/Scala/non-decimal-radices-output.scala @@ -0,0 +1,9 @@ +object Main extends App { + val radices = List(2, 8, 10, 16, 19, 36) + for (base <- radices) print(f"$base%6d") + println(s"""\n${"-" * (6 * radices.length)}""") + for (i <- BigInt(0) to 35; // BigInt has a toString(radix) method + radix <- radices; + eol = if (radix == radices.last) '\n' else '\0' + ) print(f"${i.toString(radix)}%6s$eol") +} diff --git a/Task/Nth-root/Go/nth-root.go b/Task/Nth-root/Go/nth-root-1.go similarity index 100% rename from Task/Nth-root/Go/nth-root.go rename to Task/Nth-root/Go/nth-root-1.go diff --git a/Task/Nth-root/Go/nth-root-2.go b/Task/Nth-root/Go/nth-root-2.go new file mode 100644 index 0000000000..d42c8c6815 --- /dev/null +++ b/Task/Nth-root/Go/nth-root-2.go @@ -0,0 +1,65 @@ +import "math/big" + +func Root(a *big.Float, n uint64) *big.Float { + limit := Exp(New(2), 256) + n1 := n-1 + n1f, rn := New(float64(n1)), Div(New(1.0), New(float64(n))) + x, x0 := New(1.0), Zero() + _ = x0 + for { + potx, t2 := Div(New(1.0), x), a + for b:=n1; b>0; b>>=1 { + if b&1 == 1 { + t2 = Mul(t2, potx) + } + potx = Mul(potx, potx) + } + x0, x = x, Mul(rn, Add(Mul(n1f, x), t2) ) + if Lesser(Mul(Abs(Sub(x, x0)), limit), x) { break } + } + return x +} + +func Abs(a *big.Float) *big.Float { + return Zero().Abs(a) +} + +func Exp(a *big.Float, e uint64) *big.Float { + result := Zero().Copy(a) + for i:=uint64(0); i 0 || return 0 + x = r / n + prevdx = r while true - y = x^(n-1) - dx = (A - y*x) / (n * y) - abs(dx) >= abs(prevdx) && return x + y = x ^ (n - 1) + dx = (r - y * x) / (n * y) + abs(dx) ≥ abs(prevdx) && return x x += dx prevdx = dx end end -@vectorize_2arg Number nthroot + +@show nthroot.(-5:2:5, 5.0) +@show nthroot.(-5:2:5, 5.0) - 5.0 .^ (1 ./ (-5:2:5)) diff --git a/Task/Nth-root/Sidef/nth-root-1.sidef b/Task/Nth-root/Sidef/nth-root-1.sidef index 4450d9ba21..56d2edad68 100644 --- a/Task/Nth-root/Sidef/nth-root-1.sidef +++ b/Task/Nth-root/Sidef/nth-root-1.sidef @@ -1,11 +1,11 @@ func nthroot(n, a, precision=1e-5) { - var x = 1; - var prev = 0; + var x = 1.float + var prev = 0.float while ((prev-x).abs > precision) { prev = x; - x = (((n-1)*prev + a/(prev**(n-1))) / n); - }; - return x; + x = (((n-1)*prev + a/(prev**(n-1))) / n) + } + return x } -say nthroot(5, 34); # => 2.024397458501034082599817835297912829678 +say nthroot(5, 34) # => 2.024397458501034082599817835297912829678314204 diff --git a/Task/Nth-root/Sidef/nth-root-2.sidef b/Task/Nth-root/Sidef/nth-root-2.sidef index 38b6df9118..d2678d4190 100644 --- a/Task/Nth-root/Sidef/nth-root-2.sidef +++ b/Task/Nth-root/Sidef/nth-root-2.sidef @@ -1,6 +1,6 @@ func nthroot_fast(n, a, precision=1e-5) { - { a = nthroot(2, a, precision) } * int(n-1); - a ** (2**int(n-1) / n); + { a = nthroot(2, a, precision) } * int(n-1) + a ** (2**int(n-1) / n) } -say nthroot_fast(5, 34, 1e-64); # => 2.024397458499885042510817245541937419115 +say nthroot_fast(5, 34, 1e-64) # => 2.02439745849988504251081724554193741911462170107 diff --git a/Task/Nth/AppleScript/nth.applescript b/Task/Nth/AppleScript/nth.applescript index c1b8708a16..c03fc00dfd 100644 --- a/Task/Nth/AppleScript/nth.applescript +++ b/Task/Nth/AppleScript/nth.applescript @@ -1,4 +1,4 @@ --- ORDINAL STRINGS +-- ORDINAL STRINGS ----------------------------------------------------------- -- ordinalString :: Int -> String on ordinalString(n) @@ -16,50 +16,26 @@ on ordinalSuffix(n) end if end ordinalSuffix - - --- TEST +-- TEST ---------------------------------------------------------------------- on run -- showOrdinals :: [Int] -> [String] script showOrdinals - on lambda(lstInt) + on |λ|(lstInt) map(ordinalString, lstInt) - end lambda + end |λ| end script map(showOrdinals, ¬ - map(tupleRange, ¬ + map(uncurry(enumFromTo), ¬ [[0, 25], [250, 265], [1000, 1025]])) - end run +-- GENERIC FUNCTIONS --------------------------------------------------------- - --- GENERIC FUNCTIONS - --- map :: (a -> b) -> [a] -> [b] -on map(f, xs) - tell mReturn(f) - set lng to length of xs - set lst to {} - repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) - end repeat - return lst - end tell -end map - --- tupleRange :: (Int, Int) -> [Int] -on tupleRange(lstPair) - set {m, n} to lstPair - - range(m, n) -end tupleRange - --- range :: Int -> Int -> [Int] -on range(m, n) - if n < m then +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if m > n then set d to -1 else set d to 1 @@ -69,7 +45,19 @@ on range(m, n) set end of lst to i end repeat return lst -end range +end enumFromTo + +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Script @@ -78,7 +66,17 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn + +-- uncurry :: Handler (a -> b -> c) -> Script |λ| ((a, b) -> c) +on uncurry(f) + script + on |λ|(xy) + set {x, y} to xy + mReturn(f)'s |λ|(x, y) + end |λ| + end script +end uncurry diff --git a/Task/Nth/Elena/nth.elena b/Task/Nth/Elena/nth.elena new file mode 100644 index 0000000000..f6e789367e --- /dev/null +++ b/Task/Nth/Elena/nth.elena @@ -0,0 +1,29 @@ +import extensions. +import system'math. +import system'routines. + +extension op +{ + ordinalize + [ + int i := self absolute. + if ((11,12,13) ifExists(i mod:100)) + [ + ^ i literal + "th". + ]. + + (i mod:10) => + 1 [ ^ i literal + "st" ]; + 2 [ ^ i literal + "nd" ]; + 3 [ ^ i literal + "rd" ]. + + ^ i literal + "th". + ] +} + +program = +[ + console printLine(Range new(0,26); selectBy:%"op.ordinalize"). + console printLine(Range new(250,26); selectBy:%"op.ordinalize"). + console printLine(Range new(1000,26); selectBy:%"op.ordinalize"). +]. diff --git a/Task/Nth/Fortran/nth.f b/Task/Nth/Fortran/nth.f index c39ebae344..103d92be2f 100644 --- a/Task/Nth/Fortran/nth.f +++ b/Task/Nth/Fortran/nth.f @@ -74,8 +74,10 @@ contains if (n < 1000) then if ((10 .le. tens) .and. (tens .lt. 20)) then ordinate = a // "'" // ateen(ones_index:ones_index+1) + ! ^^^^^^ remove these characters to remove the important ' else ordinate = a // "'" // a09(ones_index:ones_index+1) + ! ^^^^^^ remove these characters to remove the important ' end if else if ((10 .le. tens) .and. (tens .lt. 20)) then diff --git a/Task/Nth/GW-BASIC/nth.gw-basic b/Task/Nth/GW-BASIC/nth.gw-basic new file mode 100644 index 0000000000..7a3f2175f6 --- /dev/null +++ b/Task/Nth/GW-BASIC/nth.gw-basic @@ -0,0 +1,28 @@ +10 ' N'th +20 LET LOLIM% = 0 +30 LET HILIM% = 25 +40 GOSUB 1000 +50 LET LOLIM% = 250 +60 LET HILIM% = 265 +70 GOSUB 1000 +80 LET LOLIM% = 1000 +90 LET HILIM% = 1025 +100 GOSUB 1000 +110 END + +995 ' Print images +1000 FOR I% = LOLIM% TO HILIM% +1010 LET NR% = I% +1020 GOSUB 1500 +1030 LET SI$ = STR$(I%) +1040 PRINT RIGHT$(SI$, LEN(SI$) - 1); SUF$; " "; +1050 NEXT I% +1060 PRINT +1070 RETURN + +1495 ' Get suffix +1500 IF (NR% MOD 10 = 1) AND (NR% MOD 100 <> 11) THEN LET SUF$ = "st": GOTO 2000 +1600 IF (NR% MOD 10 = 2) AND (NR% MOD 100 <> 12) THEN LET SUF$ = "nd": GOTO 2000 +1700 IF (NR% MOD 10 = 3) AND (NR% MOD 100 <> 13) THEN LET SUF$ = "rd": GOTO 2000 +1800 LET SUF$ = "th" +2000 RETURN diff --git a/Task/Nth/Julia/nth-1.julia b/Task/Nth/Julia/nth-1.julia index 52fea395b5..fba188bd05 100644 --- a/Task/Nth/Julia/nth-1.julia +++ b/Task/Nth/Julia/nth-1.julia @@ -1,12 +1,12 @@ -function sprintfordinal{T<:Integer}(n::T) - const sfixes = ["st", "nd", "rd"] - 0 <= n || throw(ArgumentError("number to be formatted must be ≥ 0, got $n")) - u = n%10 - t = div(n, 10)%10 - if 3 < u || u == 0 || t == 1 - sf = "th" +function ordinal(n::Integer) + n < 0 && throw(DomainError()) + suffixes = ("st", "nd", "rd") + u = n % 10 + t = n ÷ 10 % 10 + if u > 3 || u == 0 || t == 1 + suf = "th" else - sf = sfixes[u] + suf = suffixes[u] end - @sprintf "%d%s" n sf + return string(n, suf) end diff --git a/Task/Nth/Julia/nth-2.julia b/Task/Nth/Julia/nth-2.julia index e8de2a3961..a973d466b7 100644 --- a/Task/Nth/Julia/nth-2.julia +++ b/Task/Nth/Julia/nth-2.julia @@ -1,24 +1,17 @@ println("Tests of ordinal formatting of integers.") for (i, n) in enumerate(0:25) - if (i-1)%10 == 0 - print("\n ") - end - print(@sprintf("%7s", sprintfordinal(n))) + (i - 1) % 10 == 0 && println() + @printf("%7s", ordinal(n)) end -println() +println() for (i, n) in enumerate(250:265) - if (i-1)%10 == 0 - print("\n ") - end - print(@sprintf("%7s", sprintfordinal(n))) + (i - 1) % 10 == 0 && println() + @printf("%7s", ordinal(n)) end -println() -for (i, n) in enumerate(1000:1025) - if (i-1)%10 == 0 - print("\n ") - end - print(@sprintf("%7s", sprintfordinal(n))) -end println() +for (i, n) in enumerate(1000:1025) + (i - 1) % 10 == 0 && println() + @printf("%7s", ordinal(n)) +end diff --git a/Task/Nth/Modula-2/nth.mod2 b/Task/Nth/Modula-2/nth.mod2 new file mode 100644 index 0000000000..1174dd85ff --- /dev/null +++ b/Task/Nth/Modula-2/nth.mod2 @@ -0,0 +1,45 @@ +MODULE Nth; + +FROM STextIO IMPORT + WriteString, WriteLn; +FROM WholeStr IMPORT + IntToStr; + +PROCEDURE Suffix(N: CARDINAL; VAR OUT Destination: ARRAY OF CHAR); +VAR + NMod10, NMod100: CARDINAL; +BEGIN + NMod10 := N MOD 10; + NMod100 := N MOD 100; + IF (NMod10 = 1) AND (NMod100 <> 11) THEN + Destination := "st"; + ELSIF (NMod10 = 2) AND (NMod100 <> 12) THEN + Destination := "nd"; + ELSIF (NMod10 = 3) AND (NMod100 <> 13) THEN + Destination := "rd"; + ELSE + Destination := "th"; + END; +END Suffix; + +PROCEDURE PrintImages(LoLim, HiLim: CARDINAL); +VAR + I: CARDINAL; + IString: ARRAY [0 .. 15] OF CHAR; + ISuff: ARRAY [0 .. 1] OF CHAR; +BEGIN + FOR I := LoLim TO HiLim DO + IntToStr(I, IString); + Suffix(I, ISuff); + WriteString(IString); + WriteString(ISuff); + WriteString(" "); + END; + WriteLn; +END PrintImages; + +BEGIN + PrintImages( 0, 25); + PrintImages( 250, 265); + PrintImages(1000, 1025); +END Nth. diff --git a/Task/Nth/Rust/nth.rust b/Task/Nth/Rust/nth.rust index f6245eca0f..964fda4928 100644 --- a/Task/Nth/Rust/nth.rust +++ b/Task/Nth/Rust/nth.rust @@ -1,26 +1,20 @@ -fn nth(num: i32) -> String { +fn nth(num: isize) -> String { format!("{}{}", num, match (num % 10, num % 100) { - (1, 11) => "th", - (1, _) => "st", - (2, 12) => "th", - (2, _) => "nd", - (3, 13) => "th", - (3, _) => "rd", - _ => "th" + (1, 11) | (2, 12) | (3, 13) => "th", + (1, _) => "st", + (2, _) => "nd", + (3, _) => "rd", + _ => "th", }) } fn main() { - let ranges = vec![ - (0, 26), - (250, 266), - (1000, 1026) - ]; - for &(s, e) in ranges.iter() { + let ranges = [(0, 26), (250, 266), (1000, 1026)]; + for &(s, e) in &ranges { println!("[{}, {}) :", s, e); for i in s..e { print!("{}, ", nth(i)); } - println!(""); + println!(); } } diff --git a/Task/Nth/Stata/nth.stata b/Task/Nth/Stata/nth.stata new file mode 100644 index 0000000000..2de559c1bc --- /dev/null +++ b/Task/Nth/Stata/nth.stata @@ -0,0 +1,18 @@ +mata +function maps(f,a) { + nr = rows(a) + nc = cols(a) + b = J(nr,nc,"") + for (i=1;i<=nr;i++) { + for (j=1;j<=nc;j++) b[i,j] = (*f)(a[i,j]) + } + return(b) +} + +function nth(n) { + k = max((min((mod(n-1,10)+1,4)),4*(mod(n-10,100)<10))) + return(strofreal(n)+("st","nd","rd","th")[k]) +} + +maps(&nth(),((0::25),(250::275),(1000::1025))) +end diff --git a/Task/Null-object/AutoIt/null-object.autoit b/Task/Null-object/AutoIt/null-object.autoit new file mode 100644 index 0000000000..0f12e8a0e5 --- /dev/null +++ b/Task/Null-object/AutoIt/null-object.autoit @@ -0,0 +1,2 @@ +Local $object = Null +If $object = Null Then MsgBox(0, "NULL", "Object is null") diff --git a/Task/Null-object/Haskell/null-object-4.hs b/Task/Null-object/Haskell/null-object-4.hs new file mode 100644 index 0000000000..5644056ead --- /dev/null +++ b/Task/Null-object/Haskell/null-object-4.hs @@ -0,0 +1,4 @@ +add_two_maybe_numbers x y do + a <- x + b <- y + return (a+b) diff --git a/Task/Null-object/Haskell/null-object-5.hs b/Task/Null-object/Haskell/null-object-5.hs new file mode 100644 index 0000000000..f33ab55328 --- /dev/null +++ b/Task/Null-object/Haskell/null-object-5.hs @@ -0,0 +1,4 @@ +*Main> add_two_maybe_numbers (Just 2) (Just 3) +Just 5 +*Main> add_two_maybe_numbers (Just 2) Nothing +Nothing diff --git a/Task/Null-object/Visual-Basic/null-object-1.vb b/Task/Null-object/Visual-Basic/null-object-1.vb new file mode 100644 index 0000000000..f7e403e4d1 --- /dev/null +++ b/Task/Null-object/Visual-Basic/null-object-1.vb @@ -0,0 +1,15 @@ +Public Sub Main() +Dim c As VBA.Collection + +' initial state: Nothing +Debug.Assert c Is Nothing + +' create an instance +Set c = New VBA.Collection +Debug.Assert Not c Is Nothing + +' release the instance +Set c = Nothing +Debug.Assert c Is Nothing + +End Sub diff --git a/Task/Null-object/Visual-Basic/null-object-2.vb b/Task/Null-object/Visual-Basic/null-object-2.vb new file mode 100644 index 0000000000..56d81efb6f --- /dev/null +++ b/Task/Null-object/Visual-Basic/null-object-2.vb @@ -0,0 +1,17 @@ +Public Sub Main() +Dim v As Variant + +' initial state: Empty +Debug.Assert IsEmpty(v) +Debug.Assert VarType(v) = vbEmpty + +v = 1& +Debug.Assert VarType(v) = vbLong + +' assigning the Null state +v = Null +' checking for Null state +Debug.Assert IsNull(v) +Debug.Assert VarType(v) = vbNull + +End Sub diff --git a/Task/Number-names/AWK/number-names.awk b/Task/Number-names/AWK/number-names.awk index 80b06f05e5..6b2beae9d7 100644 --- a/Task/Number-names/AWK/number-names.awk +++ b/Task/Number-names/AWK/number-names.awk @@ -20,6 +20,7 @@ function numtowords(n, minus,str) { str = intowords(n) } gsub(/ /," ",str) + gsub(/ $/,"",str) return(minus str) } function intowords(n) { diff --git a/Task/Number-names/Go/number-names.go b/Task/Number-names/Go/number-names.go index 9527cfaa07..4c9b83504d 100644 --- a/Task/Number-names/Go/number-names.go +++ b/Task/Number-names/Go/number-names.go @@ -3,52 +3,56 @@ package main import "fmt" func main() { - for _, n := range []int64{12, 1048576, 9e18} { - fmt.Println(say(n)) - } + for _, n := range []int64{12, 1048576, 9e18, -2, 0} { + fmt.Println(say(n)) + } } -var small = []string{"", "one", "two", "three", "four", "five", "six", - "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", - "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"} -var tens = []string{"ones", "ten", "twenty", "thirty", "forty", - "fifty", "sixty", "seventy", "eighty", "ninety"} -var illions = []string{"thousand", "million", "billion", - "trillion", "quadrillion", "quintillion"} +var small = [...]string{"zero", "one", "two", "three", "four", "five", "six", + "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", + "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"} +var tens = [...]string{"", "", "twenty", "thirty", "forty", + "fifty", "sixty", "seventy", "eighty", "ninety"} +var illions = [...]string{"", " thousand", " million", " billion", + " trillion", " quadrillion", " quintillion"} func say(n int64) string { - switch { - case n < 1: - case n < 20: - return small[n] - case n < 100: - t := tens[n/10] - s := n % 10 - if s > 0 { - t += " " + small[s] - } - return t - case n < 1000: - h := small[n/100] + " hundred" - s := n % 100 - if s > 0 { - h += " " + say(s) - } - return h - default: - sx := say(n % 1000) - for i := 0; n >= 1000; i++ { - n /= 1000 - p := n % 1000 - if p > 0 { - ix := say(p) + " " + illions[i] - if sx > "" { - ix += " " + sx - } - sx = ix - } - } - return sx - } - return "" + var t string + if n < 0 { + t = "negative " + // Note, for math.MinInt64 this leaves n negative. + n = -n + } + switch { + case n < 20: + t += small[n] + case n < 100: + t += tens[n/10] + s := n % 10 + if s > 0 { + t += "-" + small[s] + } + case n < 1000: + t += small[n/100] + " hundred" + s := n % 100 + if s > 0 { + t += " " + say(s) + } + default: + // work right-to-left + sx := "" + for i := 0; n > 0; i++ { + p := n % 1000 + n /= 1000 + if p > 0 { + ix := say(p) + illions[i] + if sx != "" { + ix += " " + sx + } + sx = ix + } + } + t += sx + } + return t } diff --git a/Task/Number-names/Java/number-names-1.java b/Task/Number-names/Java/number-names-1.java index 98195269c9..7ff9095305 100644 --- a/Task/Number-names/Java/number-names-1.java +++ b/Task/Number-names/Java/number-names-1.java @@ -1,46 +1,60 @@ -public class Int2Words { - static String[] small = {"one", "two", "three", "four", "five", "six", - "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", - "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}; - static String[] tens = {"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", - "ninety"}; - static String[] big = {"thousand", "million", "billion", "trillion"}; +public enum IntToWords { + ; + + private static final String[] small = { + "", "one", "two", "three", "four", + "five", "six", "seven", "eight", "nine", + "ten", "eleven", "twelve", "thirteen", "fourteen", + "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}; + private static final String[] tens = { + "", "", "twenty", "thirty", "forty", + "fifty", "sixty", "seventy", "eighty", "ninety"}; + private static final String[] big = { + "", "thousand", "million", "billion", "trillion", + "quadrillion", "quintillion"}; public static void main(String[] args) { - System.out.println(int2Text(900000001)); - System.out.println(int2Text(1234567890)); - System.out.println(int2Text(-987654321)); System.out.println(int2Text(0)); + System.out.println(int2Text(10)); + System.out.println(int2Text(30)); + System.out.println(int2Text(47)); + System.out.println(int2Text(100)); + System.out.println(int2Text(999)); + System.out.println(int2Text(1000)); + System.out.println(int2Text(9999)); + System.out.println(int2Text(123_456)); + System.out.println(int2Text(900_000_001)); + System.out.println(int2Text(1_234_567_890)); + System.out.println(int2Text(-987_654_321)); + System.out.println(int2Text(Long.MAX_VALUE)); + System.out.println(int2Text(Long.MIN_VALUE)); } public static String int2Text(long number) { - long num = 0; - String outP = ""; - int unit = 0; - long tmpLng1 = 0; + StringBuilder sb = new StringBuilder(); if (number == 0) { return "zero"; } - num = Math.abs(number); + long num = -Math.abs(number); - for (;;) { - tmpLng1 = num % 100; - if (tmpLng1 >= 1 && tmpLng1 <= 19) { - outP = small[(int) tmpLng1 - 1] + " " + outP; - } else if (tmpLng1 >= 20 && tmpLng1 <= 99) { - if (tmpLng1 % 10 == 0) { - outP = tens[(int) (tmpLng1 / 10) - 2] + " " + outP; + int unit = 1; + while (true) { + int rem100 = (int) -(num % 100); + if (rem100 >= 20) { + if (rem100 % 10 == 0) { + sb.insert(0, tens[rem100 / 10] + " "); } else { - outP = tens[(int) (tmpLng1 / 10) - 2] + "-" - + small[(int) (tmpLng1 % 10) - 1] + " " + outP; + sb.insert(0, tens[rem100 / 10] + "-" + small[rem100 % 10] + " "); } + } else if (rem100 != 0) { + sb.insert(0, small[rem100] + " "); } - tmpLng1 = (num % 1000) / 100; - if (tmpLng1 != 0) { - outP = small[(int) tmpLng1 - 1] + " hundred " + outP; + int hundreds = (int) -(num % 1000) / 100; + if (hundreds != 0) { + sb.insert(0, small[hundreds] + " hundred "); } num /= 1000; @@ -48,17 +62,17 @@ public class Int2Words { break; } - tmpLng1 = num % 1000; - if (tmpLng1 != 0) { - outP = big[unit] + " " + outP; + int rem1000 = (int) -(num % 1000); + if (rem1000 != 0) { + sb.insert(0, big[unit] + " "); } unit++; } if (number < 0) { - outP = "negative " + outP; + sb.insert(0, "negative "); } - return outP.trim(); + return sb.toString().trim(); } } diff --git a/Task/Number-names/JavaScript/number-names.js b/Task/Number-names/JavaScript/number-names.js new file mode 100644 index 0000000000..176d8b1b16 --- /dev/null +++ b/Task/Number-names/JavaScript/number-names.js @@ -0,0 +1,44 @@ +const divMod = y => x => [Math.floor(y/x), y % x]; + +const sayNumber = value => { + let name = ''; + let quotient, remainder; + const dm = divMod(value); + const units = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', + 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', + 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']; + const tens = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', + 'seventy', 'eighty', 'ninety']; + const big = [...['', 'thousand'], ...['m', 'b', 'tr', 'quadr', 'quint', + 'sext', 'sept', 'oct', 'non', 'dec'].map(e => `${e}illion`)]; + + if (value < 0) { + name = `negative ${sayNumber(-value)}` + } else if (value < 20) { + name = units[value] + } else if (value < 100) { + [quotient, remainder] = dm(10); + name = `${tens[quotient]} ${units[remainder]}`.replace(' zero', ''); + } else if (value < 1000) { + [quotient, remainder] = dm(100); + name = `${sayNumber(quotient)} hundred and ${sayNumber(remainder)}` + .replace(' and zero', '') + } else { + const chunks = []; + const text = []; + while (value !== 0) { + [value, remainder] = divMod(value)(1000); + chunks.push(remainder); + } + chunks.forEach((e,i) => { + if (e > 0) { + text.push(`${sayNumber(e)}${i === 0 ? '' : ' ' + big[i]}`); + if (i === 0 && e < 100) { + text.push('and'); + } + } + }); + name = text.reverse().join(', ').replace(', and,', ' and'); + } + return name; +}; diff --git a/Task/Number-reversal-game/Astro/number-reversal-game.astro b/Task/Number-reversal-game/Astro/number-reversal-game.astro index 1b2ed1546b..329cd8f5ad 100644 --- a/Task/Number-reversal-game/Astro/number-reversal-game.astro +++ b/Task/Number-reversal-game/Astro/number-reversal-game.astro @@ -1,18 +1,10 @@ -''' -number reversal game - Given a jumbled list of the numbers 1 to 9 - Show the list. - Ask the player how many digits from the left to reverse. - Reverse those digits then ask again. - until all the digits end up in ascending order. -'''.print() - -var data = list('123456789') -var trials = 0 -while data == sorted(data): random.shuffle data +print '# Number reversal game' +var data, trials = list('123456789'), 0 +while data == sorted(data): + random.shuffle data while data != sorted(data): - trials += 1 - flip = int scan '#$trials: LIST: $(join data) Flip how many?: ' - data[:flip] = data[!flip:] + trials += 1 + flip = int input '#$trials: LIST: $(join data) Flip how many?: ' + data[:flip] = data[!flip:] print '\nYou took $trials attempts to put digits in order!' diff --git a/Task/Number-reversal-game/REXX/number-reversal-game.rexx b/Task/Number-reversal-game/REXX/number-reversal-game.rexx index 5d7e8f315b..0018271d08 100644 --- a/Task/Number-reversal-game/REXX/number-reversal-game.rexx +++ b/Task/Number-reversal-game/REXX/number-reversal-game.rexx @@ -1,29 +1,29 @@ -/*REXX pgm (a game): reverse a jumbled set of numerals until they're in order.*/ -signal on halt /*allows the CBLF to HALT the program.*/ -___=copies('─',9) /*a fence used for computer's messages.*/ -say ___ "This game will show you nine random unique digits (1 ──► 9), and you'll" -say ___ "enter one of those digits which will reverse all the digits up to (and" -say ___ "including) that digit. The game's objective is to get all the" -say ___ "digits in ascending order with the fewest tries. Here are your digits:" -ok=123456789 /*the result that the string should be.*/ -$= - do until length($)==9 /*build a random unique numeric string.*/ - _=random(1,9); if pos(_,$)\==0 then iterate /*only use a dig once.*/ - $=$ || _ /*construct a string. */ - if $==ok then $= /*string can't be in order, start over.*/ - end /*until ··· */ +/*REXX program (a game): reverse a jumbled set of decimal digits 'til they're in order.*/ +signal on halt /*allows the CBLF to HALT the program.*/ +___= copies('─', 9); pad=left('', 9) /*a fence used for computer's messages.*/ +say ___ "This game will show you nine random unique digits (1 ──► 9), and you'll enter" +say ___ "one of those digits which will reverse all the digits from the left-most digit" +say ___ "up to (and including) that decimal digit. The game's objective is to get all" +say ___ "of the digits in ascending order with the fewest tries. Here're your digits:" +ok= 123456789 /*the result that the string should be.*/ +$= /* ◄─── decimal target to be generated.*/ + do until length($)==9; _=random(1, 9) /*build a random unique numeric string.*/ + if pos(_, $) \== 0 then iterate /*¬ unique? Only use a decimal dig once*/ + $=$ || _ /*construct a string of unique digits. */ + if $==ok then $= /*string can't be in order, start over.*/ + end /*until*/ - do score=1 until $==ok /* [↓] display the digs and the prompt*/ - say; say ___ $ right('please enter a digit (or Quit):', 50) - pull x .; ?=left(x,1) /*get a decimal digit (maybe) from CBLF*/ - if abbrev('QUIT',x,1) then signal halt - if length(x)>1 then do; say ___ 'oops, invalid input! ' x; iterate; end - if x=='' then iterate /*try again, CBLF didn't enter anything*/ - g=pos(?,$) /*validate if the input digit is legal.*/ - if g==0 then say ___ 'oops, invalid digit! ' ? - else $=reverse(left($, g))substr($, g+1) + do score=1 until $==ok; say /* [↓] display the digits & the prompt*/ + say ___ $ right('please enter a digit (or Quit):', 50) + parse pull ox . 1 ux . 1 x .; upper ux /*get a decimal digit (maybe) from CBLF*/ + if abbrev('QUIT', ux, 1) then signal halt /*does the CBLF want to quit this game?*/ + if length(x)>1 then do; say ___ pad '***error*** invalid input: ' ox; iterate; end + if x='' then iterate /*try again, CBLF didn't enter anything*/ + g=pos(x, $) /*validate if the input digit is legal.*/ + if g==0 then say ___ pad '***error*** invalid digit: ' ox + else $=strip(reverse(left($,g))substr($,g+1)) /*reverse some (or all) digits*/ end /*score*/ -say; say ___ $; say; say center(' Congratulations! ',70,"═"); say -say ___ 'Your score was' score; exit /*stick a fork in it, we're all done. */ -halt: say ___ 'quitting.'; exit /* " " " " " " " " */ +say; say ___ $; say; say center(' Congratulations! ', 70, "═"); say +say ___ pad 'Your score was' score; exit /*stick a fork in it, we're all done. */ +halt: say ___ pad 'quitting.'; exit /* " " " " " " " " */ diff --git a/Task/Number-reversal-game/Ring/number-reversal-game.ring b/Task/Number-reversal-game/Ring/number-reversal-game.ring new file mode 100644 index 0000000000..686009cc68 --- /dev/null +++ b/Task/Number-reversal-game/Ring/number-reversal-game.ring @@ -0,0 +1,53 @@ +# Project : Number reversal game +# Date : 2017/12/02 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +rever = 1:9 +leftrever = [] +for n = 1 to len(rever) + rnd = random(8) + 1 + temp = rever[n] + rever[n] = rever[rnd] + rever[rnd] = temp +next +see rever +see nl +while true + num = 0 + leftrever = [] + showarray(rever) + see " : Reverse how many = " + give r + r = number(r) + for n = 1 to r + add(leftrever, rever[n]) + next + leftrever = reverse(leftrever) + for pos = 1 to r + rever[pos] = leftrever[pos] + next + for m = 1 to len(rever) + if rever[m] = m + num = num + 1 + ok + next + if num = len(rever) + exit + ok +end +see "You took " + num + " attempts." + nl + +func swap(a, b) + temp = a + a = b + b = temp + return [a, b] + +func showarray(vect) + svect = "" + for n = 1 to len(vect) + svect = svect + vect[n] + " " + next + svect = left(svect, len(svect) - 1) + see svect diff --git a/Task/Numeric-error-propagation/Perl-6/numeric-error-propagation.pl6 b/Task/Numeric-error-propagation/Perl-6/numeric-error-propagation.pl6 index 29c27396fd..34d481d7b2 100644 --- a/Task/Numeric-error-propagation/Perl-6/numeric-error-propagation.pl6 +++ b/Task/Numeric-error-propagation/Perl-6/numeric-error-propagation.pl6 @@ -19,7 +19,7 @@ multi approx($x) { Approx.new: :$x, :c[0 xx +@INDEP] } # Each ± gets its own source slot. multi infix:<±>($a, $b) { .push: 0 for @INDEP; # lengthen older component lists - my $c = [ 0 xx @INDEP, $b ]; + my $c = [ flat 0 xx @INDEP, $b ]; @INDEP.push: $c; # add new component list approx $a, $c; diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/MATLAB/numerical-integration-gauss-legendre-quadrature.m b/Task/Numerical-integration-Gauss-Legendre-Quadrature/MATLAB/numerical-integration-gauss-legendre-quadrature.m new file mode 100644 index 0000000000..9503bac3ce --- /dev/null +++ b/Task/Numerical-integration-Gauss-Legendre-Quadrature/MATLAB/numerical-integration-gauss-legendre-quadrature.m @@ -0,0 +1,74 @@ +%Integration using Gauss-Legendre quad +%Does almost the same as 'integral' in MATLAB +function y=GLGD_int(fun,xmin,xmax,n) +%fun: the intergrand as a function handle +%xmin: lower boundary of integration +%xmax: upper boundary of integration +%n: order of polynomials used (number of integration ponts) +[x_IP,weight]=GLGD_para(n); +%assign global coordinates to the integraton points +x_eval=x_IP*(xmax-xmin)/2+(xmax+xmin)/2; +y=0; +for aa=1:n + y=y+feval(fun,x_eval(aa))*weight(aa)*(xmax-xmin)/2; +end +end + +function [x_IP,weight]=GLGD_para(n) +%n: the order of the polynomial +x_IP=legendreRoot(n,10^(-16)); +weight=2./(1-x_IP.^2)./diff_legendrePoly(x_IP,n).^2; +end + +%roots of the Legendre Polynomial using Newton-Raphson +function x_IP=legendreRoot(n,tol) +%n: order of the polynomial +%tol: tolerence of the error +if n<2 + disp('No root can be found'); +else + root=zeros(1,floor(n/2)); + for aa=1:floor(n/2) %iterate to find half of the roots + x=cos(pi*(aa-0.25)/(n+0.5)); + err=10*tol; + iter=0; + while (err>tol)&&(iter<1000) + dx=-legendrePoly(x,n)/diff_legendrePoly(x,n); + x=x+dx; + iter=iter+1; + err=abs(legendrePoly(x,n)); + end + root(aa)=x; + end + if mod(n,2)==0 + x_IP=[-1*root,root]; + else + x_IP=[-1*root,0,root]; + end + x_IP=sort(x_IP); +end +end + +%derivative of the Legendre Polynomial +function y=diff_legendrePoly(x_IP,n) +%n: order of the polynomial +%x_IP: coordinates of the integration points +if n==0 + y=0; +else + y=n./(x_IP.^2-1).*(x_IP.*legendrePoly(x_IP,n)-legendrePoly(x_IP,n-1)); +end +end + +%Produces Legendre Polynomials +function y=legendrePoly(x,n) +%n: order of polynomial +%x: input x +if n==0 + y=1; +elseif n==1 + y=x; +else + y=((2*n-1).*x.*legendrePoly(x,n-1)-(n-1)*legendrePoly(x,n-2))/n; +end +end diff --git a/Task/Numerical-integration/Julia/numerical-integration.julia b/Task/Numerical-integration/Julia/numerical-integration.julia index c715fd324f..3f004107b3 100644 --- a/Task/Numerical-integration/Julia/numerical-integration.julia +++ b/Task/Numerical-integration/Julia/numerical-integration.julia @@ -1,8 +1,16 @@ -function simpson(f, a,b, n) - h = (b-a)/n - s = f(a + h/2) +function simpson(f::Function, a::Number, b::Number, n::Integer) + h = (b - a) / n + s = f(a + h / 2) for i in 1:(n-1) - s += f(a + h*i + h/2) + 0.5 * f(a + h*i) + s += f(a + h * i + h / 2) + f(a + h * i) / 2 end - h/6 * (f(a) + f(b) + 4*s) + return h/6 * (f(a) + f(b) + 4*s) end + +rst = + simpson(x -> x ^ 3, 0, 1, 100), + simpson(x -> 1 / x, 1, 100, 1000), + simpson(x -> x, 0, 5000, 5_000_000), + simpson(x -> x, 0, 6000, 6_000_000) + +@show rst diff --git a/Task/Numerical-integration/Ring/numerical-integration.ring b/Task/Numerical-integration/Ring/numerical-integration.ring new file mode 100644 index 0000000000..64653bb3d4 --- /dev/null +++ b/Task/Numerical-integration/Ring/numerical-integration.ring @@ -0,0 +1,88 @@ +# Project : Numerical integration +# Date : 2018/04/087 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +decimals(8) +data = [["pow(x,3)",0,1,100], ["1/x",1, 100,1000], ["x",0,5000,5000000], ["x",0,6000,6000000]] +see "Function Range L-Rect R-Rect M-Rect Trapeze Simpson" + nl +for p = 1 to 4 + d1 = data[p][1] + d2 = data[p][2] + d3 = data[p][3] + d4 = data[p][4] + see "" + d1 + " " + d2 + " - " + d3 + " " + lrect(d1, d2, d3, d4) + " " + rrect(d1, d2, d3, d4) + see " " + mrect(d1, d2, d3, d4) + " " + trapeze(d1, d2, d3, d4) + " " + simpson(d1, d2, d3, d4) + nl +next + +func lrect(x2, a, b, n) + s = 0 + d = (b - a) / n + x = a + for i = 1 to n + eval("result = " + x2) + s = s + d * result + x = x + d + next + return s + +func rrect(x2, a, b, n) + s = 0 + d = (b - a) / n + x = a + for i = 1 to n + x = x + d + eval("result = " + x2) + s = s + d *result + next + return s + +func mrect(x2, a, b, n) + s = 0 + d = (b - a) / n + x = a + for i = 1 to n + x = x + d/2 + eval("result = " + x2) + s = s + d * result + x = x +d/2 + next + return s + +func trapeze(x2, a, b, n) + s = 0 + d = (b - a) / n + x = b + eval("result = " + x2) + f = result + x = a + eval("result = " + x2) + s = d * (f + result) / 2 + for i = 1 to n-1 + x = x + d + eval("result = " + x2) + s = s + d * result + next + return s + +func simpson(x2, a, b, n) + s1 = 0 + s = 0 + d = (b - a) / n + x = b + eval("result = " + x2) + f = result + x = a + d/2 + eval("result = " + x2) + s1 = result + for i = 1 to n-1 + x = x + d/2 + eval("result = " + x2) + s = s + result + x = x + d/2 + eval("result = " + x2) + s1 = s1 + result + next + x = a + eval("result = " + x2) + return (d / 6) * (f + result + 4 * s1 + 2 * s) diff --git a/Task/Numerical-integration/Stata/numerical-integration.stata b/Task/Numerical-integration/Stata/numerical-integration.stata new file mode 100644 index 0000000000..35ed3509db --- /dev/null +++ b/Task/Numerical-integration/Stata/numerical-integration.stata @@ -0,0 +1,41 @@ +mata +function integrate(f,a,b,n,u,v) { + s = 0 + h = (b-a)/n + m = length(u) + for (i=0; i) { + val instance1 = Person() + println(instance1) + + val instance2 = Entity() + println(instance2) + + // serialize + try { + val out = ObjectOutputStream(FileOutputStream("objects.dat")) + out.writeObject(instance1) + out.writeObject(instance2) + out.close() + println("Serialized...") + } + catch (e: IOException) { + println("Error occurred whilst serializing") + System.exit(1) + } + + // deserialize + try { + val inp = ObjectInputStream(FileInputStream("objects.dat")) + val readObject1 = inp.readObject() + val readObject2 = inp.readObject() + inp.close() + println("Deserialized...") + println(readObject1) + println(readObject2) + } + catch (e: IOException) { + println("Error occurred whilst deserializing") + System.exit(1) + } + catch (e: ClassNotFoundException) { + println("Unknown class for deserialized object") + System.exit(1) + } +} diff --git a/Task/Odd-word-problem/Ceylon/odd-word-problem.ceylon b/Task/Odd-word-problem/Ceylon/odd-word-problem.ceylon new file mode 100644 index 0000000000..c1a95ee89b --- /dev/null +++ b/Task/Odd-word-problem/Ceylon/odd-word-problem.ceylon @@ -0,0 +1,33 @@ +String[] meaning = ["what,", "is,", "the;", "meaning,", "of:", "life."]; +String[] kansas = ["we,", "are,", "not,", "in,", "kansas;", "any,", "more."]; + +shared void run() { + print("".join(reverseWords(meaning))); + print("".join(reverseWords(kansas))); +} + +String[] reverseWords(String[] words) + => recursiveReverseWords(words, []); + +String[] recursiveReverseWords(String[] remOrig, String[] revWords) + => if (nonempty remOrig) + then recursiveReverseWords(remOrig.rest, + revWords.withTrailing(reverseWordRecursive(remOrig.first.sequence(), + [], + revWords.size.even))) + else revWords; + +String reverseWordRecursive(Character[] remOldChars, Character[] revChars, Boolean isEven) + => if (nonempty remOldChars) + then let (char = remOldChars.first) reverseWordRecursive(remOldChars.rest, + conditionalAddChar(char, revChars, isEven), + isEven) + else String(revChars); + +Character[] conditionalAddChar(Character char, Character[] chars, Boolean isEven) + => if (isEven || isPunctuation(char)) + then chars.withTrailing(char) + else chars.withLeading(char); + +Boolean isPunctuation(Character char) + => ",.:;".contains(char); diff --git a/Task/Odd-word-problem/Julia/odd-word-problem.julia b/Task/Odd-word-problem/Julia/odd-word-problem.julia new file mode 100644 index 0000000000..123272be09 --- /dev/null +++ b/Task/Odd-word-problem/Julia/odd-word-problem.julia @@ -0,0 +1,33 @@ +# io = readstring(STDIN) +io = "what,is,the;meaning,of:life." +i = 0 + +readbyte!() = io[global i += 1] +writebyte(c) = print(Char(c)) + +function odd(prev::Function = () -> false) + a = readbyte!() + if !isalpha(a) + prev() + writebyte(a) + return a != '.' + end + + # delay action until later, in the shape of a closure + clos() = (writebyte(a); prev()) + + return odd(clos) +end + +function even() + while true + c = readbyte!() + writebyte(c) + if !isalpha(c) return c != '.' end + end +end + +evn = false +while evn ? odd() : even() + evn = !evn +end diff --git a/Task/Odd-word-problem/Ring/odd-word-problem.ring b/Task/Odd-word-problem/Ring/odd-word-problem.ring new file mode 100644 index 0000000000..fd3fc9bfd3 --- /dev/null +++ b/Task/Odd-word-problem/Ring/odd-word-problem.ring @@ -0,0 +1,46 @@ +# Project : Odd word problem +# Date : 2017/10/15 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +test = "what,is,the;meaning,of:life." +n1 = 1 +testarr = [] +testorigin = test +test = substr(test, ",", " ") +test = substr(test, ";", " ") +test = substr(test, ":", " ") +test = substr(test, ".", " ") + +while true + n2 = substring(test, " ", n1) + n3 = substring(test, " ", n2 + 1) + if n2>0 and n3>0 + strcut = substr(test, n2 + 1, n3 - n2) + strcut = trim(strcut) + if strcut != "" + add(testarr, strcut) + n1 = n3 + 1 + else + exit + ok + ok +end + +for n = 1 to len(testarr) + strrev = revstr(testarr[n]) + testorigin = substr(testorigin, testarr[n], strrev) +next +see testorigin + nl + +func Substring str,substr,n + newstr=right(str,len(str)-n+1) + nr = substr(newstr, substr) + return n + nr -1 + +func revstr(cStr) + cStr2 = "" + for x = len(cStr) to 1 step -1 + cStr2 += cStr[x] + next + return cStr2 diff --git a/Task/Odd-word-problem/VBA/odd-word-problem-1.vba b/Task/Odd-word-problem/VBA/odd-word-problem-1.vba new file mode 100644 index 0000000000..5e40fcb3e8 --- /dev/null +++ b/Task/Odd-word-problem/VBA/odd-word-problem-1.vba @@ -0,0 +1,35 @@ +Private Function OddWordFirst(W As String) As String +Dim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String + count = 1 + Do + flag = Not flag + l = FindNextPunct(i, W) - count + 1 + If flag Then + temp = temp & ExtractWord(W, count, l) + Else + temp = temp & ReverseWord(W, count, l) + End If + Loop While count < Len(W) + OddWordFirst = temp +End Function + +Private Function FindNextPunct(d As Integer, W As String) As Integer +Const PUNCT As String = ",;:." + Do + d = d + 1 + Loop While InStr(PUNCT, Mid(W, d, 1)) = 0 + FindNextPunct = d +End Function + +Private Function ExtractWord(W As String, c As Integer, i As Integer) As String + ExtractWord = Mid(W, c, i) + c = c + Len(ExtractWord) +End Function + +Private Function ReverseWord(W As String, c As Integer, i As Integer) As String +Dim temp As String, sep As String + temp = Left(Mid(W, c, i), Len(Mid(W, c, i)) - 1) + sep = Right(Mid(W, c, i), 1) + ReverseWord = StrReverse(temp) & sep + c = c + Len(ReverseWord) +End Function diff --git a/Task/Odd-word-problem/VBA/odd-word-problem-2.vba b/Task/Odd-word-problem/VBA/odd-word-problem-2.vba new file mode 100644 index 0000000000..f68b69b5c5 --- /dev/null +++ b/Task/Odd-word-problem/VBA/odd-word-problem-2.vba @@ -0,0 +1,39 @@ +Private Function OddWordSecond(Words As String) As String +Dim i&, count&, t$, cpt&, j&, l&, d&, f As Boolean +Const PUNCT As String = ",;:" + For i = 1 To Len(Words) + 'first word + If i = 1 Then + cpt = 1 + Do + t = t & Mid(Words, cpt, 1) + cpt = cpt + 1 + Loop While InStr(PUNCT, Mid(Words, cpt, 1)) = 0 And cpt < Len(Words) + i = cpt + t = t & Mid(Words, i, 1) + End If + If Right(t, 1) = "." Then Exit For + 'Odd words ==> reverse + While InStr(PUNCT, Mid(Words, cpt + 1, 1)) = 0 And cpt < Len(Words) + cpt = cpt + 1 + Wend + l = IIf(f = True, i, i + 1) + d = IIf(cpt = Len(Words), cpt - 1, cpt) + For j = d To l Step -1 + t = t & Mid(Words, j, 1) + Next + If cpt = Len(Words) Then t = t & ".": Exit For + f = True + i = cpt + 1 + t = t & Mid(Words, i, 1) + 'Even words + cpt = i + 1 + t = t & Mid(Words, cpt, 1) + Do + cpt = cpt + 1 + t = t & Mid(Words, cpt, 1) + Loop While InStr(PUNCT, Mid(Words, cpt, 1)) = 0 And cpt < Len(Words) + i = cpt + Next + OddWordSecond = t +End Function diff --git a/Task/Odd-word-problem/VBA/odd-word-problem-3.vba b/Task/Odd-word-problem/VBA/odd-word-problem-3.vba new file mode 100644 index 0000000000..35095defb7 --- /dev/null +++ b/Task/Odd-word-problem/VBA/odd-word-problem-3.vba @@ -0,0 +1,11 @@ +Option Explicit + +Sub Main() + Debug.Print "Input : " & "we,are;not,in,kansas;any,more." + Debug.Print "First way : " & OddWordFirst("we,are;not,in,kansas;any,more.") + Debug.Print "Second way : " & OddWordSecond("we,are;not,in,kansas;any,more.") + Debug.Print "" + Debug.Print "Input : " & "what,is,the;meaning,of:life." + Debug.Print "First way : " & OddWordFirst("what,is,the;meaning,of:life.") + Debug.Print "Second way : " & OddWordSecond("what,is,the;meaning,of:life.") +End Sub diff --git a/Task/Old-lady-swallowed-a-fly/00DESCRIPTION b/Task/Old-lady-swallowed-a-fly/00DESCRIPTION index 3408644954..93743ee8ce 100644 --- a/Task/Old-lady-swallowed-a-fly/00DESCRIPTION +++ b/Task/Old-lady-swallowed-a-fly/00DESCRIPTION @@ -4,6 +4,7 @@ Present a program which emits the lyrics to the song   ''[[wp:There Was an This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output. -;Related task: +;Related tasks: *   [[99 Bottles of Beer]] +*   [[The Twelve Days of Christmas]]

diff --git a/Task/Old-lady-swallowed-a-fly/Fortran/old-lady-swallowed-a-fly.f b/Task/Old-lady-swallowed-a-fly/Fortran/old-lady-swallowed-a-fly.f new file mode 100644 index 0000000000..f56a28da6f --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Fortran/old-lady-swallowed-a-fly.f @@ -0,0 +1,38 @@ +program fly + !A program to print the "Old lady swallowed a fly" poem + implicit none + + character(len=52), dimension(0:8,2) :: line + integer :: i,j + !Define Lines of Poem + line(1,1) = 'fly' + line(2,1) = 'spider' + line(3,1) = 'bird' + line(4,1) = 'cat' + line(5,1) = 'dog' + line(6,1) = 'goat' + line(7,1) = 'cow' + line(8,1) = 'horse' + line(0,2) = "Perhaps she'll die." + line(1,2) = "I don't know why she swallowed that fly." + line(2,2) = "That wiggled and jiggled and tickled inside her." + line(3,2) = "How absurd to swallow a bird." + line(4,2) = "Imagine that. She swallowed a cat." + line(5,2) = "What a hog to swallow a dog." + line(6,2) = "She just opened her throat and swallowed that goat." + line(7,2) = "I don't know how she swallowed that cow." + line(8,2) = "She's dead of course." + + !List each verse + verses:do i = 1,8 + write(*,*) 'There was an old lady who swallowed a '//trim(line(i,1))//"." + write(*,*) trim(line(i,2)) + !List things swallowed + swallowed:do j = i,2,-1 + write(*,*) "She swallowed the "//trim(line(j,1))//" to catch the "//trim(line(j-1,1))//"," + end do swallowed + write(*,*) trim(line(0,2)) + write(*,*) + end do verses + +end program fly diff --git a/Task/Old-lady-swallowed-a-fly/Haskell/old-lady-swallowed-a-fly.hs b/Task/Old-lady-swallowed-a-fly/Haskell/old-lady-swallowed-a-fly.hs index 470e3f8017..a58be7ec44 100644 --- a/Task/Old-lady-swallowed-a-fly/Haskell/old-lady-swallowed-a-fly.hs +++ b/Task/Old-lady-swallowed-a-fly/Haskell/old-lady-swallowed-a-fly.hs @@ -1,48 +1,16 @@ import Data.List (tails) --- Once means the phrase is only printed in the verse about that animal. --- Every means the phrase is printed for every verse. It is used for "fly", --- and could optionally be used for "spider", in the version of the song where --- "wriggled and jiggled..." is repeated every verse. --- Die is only used for the horse, and means the chain of animals won't be --- included in the verse. -data AnimalAction - = Once - | Every - | Die +animals= + ["fly.\nI don't know why she swallowed a fly.\nPerhaps she'll die.\n" + ,"spider.\nThat wiggled and jiggled and tickled inside her." + ,"bird.\t\nHow absurd, to swallow a bird." + ,"cat.\t\nImagine that. She swallowed a cat." + ,"dog.\t\nWhat a hog to swallow a dog." + ,"goat.\t\nShe just opened her throat and swallowed a goat." + ,"cow.\nI don't know how she swallowed a cow." + ,"horse.\nShe's dead, of course."] -animals = - [ ("horse", Die, "She's dead, of course!") - , ("donkey", Once, "It was rather wonky. To swallow a donkey.") - , ("cow", Once, "I don't know how. To swallow a cow.") - , ("goat", Once, "She just opened her throat. To swallow a goat.") - , ("pig", Once, "Her mouth was so big. To swallow a pig.") - , ("dog", Once, "What a hog. To swallow a dog.") - , ("cat", Once, "Fancy that. To swallow a cat.") - , ("bird", Once, "Quite absurd. To swallow a bird.") - , ("spider", Once, "That wriggled and jiggled and tickled inside her.") - , ("fly", Every, "I don't know why she swallowed the fly.") - ] - -verse :: [(String, AnimalAction, String)] -> [String] -verse ((anim, act, phrase):restAnims) = - let lns = ["I know an old lady who swallowed a " ++ anim ++ ".", phrase] - in case act of - Die -> lns - _ -> lns ++ verse' restAnims anim - -verse' :: [(String, AnimalAction, String)] -> String -> [String] -verse' [] _ = ["Perhaps she'll die."] -verse' ((anim, act, phrase):restAnims) prevAnim = - let why = "She swallowed the " ++ prevAnim ++ " to catch the " ++ anim ++ "." - lns = - case act of - Every -> [why, phrase] - _ -> [why] - in lns ++ verse' restAnims anim - -song :: [String] -song = concatMap verse . tail . reverse $ tails animals - -main :: IO () -main = putStr $ unlines song +beginnings = map ("There was an old lady who swallowed a "++) animals +lastVerse = reverse $ ["She swallowed the "++takeWhile (/='.') y++" to catch the "++ takeWhile (/='\t') x + | (x:y:_:_)<-tails animals] +main = putStr $ concatMap unlines $ zipWith (:) beginnings $ reverse $ ([]:) $ tails $ lastVerse diff --git a/Task/Old-lady-swallowed-a-fly/Julia/old-lady-swallowed-a-fly-1.julia b/Task/Old-lady-swallowed-a-fly/Julia/old-lady-swallowed-a-fly-1.julia new file mode 100644 index 0000000000..86b6193abf --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Julia/old-lady-swallowed-a-fly-1.julia @@ -0,0 +1,10 @@ +using CodecZlib + +b64 = b"""eNrtVE1rwzAMvedXaKdeRn7ENrb21rHCzmrs1m49K9gOJv9+cko/HBcGg0LHcpOfnq2np0QL + 2FuKgBbICDAoeoiKwEc0hqIUgLAxfV0tQJCdhQM7qh68kheswKeBt5ROYetTemYMCC3rii// + WMS3WkhXVyuFAaLT261JuBWwu4iDbvYp1tYzHVS68VEIObwFgaDB0KizuFs38aSdqKv3TgcJ + uPYdn2B1opwIpeKE53qPftxRd88Y6uoVbdPzWxznrQ3ZUi3DudQ/bcELbevqM32iCIrj3IIh + W6plOJf6L6xaajZjzqW/qAsKIvITBGs9Nm3glboZzkVP5l6Y+0bHLnedD0CttIyrpEU5Kv7N + Mz3XkPBc/TSN3yxGiqMiipHRekycK0ZwMhM8jerGC9zuZaoTho3kMKSfJjLaF8v8wLzmXMqM + zJvGew/jnZPzclA08yAkikegDTTUMfzwDXBcwoE=""" +println(String(transcode(ZlibDecompressor(), base64decode(b64)))) diff --git a/Task/Old-lady-swallowed-a-fly/Julia/old-lady-swallowed-a-fly-2.julia b/Task/Old-lady-swallowed-a-fly/Julia/old-lady-swallowed-a-fly-2.julia new file mode 100644 index 0000000000..5201b9f264 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Julia/old-lady-swallowed-a-fly-2.julia @@ -0,0 +1,22 @@ +animals = [ + ("fly", "I don't know why she swallowed a fly, perhaps she'll die."), + ("spider", "It wiggled and jiggled and tickled inside her."), + ("bird", "How absurd, to swallow a bird."), + ("cat", "Imagine that, she swallowed a cat."), + ("dog", "What a hog, to swallow a dog."), + ("goat", "She just opened her throat and swallowed a goat."), + ("cow", "I don't know how she swallowed a cow."), + ("horse", "She's dead, of course.")] + +for (i, (animal, lyric)) in enumerate(animals) + println("There was an old lady who swallowed a $animal.\n$lyric") + + if animal == "horse" break end + + for ((predator, _), (prey, _)) in zip(animals[i:-1:1], animals[i-1:-1:1]) + println("\tShe swallowed the $predator to catch the $prey") + end + + if animal != "fly" println(animals[1][2]) end # fly lyric + println() # new line +end diff --git a/Task/Old-lady-swallowed-a-fly/Modula-2/old-lady-swallowed-a-fly.mod2 b/Task/Old-lady-swallowed-a-fly/Modula-2/old-lady-swallowed-a-fly.mod2 new file mode 100644 index 0000000000..b1e4d37258 --- /dev/null +++ b/Task/Old-lady-swallowed-a-fly/Modula-2/old-lady-swallowed-a-fly.mod2 @@ -0,0 +1,52 @@ +MODULE OldLady; +FROM FormatString IMPORT FormatString; +FROM Terminal IMPORT WriteString,WriteLn,ReadChar; + +TYPE + AA = ARRAY[0..7] OF ARRAY[0..7] OF CHAR; + VA = ARRAY[0..7] OF ARRAY[0..63] OF CHAR; +VAR + buf : ARRAY[0..127] OF CHAR; + animals : AA; + verses : VA; + i,j : INTEGER; +BEGIN + FormatString("I don't know why she swallowed that fly.\nPerhaps she'll die\n", buf); + + animals := AA{"fly", "spider", "bird", "cat", "dog", "goat", "cow", "horse"}; + verses := VA{ + "I don't know why she swallowed that fly.", + "That wiggled and jiggled and tickled inside her", + "How absurd, to swallow a bird", + "Imagine that. She swallowed a cat", + "What a hog to swallow a dog", + "She just opened her throat and swallowed that goat", + "I don't know how she swallowed that cow", + "She's dead of course" + }; + + FOR i:=0 TO 7 DO + FormatString("There was an old lady who swallowed a %s\n%s\n", buf, animals[i], verses[i]); + WriteString(buf); + IF i=0 THEN + WriteString("Perhaps she'll die"); + WriteLn; + WriteLn; + END; + j := i; + WHILE (j>0) AND (i<7) DO + FormatString("She swallowed the %s to catch the %s\n", buf, animals[j], animals[j-1]); + WriteString(buf); + IF j=1 THEN + WriteString(verses[0]); + WriteLn; + WriteString("Perhaps she'll die"); + WriteLn; + WriteLn + END; + DEC(j) + END; + END; + + ReadChar +END OldLady. diff --git a/Task/Old-lady-swallowed-a-fly/Rust/old-lady-swallowed-a-fly.rust b/Task/Old-lady-swallowed-a-fly/Rust/old-lady-swallowed-a-fly.rust index 0708bde065..492f269fba 100644 --- a/Task/Old-lady-swallowed-a-fly/Rust/old-lady-swallowed-a-fly.rust +++ b/Task/Old-lady-swallowed-a-fly/Rust/old-lady-swallowed-a-fly.rust @@ -13,15 +13,20 @@ fn main() { , ("spider", Once , "That wriggled and jiggled and tickled inside her.") , ("fly" , Every, "I don't know why she swallowed the fly.") ]; + for (i, a) in animals.iter().enumerate().rev() { println!("There was an old lady who swallowed a {}\n{}", a.0, a.2); + if let Die = a.1 {break} + for (swallowed, to_catch) in animals[i..].iter().zip(&animals[i+1..]) { println!("She swallowed the {} to catch the {}.", swallowed.0, to_catch.0); + if let Every = to_catch.1 { println!("{}", to_catch.2); } } + println!("Perhaps she'll die.\n"); } } diff --git a/Task/One-dimensional-cellular-automata/Forth/one-dimensional-cellular-automata.fth b/Task/One-dimensional-cellular-automata/Forth/one-dimensional-cellular-automata-1.fth similarity index 100% rename from Task/One-dimensional-cellular-automata/Forth/one-dimensional-cellular-automata.fth rename to Task/One-dimensional-cellular-automata/Forth/one-dimensional-cellular-automata-1.fth diff --git a/Task/One-dimensional-cellular-automata/Forth/one-dimensional-cellular-automata-2.fth b/Task/One-dimensional-cellular-automata/Forth/one-dimensional-cellular-automata-2.fth new file mode 100644 index 0000000000..2669225a01 --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Forth/one-dimensional-cellular-automata-2.fth @@ -0,0 +1,10 @@ + ### ## # # # # # + # ##### # # # + ## ## # # + ## ### # + ## # ## + ## ### + ## # # + ## # + ## + ## ok diff --git a/Task/One-dimensional-cellular-automata/Julia/one-dimensional-cellular-automata.julia b/Task/One-dimensional-cellular-automata/Julia/one-dimensional-cellular-automata.julia index 47e4cb3877..5e9146eab3 100644 --- a/Task/One-dimensional-cellular-automata/Julia/one-dimensional-cellular-automata.julia +++ b/Task/One-dimensional-cellular-automata/Julia/one-dimensional-cellular-automata.julia @@ -1,9 +1,9 @@ function next_gen(a::BitArray{1}, isperiodic=false) b = copy(a) if isperiodic - ncnt = [a[end], a[1:end-1]] + [a[2:end], a[1]] + ncnt = prepend!(a[1:end-1], [a[end]]) + append!(a[2:end], [a[1]]) else - ncnt = [false, a[1:end-1]] + [a[2:end], false] + ncnt = prepend!(a[1:end-1], [false]) + append!(a[2:end], [false]) end b[ncnt .== 0] = false b[ncnt .== 2] = ~b[ncnt .== 2] @@ -16,7 +16,7 @@ function show_gen(a::BitArray{1}) end hi = 70 -a = randbool(hi) +a = bitrand(hi) b = falses(hi) println("A 1D Cellular Atomaton with ", hi, " cells and empty bounds.") while any(a) && any(a .!= b) @@ -24,7 +24,7 @@ while any(a) && any(a .!= b) b = copy(a) a = next_gen(a) end -a = randbool(hi) +a = bitrand(hi) b = falses(hi) println() println("A 1D Cellular Atomaton with ", hi, " cells and periodic bounds.") diff --git a/Task/One-dimensional-cellular-automata/Kotlin/one-dimensional-cellular-automata.kotlin b/Task/One-dimensional-cellular-automata/Kotlin/one-dimensional-cellular-automata.kotlin new file mode 100644 index 0000000000..5a4fa3c5eb --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Kotlin/one-dimensional-cellular-automata.kotlin @@ -0,0 +1,27 @@ +// version 1.1.4-3 + +val trans = "___#_##_" + +fun v(cell: StringBuilder, i: Int) = if (cell[i] != '_') 1 else 0 + +fun evolve(cell: StringBuilder, backup: StringBuilder): Boolean { + val len = cell.length - 2 + var diff = 0 + for (i in 1 until len) { + /* use left, self, right as binary number bits for table index */ + backup[i] = trans[v(cell, i - 1) * 4 + v(cell, i) * 2 + v(cell, i + 1)] + diff += if (backup[i] != cell[i]) 1 else 0 + } + cell.setLength(0) + cell.append(backup) + return diff != 0 +} + +fun main(args: Array) { + val c = StringBuilder("_###_##_#_#_#_#__#__") + val b = StringBuilder("____________________") + do { + println(c.substring(1)) + } + while (evolve(c,b)) +} diff --git a/Task/One-dimensional-cellular-automata/Nim/one-dimensional-cellular-automata-1.nim b/Task/One-dimensional-cellular-automata/Nim/one-dimensional-cellular-automata-1.nim index ef2639f28e..f2943c9523 100644 --- a/Task/One-dimensional-cellular-automata/Nim/one-dimensional-cellular-automata-1.nim +++ b/Task/One-dimensional-cellular-automata/Nim/one-dimensional-cellular-automata-1.nim @@ -1,68 +1,48 @@ -import math -randomize() +import random + type - TBoolArray = array[0..30, bool] # an array that is indexed with 0..10 - TSymbols = tuple[on: char , off: char] + BoolArray = array[30, bool] + Symbols = array[bool, char] + + +proc neighbours(map: BoolArray, i: int): int = + if i > 0: inc(result, int(map[i - 1])) + if i + 1 < len(map): inc(result, int(map[i + 1])) + +proc print(map: BoolArray, symbols: Symbols) = + for i in map: write(stdout, symbols[i]) + write(stdout, "\l") + +proc randomMap: BoolArray = + randomize() + for i in mitems(result): i = rand([true, false]) + const - num_turns = 20 - symbols:TSymbols = ('#','_') + num_turns = 20 + symbols = ['_', '#'] -proc `==` (x:TBoolArray,y:TBoolArray): bool = - if len(x) != len(y): - return False - for i in 0..(len(x)-1): - if x[i] != y[i]: - return False - return True + T = true + F = false -proc count_neighbours(map:TBoolArray , tile:int):int = - result = 0 - if tile != len(map)-1 and map[tile+1]: - result += 1 - if tile != 0 and map[tile-1]: - result += 1 +var map = + [F, T, T, T, F, T, T, F, T, F, T, F, T, F, T, + F, F, T, F, F, F, F, F, F, F, F, F, F, F, F] -proc print_map(map:TBoolArray, symbols:TSymbols) = - for i in map: - if i: - write(stdout,symbols[0]) - else: - write(stdout,symbols[1]) - write(stdout,"\n") +# map = randomMap() # uncomment for random start -proc random_map(): TBoolArray = - var map = [False,False,False,False,False,False,False,False,False,False,False, - False,False,False,False,False,False,False,False,False,False,False, - False,False,False,False,False,False,False,False,False] - for i in 0..(len(map)-1): - map[i] = bool(random(2)) - return map +print(map, symbols) -proc fixed_map(): TBoolArray = - var map = [False,True,True,True,False,True,True,False,True,False,True, - False,True,False,True,False,False,True,False,False,False,False, - False,False,False,False,False,False,False,False,False] - return map +for _ in 0 ..< num_turns: + var map2 = map -#make the map -var map:TBoolArray -#map = random_map() # uncomment for random start -map = fixed_map() -print_map(map,symbols) -for i in 0..num_turns: - var new_map = map - for j in 0..(len(map)-1): - if map[j]: - if count_neighbours(map, j) == 2 or - count_neighbours(map, j) == 0: - new_map[j] = False - else: - if count_neighbours(map, j) == 2: - new_map[j] = True - if new_map == map: - print_map(map,symbols) - break - map = new_map - print_map(map,symbols) + for i, v in pairs(map): + map2[i] = + if v: neighbours(map, i) == 1 + else: neighbours(map, i) == 2 + + print(map2, symbols) + + if map2 == map: break + map = map2 diff --git a/Task/One-dimensional-cellular-automata/PARI-GP/one-dimensional-cellular-automata.pari b/Task/One-dimensional-cellular-automata/PARI-GP/one-dimensional-cellular-automata-1.pari similarity index 100% rename from Task/One-dimensional-cellular-automata/PARI-GP/one-dimensional-cellular-automata.pari rename to Task/One-dimensional-cellular-automata/PARI-GP/one-dimensional-cellular-automata-1.pari diff --git a/Task/One-dimensional-cellular-automata/PARI-GP/one-dimensional-cellular-automata-2.pari b/Task/One-dimensional-cellular-automata/PARI-GP/one-dimensional-cellular-automata-2.pari new file mode 100644 index 0000000000..75831785ae --- /dev/null +++ b/Task/One-dimensional-cellular-automata/PARI-GP/one-dimensional-cellular-automata-2.pari @@ -0,0 +1 @@ +cur = [0,1,1,1,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0]; for(n=0, 9, print(cur); cur = step(cur)); diff --git a/Task/One-dimensional-cellular-automata/PARI-GP/one-dimensional-cellular-automata-3.pari b/Task/One-dimensional-cellular-automata/PARI-GP/one-dimensional-cellular-automata-3.pari new file mode 100644 index 0000000000..05db42fb36 --- /dev/null +++ b/Task/One-dimensional-cellular-automata/PARI-GP/one-dimensional-cellular-automata-3.pari @@ -0,0 +1,10 @@ +[0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0] +[0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0] +[0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0] +[0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0] +[0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0] +[0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0] +[0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0] +[0, 0, 1, 1, 0, 0, 0, 0, 0, 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, 0, 0, 0] +[0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] diff --git a/Task/One-dimensional-cellular-automata/Perl-6/one-dimensional-cellular-automata.pl6 b/Task/One-dimensional-cellular-automata/Perl-6/one-dimensional-cellular-automata.pl6 new file mode 100644 index 0000000000..5938a3ac0e --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Perl-6/one-dimensional-cellular-automata.pl6 @@ -0,0 +1,36 @@ +class Automaton { + has $.rule; + has @.cells; + has @.code = $!rule.fmt('%08b').flip.comb».Int; + + method gist { "|{ @!cells.map({+$_ ?? '#' !! ' '}).join }|" } + + method succ { + self.new: :$!rule, :@!code, :cells( + @!code[ + 4 «*« @!cells.rotate(-1) + »+« 2 «*« @!cells + »+« @!cells.rotate(1) + ] + ) + } +} + +# The rule proposed for this task is rule 0b01101000 = 104 + +my @padding = 0 xx 5; +my Automaton $a .= new: + rule => 104, + cells => flat @padding, '111011010101'.comb, @padding +; +say $a++ for ^10; + + +# Rule 104 is not particularly interesting so here is [[wp:Rule 90|Rule 90]], +# which shows a [[wp:Sierpinski Triangle|Sierpinski Triangle]]. + +say ''; +@padding = 0 xx 25; +$a = Automaton.new: :rule(90), :cells(flat @padding, 1, @padding); + +say $a++ for ^20; diff --git a/Task/One-dimensional-cellular-automata/Ring/one-dimensional-cellular-automata.ring b/Task/One-dimensional-cellular-automata/Ring/one-dimensional-cellular-automata.ring new file mode 100644 index 0000000000..746e152a81 --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Ring/one-dimensional-cellular-automata.ring @@ -0,0 +1,27 @@ +# Project : One-dimensional cellular automata +# Date : 2017/10/21 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +rule = ["0", "0", "0", "1", "0", "1", "1", "0"] +now = "01110110101010100100" + +for generation = 0 to 9 + see "generation " + generation + ": " + now + nl + nxt = "" + for cell = 1 to len(now) + str = "bintodec(" + '"' +substr("0"+now+"0", cell, 3) + '"' + ")" + eval("p=" + str) + nxt = nxt + rule[p+1] + next + temp = nxt + nxt = now + now = temp +next + +func bintodec(bin) + binsum = 0 + for n=1 to len(bin) + binsum = binsum + number(bin[n]) *pow(2, len(bin)-n) + next + return binsum diff --git a/Task/One-of-n-lines-in-a-file/00DESCRIPTION b/Task/One-of-n-lines-in-a-file/00DESCRIPTION index ee41e025bb..05df3c5e45 100644 --- a/Task/One-of-n-lines-in-a-file/00DESCRIPTION +++ b/Task/One-of-n-lines-in-a-file/00DESCRIPTION @@ -1,19 +1,24 @@ A method of choosing a line randomly from a file: -* Without reading the file more than once -* When substantial parts of the file cannot be held in memory -* Without knowing how many lines are in the file +::* Without reading the file more than once +::* When substantial parts of the file cannot be held in memory +::* Without knowing how many lines are in the file Is to: -:* keep the first line of the file as a possible choice, then -:* Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2. -:* Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3. -: ... -:* Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N +::* keep the first line of the file as a possible choice, then +::* Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2. +::* Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3. +::* ... +::* Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N + +::* Return the computed possible choice when no further lines exist in the file. -:* Return the computed possible choice when no further lines exist in the file. ;Task: # Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file.
The number returned can vary, randomly, in each run. # Use one_of_n in a ''simulation'' to find what woud be the chosen line of a 10 line file simulated 1,000,000 times. # Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works. + Note: You may choose a smaller number of repetitions if necessary, but mention this up-front. + +Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling +

diff --git a/Task/One-of-n-lines-in-a-file/Kotlin/one-of-n-lines-in-a-file.kotlin b/Task/One-of-n-lines-in-a-file/Kotlin/one-of-n-lines-in-a-file.kotlin new file mode 100644 index 0000000000..296d255558 --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/Kotlin/one-of-n-lines-in-a-file.kotlin @@ -0,0 +1,24 @@ +// version 1.1.51 + +import java.util.Random + +val r = Random() + +fun oneOfN(n: Int): Int { + var choice = 1 + for (i in 2..n) { + if (r.nextDouble() < 1.0 / i) choice = i + } + return choice +} + +fun main(args: Array) { + val n = 10 + val freqs = IntArray(n) + val reps = 1_000_000 + repeat(reps) { + val num = oneOfN(n) + freqs[num - 1]++ + } + for (i in 1..n) println("Line ${"%-2d".format(i)} = ${freqs[i - 1]}") +} diff --git a/Task/One-of-n-lines-in-a-file/Rust/one-of-n-lines-in-a-file.rust b/Task/One-of-n-lines-in-a-file/Rust/one-of-n-lines-in-a-file.rust index d778b94048..c1cc360323 100644 --- a/Task/One-of-n-lines-in-a-file/Rust/one-of-n-lines-in-a-file.rust +++ b/Task/One-of-n-lines-in-a-file/Rust/one-of-n-lines-in-a-file.rust @@ -1,22 +1,27 @@ extern crate rand; -use rand::Rng; +use rand::{Rng, thread_rng}; -fn one_of_n(rng: &mut rand::ThreadRng, n: usize) -> usize { - (1..n).fold(0, |keep, cand| - match rng.next_f64() { - y if y < (1.0 / (cand + 1) as f64) => cand, - _ => keep - } - ) +fn one_of_n(rng: &mut R, n: usize) -> usize { + (1..n).fold(0, |keep, cand| { + // Note that this will break if n is larger than u32::MAX + if rng.gen_weighted_bool(cand as u32 + 1) { + cand + } else { + keep + } + }) } fn main() { - let mut dist = [0usize; 10]; - let mut rng = rand::thread_rng(); + const LINES: usize = 10; + + let mut dist = [0; LINES]; + let mut rng = thread_rng(); for _ in 0..1_000_000 { - dist[one_of_n(&mut rng, 10)] += 1; + let num = one_of_n(&mut rng, LINES); + dist[num] += 1; } println!("{:?}", dist); diff --git a/Task/OpenGL/BaCon/opengl.bacon b/Task/OpenGL/BaCon/opengl.bacon new file mode 100644 index 0000000000..c74ee6fc59 --- /dev/null +++ b/Task/OpenGL/BaCon/opengl.bacon @@ -0,0 +1,34 @@ +PRAGMA INCLUDE +PRAGMA LDFLAGS GL glut + +OPTION PARSE FALSE + +SUB Triangle + + glViewport(0, 0, 640, 480) + glOrtho(-30.0, 30.0, -30.0, 30.0, -30.0, 30.0) + + glClearColor(0.0, 0.0, 0.0, 1.0) + glClear(GL_COLOR_BUFFER_BIT) + + glTranslatef(-15.0, -15.0, 0.0) + + glBegin(GL_TRIANGLES) + glColor3f(1.0, 0.0, 0.0) + glVertex2f(0.0, 0.0) + glColor3f(0.0, 1.0, 0.0) + glVertex2f(30.0, 0.0) + glColor3f(0.0, 0.0, 1.0) + glVertex2f(0.0, 30.0) + glEnd() + + glutSwapBuffers() + +END SUB + +glutInit(&argc, argv) +glutInitWindowSize(640, 480) +glutCreateWindow("Triangle") + +glutDisplayFunc(Triangle) +glutMainLoop() diff --git a/Task/OpenGL/Lingo/opengl.lingo b/Task/OpenGL/Lingo/opengl.lingo new file mode 100644 index 0000000000..e042c97d92 --- /dev/null +++ b/Task/OpenGL/Lingo/opengl.lingo @@ -0,0 +1,58 @@ +global gOpenGL -- RavOpenGL xtra instance +global GL -- OpenGL constants + +on startMovie + -- Load the OpenGL script xtra + gOpenGL = xtra("RavOpenGL").new() + + -- Load GL DLL + gOpenGL.RavLoadGL("", "") + + -- Function omitted in demo code: loads OpenGL constants into namespace GL + loadGLConstants() + + -- Window settings + w = 640 + h = 480 + _movie.stage.title = "Triangle" + _movie.stage.rect = rect(0, 0, w, h) + _movie.centerStage = TRUE + + -- Create OpenGL display sprite + m = new(#RavOpenGLDisplay) + _movie.puppetSprite(1, TRUE) + sprite(1).rect = rect(0, 0, w, h) + sprite(1).member = m + _movie.updateStage() + + -- Create the OpenGL buffer + mainBufferID = gOpenGL.RavCreateBuffer(w, h, 32, 32) + + -- Set the sharing mode between script and sprite xtras + dcID = gOpenGL.RavGetBufferProp(mainBufferID, #ravGC) + sprite(1).RavShareBuffer(dcID, #true) + + gOpenGL.glViewport(0, 0, w, h) + gOpenGL.glMatrixMode(GL.PROJECTION) + gOpenGL.glLoadIdentity() + gOpenGL.glOrtho(-30.0, 30.0, -30.0, 30.0, -30.0, 30.0) + gOpenGL.glMatrixMode(GL.MODELVIEW) + + gOpenGL.glClearColor(0.3, 0.3, 0.3, 0.0) + gOpenGL.glClear(GL.COLOR_BUFFER_BIT + GL.DEPTH_BUFFER_BIT) + gOpenGL.glShadeModel(GL.SMOOTH) + gOpenGL.glLoadIdentity() + gOpenGL.glTranslatef(-15.0, -15.0, 0.0) + gOpenGL.glBegin(GL.TRIANGLES) + gOpenGL.glColor3f(1.0, 0.0, 0.0) + gOpenGL.glVertex2f(0.0, 0.0) + gOpenGL.glColor3f(0.0, 1.0, 0.0) + gOpenGL.glVertex2f(30.0, 0.0) + gOpenGL.glColor3f(0.0, 0.0, 1.0) + gOpenGL.glVertex2f(0.0, 30.0) + gOpenGL.glEnd() + gOpenGL.glFlush() + + -- Show the window + _movie.stage.visible = TRUE +end diff --git a/Task/OpenGL/Racket/opengl.rkt b/Task/OpenGL/Racket/opengl.rkt index 88bfbbea89..513016e745 100644 --- a/Task/OpenGL/Racket/opengl.rkt +++ b/Task/OpenGL/Racket/opengl.rkt @@ -32,7 +32,7 @@ (define/override (on-paint) (with-gl-context (λ() (draw-opengl) (swap-gl-buffers)))) (define/override (on-size width height) - (with-gl-context (λ() (resize width height)))) + (with-gl-context (λ() (resize width height) (on-paint)))) (super-instantiate () (style '(gl))))) (define win (new frame% [label "Racket Rosetta Code OpenGL example"] diff --git a/Task/OpenGL/Ring/opengl.ring b/Task/OpenGL/Ring/opengl.ring new file mode 100644 index 0000000000..22ee024a7b --- /dev/null +++ b/Task/OpenGL/Ring/opengl.ring @@ -0,0 +1,25 @@ +# Project: OpenGL +# Date : 2018/06/09 +# Author: Gal Zsolt [~ CalmoSoft ~] +# Email : + +load "freeglut.ring" +load "opengl21lib.ring" + +func main + glutInit() + glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA) + glutInitWindowSize(320,320) + glutInitWindowPosition(100, 10) + glutCreateWindow("OpenGL") + glutDisplayFunc(:renderScene) + glutMainLoop() + +func renderScene + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) + glBegin(GL_TRIANGLES) + glVertex3f(-0.5,-0.5,0.0) + glVertex3f(0.5,0.0,0.0) + glVertex3f(0.0,0.5,0.0) + glEnd() + glutSwapBuffers() diff --git a/Task/Optional-parameters/Kotlin/optional-parameters.kotlin b/Task/Optional-parameters/Kotlin/optional-parameters.kotlin new file mode 100644 index 0000000000..02857fddd3 --- /dev/null +++ b/Task/Optional-parameters/Kotlin/optional-parameters.kotlin @@ -0,0 +1,46 @@ +// version 1.1.51 + +typealias Table = List> + +/* Note that if ordering is specified, first two parameters are ignored */ +fun Table.sort( + column: Int = 0, + reverse: Boolean = false, + ordering: Comparator> = + if (!reverse) compareBy { it[column] } + else compareByDescending { it[column] } +) = this.sortedWith(ordering) + +fun Table.print(title: String) { + println(title) + for (i in 0 until this.size) { + for (j in 0 until this[0].size) System.out.print("%-3s ".format(this[i][j])) + println() + } + println() +} + +fun main(args: Array) { + val table = listOf( + listOf("a", "b", "c"), + listOf("", "q", "z"), + listOf("zap", "zip", "Zot") + ) + table.print("Original:") + + val titles = listOf( + "Sorted by col 0:", "Sorted by col 1:", "Sorted by col 2:", + "Reverse sorted by col 0:", "Reverse sorted by col 1:", "Reverse Sorted by col 2" + ) + val params = listOf( + 0 to false, 1 to false, 2 to false, 0 to true, 1 to true, 2 to true + ) + for ((i, title) in titles.withIndex()) { + val table2 = table.sort(params[i].first, params[i].second) + table2.print(title) + } + // using non-default Comparator (case insensitive by col 2, reversed) + val comp: Comparator> = compareByDescending { it[2].toLowerCase() } + val table3 = table.sort(ordering = comp) + table3.print("Reverse case insensitive sort by col 2:") +} diff --git a/Task/Order-disjoint-list-items/Aime/order-disjoint-list-items.aime b/Task/Order-disjoint-list-items/Aime/order-disjoint-list-items.aime index 708f76a50b..ac3dee3d06 100644 --- a/Task/Order-disjoint-list-items/Aime/order-disjoint-list-items.aime +++ b/Task/Order-disjoint-list-items/Aime/order-disjoint-list-items.aime @@ -1,32 +1,29 @@ void -order(integer m, ...) +order(list a, list b) { - integer i, j; + integer j; record r; text s; - ocall(o_, 0, 1, m, " "); + a.ucall(o_, 0, " "); o_("| "); - i = (j = m) + 1; - while (i < count()) { - r[s = $i] += 1; + for (, s in b) { + r[s] += 1; o_(s, " "); - i += 1; } o_("->"); - i = 0; - do { - i += 1; - if ((r[s = $i] += -1) < 0) { + j = -1; + for (, s in a) { + if ((r[s] -= 1) < 0) { o_(" ", s); } else { - o_(" ", $(j += 1)); + o_(" ", b[j += 1]); } - } while (i < m); + } o_newline(); } @@ -34,13 +31,13 @@ order(integer m, ...) integer main(void) { - order(6, "the", "cat", "sat", "on", "the", "mat", "mat", "cat"); - order(6, "the", "cat", "sat", "on", "the", "mat", "cat", "mat"); - order(9, "A", "B", "C", "A", "B", "C", "A", "B", "C", "C", "A", "C", "A"); - order(9, "A", "B", "C", "A", "B", "D", "A", "B", "E", "E", "A", "D", "A"); - order(2, "A", "B", "B"); - order(2, "A", "B", "B", "A"); - order(4, "A", "B", "B", "A", "B", "A"); + order(list("the", "cat", "sat", "on", "the", "mat"), list("mat", "cat")); + order(list("the", "cat", "sat", "on", "the", "mat"), list("cat", "mat")); + order(list("A", "B", "C", "A", "B", "C", "A", "B", "C"), list("C", "A", "C", "A")); + order(list("A", "B", "C", "A", "B", "D", "A", "B", "E"), list("E", "A", "D", "A")); + order(list("A", "B"), list("B")); + order(list("A", "B"), list("B", "A")); + order(list("A", "B", "B", "A"), list("B", "A")); return 0; } diff --git a/Task/Order-disjoint-list-items/C++/order-disjoint-list-items.cpp b/Task/Order-disjoint-list-items/C++/order-disjoint-list-items.cpp new file mode 100644 index 0000000000..8348513254 --- /dev/null +++ b/Task/Order-disjoint-list-items/C++/order-disjoint-list-items.cpp @@ -0,0 +1,71 @@ +/* + Author: Kevin Bacon [haxifix (@gmail.com)] + Date: 2018-05-19 +*/ +#include +#include +#include +#include + +template +void print(const std::vector v) { + std::cout << "{ "; + for (const auto& e : v) { + std::cout << e << " "; + } + std::cout << "}"; +} + +template +auto orderDisjointArrayItems(std::vector M, std::vector N) { + std::vector M_p(std::size(M)); + for (auto i = 0; i < std::size(M_p); ++i) { + M_p[i] = &M[i]; + } + for (auto e : N) { + auto i = std::find_if(std::begin(M_p), std::end(M_p), [e](auto c) -> bool { + if (c != nullptr) { + if (*c == e) return true; + } + return false; + }); + if (i != std::end(M_p)) { + *i = nullptr; + } + } + for (auto i = 0; i < std::size(N); ++i) { + auto j = std::find_if(std::begin(M_p), std::end(M_p), [](auto c) -> bool { + return c == nullptr; + }); + if (j != std::end(M_p)) { + *j = &M[std::distance(std::begin(M_p), j)]; + **j = N[i]; + } + } + return M; +} + +int main() { + std::vector>> l = { + { { "the", "cat", "sat", "on", "the", "mat" }, { "mat", "cat" } }, + { { "the", "cat", "sat", "on", "the", "mat" },{ "cat", "mat" } }, + { { "A", "B", "C", "A", "B", "C", "A", "B", "C" },{ "C", "A", "C", "A" } }, + { { "A", "B", "C", "A", "B", "D", "A", "B", "E" },{ "E", "A", "D", "A" } }, + { { "A", "B" },{ "B" } }, + { { "A", "B" },{ "B", "A" } }, + { { "A", "B", "B", "A" },{ "B", "A" } } + }; + for (const auto& e : l) { + std::cout << "M: "; + print(e[0]); + std::cout << ", N: "; + print(e[1]); + std::cout << ", M': "; + auto res = orderDisjointArrayItems(e[0], e[1]); + print(res); + std::cout << std::endl; + } + std::cin.ignore(); + std::cin.get(); + return 0; +} diff --git a/Task/Order-disjoint-list-items/Perl-6/order-disjoint-list-items.pl6 b/Task/Order-disjoint-list-items/Perl-6/order-disjoint-list-items.pl6 new file mode 100644 index 0000000000..c758870c57 --- /dev/null +++ b/Task/Order-disjoint-list-items/Perl-6/order-disjoint-list-items.pl6 @@ -0,0 +1,19 @@ +sub order-disjoint-list-items(\M, \N) { + my \bag = N.BagHash; + M.map: { bag{$_}-- ?? N.shift !! $_ } +} + +# Testing: + +for q:to/---/.comb(/ [\S+]+ % ' ' /).map({[.words]}) + the cat sat on the mat mat cat + the cat sat on the mat cat mat + A B C A B C A B C C A C A + A B C A B D A B E E A D A + A B B + A B B A + A B B A B A + X X Y X + A X Y A + --- +-> $m, $n { say "\n$m ==> $n\n", order-disjoint-list-items($m, $n) } diff --git a/Task/Order-two-numerical-lists/Aime/order-two-numerical-lists.aime b/Task/Order-two-numerical-lists/Aime/order-two-numerical-lists.aime new file mode 100644 index 0000000000..d6595b669f --- /dev/null +++ b/Task/Order-two-numerical-lists/Aime/order-two-numerical-lists.aime @@ -0,0 +1,30 @@ +integer +ordl(list a, list b) +{ + integer i, l, o; + + l = min(~a, ~b); + i = 0; + while (i < l) { + if (a[i] != b[i]) { + o = a[i] < b[i]; + break; + } + + i += 1; + } + + return i < l ? o : ~a <= ~b; +} + +integer +main(void) +{ + o_(ordl(list(1, 2), list(1, 2)), "\n"); + o_(ordl(list(1e2, 2), list(1e2, 2, 3)), "\n"); + o_(ordl(list(1, 2, 3), list(1, 2)), "\n"); + o_(ordl(list(.5, 4), list(.5, 2)), "\n"); + o_(ordl(list(1, 4, 2, 3), list(1, 4, 2.1, 3)), "\n"); + + return 0; +} diff --git a/Task/Order-two-numerical-lists/J/order-two-numerical-lists-2.j b/Task/Order-two-numerical-lists/J/order-two-numerical-lists-2.j index 2fec517edd..62dbc69346 100644 --- a/Task/Order-two-numerical-lists/J/order-two-numerical-lists-2.j +++ b/Task/Order-two-numerical-lists/J/order-two-numerical-lists-2.j @@ -1,49 +1 @@ - (,0) before '' -0 - '' before '' -0 - '' before ,0 -1 - (,_1) before ,0 -1 - (,0) before ,0 -0 - (,0) before ,_1 -0 - (,0) before 0 _1 -1 - (,0) before 0 0 -1 - (,0) before 0 1 -1 - 0 _1 before ,0 -0 - 0 0 before ,0 -0 - 0 0 before ,1 -1 - - (,'b') before '' -0 - '' before '' -0 - '' before ,'b' -1 - (,'a') before ,'b' -1 - (,'b') before ,'b' -0 - (,'b') before ,'a' -0 - (,'b') before 'ba' -1 - (,'b') before 'bb' -1 - (,'b') before 'bc' -1 - 'ba' before ,'b' -0 - 'bb' before ,'b' -0 - 'bb' before ,'c' -1 +cmp=: {.@\:@,:&(,&__) diff --git a/Task/Order-two-numerical-lists/J/order-two-numerical-lists-3.j b/Task/Order-two-numerical-lists/J/order-two-numerical-lists-3.j new file mode 100644 index 0000000000..27057008f3 --- /dev/null +++ b/Task/Order-two-numerical-lists/J/order-two-numerical-lists-3.j @@ -0,0 +1,29 @@ + cmp&.>"{~ ('';0;(,0);1;(,1);1 1) +┌─┬─┬─┬─┬─┬─┐ +│0│1│1│1│1│1│ +├─┼─┼─┼─┼─┼─┤ +│0│0│0│1│1│1│ +├─┼─┼─┼─┼─┼─┤ +│0│0│0│1│1│1│ +├─┼─┼─┼─┼─┼─┤ +│0│0│0│0│0│1│ +├─┼─┼─┼─┼─┼─┤ +│0│0│0│0│0│1│ +├─┼─┼─┼─┼─┼─┤ +│0│0│0│0│0│0│ +└─┴─┴─┴─┴─┴─┘ + +before&.>"{~ (0;1;'';(,0);(,1);1 1) +┌─┬─┬─┬─┬─┬─┐ +│0│1│1│1│1│1│ +├─┼─┼─┼─┼─┼─┤ +│0│0│1│1│1│1│ +├─┼─┼─┼─┼─┼─┤ +│0│0│0│1│1│1│ +├─┼─┼─┼─┼─┼─┤ +│0│0│0│0│1│1│ +├─┼─┼─┼─┼─┼─┤ +│0│0│0│0│0│1│ +├─┼─┼─┼─┼─┼─┤ +│0│0│0│0│0│0│ +└─┴─┴─┴─┴─┴─┘ diff --git a/Task/Order-two-numerical-lists/Julia/order-two-numerical-lists.julia b/Task/Order-two-numerical-lists/Julia/order-two-numerical-lists.julia new file mode 100644 index 0000000000..547cc3fc05 --- /dev/null +++ b/Task/Order-two-numerical-lists/Julia/order-two-numerical-lists.julia @@ -0,0 +1,13 @@ +function islexless(a::AbstractArray{<:Real}, b::AbstractArray{<:Real}) + for (x, y) in zip(a, b) + if x == y continue end + return x < y + end + return length(a) < length(b) +end + +using Primes, Combinatorics +tests = [[1, 2, 3], primes(10), 0:2:6, [-Inf, 0.0, Inf], [π, e, φ, catalan], [2015, 5], [-sqrt(50.0), 50.0 ^ 2]] +println("List not sorted:\n - ", join(tests, "\n - ")) +sort!(tests; lt=islexless) +println("List sorted:\n - ", join(tests, "\n - ")) diff --git a/Task/Ordered-Partitions/00DESCRIPTION b/Task/Ordered-Partitions/00DESCRIPTION index 0278b77309..0d23d3f1ca 100644 --- a/Task/Ordered-Partitions/00DESCRIPTION +++ b/Task/Ordered-Partitions/00DESCRIPTION @@ -1,4 +1,6 @@ -In this task we want to find the ordered partitions into fixed-size blocks. This task is related to [[Combinations]] in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task. +In this task we want to find the ordered partitions into fixed-size blocks. + +This task is related to [[Combinations]] in that it has to do with discrete mathematics and moreover a helper function to compute combinations is (probably) needed to solve this task. partitions(\mathit{arg}_1,\mathit{arg}_2,...,\mathit{arg}_n) should generate all distributions of the elements in \{1,...,\Sigma_{i=1}^n\mathit{arg}_i\} into n blocks of respective size \mathit{arg}_1,\mathit{arg}_2,...,\mathit{arg}_n. @@ -27,7 +29,9 @@ Example 2: partitions(1,1,1) would create: Note that the number of elements in the list is :{\mathit{arg}_1+\mathit{arg}_2+...+\mathit{arg}_n \choose \mathit{arg}_1} \cdot {\mathit{arg}_2+\mathit{arg}_3+...+\mathit{arg}_n \choose \mathit{arg}_2} \cdot \ldots \cdot {\mathit{arg}_n \choose \mathit{arg}_n} (see [http://en.wikipedia.org/wiki/Binomial_coefficient the definition of the binomial coefficient] if you are not familiar with this notation) and the number of elements remains the same regardless of how the argument is permuted -(i.e. the [http://en.wikipedia.org/wiki/Multinomial_coefficient multinomial coefficient]). Also, partitions(1,1,1) creates the permutations of \{1,2,3\} and thus there would be 3! = 6 elements in the list. +(i.e. the [http://en.wikipedia.org/wiki/Multinomial_coefficient multinomial coefficient]). + +Also, partitions(1,1,1) creates the permutations of \{1,2,3\} and thus there would be 3! = 6 elements in the list. Note: Do not use functions that are not in the standard library of the programming language you use. Your file should be written so that it can be executed on the command line and by default outputs the result of partitions(2,0,2). If the programming language does not support polyvariadic functions pass a list as an argument. @@ -35,4 +39,9 @@ Note: Do not use functions that are not in the standard library of the programmi Here are some explanatory remarks on the notation used in the task description: -\{1, \ldots, n\} denotes the set of consecutive numbers from 1 to n, e.g. \{1,2,3\} if n = 3. \Sigma is the mathematical notation for summation, e.g. \Sigma_{i=1}^3 i = 6 (see also [http://en.wikipedia.org/wiki/Summation#Capital-sigma_notation]). \mathit{arg}_1,\mathit{arg}_2,...,\mathit{arg}_n are the arguments — natural numbers — that the sought function receives. +\{1, \ldots, n\} denotes the set of consecutive numbers from 1 to n, e.g. \{1,2,3\} if n = 3. + +\Sigma is the mathematical notation for summation, e.g. \Sigma_{i=1}^3 i = 6 (see also [http://en.wikipedia.org/wiki/Summation#Capital-sigma_notation]). + +\mathit{arg}_1,\mathit{arg}_2,...,\mathit{arg}_n are the arguments — natural numbers — that the sought function receives. +

diff --git a/Task/Ordered-Partitions/C++/ordered-partitions.cpp b/Task/Ordered-Partitions/C++/ordered-partitions.cpp new file mode 100644 index 0000000000..54e5de22f0 --- /dev/null +++ b/Task/Ordered-Partitions/C++/ordered-partitions.cpp @@ -0,0 +1,57 @@ +/* + Author: Kevin Bacon [haxifix (@gmail.com)] + Date: 2018-05-16 +*/ +#include +#include +#include +#include + +void partitions(std::vector args) { + size_t sum = std::accumulate(std::begin(args), std::end(args), 0); + std::vector nums(sum); + std::iota(std::begin(nums), std::end(nums), 1); + do { + size_t total_index = 0; + std::vector> parts; + for (const auto& a : args) { + std::vector part; + bool cont = true; + for (size_t j = 0; j < a; ++j) { + for (const auto& p : part) { + if (nums[total_index] < p) { + cont = false; + break; + } + } + if (cont) { + part.push_back(nums[total_index]); + ++total_index; + } + } + if (part.size() != a) { + break; + } + parts.push_back(part); + } + if (parts.size() == args.size()) { + std::cout << "("; + for (const auto& p : parts) { + std::cout << "{ "; + for (const auto& e : p) { + std::cout << e << " "; + } + std::cout << "},"; + } + std::cout << ")," << std::endl; + } + } while (std::next_permutation(std::begin(nums), std::end(nums))); +} + +int main() { + std::vector args = { 2, 0, 2 }; + partitions(args); + std::cin.ignore(); + std::cin.get(); + return 0; +} diff --git a/Task/Ordered-Partitions/Julia/ordered-partitions.julia b/Task/Ordered-Partitions/Julia/ordered-partitions.julia new file mode 100644 index 0000000000..ba5919c864 --- /dev/null +++ b/Task/Ordered-Partitions/Julia/ordered-partitions.julia @@ -0,0 +1,24 @@ +using Combinatorics + +function masked(mask, lis) + combos = [] + idx = 1 + for step in mask + if(step < 1) + push!(combos, Array{Int,1}[]) + else + push!(combos, sort(lis[idx:idx+step-1])) + idx += step + end + end + Array{Array{Int, 1}, 1}(combos) +end + +function orderedpartitions(mask) + tostring(masklis) = replace("$masklis", r"Array{Int\d?\d?,1}|Int\d?\d?", "") + join([tostring(lis) for lis in unique([masked(mask, p) + for p in permutations(1:sum(mask))])], "\n") +end + +println(orderedpartitions([2, 0, 2])) +println(orderedpartitions([1, 1, 1])) diff --git a/Task/Ordered-Partitions/Perl-6/ordered-partitions.pl6 b/Task/Ordered-Partitions/Perl-6/ordered-partitions.pl6 index 76cbc2a50e..bfa86e6ac6 100644 --- a/Task/Ordered-Partitions/Perl-6/ordered-partitions.pl6 +++ b/Task/Ordered-Partitions/Perl-6/ordered-partitions.pl6 @@ -1,10 +1,15 @@ sub partition(@mask is copy) { - my $last = [+] @mask or return [[] xx @mask]; - sort gather for @mask.kv -> $k,$v { + my @op; + my $last = [+] @mask or return [] xx 1; + for @mask.kv -> $k, $v { next unless $v; temp @mask[$k] -= 1; - for partition @mask { .take.[$k].push($last) } + for partition @mask -> @p { + @p[$k].push: $last; + @op.push: @p; + } } + return @op; } -.perl.say for partition [2,0,2]; +.say for reverse partition [2,0,2]; diff --git a/Task/Ordered-Partitions/REXX/ordered-partitions.rexx b/Task/Ordered-Partitions/REXX/ordered-partitions.rexx index b04b261394..f86d71bad2 100644 --- a/Task/Ordered-Partitions/REXX/ordered-partitions.rexx +++ b/Task/Ordered-Partitions/REXX/ordered-partitions.rexx @@ -1,46 +1,44 @@ -/*REXX program displays ordered partitions: orderedPartitions(i, j, k, ···). */ +//*REXX program displays the ordered partitions as: orderedPartitions(i, j, k, ···). */ call orderedPartitions 2,0,2 /*Note: 2,,2 will also work. */ call orderedPartitions 1,1,1 -call orderedPartitions 1,2,0,1 /*Note: 1,2,1 will also work. */ +call orderedPartitions 1,2,0,1 /*Note: 1,2,,1 will also work. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -orderedPartitions: procedure; #=arg(); hdr=; bot.=; top.=; low=; high=; d=123456789 +orderedPartitions: procedure; #=arg(); bot.=; top.=; low=; high=; d=123456789 t=0 /*T: is the sum of all the arguments.*/ - do i=1 for #; t=t + arg(i) /*sum all the highest numbers in parts.*/ - end /*i*/ /* [↑] may have an omitted argument. */ - /* [↓] process each of the arguments. */ - do j=1 for #; _=arg(j) /* _: is the Jth argument. */ - len.j=max(1, _) /*LEN: length of args, 0=special. */ - bot.j=left(d, _); if _==0 then bot.j=0 /*define the bottom number. */ - top.j=right(left(d,t),_); if _==0 then top.j=0 /* " " top " */ + do i=1 for #; t=t + arg(i) /*sum all the highest numbers in parts.*/ + end /*i*/ /* [↑] may have an omitted argument. */ +hdr= ' partitions for: ' /*define the start of the header text. */ + do j=1 for #; _= arg(j) /* _: is the Jth argument. */ + len.j=max(1, _) /*LEN: length of args. «0 is special»*/ + bot.j=left(d, _); if _==0 then bot.j=0 /*define the bottom number for range.*/ + top.j=right(left(d,t),_); if _==0 then top.j=0 /* " " top " " " */ @.j=left(d, t); if _==0 then @.j=0 /*define the digits used for VERIFY. */ hdr=hdr _ /*build (by appending) display header.*/ low=low || bot.j; high=high || top.j /*the low and high numbers for DO below*/ end /*j*/ - -okD=left(0 || d, t+1) /*define the legal digits to be used. */ -say center(' partitions for: ' hdr" ", 60, '─') /*display centered title for the output*/ -say + /* [↓] same as: okD=left('0'd, t+1) */ + /*define the legal digits to be used. */ +okD=left(0 || d, t + 1) /*define the legal digits to be used. */ +say; hdr=center(hdr" ", 60, '═'); say hdr /*display centered title for the output*/ +say /*show a blank line (as a separator). */ do g=low to high /* [↑] generate the ordered partitions*/ - if verify(g, okD)\==0 then iterate /*filter out unwanted decimal digits. */ + if verify(g, okD) \==0 then iterate /*filter out unwanted partitions (digs)*/ p=1 /*P: is the position of a decimal dig.*/ $= /*$: will be the transformed numbers. */ - do k=1 for # /*verify the partitions numbers. */ - /*validate number: dups/ordered/repeats*/ - _=substr(g,p,len.k) /*ordered partition number to be tested*/ - if verify(_, @.k)\==0 then iterate g /*is the decimal digit not valid ? */ + do k=1 for #; _=substr(g, p, len.k) /*verify the partitions numbers. */ + if verify(_, @.k) \==0 then iterate g /*is the decimal digit not valid ? */ != /* [↓] validate the decimal number. */ - if @.k\==0 then do j=1 for length(_); z=substr(_, j, 1) - if pos(z, $)\==0 then iterate g /*previous. */ - !=!','z - if j==1 then iterate /*is firstt?*/ - if z<=substr(_, j-1, 1) then iterate g /*ordered. */ - if pos(z, _, 1+pos(z,_))\==0 then iterate g /*duplicate.*/ + if @.k\==0 then do j=1 for length(_); z=substr(_, j, 1) /*get a dig.*/ + if pos(z, $)\==0 then iterate g /*previous ?*/ + !=!','z /*add comma.*/ + if j==1 then iterate /*is firstt?*/ + if z<=substr(_, j-1, 1) then iterate g /*ordered ?*/ + if pos(z, _, 1 +pos(z, _))\==0 then iterate g /*duplicate?*/ end /*j*/ - p=p + len.k /*point to the next decimal number. */ - $=$ ' {'strip( translate(!, ,0), ,",")'}' /*dress number up by suppressing LZ ···*/ + p=p + len.k /*point to the next decimal digit (num)*/ + $=$ ' {'strip(translate(!, ,0), ,",")'}' /*dress number up by suppessing LZ ··· */ end /*k*/ - say ' ' $ /*display numbers in ordered partition.*/ + say center($, length(hdr) ) /*display numbers in ordered partition.*/ end /*g*/ -say return diff --git a/Task/Ordered-words/Aime/ordered-words.aime b/Task/Ordered-words/Aime/ordered-words.aime index b2b9abdb6c..d6272af6b1 100644 --- a/Task/Ordered-words/Aime/ordered-words.aime +++ b/Task/Ordered-words/Aime/ordered-words.aime @@ -1,57 +1,39 @@ integer -ordered(text s) +ordered(data s) { - integer a, i, l; + integer a, c, p; a = 1; - l = length(s); - if (l) { - l -= 1; - i = 0; - while (i < l) { - if (character(s, i + 1) < character(s, i)) { - a = 0; - break; - } - i += 1; + p = -1; + for (, c in s) { + if (c < p) { + a = 0; + break; + } else { + p = c; } } - return a; + a; } integer main(void) { - integer l, m; file f; - list w; text s; + index x; - f_affix(f, "unixdict.txt"); + f.affix("unixdict.txt"); - m = 0; - - while ((l = f_line(f, s)) != -1) { - if (m <= l) { - if (ordered(s)) { - if (m < l) { - m = l; - l_clear(w); - } - l_append(w, s); - } + while (f.line(s) != -1) { + if (ordered(s)) { + x.v_list(~s).append(s); } } - l = l_length(w); - m = 0; - while (m < l) { - o_text(l_q_text(w, m)); - o_byte('\n'); - m += 1; - } + l_ucall(x.back, o_, 0, "\n"); return 0; } diff --git a/Task/Ordered-words/Julia/ordered-words-1.julia b/Task/Ordered-words/Julia/ordered-words-1.julia index 5a21dccf58..c192db7a9d 100644 --- a/Task/Ordered-words/Julia/ordered-words-1.julia +++ b/Task/Ordered-words/Julia/ordered-words-1.julia @@ -1,8 +1 @@ -function isordered{T<:String}(w::T) - p = '\0' - for c in w - p <= c || return false - p = c - end - return true -end +issorted("abc") # true diff --git a/Task/Ordered-words/Julia/ordered-words-2.julia b/Task/Ordered-words/Julia/ordered-words-2.julia index c73bc5b2a1..4594386cdf 100644 --- a/Task/Ordered-words/Julia/ordered-words-2.julia +++ b/Task/Ordered-words/Julia/ordered-words-2.julia @@ -1,20 +1,4 @@ -maxlen = 0 -wlst = String[] -WL = open("ordered_words.txt", "r") - -for w in eachline(WL) - w = chomp(w) - wlen = length(w) - wlen>=maxlen && isordered(w) || continue - if wlen > maxlen - maxlen = wlen - wlst = [w] - else - push!(wlst, w) - end -end -close(WL) - -for w in wlst - println(" ", w) -end +lst = readlines("data/unixdict.txt") +filter!(issorted, lst) +filter!(x -> length(x) == maximum(length, lst), lst) +println.(lst) diff --git a/Task/Ordered-words/Maple/ordered-words.maple b/Task/Ordered-words/Maple/ordered-words.maple new file mode 100644 index 0000000000..eb042d2347 --- /dev/null +++ b/Task/Ordered-words/Maple/ordered-words.maple @@ -0,0 +1,19 @@ +lst := StringTools:-Split(Import("http://www.puzzlers.org/pub/wordlists/unixdict.txt"), "\n"): +longest := 0: +words := Array(): +i := 1: +for word in lst do + if StringTools:-IsSorted(word) then + len := StringTools:-Length(word): + if len > longest then + longest := len: + words := Array(): + words(1) := word: + i := 2: + elif len = longest then + words(i) := word: + i++: + end if; + end if; +end do; +for word in words do print(word); end do; diff --git a/Task/Ordered-words/Red/ordered-words.red b/Task/Ordered-words/Red/ordered-words.red new file mode 100644 index 0000000000..33f097de20 --- /dev/null +++ b/Task/Ordered-words/Red/ordered-words.red @@ -0,0 +1,15 @@ +Red [] +;; code to read url and save to local file: +;;data: read/binary http://www.puzzlers.org/pub/wordlists/unixdict.txt +;;write %unixdict.txt data + +max: [ "" ] ;; init array with one empty string (length 0 ) + +foreach word read/lines %unixdict.txt [ ;; read local file + len: either word = sort copy word [ length? word ] [ -1 ] ;; check if ordered and get length + case [ + len > length? first max [ max: reduce [ word ]] ;; init new block + len = length? first max [ append max word ] + ] +] +probe max diff --git a/Task/Palindrome-detection/Common-Lisp/palindrome-detection.lisp b/Task/Palindrome-detection/Common-Lisp/palindrome-detection-1.lisp similarity index 100% rename from Task/Palindrome-detection/Common-Lisp/palindrome-detection.lisp rename to Task/Palindrome-detection/Common-Lisp/palindrome-detection-1.lisp diff --git a/Task/Palindrome-detection/Common-Lisp/palindrome-detection-2.lisp b/Task/Palindrome-detection/Common-Lisp/palindrome-detection-2.lisp new file mode 100644 index 0000000000..9b939e5b20 --- /dev/null +++ b/Task/Palindrome-detection/Common-Lisp/palindrome-detection-2.lisp @@ -0,0 +1,16 @@ +;; Project : Palindrome detection +;; Date : 2018/03/06 +;; Author : Gal Zsolt [~ CalmoSoft ~] +;; Email : + +(defun palindrome(x) + (if (string= x (reverse x)) + (format t "~d" ": palindrome" (format t x)) + (format t "~d" ": not palindrome" (format t x)))) +(terpri) +(setq x "radar") +(palindrome x) +(terpri) +(setq x "books") +(palindrome x) +(terpri) diff --git a/Task/Palindrome-detection/Falcon/palindrome-detection-1.falcon b/Task/Palindrome-detection/Falcon/palindrome-detection-1.falcon new file mode 100644 index 0000000000..08d445c27c --- /dev/null +++ b/Task/Palindrome-detection/Falcon/palindrome-detection-1.falcon @@ -0,0 +1,11 @@ +/* created by Aykayayciti Earl Lamont Montgomery +April 9th, 2018 */ + +function is_palindrome(a) + a = strUpper(a).replace(" ", "") + b = a[-1:0] + return b == a +end + +a = "mom" +> is_palindrome(a) diff --git a/Task/Palindrome-detection/Falcon/palindrome-detection-2.falcon b/Task/Palindrome-detection/Falcon/palindrome-detection-2.falcon new file mode 100644 index 0000000000..247c06975e --- /dev/null +++ b/Task/Palindrome-detection/Falcon/palindrome-detection-2.falcon @@ -0,0 +1,5 @@ +/* created by Aykayayciti Earl Lamont Montgomery +April 9th, 2018 */ + +b = "mom" +> strUpper(b).replace(" ", "") == strUpper(b[-1:0]) ? "Is a palindrome" : "Is not a palindrome" diff --git a/Task/Palindrome-detection/Forth/palindrome-detection-2.fth b/Task/Palindrome-detection/Forth/palindrome-detection-2.fth index 0ce7ed47eb..58f866cada 100644 --- a/Task/Palindrome-detection/Forth/palindrome-detection-2.fth +++ b/Task/Palindrome-detection/Forth/palindrome-detection-2.fth @@ -24,7 +24,7 @@ variable temp-addr : reverse-copy ( addr1 addr2 u -- addr1 addr2 ) 0 do over I' 1- I - + over I + 1 cmove loop 2drop ; -: palindrome? ( addr1 u1 -- ) +: palindrome? ( -- ) get-phrase strip-input position-phrase reverse-copy compare 0= if ." << Valid >> Palindrome." else ." << Not >> a Palindrome." diff --git a/Task/Palindrome-detection/Modula-2/palindrome-detection.mod2 b/Task/Palindrome-detection/Modula-2/palindrome-detection.mod2 new file mode 100644 index 0000000000..12b3b02b88 --- /dev/null +++ b/Task/Palindrome-detection/Modula-2/palindrome-detection.mod2 @@ -0,0 +1,39 @@ +MODULE Palindrome; +FROM FormatString IMPORT FormatString; +FROM Terminal IMPORT WriteString,ReadChar; + +PROCEDURE IsPalindrome(str : ARRAY OF CHAR) : BOOLEAN; +VAR i,m : INTEGER; +VAR buf : ARRAY[0..63] OF CHAR; +BEGIN + i := 0; + m := HIGH(str) - 1; + WHILE i= len - then (String.sub res 0 j) + then (Bytes.sub_string res 0 j) else match str.[i] with - | ' ' | '\n' | '\t' | '\r' -> + | ' ' | '\n' | '\t' | '\r' -> aux (i+1) (j) - | _ -> - res.[j] <- str.[i]; + | _ -> + Bytes.set res j str.[i]; aux (i+1) (j+1) in aux 0 0 diff --git a/Task/Palindrome-detection/Processing/palindrome-detection b/Task/Palindrome-detection/Processing/palindrome-detection new file mode 100644 index 0000000000..b8e83b6ea9 --- /dev/null +++ b/Task/Palindrome-detection/Processing/palindrome-detection @@ -0,0 +1,21 @@ +void setup(){ + println(isPalindrome(InsertPalindromeHere)); +} + +boolean isPalindrome(string check){ + char[] letters = new char[check.length]; + string invert = " "; + string modCheck = " " + check; + for(int i = 0; i < letters.length; i++){ + letters[i] = check.charAt(i); + } + for(int i = letters.length-1; i >= 0; i--){ + invert = invert + letters[i]; + } + + if(invert == modCheck){ + return true; + } else { + return false; + } +} diff --git a/Task/Palindrome-detection/Rust/palindrome-detection-1.rust b/Task/Palindrome-detection/Rust/palindrome-detection-1.rust index 81979f29e2..b538a6adc9 100644 --- a/Task/Palindrome-detection/Rust/palindrome-detection-1.rust +++ b/Task/Palindrome-detection/Rust/palindrome-detection-1.rust @@ -1,6 +1,6 @@ fn is_palindrome(string: &str) -> bool { let half_len = string.len()/2; - string.chars().take(half_len).eq(string.chars().take(half_len).rev()) + string.chars().take(half_len).eq(string.chars().rev().take(half_len)) } macro_rules! test { diff --git a/Task/Palindrome-detection/UNIX-Shell/palindrome-detection.sh b/Task/Palindrome-detection/UNIX-Shell/palindrome-detection.sh new file mode 100644 index 0000000000..52ed8076af --- /dev/null +++ b/Task/Palindrome-detection/UNIX-Shell/palindrome-detection.sh @@ -0,0 +1,5 @@ +if [[ "${text}" == "$(rev <<< "${text}")" ]]; then + echo "Palindrome" +else + echo "Not a palindrome" +fi diff --git a/Task/Pangram-checker/ATS/pangram-checker.ats b/Task/Pangram-checker/ATS/pangram-checker-1.ats similarity index 100% rename from Task/Pangram-checker/ATS/pangram-checker.ats rename to Task/Pangram-checker/ATS/pangram-checker-1.ats diff --git a/Task/Pangram-checker/ATS/pangram-checker-2.ats b/Task/Pangram-checker/ATS/pangram-checker-2.ats new file mode 100644 index 0000000000..0ccc2c49ae --- /dev/null +++ b/Task/Pangram-checker/ATS/pangram-checker-2.ats @@ -0,0 +1,19 @@ +fn is_pangram{n:nat}(s: string(n)): bool = loop(s, i2sz(0)) where { + val letters: arrayref(bool, 26) = arrayref_make_elt(i2sz(26), false) + fn check(): bool = loop(0) where { + fun loop{i:int | i >= 0 && i <= 26}(i: int(i)) = + if i < 26 then + if letters[i] then loop(i+1) else + false + else true + } + fun add{c:int}(c: char(c)): void = + if (c >= 'A') * (c <= 'Z') then letters[char2int1(c) - char2int1('A')] := true else + if (c >= 'a') * (c <= 'z') then letters[char2int1(c) - char2int1('a')] := true + fun loop{i:nat | i <= n}..(s: string(n), i: size_t(i)): bool = + if string_is_atend(s, i) then check() else + begin + add(s[i]); + loop(s, succ(i)) + end +} diff --git a/Task/Pangram-checker/AppleScript/pangram-checker-1.applescript b/Task/Pangram-checker/AppleScript/pangram-checker-1.applescript index ff29991f66..c9f7eece12 100644 --- a/Task/Pangram-checker/AppleScript/pangram-checker-1.applescript +++ b/Task/Pangram-checker/AppleScript/pangram-checker-1.applescript @@ -1,22 +1,21 @@ use framework "Foundation" -- ( for case conversion function ) +-- PANGRAM CHECK ------------------------------------------------------------- -- isPangram :: String -> Bool on isPangram(s) script charUnUsed - property lowerCaseString : my toLowerCase(s) - - on lambda(c) + property lowerCaseString : my toLower(s) + on |λ|(c) lowerCaseString does not contain c - end lambda + end |λ| end script length of filter(charUnUsed, "abcdefghijklmnopqrstuvwxyz") = 0 end isPangram --- TEST - +-- TEST ---------------------------------------------------------------------- on run map(isPangram, {¬ "is this a pangram", ¬ @@ -25,8 +24,7 @@ on run --> {false, true} end run - --- GENERIC HIGHER ORDER FUNCTIONS (FILTER AND MAP) +-- GENERIC FUNCTIONS --------------------------------------------------------- -- filter :: (a -> Bool) -> [a] -> [a] on filter(f, xs) @@ -35,7 +33,7 @@ on filter(f, xs) set lng to length of xs repeat with i from 1 to lng set v to item i of xs - if lambda(v, i, xs) then set end of lst to v + if |λ|(v, i, xs) then set end of lst to v end repeat return lst end tell @@ -47,7 +45,7 @@ on map(f, xs) set lng to length of xs set lst to {} repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) + set end of lst to |λ|(item i of xs, i, xs) end repeat return lst end tell @@ -60,32 +58,14 @@ on mReturn(f) f else script - property lambda : f + property |λ| : f end script end if end mReturn --- OBJC function: lowercaseStringWithLocale - --- toLowerCase :: String -> String -on toLowerCase(str) +-- toLower :: String -> String +on toLower(str) set ca to current application - unwrap(wrap(str)'s ¬ - lowercaseStringWithLocale:(ca's NSLocale's currentLocale)) -end toLowerCase - --- wrap :: AS value -> NSObject -on wrap(v) - set ca to current application - ca's (NSArray's arrayWithObject:v)'s objectAtIndex:0 -end wrap - --- unwrap :: NSObject -> AS value -on unwrap(objCValue) - if objCValue is missing value then - return missing value - else - set ca to current application - item 1 of ((ca's NSArray's arrayWithObject:objCValue) as list) - end if -end unwrap + ((ca's NSString's stringWithString:(str))'s ¬ + lowercaseStringWithLocale:(ca's NSLocale's currentLocale())) as text +end toLower diff --git a/Task/Pangram-checker/Julia/pangram-checker.julia b/Task/Pangram-checker/Julia/pangram-checker.julia index 99de27e99e..9bb647d2eb 100644 --- a/Task/Pangram-checker/Julia/pangram-checker.julia +++ b/Task/Pangram-checker/Julia/pangram-checker.julia @@ -1,25 +1,20 @@ -function makepangramchecker{T<:String}(a::T) - abet = sort(unique(split(uppercase(a), ""))) - alen = length(abet) - function ispangram{T<:String}(s::T) - alen <= length(s) || return false - ps = filter(c->(c in abet), unique(split(uppercase(s), ""))) - return length(ps) == alen +function makepangramchecker(alphabet) + alphabet = Set(uppercase.(alphabet)) + function ispangram(s) + lengthcheck = length(s) ≥ length(alphabet) + return lengthcheck && all(c in uppercase(s) for c in alphabet) end + return ispangram end -tests = ["Pack my box with five dozen liquor jugs.", - "The quick brown fox jumps over a lazy dog.", - "The quick brown fox jumps\u2323over the lazy dog.", - "The five boxing wizards jump quickly.", - "This sentence contains A-Z but not the whole alphabet."] +const tests = ["Pack my box with five dozen liquor jugs.", + "The quick brown fox jumps over a lazy dog.", + "The quick brown fox jumps\u2323over the lazy dog.", + "The five boxing wizards jump quickly.", + "This sentence contains A-Z but not the whole alphabet."] -isenglishpang = makepangramchecker("abcdefghijklmnopqrstuvwxyz") +is_english_pangram = makepangramchecker('a':'z') for s in tests - print("The sentence \"", s, "\" is ") - if !isenglishpang(s) - print("not ") - end - println("a pangram.") + println("The sentence \"", s, "\" is ", is_english_pangram(s) ? "" : "not ", "a pangram.") end diff --git a/Task/Pangram-checker/Maple/pangram-checker-1.maple b/Task/Pangram-checker/Maple/pangram-checker-1.maple new file mode 100644 index 0000000000..68a252e7ad --- /dev/null +++ b/Task/Pangram-checker/Maple/pangram-checker-1.maple @@ -0,0 +1,7 @@ +#Used built-in StringTools package +is_pangram := proc(str) + local present := StringTools:-LowerCase~(select(StringTools:-HasAlpha, StringTools:-Explode(str))); + local alphabets := {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"}; + present := convert(present, set); + return evalb(present = alphabets); +end proc; diff --git a/Task/Pangram-checker/Maple/pangram-checker-2.maple b/Task/Pangram-checker/Maple/pangram-checker-2.maple new file mode 100644 index 0000000000..6bd8eb8ce6 --- /dev/null +++ b/Task/Pangram-checker/Maple/pangram-checker-2.maple @@ -0,0 +1,3 @@ +is_pangram("The quick brown fox jumps over the lazy dog."); +is_pangram("The 2 QUIck brown foxes jumped over the lazy DOG!!"); +is_pangram(""The quick brown fox jumps over the lay dog."); diff --git a/Task/Pangram-checker/REXX/pangram-checker.rexx b/Task/Pangram-checker/REXX/pangram-checker.rexx index 621df2257c..387201b795 100644 --- a/Task/Pangram-checker/REXX/pangram-checker.rexx +++ b/Task/Pangram-checker/REXX/pangram-checker.rexx @@ -1,13 +1,17 @@ /*REXX program verifies if an entered/supplied string (sentence) is a pangram. */ @abc= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' /*a list of all (Latin) capital letters*/ - do forever; say /*keep promoting 'til null (or blanks).*/ - say '──────── Please enter a pangramic sentence (or a blank to quit):'; say + do forever /*keep promoting 'til null (or blanks).*/ + say + say '──────── Please enter a pangramic sentence (or a blank to quit):' + say pull y /*this also uppercases the Y variable.*/ if y='' then leave /*if nothing entered, then we're done.*/ - ?=verify(@abc, y) /*Are all the (Latin) letters present? */ - if ?==0 then say '──────── Sentence is a pangram.' - else say "──────── Sentence isn't a pangram, missing:" substr(@abc, ?, 1) + + absent= space( translate( @abc, , y), 0) /*obtain a list of any absent letters. */ + + if absent=='' then say '──────── Sentence is a pangram.' + else say "──────── Sentence isn't a pangram, missing: " absent say end /*forever*/ diff --git a/Task/Paraffins/Scala/paraffins.scala b/Task/Paraffins/Scala/paraffins.scala new file mode 100644 index 0000000000..86464b80d2 --- /dev/null +++ b/Task/Paraffins/Scala/paraffins.scala @@ -0,0 +1,34 @@ +object Paraffins extends App { + val (nMax, nBranches) = (250, 4) + val rooted, unrooted = Array.tabulate(nMax + 1)(i => if (i < 2) BigInt(1) else BigInt(0)) + val (unrooted, c) = (rooted.clone(), new Array[BigInt](nBranches)) + + for (n <- 1 to nMax) { + def tree(br: Int, n: Int, l: Int, inSum: Int, cnt: BigInt): Unit = { + var sum = inSum + for (b <- br + 1 to nBranches) { + sum += n + if (sum > nMax || (l * 2 >= sum && b >= nBranches)) return + + if (b == br + 1) c(br) = rooted(n) * cnt + else { + c(br) = c(br) * (rooted(n) + BigInt(b - br - 1)) + c(br) = c(br) / BigInt(b - br) + } + if (l * 2 < sum) unrooted(sum) = unrooted(sum) + c(br) + if (b < nBranches) rooted(sum) = rooted(sum) + c(br) + + for (m <- n - 1 to 1 by -1) tree(b, m, l, sum, c(br)) + } + } + + def bicenter(s: Int): Unit = if ((s & 1) == 0) { + val halves = rooted(s / 2) + unrooted(s) = unrooted(s) + ((halves + BigInt(1)) * halves >> 1) + } + + tree(0, n, n, 1, BigInt(1)) + bicenter(n) + println(f"$n%3d: ${unrooted(n)}%s") + } +} diff --git a/Task/Parallel-calculations/Julia/parallel-calculations.julia b/Task/Parallel-calculations/Julia/parallel-calculations.julia new file mode 100644 index 0000000000..d0521a6acb --- /dev/null +++ b/Task/Parallel-calculations/Julia/parallel-calculations.julia @@ -0,0 +1,21 @@ +using Primes + +factortodict(d, n) = (d[minimum(collect(keys(factor(n))))] = n) + +# Numbers are from from the Perl 6 example. +numbers = [64921987050997300559, 70251412046988563035, 71774104902986066597, + 83448083465633593921, 84209429893632345702, 87001033462961102237, + 87762379890959854011, 89538854889623608177, 98421229882942378967, + 259826672618677756753, 262872058330672763871, 267440136898665274575, + 278352769033314050117, 281398154745309057242, 292057004737291582187] + +mins = Dict() + +Base.@sync( + Threads.@threads for n in numbers + factortodict(mins, n) + end +) + +answer = maximum(keys(mins)) +println("The number that has the largest minimum prime factor is $(mins[answer]), with a smallest factor of $answer") diff --git a/Task/Parallel-calculations/Kotlin/parallel-calculations.kotlin b/Task/Parallel-calculations/Kotlin/parallel-calculations.kotlin new file mode 100644 index 0000000000..995650d314 --- /dev/null +++ b/Task/Parallel-calculations/Kotlin/parallel-calculations.kotlin @@ -0,0 +1,52 @@ +// version 1.1.51 + +import java.util.stream.Collectors + +/* returns the number itself, its smallest prime factor and all its prime factors */ +fun primeFactorInfo(n: Int): Triple> { + if (n <= 1) throw IllegalArgumentException("Number must be more than one") + if (isPrime(n)) return Triple(n, n, listOf(n)) + val factors = mutableListOf() + var factor = 2 + var nn = n + while (true) { + if (nn % factor == 0) { + factors.add(factor) + nn /= factor + if (nn == 1) return Triple(n, factors.min()!!, factors) + if (isPrime(nn)) factor = nn + } + else if (factor >= 3) factor += 2 + else factor = 3 + } +} + +fun isPrime(n: Int) : Boolean { + if (n < 2) return false + if (n % 2 == 0) return n == 2 + if (n % 3 == 0) return n == 3 + var d = 5 + while (d * d <= n) { + if (n % d == 0) return false + d += 2 + if (n % d == 0) return false + d += 4 + } + return true +} + +fun main(args: Array) { + val numbers = listOf( + 12757923, 12878611, 12878893, 12757923, 15808973, 15780709, 197622519 + ) + val info = numbers.stream() + .parallel() + .map { primeFactorInfo(it) } + .collect(Collectors.toList()) + val maxFactor = info.maxBy { it.second }!!.second + val results = info.filter { it.second == maxFactor } + println("The following number(s) have the largest minimal prime factor of $maxFactor:") + for (result in results) { + println(" ${result.first} whose prime factors are ${result.third}") + } +} diff --git a/Task/Parallel-calculations/Perl-6/parallel-calculations.pl6 b/Task/Parallel-calculations/Perl-6/parallel-calculations.pl6 index ee472bfb0e..59fdfc7c57 100644 --- a/Task/Parallel-calculations/Perl-6/parallel-calculations.pl6 +++ b/Task/Parallel-calculations/Perl-6/parallel-calculations.pl6 @@ -1,5 +1,32 @@ -my @nums = 12757923, 12878611, 123456789, 15808973, 15780709, 197622519; +my @nums = 64921987050997300559, 70251412046988563035, 71774104902986066597, + 83448083465633593921, 84209429893632345702, 87001033462961102237, + 87762379890959854011, 89538854889623608177, 98421229882942378967, + 259826672618677756753, 262872058330672763871, 267440136898665274575, + 278352769033314050117, 281398154745309057242, 292057004737291582187; -my @factories; -@factories[$_] := factors(@nums[$_]) for ^@nums; -my $gmf = ([max] @factories»[0] »=>« @nums).value; +my \factories = @nums.hyper.map: *.&prime-factors.cache; +say my $gmf = {}.append(factories»[0] »=>« @nums).max: {+.key}; + +sub prime-factors ( Int $n where * > 0 ) { + return $n if $n.is-prime; + return [] if $n == 1; + my $factor = find-factor( $n ); + sort flat prime-factors( $factor ), prime-factors( $n div $factor ); +} + +sub find-factor ( Int $n, $constant = 1 ) { + my $x = 2; + my $rho = 1; + my $factor = 1; + while $factor == 1 { + $rho *= 2; + my $fixed = $x; + for ^$rho { + $x = ( $x * $x + $constant ) % $n; + $factor = ( $x - $fixed ) gcd $n; + last if 1 < $factor; + } + } + $factor = find-factor( $n, $constant + 1 ) if $n == $factor; + $factor; +} diff --git a/Task/Parallel-calculations/Perl/parallel-calculations.pl b/Task/Parallel-calculations/Perl/parallel-calculations.pl new file mode 100644 index 0000000000..dab5e03243 --- /dev/null +++ b/Task/Parallel-calculations/Perl/parallel-calculations.pl @@ -0,0 +1,19 @@ +use ntheory qw/factor vecmax/; +use threads; +use threads::shared; +my @results :shared; + +my $tnum = 0; +$_->join() for + map { threads->create('tfactor', $tnum++, $_) } + (qw/576460752303423487 576460752303423487 576460752303423487 112272537195293 + 115284584522153 115280098190773 115797840077099 112582718962171 299866111963290359/); + +my $lmf = vecmax( map { $_->[1] } @results ); +print "Largest minimal factor of $lmf found in:\n"; +print " $_->[0] = [@$_[1..$#$_]]\n" for grep { $_->[1] == $lmf } @results; + +sub tfactor { + my($tnum, $n) = @_; + push @results, shared_clone([$n, factor($n)]); +} diff --git a/Task/Parametric-polymorphism/00DESCRIPTION b/Task/Parametric-polymorphism/00DESCRIPTION index 3d5c777449..bb9ef69b98 100644 --- a/Task/Parametric-polymorphism/00DESCRIPTION +++ b/Task/Parametric-polymorphism/00DESCRIPTION @@ -1,5 +1,11 @@ [[wp:Parametric Polymorphism|Parametric Polymorphism]] is a way to define types or functions that are generic over other types. The genericity can be expressed by using ''type variables'' for the parameter type, and by a mechanism to explicitly or implicitly replace the type variables with concrete types when necessary. -Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. A good example is a container type, let's say a binary tree, together with some function that traverses the tree, say, a ''map''-function that operates on every element of the tree. + +;Task: +Write a small example for a type declaration that is parametric over another type, together with a short bit of code (and its type signature) that uses it. + + +A good example is a container type, let's say a binary tree, together with some function that traverses the tree, say, a ''map''-function that operates on every element of the tree. This language feature only applies to statically-typed languages. +

diff --git a/Task/Parametric-polymorphism/Julia/parametric-polymorphism.julia b/Task/Parametric-polymorphism/Julia/parametric-polymorphism.julia new file mode 100644 index 0000000000..0af70095a8 --- /dev/null +++ b/Task/Parametric-polymorphism/Julia/parametric-polymorphism.julia @@ -0,0 +1,12 @@ +mutable struct Tree{T} + value::T + lchild::Nullable{Tree{T}} + rchild::Nullable{Tree{T}} +end + +function replaceall!(t::Tree{T}, v::T) where T + t.value = v + isnull(lchild) || replaceall(get(lchild), v) + isnull(rchild) || replaceall(get(rchild), v) + return t +end diff --git a/Task/Parametric-polymorphism/REXX/parametric-polymorphism.rexx b/Task/Parametric-polymorphism/REXX/parametric-polymorphism.rexx index bad78b141a..fb4acf888c 100644 --- a/Task/Parametric-polymorphism/REXX/parametric-polymorphism.rexx +++ b/Task/Parametric-polymorphism/REXX/parametric-polymorphism.rexx @@ -1,4 +1,4 @@ -/*REXX program demonstrates (with displays) a method of parametric polymorphism in REXX.*/ +/*REXX program demonstrates (with displays) a method of parametric polymorphism. */ call newRoot 1.00, 3 /*new root, and also indicate 3 stems.*/ /* [↓] no need to label the stems. */ call addStem 1.10 /*a new stem and its initial value. */ @@ -12,24 +12,21 @@ call modRoot 50 /*modRoot will add fifty to all call sayNodes /*display some nicely formatted values.*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -addStem: nodes=nodes+1; do j=1 for stems; root.nodes.j=arg(1); end; return +addStem: nodes=nodes + 1; do j=1 for stems; root.nodes.j=arg(1); end; return +newRoot: parse arg @,stems; nodes=-1; call addStem copies('═',9); call addStem @; return /*──────────────────────────────────────────────────────────────────────────────────────*/ -modRoot: do j=1 for nodes /*traipse through all the defined nodes*/ - do k=1 for stems - if datatype(root.j.k, 'N') then root.j.k=root.j.k + arg(1) /*bias.*/ - end /*k*/ /* [↑] only add if numeric stem value.*/ - end /*j*/ - return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -newRoot: stems=arg(2); nodes= -1 /*set NODES to a kind of "null". */ - call addStem copies('═', 9); call addStem arg(1) - return -/*──────────────────────────────────────────────────────────────────────────────────────*/ -sayNodes: say; do j=0 to nodes; _= /*ensure each of the nodes gets shown. */ - do k=1 for stems; _=_ right(root.j.k, 9) - end /*k*/ - say substr(_, 2) /*ignore the first (leading) blank. */ +modRoot: arg #; do j=1 for nodes /*traipse through all the defined nodes*/ + do k=1 for stems + if datatype(root.j.k,'N') then root.j.k=root.j.k + # /*add bias.*/ + end /*k*/ /* [↑] only add if numeric stem value.*/ end /*j*/ - - say left('', stems*11) || '('nodes" nodes)" /*also show number of nodes.*/ return +/*──────────────────────────────────────────────────────────────────────────────────────*/ +sayNodes: w=9; do j=0 to nodes; _= /*ensure each of the nodes gets shown. */ + do k=1 for stems; _=_ center(root.j.k, w) /*concatenate a node*/ + end /*k*/ + $=word('node='j, 1 + (j<1) ) /*define a label for this line's output*/ + say center($, w) substr(_, 2) /*ignore 1st (leading) blank which was */ + end /*j*/ /* [↑] caused by concatenation.*/ + say /*show a blank line to separate outputs*/ + return /* [↑] extreme indentation to terminal*/ diff --git a/Task/Parametrized-SQL-statement/Haskell/parametrized-sql-statement.hs b/Task/Parametrized-SQL-statement/Haskell/parametrized-sql-statement.hs new file mode 100644 index 0000000000..536d69530a --- /dev/null +++ b/Task/Parametrized-SQL-statement/Haskell/parametrized-sql-statement.hs @@ -0,0 +1,20 @@ +module Main (main) where + +import Database.HDBC (IConnection, commit, run, toSql) + +updatePlayers :: IConnection a => a -> String -> Int -> Bool -> Int -> IO Bool +updatePlayers conn name score active jerseyNum = do + rowCount <- run conn + "UPDATE players\ + \ SET name = ?, score = ?, active = ?\ + \ WHERE jerseyNum = ?" + [ toSql name + , toSql score + , toSql active + , toSql jerseyNum + ] + commit conn + return $ rowCount == 1 + +main :: IO () +main = undefined diff --git a/Task/Parametrized-SQL-statement/Julia/parametrized-sql-statement.julia b/Task/Parametrized-SQL-statement/Julia/parametrized-sql-statement.julia new file mode 100644 index 0000000000..487e0680a6 --- /dev/null +++ b/Task/Parametrized-SQL-statement/Julia/parametrized-sql-statement.julia @@ -0,0 +1,19 @@ +using SQLite + +name = "Smith, Steve" +jerseys = Dict("Smith, Steve" => 99) +sqlbool(tf::Bool) = if(tf) "TRUE" else "FALSE" end + +db = SQLite.DB() # no filename given, so create an in-memory temporary +SQLite.execute!(db, "create table players (id integer primary key, + name text, + score number, + active bool, + jerseynum integer)") + +SQLite.query(db, "INSERT INTO players (name, score, active, jerseynum) values ('Jones, James', 9, 'FALSE', 99)") +SQLite.query(db, "UPDATE players SET name = ?, score = ?, active = ? WHERE jerseynum = ?"; + values = ["Smith, Steve", 42, sqlbool(true), jerseys[name]]) + +tbl = SQLite.query(db, "SELECT * from players") +println(tbl) diff --git a/Task/Parametrized-SQL-statement/Kotlin/parametrized-sql-statement.kotlin b/Task/Parametrized-SQL-statement/Kotlin/parametrized-sql-statement.kotlin new file mode 100644 index 0000000000..bc367d9ee2 --- /dev/null +++ b/Task/Parametrized-SQL-statement/Kotlin/parametrized-sql-statement.kotlin @@ -0,0 +1,24 @@ +// Version 1.2.41 + +import java.sql.DriverManager +import java.sql.Connection + +fun main(args: Array) { + val url = "jdbc:mysql://localhost:3306/test" + val username = "example" + val password = "password123" + val conn = DriverManager.getConnection(url, username, password) + val query = conn.prepareStatement( + "UPDATE players SET name = ?, score = ?, active = ? WHERE jerseyNum = ?" + ) + with (query) { + setString(1, "Smith, Steve") + setInt(2, 42) + setBoolean(3, true) + setInt(4, 99) + val rowCount = executeUpdate() + if (rowCount == 0) println("Update failed") + close() + } + conn.close() +} diff --git a/Task/Parse-an-IP-Address/Julia/parse-an-ip-address.julia b/Task/Parse-an-IP-Address/Julia/parse-an-ip-address.julia new file mode 100644 index 0000000000..870919aaa9 --- /dev/null +++ b/Task/Parse-an-IP-Address/Julia/parse-an-ip-address.julia @@ -0,0 +1,34 @@ +const testdata = ["127.0.0.1", "127.0.0.1:80", "::1", "[::1]:80", + "2605:2700:0:3::4713:93e3", "[2605:2700:0:3::4713:93e3]:80", + "::ffff:192.168.173.22", "[::ffff:192.168.173.22]:80", + "1::", "[1::]:80", "::", "[::]:80"] + +maybev4(ip) = search(ip, '.') > 0 && length(matchall(r":", ip)) < 2 +maybev6(ip) = length(matchall(r":", ip)) > 1 + +function parseip(ip) + if (mat = match(r"^\[([:.\da-fA-F]+)\]:(\d+)$", ip))!= nothing || + (mat = match(r"^([\d.]+)[:/](\d+)$", ip)) != nothing + port = mat.captures[2] + ip = mat.captures[1] + else + port = "none" + end + if maybev4(ip) + println("Processing ip v4 $ip") + iphex = hex(Int(Base.IPv4(ip))) + addresspace = "IPv4" + elseif maybev6(ip) + println("Processing ip v6 $ip") + iphex = hex(UInt128(Base.IPv6(ip))) + addresspace = "IPv6" + else + throw("Bad IP address argument $ip") + end + iphex, addresspace, port +end + +for ip in testdata + hx, add, por = parseip(ip) + println("For input $ip, IP in hex is $hx, address space $add, port $por.") +end diff --git a/Task/Parse-an-IP-Address/Scala/parse-an-ip-address.scala b/Task/Parse-an-IP-Address/Scala/parse-an-ip-address.scala new file mode 100644 index 0000000000..f63e68d301 --- /dev/null +++ b/Task/Parse-an-IP-Address/Scala/parse-an-ip-address.scala @@ -0,0 +1,296 @@ +object IPparser extends App { + + /* + Parse an IP (v4/v6) Address + + This software can parse all ipv4/ipv6 address text representations + of IP Address in common usage against the IEF RFC 5952 specification. + + The results of the parse are: + - The parts of the text are valid representations. This is indicated in the list by a ✔ or ✘. + - The intended version; 4 or 6. + - Compliance with RFC 5952 in respect with double colons Compressed zeroes expansion ('::') and lower case letters. + - Hexadecimal representation of the intended IP address. + - If part in the text the port number which is optional. + - The used text string search pattern. + + As much of the information is produced if there are invalid parts in the remark field. + */ + + def myCases = Map( + "http:" -> IPInvalidAddressComponents(remark = "No match at all: 'http:'."), + "http://" -> IPInvalidAddressComponents(remark = "No match at all: 'http://'."), + "http:// " -> IPInvalidAddressComponents(remark = "No match at all: 'http:// '."), + "http://127.0.0.1/" -> ResultContainer(4, BigInt("7F000001", 16)), + "http://127.0.0.1:80/" -> ResultContainer(4, BigInt("7F000001", 16), Some(80)), + "http://127.0.0.1:65536" -> + IPInvalidAddressComponents(4, BigInt("7F000001", 16), Some(65536), remark = "Port number out of range."), + "http://192.168.0.1" -> ResultContainer(4, BigInt("C0A80001", 16)), + "http:/1::" -> ResultContainer(6, BigInt("10000000000000000000000000000", 16)), + "http:/2001:0db8:0:0:0:0:1428:57ab/" -> ResultContainer(6, BigInt("20010db80000000000000000142857ab", 16)), + "2001:0db8:0:0:8d3:0:0:0" -> ResultContainer(6, BigInt("20010db80000000008d3000000000000", 16)), + "2001:db8:0:0:8d3::" -> ResultContainer(6, BigInt("20010db80000000008d3000000000000", 16)), + "http:/2001:db8:3:4::192.0.2.33" -> ResultContainer(6, BigInt("20010db80003000400000000c0000221", 16)), + "2001:db8:85a3:0:0:8a2e:370:7334" -> ResultContainer(6, BigInt("20010db885a3000000008a2e03707334", 16)), + "2001:db8::1428:57ab" -> ResultContainer(6, BigInt("20010db80000000000000000142857ab", 16)), + "2001:db8::8d3:0:0:0" -> ResultContainer(6, BigInt("20010db80000000008d3000000000000", 16)), + "256.0.0.0" -> IPInvalidAddressComponents(4, remark = "Invalid octets."), + "2605:2700:0:3::4713:93e3" -> ResultContainer(6, BigInt("260527000000000300000000471393e3", 16)), + "::" -> ResultContainer(6, BigInt("00000000000000000000000000000000", 16)), + "1::8" -> ResultContainer(6, BigInt("00010000000000000000000000000008", 16)), + "::1" -> ResultContainer(6, BigInt("00000000000000000000000000000001", 16)), + "::192.168.0.1" -> ResultContainer(6, BigInt("000000000000000000000000c0a80001", 16)), + "::255.255.255.255" -> ResultContainer(6, BigInt("000000000000000000000000ffffffff", 16)), + "http:/[::255.255.255.255]:65536" -> + IPInvalidAddressComponents(6, BigInt("000000000000000000000000ffffffff", 16), Some(65536), remark = "Port number out of range."), + "::2:3:4:5:6:7:8" -> ResultContainer(6, BigInt("00000002000300040005000600070008", 16), strictRFC5952 = false), + "::8" -> ResultContainer(6, BigInt("00000000000000000000000000000008", 16)), + "::c0a8:1" -> ResultContainer(6, BigInt("000000000000000000000000c0a80001", 16)), + "::ffff:0:255.255.255.255" -> ResultContainer(6, BigInt("0000000000000000ffff0000ffffffff", 16)), + "::ffff:127.0.0.0.1" -> IPInvalidAddressComponents(4, remark = "Address puntation error: ':127.0.0.0.1'."), + "::ffff:127.0.0.1" -> ResultContainer(6, BigInt("00000000000000000000ffff7f000001", 16)), + "::ffff:192.168.0.1" -> ResultContainer(6, BigInt("00000000000000000000ffffc0a80001", 16)), + "::ffff:192.168.173.22" -> ResultContainer(6, BigInt("00000000000000000000ffffc0a8ad16", 16)), + "::ffff:255.255.255.255" -> ResultContainer(6, BigInt("00000000000000000000ffffffffffff", 16)), + "::ffff:71.19.147.227" -> ResultContainer(6, BigInt("00000000000000000000ffff471393e3", 16)), + "1:2:3:4:5:6:7::" -> ResultContainer(6, BigInt("00010002000300040005000600070000", 16), strictRFC5952 = false), + "8000:2:3:4:5:6:7::" -> ResultContainer(6, BigInt("80000002000300040005000600070000", 16), strictRFC5952 = false), + "1:2:3:4:5:6::8" -> ResultContainer(6, BigInt("00010002000300040005000600000008", 16), strictRFC5952 = false), + "1:2:3:4:5::8" -> ResultContainer(6, BigInt("00010002000300040005000000000008", 16)), + "1::7:8" -> ResultContainer(6, BigInt("00010000000000000000000000070008", 16)), + "a::b::1" -> IPInvalidAddressComponents(remark = "Noise found: 'a::b::1'."), + "fff:ffff:ffff:ffff:ffff:ffff:ffff:ffff" -> ResultContainer(6, BigInt("0fffffffffffffffffffffffffffffff", 16)), + "FFFF:ffff:ffff:ffff:ffff:ffff:ffff:ffff" -> ResultContainer(6, BigInt("ffffffffffffffffffffffffffffffff", 16), strictRFC5952 = false), + "ffff:ffff:ffff:fffg:ffff:ffff:ffff:ffff" -> IPInvalidAddressComponents(remark = "No match at all: 'ffff:ffff:ffff:fffg…'."), + "g::1" -> IPInvalidAddressComponents(6, remark ="Invalid input 'g::1'."), + "[g::1]:192.0.2.33" -> IPInvalidAddressComponents(4, remark = "Address puntation error: ':192.0.2.33'."), + "1:2:3:4:5:6:7:8" -> ResultContainer(6, BigInt("00010002000300040005000600070008", 16)), + "1:2:3:4:5::7:8" -> ResultContainer(6, BigInt("00010002000300040005000000070008", 16), strictRFC5952 = false), + "1:2:3:4::6:7:8" -> ResultContainer(6, BigInt("00010002000300040000000600070008", 16), strictRFC5952 = false), + "1:2:3:4::8" -> ResultContainer(6, BigInt("00010002000300040000000000000008", 16)), + "1:2:3::5:6:7:8" -> ResultContainer(6, BigInt("00010002000300000005000600070008", 16), strictRFC5952 = false), + "1:2:3::8" -> ResultContainer(6, BigInt("00010002000300000000000000000008", 16)), + "1:2::4:5:6:7:8" -> ResultContainer(6, BigInt("00010002000000040005000600070008", 16), strictRFC5952 = false), + "1:2::8" -> ResultContainer(6, BigInt("00010002000000000000000000000008", 16)), + "1::3:4:5:6:7:8" -> ResultContainer(6, BigInt("00010000000300040005000600070008", 16), strictRFC5952 = false), + "1::4:5:6:7:8" -> ResultContainer(6, BigInt("00010000000000040005000600070008", 16)), + "1::5:6:7:8" -> ResultContainer(6, BigInt("00010000000000000005000600070008", 16)), + "[1::6:7:8]" -> ResultContainer(6, BigInt("0010000000000000000000600070008", 16)), + "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff" -> ResultContainer(6, BigInt("ffffffffffffffffffffffffffffffff", 16)), + "64:ff9b::192.0.2.33" -> ResultContainer(6, BigInt("0064ff9b0000000000000000c0000221", 16)), + "64:ff9b::256.0.2.33" -> + IPInvalidAddressComponents(6, BigInt("0064ff9b000000000000000000000000", 16), remark = "Invalid octets."), + "[2001:db8:85a3:8d3:1319:8a2e:370:7348]:443" -> ResultContainer(6, BigInt("20010db885a308d313198a2e03707348", 16), Some(443)), + "[2001:db8:85a3:8d3:1319:8a2e:370:7348]:100000" -> + IPInvalidAddressComponents(6, BigInt("20010db885a308d313198a2e03707348", 16), Some(100000), remark = "Port number out of range."), + "[2605:2700:0:3::4713:93e3]:80" -> ResultContainer(6, BigInt("260527000000000300000000471393e3", 16), Some(80)), + "[::ffff:192.168.0.1]:22" -> ResultContainer(6, BigInt("00000000000000000000ffffc0a80001", 16), Some(22)), + "[::ffff:192.168.173.22]:80" -> ResultContainer(6, BigInt("00000000000000000000ffffc0a8ad16", 16), Some(80)), + "[::ffff:71.19.147.227]:80" -> ResultContainer(6, BigInt("00000000000000000000FFFF471393E3", 16), Some(80)), + "2001:0DB8:0:0:0:0:1428:57AB" -> ResultContainer(6, BigInt("20010DB80000000000000000142857AB", 16), strictRFC5952 = false), + "2001:0DB8:0:0:8D3:0:0:0" -> ResultContainer(6, BigInt("20010DB80000000008D3000000000000", 16), strictRFC5952 = false), + "2001:DB8:0:0:8D3::" -> ResultContainer(6, BigInt("20010DB80000000008D3000000000000", 16), strictRFC5952 = false), + "2001:DB8:3:4::192.0.2.33" -> ResultContainer(6, BigInt("20010DB80003000400000000C0000221", 16), strictRFC5952 = false), + "2001:DB8:85A3:0:0:8A2E:370:7334" -> ResultContainer(6, BigInt("20010DB885A3000000008A2E03707334", 16), strictRFC5952 = false), + "2001:DB8::1428:57AB" -> ResultContainer(6, BigInt("20010DB80000000000000000142857AB", 16), strictRFC5952 = false), + "2001:DB8::8D3:0:0:0" -> ResultContainer(6, BigInt("20010DB80000000008D3000000000000", 16), strictRFC5952 = false), + "2605:2700:0:3::4713:93E3" -> ResultContainer(6, BigInt("260527000000000300000000471393E3", 16), strictRFC5952 = false), + "::192.168.0.1" -> ResultContainer(6, BigInt("000000000000000000000000C0A80001", 16)), + "::255.255.255.255" -> ResultContainer(6, BigInt("000000000000000000000000FFFFFFFF", 16)), + "::C0A8:1" -> ResultContainer(6, BigInt("000000000000000000000000c0a80001", 16), strictRFC5952 = false), + "::FFFF:0:255.255.255.255" -> ResultContainer(6, BigInt("0000000000000000FFFF0000FFFFFFFF", 16), strictRFC5952 = false), + "::FFFF:127.0.0.0.1" -> IPInvalidAddressComponents(4, remark = "Address puntation error: ':127.0.0.0.1'."), + "::FFFF:127.0.0.1" -> ResultContainer(6, BigInt("00000000000000000000FFFF7F000001", 16), strictRFC5952 = false), + "::FFFF:192.168.0.1" -> ResultContainer(6, BigInt("00000000000000000000FFFFC0A80001", 16), strictRFC5952 = false), + "::FFFF:192.168.173.22" -> ResultContainer(6, BigInt("00000000000000000000FFFFC0A8AD16", 16), strictRFC5952 = false), + "::FFFF:255.255.255.255" -> ResultContainer(6, BigInt("00000000000000000000FFFFFFFFFFFF", 16), strictRFC5952 = false), + "::FFFF:71.19.147.227" -> ResultContainer(6, BigInt("00000000000000000000FFFF471393E3", 16), strictRFC5952 = false), + "[1::]:80" -> ResultContainer(6, BigInt("00010000000000000000000000000000", 16), Some(80)), + "[2001:DB8:85A3:8D3:1319:8A2E:370:7348]:443" -> ResultContainer(6, BigInt("20010db885a308d313198a2e03707348", 16), Some(443), strictRFC5952 = false), + "[2605:2700:0:3::4713:93E3]:80" -> ResultContainer(6, BigInt("260527000000000300000000471393e3", 16), Some(80), strictRFC5952 = false), + "[::1]:80" -> ResultContainer(6, BigInt("00000000000000000000000000000001", 16), Some(80)), + "[::1]:65536" -> + IPInvalidAddressComponents(6, BigInt("00000000000000000000000000000001", 16), Some(65536), remark = "Port number out of range."), + "[::]:80" -> ResultContainer(6, BigInt("00000000000000000000000000000000", 16), Some(80)), + "[::FFFF:192.168.0.1]:22" -> ResultContainer(6, BigInt("00000000000000000000ffffc0a80001", 16), Some(22), strictRFC5952 = false), + "[::FFFF:192.168.173.22]:80" -> ResultContainer(6, BigInt("00000000000000000000ffffc0a8ad16", 16), Some(80), strictRFC5952 = false), + "[::FFFF:71.19.147.227]:80" -> ResultContainer(6, BigInt("00000000000000000000ffff471393e3", 16), Some(80), strictRFC5952 = false), + "A::B::1" -> IPInvalidAddressComponents(remark = "Noise found: 'A::B::1'."), + "FFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF" -> ResultContainer(6, BigInt("0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16), strictRFC5952 = false), + "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF" -> ResultContainer(6, BigInt("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16), strictRFC5952 = false), + "FFFF:FFFF:FFFF:FFFG:FFFF:FFFF:FFFF:FFFF" -> IPInvalidAddressComponents(remark = "No match at all: 'FFFF:FFFF:FFFF:FFFG…'."), + "G::1" -> IPInvalidAddressComponents(6, remark = "Invalid input 'G::1'."), + "64:FF9B::192.0.2.33" -> ResultContainer(6, BigInt("0064FF9B0000000000000000C0000221", 16), strictRFC5952 = false), + "64:FF9B::256.0.2.33" -> IPInvalidAddressComponents(6, BigInt("0064FF9B000000000000000000000000", 16), remark = "Invalid octets.") + ) + + def IPInvalidAddressComponents(version: Int = 0, + address: BigInt = BigInt(0), + port: Option[Int] = None, + valid: Boolean = false, + remark: String = "", + strict: Boolean = false) = ResultContainer(version, address, port, valid, remark, strict) + + case class ResultContainer(version: Int, + address: BigInt, + port: Option[Int] = None, + valid: Boolean = true, + remark: String = "", + strictRFC5952: Boolean = true) + + class IpAddress(val originalString: String) { + + import IpAddress._ + + val (usedPattern, result: ResultContainer) = originalString match { + case trapPattern() => (trapPattern, IPInvalidAddressComponents(remark = s"Noise found: '${shortener(originalString)}'.")) + case allIpV6PortedPatternsCompiled(adr, port) => parseIpV6(adr, Option(port).map(_.toInt)) + case allIpV6UnspecPortPatternsCompiled(adr) => parseIpV6(adr) + case ipV4PortSpecCompiled(adr, port) => (ipV4PortSpecCompiled, parseIpV4(adr, Option(port).map(_.toInt))) + case _ => ("Exhausted of all matches.", IPInvalidAddressComponents(remark = s"No match at all: '${shortener(originalString, 19)}'.")) + } + + override def toString: String = { + def hexAddr = if (result.version == 6) f"${result.address}%#034x" else f"${result.address}%#010x" + + def validInd = if (result.valid) '\u2714' else '\u2718' + + def rfc5952 = if (result.strictRFC5952) "comply" else "broken" + + def version = result.version match { + case 0 => " ?" + case 4 => "IPv4" + case 6 => "IPv6" + } + + def surround(s: String) = if (result.valid) s" $s " else s"($s)" + + def port = if (result.port.isDefined) surround(result.port.get.toString) else if (result.valid) " " else "? " + + def hexAddrField = f"${if (result.valid || result.address != 0) surround(hexAddr) else "? "}%36s " + + f"${shortener(originalString, 45)}%46s $version $validInd $rfc5952 $hexAddrField $port%8s ${result.remark}%-40s $usedPattern" + } + + def shortener(s: String, maxlength: Int = 12): String = { + val size = s.length() + s.substring(0, math.min(size, maxlength)) + (if (size > maxlength) "…" else "") + } + + private def parseIpV6(ipAddress: String, port: Option[Int] = None): (String, ResultContainer) = { + + def colonedStringToBigInt(colonedString: String): (BigInt, Int) = { + // Compressed zeroes expansion + val ar = if (colonedString contains "::") colonedString.split("::", 2) else Array("", colonedString) + val (left, right) = (ar.head.split(':').filterNot(_.isEmpty), ar(1).split(':').filterNot(_.isEmpty)) + val sixteenBitExpansions = 8 - (right.length + left.length) + + ((left ++ Seq.fill(sixteenBitExpansions)("0") ++ right) + .map(BigInt(_, 16).toLong).map(BigInt(_)).reduceLeft((acc, i) => (acc << 16) | i), + sixteenBitExpansions) + } + + def parseEmbeddedV4(seg: String, ip4Seg: String, usedRegEx: String): (String, ResultContainer) = { + val (ip4, ip6Parser, test) = + (parseIpV4(ip4Seg), colonedStringToBigInt(seg.replaceFirst(ipV4Regex("3"), "0:0")), portNumberTest(port)) + + (usedRegEx, ResultContainer(originalString, 6, ip4.address + ip6Parser._1, port, + ip4.valid && test.isEmpty, ip4.remark + test, ip4.valid && test.isEmpty)) + } + + if (!ipAddress.forall((('A' to 'F') ++ ('a' to 'f') ++ ('0' to '9') ++ Vector(':', '.')).contains(_))) + ("[^:.[0-9][A-F][a-f]]", IPInvalidAddressComponents(6, remark = s"Invalid input '${shortener(ipAddress)}'.")) + else + ipAddress match { + case pattern10Compiled(seg, ip4Seg) => parseEmbeddedV4(seg, ip4Seg, pattern10Compiled.toString()) + case pattern11Compiled(seg, ip4Seg) => parseEmbeddedV4(seg, ip4Seg, pattern11Compiled.toString()) + case ip6PatternsRawCompiled(seg, _*) => + val (ip6Parser, test) = (colonedStringToBigInt(seg), portNumberTest(port)) + + (ip6PatternsRawCompiled.toString(), + ResultContainer(ipAddress, 6, ip6Parser._1, port, + valid = test.isEmpty, test, strictRFC5952 = ip6Parser._2 != 1 && test.isEmpty)) + case _ => ("V6 match exhausted.", IPInvalidAddressComponents(6, remark = "V6 address puntation error.")) + } + } // parseIpV6 + + + private def parseIpV4(sIP: String, port: Option[Int] = None): ResultContainer = { + + def wordsToNum(words: Array[Long]): Long = words.reduceLeft((acc, i) => (acc << 8) | i) + + if (sIP.head.isDigit && sIP.matches(ipV4Regex("3"))) { + val octets = sIP.split('.').map(_.toLong) + if (octets.forall(_ < 256)) { + val portNumberOK = portNumberTest(port) + ResultContainer(4, BigInt(wordsToNum(octets)), port, portNumberOK.isEmpty, portNumberOK, portNumberOK.isEmpty) + } else IPInvalidAddressComponents(4, remark = "Invalid octets.") + } + else IPInvalidAddressComponents(4, remark = s"Address puntation error: '${shortener(sIP)}'.") + } + + private def portNumberTest(port: Option[Int]) = if (port.isEmpty || port.get < math.pow(2, 16)) "" else "Port number out of range." + } // IpAddress + + object IpAddress { + val (ip6PatternsRawCompiled, pattern11Compiled) = (ipV6Patterns.mkString("(", "|", ")").r, embeddedV4patterns()(1).r) + val (trapPattern, pattern10Compiled) = (""".*?(?:(?:\w*:{2,}?){2,}?\w)|(?:\[?)""".r, embeddedV4patterns().head.r) + val allIpV6PortedPatternsCompiled = ("""[^\\.]*?\[(""" + allIpV6 +""")\](?::(\d{1,6}))?[^\.:]*?""").r + val allIpV6UnspecPortPatternsCompiled = (""".*?(""" + allIpV6 +""")[^\.:]*?""").r + val ipV4PortSpecCompiled = s".*?([:.\\]]?${ipV4Regex()})(?::(\\d{1,6}))?.*?".r + + // Make a regex pattern with non-capturing groups by the disabling the capturing group syntax (?:). + def allIpV6 = (embeddedV4patterns("(?:") ++ ipV6Patterns).map(s => "(?:" + s.drop(1)).mkString("|") + + def ipV6Patterns = { + def ipV6SegRegWC = """\w{1,4}""" + + Seq( + s"((?::(?:(?::$ipV6SegRegex){1,7}|:)))", + s"((?:$ipV6SegRegWC:(?::$ipV6SegRegex){1,6}))", + s"((?:$ipV6SegRegex:){1,2}(?::$ipV6SegRegex){1,5})", + s"((?:$ipV6SegRegex:){1,3}(?::$ipV6SegRegex){1,4})", + s"((?:$ipV6SegRegex:){1,4}(?::$ipV6SegRegex){1,3})", + s"((?:$ipV6SegRegex:){1,5}(?::$ipV6SegRegex){1,2})", + s"((?:$ipV6SegRegex:){1,6}:$ipV6SegRegex)", + s"((?:$ipV6SegRegex:){1,7}:)", + s"((?:$ipV6SegRegex:){7}$ipV6SegRegex)" + ) + } + + private def embeddedV4patterns(nonCapturePrefix: String = "(") = + Seq(s"(::(?:(?:FFFF|ffff)(?::0{1,4}){0,1}:){0,1}$nonCapturePrefix${ipV4Regex("3")}))", + s"((?:$ipV6SegRegex:){1,4}:$nonCapturePrefix${ipV4Regex("3")}))") + + private def ipV6SegRegex = """[\dA-Fa-f]{1,4}""" + + private def ipV4Regex(octets: String = "3,") = s"(?:\\d{1,3}\\.){$octets}\\d{1,3}" + } + + object ResultContainer { + def apply(orginalString: String, version: Int, + address: BigInt, port: Option[Int], + valid: Boolean, remark: String, + strictRFC5952: Boolean): ResultContainer = + // To comply with strictRFC5952 all alpha character must be lowercase too. + this (version, address, port, valid, remark, strictRFC5952 && !orginalString.exists(_.isUpper)) + } + + { + val headline = Seq(f"${"IP addresses to be parsed. "}%46s", "Ver.", f"${"S"}%1s", "RFC5952", + f"${"Hexadecimal IP address"}%34s", f"${"Port "}%10s", f"${" Remark"}%-40s", f"${" Effective RegEx"}%-40s") + + println(headline.mkString("|") + "\n" + headline.map(s => "-" * s.length).mkString("+")) + + val cases: Set[IpAddress] = myCases.keySet.map(new IpAddress(_)) + + println(cases.toList.sortBy(s => (s.originalString.length, s.originalString)).mkString("\n")) + logInfo(s"Concluding: ${myCases.size} cases processed, ${cases.count(_.result.valid)} valid ✔ and ${cases.count(!_.result.valid)} invalid ✘.") + logInfo("Successfully completed without errors.") + + def logInfo(info: String) { + println(f"[Info][${System.currentTimeMillis() - executionStart}%5d ms]" + info) + } + } + +} // IPparser cloc.exe : 235 loc diff --git a/Task/Parsing-RPN-calculator-algorithm/Factor/parsing-rpn-calculator-algorithm-1.factor b/Task/Parsing-RPN-calculator-algorithm/Factor/parsing-rpn-calculator-algorithm-1.factor new file mode 100644 index 0000000000..bce2e29cfc --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/Factor/parsing-rpn-calculator-algorithm-1.factor @@ -0,0 +1,4 @@ +IN: scratchpad 3 4 2 * 1 5 - 2 3 ^ ^ / + + +--- Data stack: +3+1/8192 diff --git a/Task/Parsing-RPN-calculator-algorithm/Factor/parsing-rpn-calculator-algorithm-2.factor b/Task/Parsing-RPN-calculator-algorithm/Factor/parsing-rpn-calculator-algorithm-2.factor new file mode 100644 index 0000000000..61e176cff5 --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/Factor/parsing-rpn-calculator-algorithm-2.factor @@ -0,0 +1,2 @@ +{ 3 4 2 * 1 5 - 2 3 ^ ^ / + } [ 1quotation ] map +[ dup pprint bl call datastack . ] each diff --git a/Task/Parsing-RPN-calculator-algorithm/Maxima/parsing-rpn-calculator-algorithm-1.maxima b/Task/Parsing-RPN-calculator-algorithm/Maxima/parsing-rpn-calculator-algorithm-1.maxima new file mode 100644 index 0000000000..a10f9055ea --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/Maxima/parsing-rpn-calculator-algorithm-1.maxima @@ -0,0 +1,39 @@ +rmod(i, j) := mod(j, i)$ +rpow(x, y) := y^x$ + +rpn(sexpr) := ( + operands: [], + expr: charlist(sexpr), + + for token in expr do ( + if token = "+" then ( + push(pop(operands) + pop(operands), operands) + ) + elseif token = "-" then ( + push(-1 * (pop(operands) - pop(operands)), operands) + ) + elseif token = "*" then ( + push(pop(operands) * pop(operands), operands) + ) + elseif token = "/" then ( + push(1 / (pop(operands) / pop(operands)), operands) + ) + elseif token = "%" then ( + push(rmod(pop(operands), pop(operands)), operands) + ) + elseif token = "^" then ( + push(rpow(pop(operands), pop(operands)), operands) + ) + elseif token # " " then ( + push(parse_string(token), operands) + ), + + if token # " " then ( + print(token, " : ", operands) + ) + ), + + pop(operands) +)$ + +rpn("3 4 2 * 1 5 - 2 3 ^ ^ / +"), numer; diff --git a/Task/Parsing-RPN-calculator-algorithm/Maxima/parsing-rpn-calculator-algorithm-2.maxima b/Task/Parsing-RPN-calculator-algorithm/Maxima/parsing-rpn-calculator-algorithm-2.maxima new file mode 100644 index 0000000000..a277f58176 --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/Maxima/parsing-rpn-calculator-algorithm-2.maxima @@ -0,0 +1,15 @@ +(%i5) ev(rpn("3 4 2 * 1 5 - 2 3 ^ ^ / +"),numer) +3 : [3] +4 : [4, 3] +2 : [2, 4, 3] +* : [8, 3] +1 : [1, 8, 3] +5 : [5, 1, 8, 3] +- : [- 4, 8, 3] +2 : [2, - 4, 8, 3] +3 : [3, 2, - 4, 8, 3] +^ : [8, - 4, 8, 3] +^ : [65536, 8, 3] +/ : [1.220703125e-4, 3] ++ : [3.0001220703125] +(%o5) 3.0001220703125 diff --git a/Task/Parsing-RPN-calculator-algorithm/N-t-roff/parsing-rpn-calculator-algorithm-1.n b/Task/Parsing-RPN-calculator-algorithm/N-t-roff/parsing-rpn-calculator-algorithm-1.n new file mode 100644 index 0000000000..1c7a1f7cf2 --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/N-t-roff/parsing-rpn-calculator-algorithm-1.n @@ -0,0 +1,118 @@ +.ig + RPN parser implementation in TROFF + + Originally written on November 21, 2017. + Modified for Rosettacode on December 3, 2017. + + Stephanie Björk (Katt) +.. +.\" \(*A stack implementation +.nr Ac 0 +.af Ac 1 +.de APUSH +.if (\\n(Ac>=0)&(\\n(Ac<27) \{ \ +. nr Ac +1 +. af Ac A +. nr A\\n(Ac \\$1 +. af Ac 1 +\} +.. +.de APOP +.if (\\n(Ac>0)&(\\n(Ac<27) \{ \ +. af Ac A +. rr A\\n(Ac \\$1 +. af Ac 1 +. nr Ac -1 +.. +.\" Facility to print entire stack +.de L2 +.af Ac 1 +.if \\n(Li<=\\n(Ac \{ \ +. af Li A +\\n(A\\n(Li +. af Li 1 +. nr Li +1 +. L2 +\} +.. +.de APRINT +.nr Li 1 +.L2 +.br +.. +.\" Integer exponentiation algorithm +.de L1 +.if \\n(Li<\\$2 \{ \ +. nr Rs \\n(Rs*\\$1 +. nr Li +1 +. L1 \\$1 \\$2 +\} +.. +.de EXP +.nr Li 0 +.nr Rs 1 +.L1 \\$1 \\$2 +.. +.\" RPN Parser +.de REAP +.af Ac A +.nr O2 \\n(A\\n(Ac +.af Ac 1 +.nr Ai \\n(Ac-1 +.af Ai A +.nr O1 \\n(A\\n(Ai +.APOP +.APOP +.. +.de RPNPUSH +.ie '\\$1'+' \{ \ +. REAP +. nr Rs \\n(O1+\\n(O2 +\} +.el \{ \ +. ie '\\$1'-' \{ \ +. REAP +. nr Rs \\n(O1-\\n(O2 +\} +. el \{ \ +. ie '\\$1'*' \{ \ +. REAP +. nr Rs \\n(O1*\\n(O2 +\} +. el \{ \ +. ie '\\$1'/' \{ \ +. REAP +. nr Rs \\n(O1/\\n(O2 +\} +. el \{ \ +. ie '\\$1'%' \{ \ +. REAP +. nr Rs \\n(O1%\\n(O2 +\} +. el \{ \ +. ie '\\$1'^' \{ \ +. REAP +. EXP \\n(O1 \\n(O2 +\} +. el .nr Rs \\$1 +\} +\} +\} +\} +\} +.APUSH \\n(Rs +.APRINT +.. +.de RPNPRINT +.if \\n(Ac>1 .tm ERROR (rpn.roff): Malformed input expression. Evaluation stack size: \\n(Ac > 1 . +\\n(AA +.. +.de RPNPARSE +.RPNPUSH \\$1 +.ie \\n(.$>1 \{ \ +. shift +. RPNPARSE \\$@ +\} +.el .RPNPRINT +.. +.RPNPARSE 3 4 2 * 1 5 - 2 3 ^ ^ / + \" Our input expression diff --git a/Task/Parsing-RPN-calculator-algorithm/N-t-roff/parsing-rpn-calculator-algorithm-2.n b/Task/Parsing-RPN-calculator-algorithm/N-t-roff/parsing-rpn-calculator-algorithm-2.n new file mode 100644 index 0000000000..fd93d79cc7 --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/N-t-roff/parsing-rpn-calculator-algorithm-2.n @@ -0,0 +1,14 @@ + 3 + 3 4 + 3 4 2 + 3 8 + 3 8 1 + 3 8 1 5 + 3 8 ‐4 + 3 8 ‐4 2 + 3 8 ‐4 2 3 + 3 8 ‐4 8 + 3 8 16 + 3 0 + 3 +3 diff --git a/Task/Parsing-RPN-calculator-algorithm/N-t-roff/parsing-rpn-calculator-algorithm-3.n b/Task/Parsing-RPN-calculator-algorithm/N-t-roff/parsing-rpn-calculator-algorithm-3.n new file mode 100644 index 0000000000..2f207dc430 --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/N-t-roff/parsing-rpn-calculator-algorithm-3.n @@ -0,0 +1,89 @@ +.ig +=========================== + Array implementation +=========================== +.. +.de end +.. +.de array +. nr \\$1.c 0 1 +. de \\$1.push end +. nr \\$1..\\\\n+[\\$1.c] \\\\$1 +. end +. de \\$1.pop end +. if \\\\n[\\$1.c]>0 \{ \ +. rr \\$1..\\\\n[\\$1.c] +. nr \\$1.c -1\ +. \} +. end +. de \\$1.dump end +. nr i 0 1 +. rm ou +. while \\\\n+i<=\\\\n[\\$1.c] \{ \ +. as ou "\\\\n[\\$1..\\\\ni] +. \} +. tm \\\\*(ou +. rr i +. end +.. +.ig +========================== + End array implementation +========================== +.. +.array stack +.de hyper3 +. nr rs 1 +. nr i 0 1 +. while \\n+i<=\\$2 .nr rs \\n(rs*\\$1 +. rr i +.. +.de pop2 +. nr O2 \\n[\\$1..\\n[\\$1.c]] +. \\$1.pop +. nr O1 \\n[\\$1..\\n[\\$1.c]] +. \\$1.pop +.. +.de rpn +. ie '\\$1'+' \{ \ +. pop2 stack +. nr rs \\n(O1+\\n(O2 +. \} +. el \{ \ +. ie '\\$1'-' \{ \ +. pop2 stack +. nr rs \\n(O1-\\n(O2 +. \} +. el \{ \ +. ie '\\$1'*' \{ \ +. pop2 stack +. nr rs \\n(O1*\\n(O2 +. \} +. el \{ \ +. ie '\\$1'/' \{ \ +. pop2 stack +. nr rs \\n(O1/\\n(O2 +. \} +. el \{ \ +. ie '\\$1'%' \{ \ +. pop2 stack +. nr rs \\n(O1%\\n(O2 +. \} +. el \{ \ +. ie '\\$1'^' \{ \ +. pop2 stack +. hyper3 \\n(O1 \\n(O2 +. \} +. el .nr rs \\$1 +. \}\}\}\}\} +. +. stack.push \\n(rs +. stack.dump +. +. if \\n(.$>1 \{ \ +. shift +. rpn \\$@ +. \} +.. +.rpn 3 4 2 * 1 5 - 2 3 ^ ^ / + +.stack.dump diff --git a/Task/Parsing-RPN-calculator-algorithm/N-t-roff/parsing-rpn-calculator-algorithm-4.n b/Task/Parsing-RPN-calculator-algorithm/N-t-roff/parsing-rpn-calculator-algorithm-4.n new file mode 100644 index 0000000000..83c29c9749 --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/N-t-roff/parsing-rpn-calculator-algorithm-4.n @@ -0,0 +1,14 @@ +3 +3 4 +3 4 2 +3 8 +3 8 1 +3 8 1 5 +3 8 -4 +3 8 -4 2 +3 8 -4 2 3 +3 8 -4 8 +3 8 16 +3 0 +3 +3 diff --git a/Task/Parsing-RPN-calculator-algorithm/PARI-GP/parsing-rpn-calculator-algorithm-1.pari b/Task/Parsing-RPN-calculator-algorithm/PARI-GP/parsing-rpn-calculator-algorithm-1.pari new file mode 100644 index 0000000000..31861541fe --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/PARI-GP/parsing-rpn-calculator-algorithm-1.pari @@ -0,0 +1,39 @@ +estack = []; + +epush(x) = { + estack = vector(#estack + 1, i, if(i <= #estack, estack[i], x)); + return(#estack); +}; + +epop() = { + local(val = estack[#estack]); + estack = vector(#estack - 1, i, estack[i]); + return(val); +}; + +registerRPNToken(t) = { + local(o1, o2); + + if(type(t) == "t_STR", + if(t == "+", o2 = epop(); o1 = epop(); epush(o1 + o2), + if(t == "-", o2 = epop(); o1 = epop(); epush(o1 - o2), + if(t == "*", o2 = epop(); o1 = epop(); epush(o1 * o2), + if(t == "/", o2 = epop(); o1 = epop(); epush(o1 / o2), + if(t == "%", o2 = epop(); o1 = epop(); epush(o1 % o2), + if(t == "^", o2 = epop(); o1 = epop(); epush(o1 ^ o2) + )))))), + if(type(t) == "t_INT" || type(t) == "t_REAL" || type(t) == "t_FRAC", + epush(t)) + ); + print(estack); +}; + +parseRPN(s) = { + estack = []; + for(i = 1, #s, registerRPNToken(s[i])); + + if(#estack > 1, error("Malformed postfix expression.")); + return(estack[1]); +}; + +parseRPN([3, 4, 2, "*", 1, 5, "-", 2, 3, "^", "^", "/", "+"]); \\ Our input expression diff --git a/Task/Parsing-RPN-calculator-algorithm/PARI-GP/parsing-rpn-calculator-algorithm-2.pari b/Task/Parsing-RPN-calculator-algorithm/PARI-GP/parsing-rpn-calculator-algorithm-2.pari new file mode 100644 index 0000000000..8a88369c1f --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/PARI-GP/parsing-rpn-calculator-algorithm-2.pari @@ -0,0 +1,13 @@ +[3] +[3, 4] +[3, 4, 2] +[3, 8] +[3, 8, 1] +[3, 8, 1, 5] +[3, 8, -4] +[3, 8, -4, 2] +[3, 8, -4, 2, 3] +[3, 8, -4, 8] +[3, 8, 65536] +[3, 1/8192] +[24577/8192] diff --git a/Task/Parsing-RPN-calculator-algorithm/UNIX-Shell/parsing-rpn-calculator-algorithm-1.sh b/Task/Parsing-RPN-calculator-algorithm/UNIX-Shell/parsing-rpn-calculator-algorithm-1.sh new file mode 100644 index 0000000000..5010ea80fe --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/UNIX-Shell/parsing-rpn-calculator-algorithm-1.sh @@ -0,0 +1,65 @@ +#!/bin/sh + +exp() { + R=1 + local i=1 + + while [ $i -le $2 ]; do + R=$(($R * $1)) + i=$(($i + 1)) + done +} + +rpn() { + local O1 O2 stack + + while [ $# -ge 1 ]; do + grep -iE '^-?[0-9]+$' <<< "$1" > /dev/null 2>&1 + if [ "$?" -eq 0 ]; then + stack=`sed -e '$a'"$1" -e '/^$/d' <<< "$stack"` + else + grep -iE '^[-\+\*\/\%\^]$' <<< "$1" > /dev/null 2>&1 + if [ "$?" -eq 0 ]; then + O2=`sed -n '$p' <<< "$stack"` + stack=`sed '$d' <<< "$stack"` + O1=`sed -n '$p' <<< "$stack"` + + case "$1" in + '+') + stack=`sed -e '$a'"$(($O1 + $O2))" -e '/^$/d' -e '$d' \ + <<< "$stack"`;; + '-') + stack=`sed -e '$a'"$(($O1 - $O2))" -e '/^$/d' -e '$d' \ + <<< "$stack"`;; + '*') + stack=`sed -e '$a'"$(($O1 * $O2))" -e '/^$/d' -e '$d' \ + <<< "$stack"`;; + '/') + stack=`sed -e '$a'"$(($O1 / $O2))" -e '/^$/d' -e '$d' \ + <<< "$stack"`;; + '%') + stack=`sed -e '$a'"$(($O1 % $O2))" -e '/^$/d' -e '$d' \ + <<< "$stack"`;; + '^') + exp $O1 $O2 + stack=`sed -e '$a'"$(($R))" -e '/^$/d' -e '$d' <<< \ + "$stack"`;; + esac + else + echo "Unknown RPN token \`\`$1''" + fi + fi + echo "$1" ":" $stack + shift + done + + sed -n '1p' <<< "$stack" + if [ "`wc -l <<< "$stack"`" -gt 1 ]; then + echo "Malformed input expression" > /dev/stderr + return 1 + else + return 0 + fi +} + +rpn 3 4 2 '*' 1 5 '-' 2 3 '^' '^' '/' '+' diff --git a/Task/Parsing-RPN-calculator-algorithm/UNIX-Shell/parsing-rpn-calculator-algorithm-2.sh b/Task/Parsing-RPN-calculator-algorithm/UNIX-Shell/parsing-rpn-calculator-algorithm-2.sh new file mode 100644 index 0000000000..c27332041f --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/UNIX-Shell/parsing-rpn-calculator-algorithm-2.sh @@ -0,0 +1,14 @@ +3 : 3 +4 : 3 4 +2 : 3 4 2 +* : 3 8 +1 : 3 8 1 +5 : 3 8 1 5 +- : 3 8 -4 +2 : 3 8 -4 2 +3 : 3 8 -4 2 3 +^ : 3 8 -4 8 +^ : 3 8 65536 +/ : 3 0 ++ : 3 +3 diff --git a/Task/Parsing-RPN-to-infix-conversion/C++/parsing-rpn-to-infix-conversion.cpp b/Task/Parsing-RPN-to-infix-conversion/C++/parsing-rpn-to-infix-conversion.cpp index b2eb5a992b..3eb8ee9212 100644 --- a/Task/Parsing-RPN-to-infix-conversion/C++/parsing-rpn-to-infix-conversion.cpp +++ b/Task/Parsing-RPN-to-infix-conversion/C++/parsing-rpn-to-infix-conversion.cpp @@ -1,3 +1,4 @@ +/*Corrected by Abhishek Ghosh, 6th November 2017*/ #include #include #include @@ -31,7 +32,7 @@ void AddToken(stack* stack, const string& token) else { // it's an operator if (stack->size() < 2) - throw exception("Stack underflow"); + cout<<"Stack underflow"; auto rhs = stack->top(); Parenthesize(&rhs, token, false); stack->pop(); @@ -58,7 +59,7 @@ string ToInfix(const string& src) } } if (stack.size() != 1) - throw exception("Incomplete expression"); + cout<<"Incomplete expression"; return stack.top().expr_; } diff --git a/Task/Parsing-RPN-to-infix-conversion/C/parsing-rpn-to-infix-conversion.c b/Task/Parsing-RPN-to-infix-conversion/C/parsing-rpn-to-infix-conversion.c new file mode 100644 index 0000000000..2764e9b718 --- /dev/null +++ b/Task/Parsing-RPN-to-infix-conversion/C/parsing-rpn-to-infix-conversion.c @@ -0,0 +1,127 @@ +/*Abhishek Ghosh, 7th November 2017*/ + +#include +#include +#include + +char** components; +int counter = 0; + +typedef struct elem{ + char data[10]; + struct elem* left; + struct elem* right; +}node; + +typedef node* tree; + +int precedenceCheck(char oper1,char oper2){ + return (oper1==oper2)? 0:(oper1=='^')? 1:(oper2=='^')? 2:(oper1=='/')? 1:(oper2=='/')? 2:(oper1=='*')? 1:(oper2=='*')? 2:(oper1=='+')? 1:(oper2=='+')? 2:(oper1=='-')? 1:2; +} + +int isOperator(char c){ + return (c=='+'||c=='-'||c=='*'||c=='/'||c=='^'); +} + +void inorder(tree t){ + if(t!=NULL){ + if(t->left!=NULL && isOperator(t->left->data[0])==1 && (precedenceCheck(t->data[0],t->left->data[0])==1 || (precedenceCheck(t->data[0],t->left->data[0])==0 && t->data[0]=='^'))){ + printf("("); + inorder(t->left); + printf(")"); + } + else + inorder(t->left); + + printf(" %s ",t->data); + + if(t->right!=NULL && isOperator(t->right->data[0])==1 && (precedenceCheck(t->data[0],t->right->data[0])==1 || (precedenceCheck(t->data[0],t->right->data[0])==0 && t->data[0]!='^'))){ + printf("("); + inorder(t->right); + printf(")"); + } + else + inorder(t->right); + } +} + +char* getNextString(){ + if(counter<0){ + printf("\nInvalid RPN !"); + exit(0); + } + return components[counter--]; +} + +tree buildTree(char* obj,char* trace){ + tree t = (tree)malloc(sizeof(node)); + + strcpy(t->data,obj); + + t->right = (isOperator(obj[0])==1)?buildTree(getNextString(),trace):NULL; + t->left = (isOperator(obj[0])==1)?buildTree(getNextString(),trace):NULL; + + if(trace!=NULL){ + printf("\n"); + inorder(t); + } + + return t; +} + +int checkRPN(){ + int i, operSum = 0, numberSum = 0; + + if(isOperator(components[counter][0])==0) + return 0; + + for(i=0;i<=counter;i++) + (isOperator(components[i][0])==1)?operSum++:numberSum++; + + return (numberSum - operSum == 1); +} + +void buildStack(char* str){ + int i; + char* token; + + for(i=0;str[i]!=00;i++) + if(str[i]==' ') + counter++; + + components = (char**)malloc((counter + 1)*sizeof(char*)); + + token = strtok(str," "); + + i = 0; + + while(token!=NULL){ + components[i] = (char*)malloc(strlen(token)*sizeof(char)); + strcpy(components[i],token); + token = strtok(NULL," "); + i++; + } +} + +int main(int argC,char* argV[]){ + int i; + tree t; + + if(argC==1) + printf("Usage : %s ",argV[0]); + else{ + buildStack(argV[1]); + + if(checkRPN()==0){ + printf("\nInvalid RPN !"); + return 0; + } + + t = buildTree(getNextString(),argV[2]); + + printf("\nFinal infix expression : "); + inorder(t); + } + + return 0; +} diff --git a/Task/Parsing-RPN-to-infix-conversion/Julia/parsing-rpn-to-infix-conversion.julia b/Task/Parsing-RPN-to-infix-conversion/Julia/parsing-rpn-to-infix-conversion.julia new file mode 100644 index 0000000000..c5e5e61aca --- /dev/null +++ b/Task/Parsing-RPN-to-infix-conversion/Julia/parsing-rpn-to-infix-conversion.julia @@ -0,0 +1,20 @@ +function parseRPNstring(rpns) + infix = [] + rpn = split(rpns) + for tok in rpn + if all(isnumber, tok) + push!(infix, parse(Int, tok)) + else + last = pop!(infix) + prev = pop!(infix) + push!(infix, Expr(:call, Symbol(tok), prev, last)) + println("Current step: $infix") + end + end + infix +end + +unany(s) = replace(string(s), r"Any\[:\((.+)\)\]", s"\1") + +println("The final infix result: ", parseRPNstring("3 4 2 * 1 5 - 2 3 ^ ^ / +") |> unany, "\n") +println("The final infix result: ", parseRPNstring("1 2 + 3 4 + ^ 5 6 + ^") |> unany) diff --git a/Task/Parsing-RPN-to-infix-conversion/Kotlin/parsing-rpn-to-infix-conversion.kotlin b/Task/Parsing-RPN-to-infix-conversion/Kotlin/parsing-rpn-to-infix-conversion.kotlin new file mode 100644 index 0000000000..e7a3081962 --- /dev/null +++ b/Task/Parsing-RPN-to-infix-conversion/Kotlin/parsing-rpn-to-infix-conversion.kotlin @@ -0,0 +1,52 @@ +// version 1.2.0 + +import java.util.Stack + +class Expression(var ex: String, val op: String = "", val prec: Int = 3) { + + constructor(e1: String, e2: String, o: String) : + this("$e1 $o $e2", o, OPS.indexOf(o) / 2) + + override fun toString() = ex + + companion object { + const val OPS = "-+/*^" + } +} + +fun postfixToInfix(postfix: String): String { + val expr = Stack() + val rx = Regex("""\s+""") + for (token in postfix.split(rx)) { + val c = token[0] + val idx = Expression.OPS.indexOf(c) + if (idx != -1 && token.length == 1) { + val r = expr.pop() + val l = expr.pop() + val opPrec = idx / 2 + if (l.prec < opPrec || (l.prec == opPrec && c == '^')) { + l.ex = "(${l.ex})" + } + if (r.prec < opPrec || (r.prec == opPrec && c != '^')) { + r.ex = "(${r.ex})" + } + expr.push(Expression(l.ex, r.ex, token)) + } + else { + expr.push(Expression(token)) + } + println("$token -> $expr") + } + return expr.peek().ex +} + +fun main(args: Array) { + val es = listOf( + "3 4 2 * 1 5 - 2 3 ^ ^ / +", + "1 2 + 3 4 + ^ 5 6 + ^" + ) + for (e in es) { + println("Postfix : $e") + println("Infix : ${postfixToInfix(e)}\n") + } +} diff --git a/Task/Parsing-Shunting-yard-algorithm/8th/parsing-shunting-yard-algorithm.8th b/Task/Parsing-Shunting-yard-algorithm/8th/parsing-shunting-yard-algorithm.8th new file mode 100644 index 0000000000..6853300124 --- /dev/null +++ b/Task/Parsing-Shunting-yard-algorithm/8th/parsing-shunting-yard-algorithm.8th @@ -0,0 +1,130 @@ +\ Convert infix expression to postfix, using 'shunting-yard' algorithm +\ https://en.wikipedia.org/wiki/Shunting-yard_algorithm + + +\ precedence of infix tokens. negative means 'right-associative', otherwise left: +with: n +{ + "+" : 2, + "-" : 2, + "/" : 3, + "*" : 3, + "^" : -4, + "(" : 1, + ")" : -1 +} var, tokens + +: precedence \ s -- s n + tokens @ over m:@ nip + null? if drop 0 then ; + +var ops +var out + +: >out \ x -- + out @ swap + a:push drop ; + +: >ops \ op prec -- + 2 a:close + ops @ swap + a:push drop ; + +: a:peek -1 a:@ ; + +\ Check the array for items with greater or equal precedence, +\ and move them to the out queue: +: pop-ops \ op prec ops -- op prec ops + \ empty array, do nothing: + a:len not if ;; then + + \ Look at top of ops stack: + a:peek a:open \ op p ops[] op2 p2 + + \ if the 'p2' is not less p (meaning item on top of stack is greater or equal + \ in precedence), then pop the item from the ops stack and push onto the out: + 3 pick \ p2 p + < not if + \ op p ops[] op2 + >out a:pop drop recurse ;; + then + drop ; + + +: right-paren + "RIGHTPAREN" . cr + 2drop + \ move non-left-paren from ops and move to out: + ops @ + repeat + a:len not if + break + else + a:pop a:open + 1 = if + 2drop ;; + else + >out + then + then + again drop ; + +: .state \ n -- +drop \ "Token: %s\n" s:strfmt . + "Out: " . + out @ ( . space drop ) a:each drop cr + "ops: " . ops @ ( 0 a:@ . space 2drop ) a:each drop cr cr ; + +: handle-number \ s n -- + "NUMBER " . over . cr + drop >out ; + +: left-paren \ s n -- + "LEFTPAREN" . cr + >ops ; + +: handle-op \ s n -- + "OPERATOR " . over . cr + \ op precedence + \ Is the current op left-associative? + dup sgn 1 = if + \ it is, so check the ops array for items with greater or equal precedence, + \ and move them to the out queue: + ops @ pop-ops drop + then + \ push the operator + >ops ; + +: handle-token \ s -- + precedence dup not if + \ it's a number: + handle-number + else + dup 1 = if left-paren + else dup -1 = if right-paren + else handle-op + then then + then ; + +: infix>postfix \ s -- s + /\s+/ s:/ \ split to indiviual whitespace-delimited tokens + + \ Initialize our data structures + a:new ops ! a:new out ! + + ( + nip dup >r + handle-token + r> .state + ) a:each drop + \ remove all remaining ops and put on output: + out @ + ops @ a:rev + ( nip a:open drop a:push ) a:each drop + \ final string: + " " a:join ; + +"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3" infix>postfix . cr + +"Expected: \n" . "3 4 2 * 1 5 - 2 3 ^ ^ / +" . cr +bye diff --git a/Task/Parsing-Shunting-yard-algorithm/D/parsing-shunting-yard-algorithm.d b/Task/Parsing-Shunting-yard-algorithm/D/parsing-shunting-yard-algorithm.d new file mode 100644 index 0000000000..825da25bf9 --- /dev/null +++ b/Task/Parsing-Shunting-yard-algorithm/D/parsing-shunting-yard-algorithm.d @@ -0,0 +1,90 @@ +import std.container; +import std.stdio; + +void main() { + string infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"; + writeln("infix: ", infix); + writeln("postfix: ", infixToPostfix(infix)); +} + +string infixToPostfix(string infix) { + import std.array; + + /* To find out the precedence, we take the index of the + token in the ops string and divide by 2 (rounding down). + This will give us: 0, 0, 1, 1, 2 */ + immutable ops = ["+", "-", "/", "*", "^"]; + + auto sb = appender!string; + SList!int stack; + + // split the input on whitespace + foreach (token; infix.split) { + if (token.empty) { + continue; + } + + int idx = ops.indexOf(token); + + // check for operator + if (idx != -1) { + while (!stack.empty) { + int prec2 = stack.peek / 2; + int prec1 = idx / 2; + if (prec2 > prec1 || (prec2 == prec1 && token != "^")) { + sb.put(ops[stack.pop]); + sb.put(' '); + } else { + break; + } + } + stack.push(idx); + } else if (token == "(") { + stack.push(-2); // -2 stands for '(' + } else if (token == ")") { + // until '(' on stack, pop operators. + while (stack.peek != -2) { + sb.put(ops[stack.pop]); + sb.put(' '); + } + stack.pop(); + } else { + sb.put(token); + sb.put(' '); + } + } + + while (!stack.empty) { + sb.put(ops[stack.pop]); + sb.put(' '); + } + + return sb.data; +} + +// Find the first index of the specified value, or -1 if not found. +int indexOf(T)(const T[] a, const T v) { + foreach(i,e; a) { + if (e == v) { + return i; + } + } + return -1; +} + +// Convienience for adding a new element +void push(T)(ref SList!T s, T v) { + s.insertFront(v); +} + +// Convienience for accessing the top element +auto peek(T)(SList!T s) { + return s.front; +} + +// Convienience for removing and returning the top element +auto pop(T)(ref SList!T s) { + auto v = s.front; + s.removeFront; + return v; +} diff --git a/Task/Parsing-Shunting-yard-algorithm/JavaScript/parsing-shunting-yard-algorithm.js b/Task/Parsing-Shunting-yard-algorithm/JavaScript/parsing-shunting-yard-algorithm.js index e55864c6ea..a98515481e 100644 --- a/Task/Parsing-Shunting-yard-algorithm/JavaScript/parsing-shunting-yard-algorithm.js +++ b/Task/Parsing-Shunting-yard-algorithm/JavaScript/parsing-shunting-yard-algorithm.js @@ -65,7 +65,5 @@ for (var i = 0; i < infix.length; i++) { s.pop(); // pop (, but not onto the output queue } } -while (s.length()>0){ - postfix += s.pop() + " "; -} +postfix += s.dataStore.reverse().join(" "); print(postfix); diff --git a/Task/Parsing-Shunting-yard-algorithm/Julia/parsing-shunting-yard-algorithm.julia b/Task/Parsing-Shunting-yard-algorithm/Julia/parsing-shunting-yard-algorithm.julia new file mode 100644 index 0000000000..02cc372800 --- /dev/null +++ b/Task/Parsing-Shunting-yard-algorithm/Julia/parsing-shunting-yard-algorithm.julia @@ -0,0 +1,41 @@ +function parseinfix2rpn(s) + outputq = [] + opstack = [] + infix = split(s) + for tok in infix + if all(isnumber, tok) + push!(outputq, tok) + elseif tok == "(" + push!(opstack, tok) + elseif tok == ")" + while !isempty(opstack) && (op = pop!(opstack)) != "(" + push!(outputq, op) + end + else # operator + while !isempty(opstack) + op = pop!(opstack) + if Base.operator_precedence(Symbol(op)) > Base.operator_precedence(Symbol(tok)) || + (Base.operator_precedence(Symbol(op)) == + Base.operator_precedence(Symbol(tok)) && op != "^") + push!(outputq, op) + else + push!(opstack, op) # undo peek + break + end + end + push!(opstack, tok) + end + println("The working output stack is $outputq") + end + while !isempty(opstack) + if (op = pop!(opstack)) == "(" + throw("mismatched parentheses") + else + push!(outputq, op) + end + end + outputq +end + +teststring = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3" +println("\nResult: $teststring becomes $(join(parseinfix2rpn(teststring), ' '))") diff --git a/Task/Parsing-Shunting-yard-algorithm/Kotlin/parsing-shunting-yard-algorithm.kotlin b/Task/Parsing-Shunting-yard-algorithm/Kotlin/parsing-shunting-yard-algorithm.kotlin new file mode 100644 index 0000000000..f3669d5ca1 --- /dev/null +++ b/Task/Parsing-Shunting-yard-algorithm/Kotlin/parsing-shunting-yard-algorithm.kotlin @@ -0,0 +1,61 @@ +// version 1.2.0 + +import java.util.Stack + +/* To find out the precedence, we take the index of the + token in the OPS string and divide by 2 (rounding down). + This will give us: 0, 0, 1, 1, 2 */ +const val OPS = "-+/*^" + +fun infixToPostfix(infix: String): String { + val sb = StringBuilder() + val s = Stack() + val rx = Regex("""\s""") + for (token in infix.split(rx)) { + if (token.isEmpty()) continue + val c = token[0] + val idx = OPS.indexOf(c) + + // check for operator + if (idx != - 1) { + if (s.isEmpty()) { + s.push(idx) + } + else { + while (!s.isEmpty()) { + val prec2 = s.peek() / 2 + val prec1 = idx / 2 + if (prec2 > prec1 || (prec2 == prec1 && c != '^')) { + sb.append(OPS[s.pop()]).append(' ') + } + else break + } + s.push(idx) + } + } + else if (c == '(') { + s.push(-2) // -2 stands for '(' + } + else if (c == ')') { + // until '(' on stack, pop operators. + while (s.peek() != -2) sb.append(OPS[s.pop()]).append(' ') + s.pop() + } + else { + sb.append(token).append(' ') + } + } + while (!s.isEmpty()) sb.append(OPS[s.pop()]).append(' ') + return sb.toString() +} + +fun main(args: Array) { + val es = listOf( + "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3", + "( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )" + ) + for (e in es) { + println("Infix : $e") + println("Postfix : ${infixToPostfix(e)}\n") + } +} diff --git a/Task/Parsing-Shunting-yard-algorithm/Rust/parsing-shunting-yard-algorithm.rust b/Task/Parsing-Shunting-yard-algorithm/Rust/parsing-shunting-yard-algorithm.rust new file mode 100644 index 0000000000..dbf5dad6c0 --- /dev/null +++ b/Task/Parsing-Shunting-yard-algorithm/Rust/parsing-shunting-yard-algorithm.rust @@ -0,0 +1,159 @@ +type Number = f64; + +#[derive(Debug, Copy, Clone, PartialEq)] +struct Operator { + token: char, + operation: fn(Number, Number) -> Number, + precedence: u8, + is_left_associative: bool, +} + +#[derive(Debug, Clone, PartialEq)] +enum Token { + Digit(Number), + Operator(Operator), + LeftParen, + RightParen, +} + +impl Operator { + fn new_token( + token: char, + precedence: u8, + is_left_associative: bool, + operation: fn(Number, Number) -> Number, + ) -> Token { + Token::Operator(Operator { + token: token, + operation: operation, + precedence: precedence, + is_left_associative, + }) + } + + fn apply(&self, x: Number, y: Number) -> Number { + (self.operation)(x, y) + } +} + +trait Stack { + fn top(&self) -> Option; +} + +impl Stack for Vec { + fn top(&self) -> Option { + if self.is_empty() { + return None; + } + self.get(self.len() - 1).map(|value| value.clone()) + } +} +fn lex_token(input: char) -> Result { + match input { + '0'...'9' => Ok(Token::Digit(input.to_digit(10).unwrap() as Number)), + '+' => Ok(Operator::new_token('+', 1, true, |x, y| x + y)), + '-' => Ok(Operator::new_token('-', 1, true, |x, y| x - y)), + '*' => Ok(Operator::new_token('*', 2, true, |x, y| x * y)), + '/' => Ok(Operator::new_token('/', 2, true, |x, y| x / y)), + '^' => Ok(Operator::new_token('^', 3, false, |x, y| x.powf(y))), + '(' => Ok(Token::LeftParen), + ')' => Ok(Token::RightParen), + _ => Err(input), + } +} + +fn lex(input: String) -> Result, char> { + input + .chars() + .filter(|c| !c.is_whitespace()) + .map(lex_token) + .collect() +} + +fn tilt_until(operators: &mut Vec, output: &mut Vec, stop: Token) -> bool { + while let Some(token) = operators.pop() { + if token == stop { + return true; + } + output.push(token) + } + false +} + +fn shunting_yard(tokens: Vec) -> Result, String> { + let mut output: Vec = Vec::new(); + let mut operators: Vec = Vec::new(); + + for token in tokens { + match token { + Token::Digit(_) => output.push(token), + Token::LeftParen => operators.push(token), + Token::Operator(operator) => { + while let Some(top) = operators.top() { + match top { + Token::LeftParen => break, + Token::Operator(top_op) => { + let p = top_op.precedence; + let q = operator.precedence; + if (p > q) || (p == q && operator.is_left_associative) { + output.push(operators.pop().unwrap()); + } else { + break; + } + } + _ => unreachable!("{:?} must not be on operator stack", token), + } + } + operators.push(token); + } + Token::RightParen => { + if !tilt_until(&mut operators, &mut output, Token::LeftParen) { + return Err(String::from("Mismatched ')'")); + } + } + } + } + + if tilt_until(&mut operators, &mut output, Token::LeftParen) { + return Err(String::from("Mismatched '('")); + } + + assert!(operators.is_empty()); + Ok(output) +} + +fn calculate(postfix_tokens: Vec) -> Result { + let mut stack = Vec::new(); + + for token in postfix_tokens { + match token { + Token::Digit(number) => stack.push(number), + Token::Operator(operator) => { + if let Some(y) = stack.pop() { + if let Some(x) = stack.pop() { + stack.push(operator.apply(x, y)); + continue; + } + } + return Err(format!("Missing operand for operator '{}'", operator.token)); + } + _ => unreachable!("Unexpected token {:?} during calculation", token), + } + } + + assert!(stack.len() == 1); + Ok(stack.pop().unwrap()) +} + +fn run(input: String) -> Result { + let tokens = match lex(input) { + Ok(tokens) => tokens, + Err(c) => return Err(format!("Invalid character: {}", c)), + }; + let postfix_tokens = match shunting_yard(tokens) { + Ok(tokens) => tokens, + Err(message) => return Err(message), + }; + + calculate(postfix_tokens) +} diff --git a/Task/Parsing-Shunting-yard-algorithm/UNIX-Shell/parsing-shunting-yard-algorithm-1.sh b/Task/Parsing-Shunting-yard-algorithm/UNIX-Shell/parsing-shunting-yard-algorithm-1.sh new file mode 100644 index 0000000000..eecaa99bd6 --- /dev/null +++ b/Task/Parsing-Shunting-yard-algorithm/UNIX-Shell/parsing-shunting-yard-algorithm-1.sh @@ -0,0 +1,103 @@ +#!/bin/sh + +getopprec() { + case "$1" in + '+') echo 2;; + '-') echo 2;; + '*') echo 3;; + '/') echo 4;; + '%') echo 4;; + '^') echo 4;; + '(') echo 5;; + esac +} + +getopassoc() { + case "$1" in + '^') echo r;; + *) echo l;; + esac +} + +showstacks() { + [ -n "$1" ] && echo "Token: $1" || echo "End parsing" + echo -e "\tOutput: `tr $'\n' ' ' <<< "$out"`" + echo -e "\tOperators: `tr $'\n' ' ' <<< "$ops"`" +} + +infix() { + local out="" ops="" + + while [ "$#" -gt 0 ]; do + grep -qE '^[0-9]+$' <<< "$1" + if [ "$?" -eq 0 ]; then + out="`sed -e '$a'"$1" -e '/^$/d' <<< "$out"`" + + showstacks "$1" + shift && continue + fi + + grep -q '^[-+*/^%]$' <<< "$1" + if [ "$?" -eq 0 ]; then + if [ -n "$ops" ]; then + thispred=`getopprec "$1"` + thisassoc=`getopassoc "$1"` + topop="`sed -n '$p' <<< "$ops"`" + thatpred=`getopprec "$topop"` + thatassoc=`getopassoc "$topop"` + while [ $thatpred -gt $thispred ] 2> /dev/null || ( [ \ + $thatpred -eq $thispred ] 2> /dev/null && [ $thisassoc = \ + 'l' ] 2> /dev/null ); do # To /dev/null 'cus u r fake news + + [ "$topop" = '(' ] && break + + op="`sed -n '$p' <<< "$ops"`" + out="`sed -e '$a'"$op" -e '/^$/d' <<< "$out"`" + ops="`sed '$d' <<< "$ops"`" + + topop="`sed -n '$p' <<< "$ops"`" + thatpred=`getopprec "$topop"` + thatassoc=`getopassoc "$topop"` + done + fi + ops="`sed -e '$a'"$1" -e '/^$/d' <<< "$ops"`" + + showstacks "$1" + shift && continue + fi + + if [ "$1" = '(' ]; then + ops="`sed -e '$a'"$1" -e '/^$/d' <<< "$ops"`" + + showstacks "$1" + shift && continue + fi + + if [ "$1" = ')' ]; then + grep -q '^($' <<< "`sed -n '$p' <<< "$ops"`" + while [ "$?" -ne 0 ]; do + op="`sed -n '$p' <<< "$ops"`" + out="`sed -e '$a'"$op" -e '/^$/d' <<< "$out"`" + ops="`sed '$d' <<< "$ops"`" + + grep -q '^($' <<< "`sed '$p' <<< "$ops"`" + done + ops="`sed '$d' <<< "$ops"`" + + showstacks "$1" + shift && continue + fi + + shift + done + + while [ -n "$ops" ]; do + op="`sed -n '$p' <<< "$ops"`" + out="`sed -e '$a'"$op" -e '/^$/d' <<< "$out"`" + ops="`sed '$d' <<< "$ops"`" + done + + showstacks "$1" +} + +infix 3 + 4 \* 2 / \( 1 - 5 \) ^ 2 ^ 3 diff --git a/Task/Parsing-Shunting-yard-algorithm/UNIX-Shell/parsing-shunting-yard-algorithm-2.sh b/Task/Parsing-Shunting-yard-algorithm/UNIX-Shell/parsing-shunting-yard-algorithm-2.sh new file mode 100644 index 0000000000..6acf6f2bc3 --- /dev/null +++ b/Task/Parsing-Shunting-yard-algorithm/UNIX-Shell/parsing-shunting-yard-algorithm-2.sh @@ -0,0 +1,48 @@ +Token: 3 + Output: 3 + Operators: +Token: + + Output: 3 + Operators: + +Token: 4 + Output: 3 4 + Operators: + +Token: * + Output: 3 4 + Operators: + * +Token: 2 + Output: 3 4 2 + Operators: + * +Token: / + Output: 3 4 2 + Operators: + * / +Token: ( + Output: 3 4 2 + Operators: + * / ( +Token: 1 + Output: 3 4 2 1 + Operators: + * / ( +Token: - + Output: 3 4 2 1 + Operators: + * / ( - +Token: 5 + Output: 3 4 2 1 5 + Operators: + * / ( - +Token: ) + Output: 3 4 2 1 5 - + Operators: + * / +Token: ^ + Output: 3 4 2 1 5 - + Operators: + * / ^ +Token: 2 + Output: 3 4 2 1 5 - 2 + Operators: + * / ^ +Token: ^ + Output: 3 4 2 1 5 - 2 + Operators: + * / ^ ^ +Token: 3 + Output: 3 4 2 1 5 - 2 3 + Operators: + * / ^ ^ +End parsing + Output: 3 4 2 1 5 - 2 3 ^ ^ / * + + Operators: diff --git a/Task/Partial-function-application/Elena/partial-function-application.elena b/Task/Partial-function-application/Elena/partial-function-application.elena index d576c4f067..38267c0a7b 100644 --- a/Task/Partial-function-application/Elena/partial-function-application.elena +++ b/Task/Partial-function-application/Elena/partial-function-application.elena @@ -6,13 +6,13 @@ program = [ var partial := (:afs:af)((:s)(afs eval(af, s))). - var fs := (:f:s)(s selectBy(:x)(f eval:x); summarize(ArrayList new); toArray). + var fs := (:f:s)(s selectBy(:x)(f(x)); summarize(ArrayList new); toArray). var f1 := (:x)(x * 2). var f2 := (:x)(x * x). - var fsf1 := partial eval(fs, f1). - var fsf2 := partial eval(fs, f2). + var fsf1 := partial(fs, f1). + var fsf2 := partial(fs, f2). - console printLine(fsf1 eval:(2,4,6,8)). - console printLine(fsf2 eval:(2,4,6,8)). + console printLine(fsf1((2,4,6,8))). + console printLine(fsf2((2,4,6,8))). ]. diff --git a/Task/Partial-function-application/Factor/partial-function-application.factor b/Task/Partial-function-application/Factor/partial-function-application.factor new file mode 100644 index 0000000000..dd1e0a3f2f --- /dev/null +++ b/Task/Partial-function-application/Factor/partial-function-application.factor @@ -0,0 +1,11 @@ +USING: kernel math prettyprint sequences ; +IN: rosetta-code.partial-function-application + +ALIAS: fs map +: f1 ( n -- m ) 2 * ; +: f2 ( n -- m ) dup * ; +: fsf1 ( s -- s' ) [ f1 ] fs ; +: fsf2 ( s -- s' ) [ f2 ] fs ; + +{ 0 1 2 3 } [ fsf1 . ] [ fsf2 . ] bi +{ 2 4 6 8 } [ fsf1 . ] [ fsf2 . ] bi diff --git a/Task/Partial-function-application/Julia/partial-function-application.julia b/Task/Partial-function-application/Julia/partial-function-application.julia new file mode 100644 index 0000000000..332fdc2621 --- /dev/null +++ b/Task/Partial-function-application/Julia/partial-function-application.julia @@ -0,0 +1,12 @@ +fs(f, s) = map(f, s) +f1(x) = 2x +f2(x) = x^2 +fsf1(s) = fs(f1, s) +fsf2(s) = fs(f2, s) + +s1 = [0, 1, 2 ,3] +s2 = [2, 4, 6, 8] +println("fsf1 of s1 is $(fsf1(s1))") +println("fsf2 of s1 is $(fsf2(s1))") +println("fsf1 of s2 is $(fsf1(s2))") +println("fsf2 of s2 is $(fsf2(s2))") diff --git a/Task/Pascals-triangle-Puzzle/Julia/pascals-triangle-puzzle.julia b/Task/Pascals-triangle-Puzzle/Julia/pascals-triangle-puzzle.julia new file mode 100644 index 0000000000..47555bf338 --- /dev/null +++ b/Task/Pascals-triangle-Puzzle/Julia/pascals-triangle-puzzle.julia @@ -0,0 +1,14 @@ +function pascal(a::Integer, b::Integer, mid::Integer, top::Integer) + yd = round((top - 4 * (a + b)) / 7) + !isinteger(yd) && return 0, 0, 0 + y = Int(yd) + x = mid - 2a - y + return x, y, y - x +end + +x, y, z = pascal(11, 4, 40, 151) +if !iszero(x) + println("Solution: x = $x, y = $y, z = $z.") +else + println("There is no solution.") +end diff --git a/Task/Pascals-triangle-Puzzle/REXX/pascals-triangle-puzzle.rexx b/Task/Pascals-triangle-Puzzle/REXX/pascals-triangle-puzzle.rexx index 8a1e5ac53f..4694e63479 100644 --- a/Task/Pascals-triangle-Puzzle/REXX/pascals-triangle-puzzle.rexx +++ b/Task/Pascals-triangle-Puzzle/REXX/pascals-triangle-puzzle.rexx @@ -1,33 +1,33 @@ -/*REXX program solves a "Pyramid of Numbers" puzzle given four values.*/ - /*┌──────────────────────────────────────────────┐ - ┌─┘ └─┐ - │ answer │ - │ mid / │ - │ \ / │ - │ \ 151 │ - │ \ ααα ααα │ - │ 40 ααα ααα │ - │ ααα ααα ααα ααα │ - │ x 11 y 4 z │ - │ / \ │ - │ / \ │ - │ / \ │ - │ B D │ - └─┐ ┌─┘ - └──────────────────────────────────────────────┘*/ -parse arg x b y d z mid answer . /*get some values, others, just X*/ - pad=left('',15) /*for inserting spaces in output.*/ - top=answer - 4*b - 4*d /*calculate the top # - constants*/ -middle=mid - 2*b /*calculate the mod # - constants*/ +/*REXX program solves a (Pascal's) "Pyramid of Numbers" puzzle given four values. */ + /*┌───────────────────────────────────────────────────────────┐ + │ answer │ + │ mid / │ + │ \ / │ + │ \ 151 │ + │ \ ααα ααα │ + │ 40 ααα ααα │ + │ ααα ααα ααα ααα │ + │ x 11 y 4 z │ + │ / \ │ + │ / \ │ + │ / \ │ + │Find: x y z b d │ + └───────────────────────────────────────────────────────────┘*/ +parse arg b d mid answer . /*obtain optional variables from the CL*/ +if b=='' | b=="," then b= 11 /*Not specified? Then use the default.*/ +if d=='' | d=="," then d= 4 /* " " " " " " */ +if mid='' | mid=="," then mid= 40 /* " " " " " " */ +if answer='' | answer=="," then answer= 151 /* " " " " " " */ + pad= left('', 15) /*used for inserting spaces in output. */ + big= answer - 4*b - 4*d /*calculate big number less constants*/ +middle= mid - 2*b /* " middle " " " */ - do x =-top to top - do y=-top to top - if x+y\==middle then iterate /*40 = x+2B+Y -or- 40-2*11 =x+y*/ - y6=y*6 /*calculate a short cut. */ - do z=-top to top - if z\==y-x then iterate /*z has to equal y-x (y=x+z) */ - if x+y6+z==top then say pad 'x = ' x pad "y = " y pad 'z = ' z - end /*z*/ - end /*y*/ - end /*x*/ - /*stick a fork in it, we're done.*/ + do x =-big to big + do y=-big to big + if x+y\==middle then iterate /*40 = x+2B+Y ──or── 40-2*11 = x+y */ + do z=-big to big + if z \== y - x then iterate /*z has to equal y-x (y=x+z) */ + if x+y*6+z == big then say pad 'x = ' x pad "y = " y pad 'z = ' z + end /*z*/ + end /*y*/ + end /*x*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Pascals-triangle-Puzzle/Scala/pascals-triangle-puzzle.scala b/Task/Pascals-triangle-Puzzle/Scala/pascals-triangle-puzzle.scala new file mode 100644 index 0000000000..47ad036461 --- /dev/null +++ b/Task/Pascals-triangle-Puzzle/Scala/pascals-triangle-puzzle.scala @@ -0,0 +1,12 @@ +object PascalTriangle extends App { + + val (x, y, z) = pascal(11, 4, 40, 151) + + def pascal(a: Int, b: Int, mid: Int, top: Int): (Int, Int, Int) = { + val y = (top - 4 * (a + b)) / 7 + val x = mid - 2 * a - y + (x, y, y - x) + } + + println(if (x != 0) s"Solution is: x = $x, y = $y, z = $z" else "There is no solution.") +} diff --git a/Task/Pascals-triangle/00DESCRIPTION b/Task/Pascals-triangle/00DESCRIPTION index b82e9f9d80..bf1aa0d477 100644 --- a/Task/Pascals-triangle/00DESCRIPTION +++ b/Task/Pascals-triangle/00DESCRIPTION @@ -1,4 +1,4 @@ -[[wp:Pascal's triangle|Pascal's triangle]]   is an arithmetic and geometric figure first imagined by   [[wp:Blaise Pascal|Blaise Pascal]]. +[[wp:Pascal's triangle|Pascal's triangle]] is an arithmetic and geometric figure often associated with the name of [[wp:Blaise Pascal|Blaise Pascal]], but also studied centuries earlier in India, Persia, China and elsewhere. Its first few rows look like this: 1 diff --git a/Task/Pascals-triangle/Commodore-BASIC/pascals-triangle-1.commodore b/Task/Pascals-triangle/Commodore-BASIC/pascals-triangle-1.commodore new file mode 100644 index 0000000000..4b6b76283f --- /dev/null +++ b/Task/Pascals-triangle/Commodore-BASIC/pascals-triangle-1.commodore @@ -0,0 +1,24 @@ +10 INPUT "HOW MANY";N +20 IF N<1 THEN END +30 DIM C(N) +40 DIM D(N) +50 LET C(1)=1 +60 LET D(1)=1 +70 FOR J=1 TO N +80 FOR I=1 TO N-J+1 +90 PRINT " "; +100 NEXT I +110 FOR I=1 TO J +120 PRINT C(I)" "; +130 NEXT I +140 PRINT +150 IF J=N THEN END +160 C(J+1)=1 +170 D(J+1)=1 +180 FOR I=1 TO J-1 +190 D(I+1)=C(I)+C(I+1) +200 NEXT I +210 FOR I=1 TO J +220 C(I)=D(I) +230 NEXT I +240 NEXT J diff --git a/Task/Pascals-triangle/Commodore-BASIC/pascals-triangle-2.commodore b/Task/Pascals-triangle/Commodore-BASIC/pascals-triangle-2.commodore new file mode 100644 index 0000000000..420944aa95 --- /dev/null +++ b/Task/Pascals-triangle/Commodore-BASIC/pascals-triangle-2.commodore @@ -0,0 +1,12 @@ +RUN +HOW MANY? 8 + 1 + 1 1 + 1 2 1 + 1 3 3 1 + 1 4 6 4 1 + 1 5 10 10 5 1 + 1 6 15 20 15 6 1 + 1 7 21 35 35 21 7 1 + 1 8 28 56 70 56 28 8 1 +READY. diff --git a/Task/Pascals-triangle/Modula-2/pascals-triangle.mod2 b/Task/Pascals-triangle/Modula-2/pascals-triangle.mod2 new file mode 100644 index 0000000000..33d2480b93 --- /dev/null +++ b/Task/Pascals-triangle/Modula-2/pascals-triangle.mod2 @@ -0,0 +1,33 @@ +MODULE Pascal; +FROM FormatString IMPORT FormatString; +FROM Terminal IMPORT WriteString,WriteLn,ReadChar; + +PROCEDURE PrintLine(n : INTEGER); +VAR + buf : ARRAY[0..63] OF CHAR; + m,j : INTEGER; +BEGIN + IF n<1 THEN RETURN END; + m := 1; + WriteString("1 "); + FOR j:=1 TO n-1 DO + m := m * (n - j) DIV j; + FormatString("%i ", buf, m); + WriteString(buf) + END; + WriteLn +END PrintLine; + +PROCEDURE Print(n : INTEGER); +VAR i : INTEGER; +BEGIN + FOR i:=1 TO n DO + PrintLine(i) + END +END Print; + +BEGIN + Print(10); + + ReadChar +END Pascal. diff --git a/Task/Pascals-triangle/Perl/pascals-triangle-4.pl b/Task/Pascals-triangle/Perl/pascals-triangle-4.pl new file mode 100644 index 0000000000..d0a78e7fa8 --- /dev/null +++ b/Task/Pascals-triangle/Perl/pascals-triangle-4.pl @@ -0,0 +1,34 @@ +#!/usr/bin/perl +use strict; +use warnings; + +{ + my @tartaglia ; + sub tartaglia { + my ($x,$y) = @_; + if ($x == 0 or $y == 0) { $tartaglia[$x][$y]=1 ; return 1}; + my $ret ; + foreach my $yps (0..$y){ + $ret += ( $tartaglia[$x-1][$yps] || tartaglia($x-1,$yps) ); + } + $tartaglia[$x][$y] = $ret; + return $ret; + } +} +sub tartaglia_row { + my $y = shift; + my $x = 0; + my @row; + $row[0] = &tartaglia($x,$y+1); + foreach my $pos (0..$y-1) {push @row, tartaglia(++$x,--$y)} + return @row; +} + + +for (0..5) {print join ' ', tartaglia_row($_),"\n"} +print "\n\n"; + + +print tartaglia(3,3),"\n"; +my @third = tartaglia_row(5); +print "@third\n"; diff --git a/Task/Pascals-triangle/Ruby/pascals-triangle-1.rb b/Task/Pascals-triangle/Ruby/pascals-triangle-1.rb index e13fea3a8b..3a9f67515b 100644 --- a/Task/Pascals-triangle/Ruby/pascals-triangle-1.rb +++ b/Task/Pascals-triangle/Ruby/pascals-triangle-1.rb @@ -3,7 +3,7 @@ def pascal(n) yield ar = [1] (n-1).times do ar.unshift(0).push(0) # tack a zero on both ends - yield ar = ar.each_cons(2).map{|a, b| a + b } + yield ar = ar.each_cons(2).map(&:sum) end end diff --git a/Task/Pascals-triangle/Rust/pascals-triangle.rust b/Task/Pascals-triangle/Rust/pascals-triangle.rust new file mode 100644 index 0000000000..c5794ebce5 --- /dev/null +++ b/Task/Pascals-triangle/Rust/pascals-triangle.rust @@ -0,0 +1,15 @@ +fn pascal_triangle(n: u64) +{ + + for i in 0..n { + let mut c = 1; + for _j in 1..2*(n-1-i)+1 { + print!(" "); + } + for k in 0..i+1 { + print!("{:2} ", c); + c = c * (i-k)/(k+1); + } + println!(); + } +} diff --git a/Task/Pascals-triangle/Scala/pascals-triangle-1.scala b/Task/Pascals-triangle/Scala/pascals-triangle-1.scala index 8aa9596950..2110e19ce2 100644 --- a/Task/Pascals-triangle/Scala/pascals-triangle-1.scala +++ b/Task/Pascals-triangle/Scala/pascals-triangle-1.scala @@ -1,5 +1,5 @@ -def tri(row:Int):List[Int] = { row match { - case 1 => List(1) - case n:Int => List(1) ::: ((tri(n-1) zip tri(n-1).tail) map {case (a,b) => a+b}) ::: List(1) - } -} + def tri(row: Int): List[Int] = + row match { + case 1 => List(1) + case n: Int => 1 +: ((tri(n - 1) zip tri(n - 1).tail) map { case (a, b) => a + b }) :+ 1 + } diff --git a/Task/Pascals-triangle/Scala/pascals-triangle-2.scala b/Task/Pascals-triangle/Scala/pascals-triangle-2.scala index 9ed22218e5..3d6bea4974 100644 --- a/Task/Pascals-triangle/Scala/pascals-triangle-2.scala +++ b/Task/Pascals-triangle/Scala/pascals-triangle-2.scala @@ -1,2 +1,3 @@ -def prettytri(n:Int) = (1 to n) foreach {i=>print(" "*(n-i)); tri(i) map (c=>print(c+" ")); println} -prettytri(5) +def prettyTri(n:Int) = (1 to n) foreach {i => print(" "*(n-i)); tri(i) map (c => print(c + " ")); println} + +prettyTri(5) diff --git a/Task/Pascals-triangle/Scala/pascals-triangle-3.scala b/Task/Pascals-triangle/Scala/pascals-triangle-3.scala new file mode 100644 index 0000000000..f98a103638 --- /dev/null +++ b/Task/Pascals-triangle/Scala/pascals-triangle-3.scala @@ -0,0 +1,10 @@ +object Blaise extends App { + def pascalTriangle(): Stream[Vector[Int]] = + Vector(1) #:: Stream.iterate(Vector(1, 1))(1 +: _.sliding(2).map(_.sum).toVector :+ 1) + + val output = pascalTriangle().take(15).map(_.mkString(" ")) + val longest = output.last.length + + println("Pascal's Triangle") + output.foreach(line => println(s"${" " * ((longest - line.length) / 2)}$line")) +} diff --git a/Task/Pascals-triangle/Stata/pascals-triangle-1.stata b/Task/Pascals-triangle/Stata/pascals-triangle-1.stata new file mode 100644 index 0000000000..25ea6c51e0 --- /dev/null +++ b/Task/Pascals-triangle/Stata/pascals-triangle-1.stata @@ -0,0 +1,26 @@ +function pascal1(n) { + return(comb(J(1,n,0::n-1),J(n,1,0..n-1))) +} + +function pascal2(n) { + a = I(n) + a[.,1] = J(n,1,1) + for (i=3; i<=n; i++) { + a[i,2..i-1] = a[i-1,2..i-1]+a[i-1,1..i-2] + } + return(a) +} + +function pascal3(n) { + a = J(n,n,0) + for (i=1; i=n THEN GO TO 140 +130 LET d(r+1)=1 +140 FOR i=2 TO r +150 LET d(i)=c(i-1)+c(i) +160 NEXT i +165 IF r>=n THEN GO TO 200 +170 FOR i=1 TO r+1 +180 LET c(i)=d(i) +190 NEXT i +200 NEXT r diff --git a/Task/Pascals-triangle/ZX-Spectrum-Basic/pascals-triangle-2.zx b/Task/Pascals-triangle/ZX-Spectrum-Basic/pascals-triangle-2.zx new file mode 100644 index 0000000000..f7081fdaea --- /dev/null +++ b/Task/Pascals-triangle/ZX-Spectrum-Basic/pascals-triangle-2.zx @@ -0,0 +1 @@ +RUN diff --git a/Task/Pattern-matching/00DESCRIPTION b/Task/Pattern-matching/00DESCRIPTION index 7d59f784d4..a3104bbdf2 100644 --- a/Task/Pattern-matching/00DESCRIPTION +++ b/Task/Pattern-matching/00DESCRIPTION @@ -2,4 +2,9 @@ Some languages offer direct support for [[wp:Algebraic_data_type|algebraic data types]] and pattern matching on them. While this of course can always be simulated with manual tagging and conditionals, it allows for terse code which is easy to read, and can represent the algorithm directly. -As an example, implement insertion in a [[wp:Red_Black_Tree|red-black-tree]]. A red-black-tree is a binary tree where each internal node has a color attribute ''red'' or ''black''. Moreover, no red node can have a red child, and every path from the root to an empty node must contain the same number of black nodes. As a consequence, the tree is balanced, and must be re-balanced after an insertion. + +;Task: +As an example, implement insertion in a [[wp:Red_Black_Tree|red-black-tree]]. + +A red-black-tree is a binary tree where each internal node has a color attribute ''red'' or ''black''. Moreover, no red node can have a red child, and every path from the root to an empty node must contain the same number of black nodes. As a consequence, the tree is balanced, and must be re-balanced after an insertion. +

diff --git a/Task/Pattern-matching/C++/pattern-matching-1.cpp b/Task/Pattern-matching/C++/pattern-matching-1.cpp new file mode 100644 index 0000000000..a1b4eee3a0 --- /dev/null +++ b/Task/Pattern-matching/C++/pattern-matching-1.cpp @@ -0,0 +1,45 @@ +enum Color { R, B }; +template struct T; +struct E; + +template struct balance { + using type = T; +}; +template +struct balance, y, c>, z, d> { + using type = T, y, T>; +}; +template +struct balance>, z, d> { + using type = T, y, T>; +}; +template +struct balance, z, d>> { + using type = T, y, T>; +}; +template +struct balance>> { + using type = T, y, T>; +}; + +template struct insert { + template struct ins; + template struct ins { using type = T; }; + template struct ins> { + template struct cond; + template struct cond<-1, _> : balance::type, y, b> {}; + template struct cond<1, _> : balance::type> {}; + template struct cond<0, _> { using type = T; }; + using type = typename cond::type; + }; + template struct repaint; + template + struct repaint> { using type = T; }; + using type = typename repaint::type>::type; +}; +template using insert_t = typename insert::type; + +template void print(); +int main() { + print>>>>(); +} diff --git a/Task/Pattern-matching/C++/pattern-matching-2.cpp b/Task/Pattern-matching/C++/pattern-matching-2.cpp new file mode 100644 index 0000000000..552e29ca47 --- /dev/null +++ b/Task/Pattern-matching/C++/pattern-matching-2.cpp @@ -0,0 +1,103 @@ +#include +#include + +template struct overloaded : Ts... { using Ts::operator()...; }; +template overloaded(Ts...) -> overloaded; + +enum Color { R, B }; +using E = std::monostate; +template struct Node; +template using Ptr = std::unique_ptr>; +template using Tree = std::variant, Ptr>; +template struct Node { + static constexpr auto C = Col; + Tree left; + T value; + Tree right; +}; +template Tree tree(A&& a, T& x, B&& b) { + return Tree{Ptr{new Node{std::move(a), std::move(x), std::move(b)}}}; +} + +template Tree balance(Tree s) { + auto&& ll = [](Ptr& s, Ptr& t, auto&, Ptr& u, auto&, auto&, auto&) { + auto& [a, x, b] = *s; + auto& [s_, y, c] = *t; + auto& [t_, z, d] = *u; + return tree(tree(a, x, b), y, tree(c, z, d)); + }; + auto&& lr = [](auto&, Ptr& s, Ptr& t, Ptr& u, auto&, auto&, auto&) { + auto& [a, x, t_] = *s; + auto& [b, y, c] = *t; + auto& [s_, z, d] = *u; + return tree(tree(a, x, b), y, tree(c, z, d)); + }; + auto&& rl = [](auto&, auto&, auto&, Ptr& s, Ptr& t, Ptr& u, auto&) { + auto& [a, x, u_] = *s; + auto& [b, y, c] = *t; + auto& [t_, z, d] = *u; + return tree(tree(a, x, b), y, tree(c, z, d)); + }; + auto&& rr = [](auto&, auto&, auto&, Ptr& s, auto&, Ptr& t, Ptr& u) { + auto& [a, x, t_] = *s; + auto& [b, y, u_] = *t; + auto& [c, z, d] = *u; + return tree(tree(a, x, b), y, tree(c, z, d)); + }; + auto&& l = [](auto& s) -> Tree& { + return *std::visit(overloaded{[&](E) { return &s; }, [](auto& t) { return &t->left; }}, s); + }; + auto&& r = [](auto& s) -> Tree& { + return *std::visit(overloaded{[&](E) { return &s; }, [](auto& t) { return &t->right; }}, s); + }; + return std::visit([&](auto&... ss) -> Tree { + if constexpr (1 < + std::is_invocable_v + + std::is_invocable_v + + std::is_invocable_v + + std::is_invocable_v) + throw std::logic_error{""}; + else + return overloaded{ll, lr, rl, rr, [&](auto&... ss) { return std::move(s); }}(ss...); + }, l(l(s)), l(s), r(l(s)), s, l(r(s)), r(s), r(r(s))); +} +template Tree ins(T& x, Tree& s) { + return std::visit(overloaded{ + [&](E) -> Tree { return tree(s, x, s); }, + [&](auto& t) { + auto& [a, y, b] = *t; + static constexpr auto Col = std::remove_reference_t::C; + return x < y ? balance(tree
(ins(x, a), y, b)) : + y < x ? balance(tree(a, y, ins(x, b))) : + std::move(s); + }, + }, s); +} +template Tree insert(T x, Tree s) { + return std::visit(overloaded{ + [](E) -> Tree { throw std::logic_error{""}; }, + [](auto&& t) { + auto& [a, y, b] = *t; + return tree(a, y, b); + } + }, ins(x, s)); +} + +#include +template void print(Tree const& s, int i = 0) { + std::visit(overloaded{ + [](E) {}, + [&](auto& t) { + auto& [a, y, b] = *t; + print(a, i + 1); + std::cout << std::string(i, ' ') << "RB"[t->C] << " " << y << "\n"; + print(b, i + 1); + } + }, s); +} +int main(int argc, char* argv[]) { + auto t = Tree{}; + for (auto i = 1; i != argc; ++i) + t = insert(std::string{argv[i]}, std::move(t)); + print(t); +} diff --git a/Task/Pattern-matching/Kotlin/pattern-matching.kotlin b/Task/Pattern-matching/Kotlin/pattern-matching.kotlin new file mode 100644 index 0000000000..81a77996d6 --- /dev/null +++ b/Task/Pattern-matching/Kotlin/pattern-matching.kotlin @@ -0,0 +1,84 @@ +// version 1.1.51 + +import Color.* + +enum class Color { R, B } + +sealed class Tree> { + + fun insert(x: A): Tree { + val t = ins(x) + return when (t) { + is T -> { + val (_, a, y, b) = t + T(B, a, y, b) + } + + is E -> E() + } + } + + abstract fun ins(x: A): Tree +} + +class E> : Tree() { + + override fun ins(x: A): Tree = T(R, E(), x, E()) + + override fun toString() = "E" +} + +data class T>( + val cl: Color, + val le: Tree, + val aa: A, + val ri: Tree +) : Tree() { + + private fun balance(): Tree { + if (cl != B) return this + val res = + if (le is T && le.le is T && le.cl == R && le.le.cl == R) { + val (_, t, z, d) = this + val (_, t2, y, c) = t as T + val (_, a, x, b) = t2 as T + T(R, T(B, a, x, b), y, T(B, c, z, d)) + } + else if (le is T && le.ri is T && le.cl == R && le.ri.cl == R) { + val (_, t, z, d) = this + val (_, a, x, t2) = t as T + val (_, b, y, c) = t2 as T + T(R, T(B, a, x, b), y, T(B, c, z, d)) + } + else if (ri is T && ri.le is T && ri.cl == R && ri.le.cl == R) { + val (_, a, x, t) = this + val (_, t2, z, d) = t as T + val (_, b, y, c) = t2 as T + T(R, T(B, a, x, b), y, T(B, c, z, d)) + } + else if (ri is T && ri.ri is T && ri.cl == R && ri.ri.cl == R) { + val (_, a, x, t) = this + val (_, b, y, t2) = t as T + val (_, c, z, d) = t2 as T + T(R, T(B, a, x, b), y, T(B, c, z, d)) + } + else this + return res + } + + override fun ins(x: A): Tree = when (x.compareTo(aa)) { + -1 -> T(cl, le.ins(x), aa, ri).balance() + +1 -> T(cl, le, aa, ri.ins(x)).balance() + else -> this + } + + override fun toString() = "T($cl, $le, $aa, $ri)" +} + +fun main(args: Array) { + var tree: Tree = E() + for (i in 1..16) { + tree = tree.insert(i) + } + println(tree) +} diff --git a/Task/Pattern-matching/REXX/pattern-matching.rexx b/Task/Pattern-matching/REXX/pattern-matching.rexx new file mode 100644 index 0000000000..6d83318cab --- /dev/null +++ b/Task/Pattern-matching/REXX/pattern-matching.rexx @@ -0,0 +1,38 @@ +/*REXX pgm builds a red/black tree (with verification & validation), balances as needed.*/ +parse arg nodes '/' insert /*obtain optional arguments from the CL*/ +if nodes='' then nodes = 13.8.17 8.1.11 17.15.25 1.6 25.22.27 /*default nodes.*/ +if insert='' then insert= 22.44 44.66 /* " inserts*/ +top=. +call Dnodes nodes /*define nodes, balance them as added. */ +call Dnodes insert /*insert nodes, balance them as needed.*/ +call Lnodes /*list the nodes (with indentation). */ +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +Dnodes: arg $d; do j=1 for words($d); t=word($d, j) /*color: encoded into LEV.*/ + parse var t p '.' a "." b '.' x 1 . . . xx + call Vnodes p a b + if x\=='' then call err "too many nodes specified: " xx + if p\==top then if @.p==. then call err "node isn't defined: " p + if p ==top then do; !.p=1; L.1=p; end /*assign the top node. */ + @.p=a b; n=!.p + 1 /*assign node; bump level.*/ + if a\=='' then do; !.a=n; @.a=; maxL=max(maxL, !.a); end + if b\=='' then do; !.b=n; @.b=; maxL=max(maxL, !.b); end + L.n=space(L.n a b) /*append to the level list*/ + end /*j*/ + return +/*──────────────────────────────────────────────────────────────────────────────────────*/ +err: say; say '***error***: ' arg(1); say; exit 13 +/*──────────────────────────────────────────────────────────────────────────────────────*/ +Lnodes: do L=1 for maxL; w=length(maxL); rb=word('(red) (black)', 1 + L//2) + say "level:" right(L, w) left('', L+L) " ───► " rb ' ' L.L + end /*lev*/ + return +/*──────────────────────────────────────────────────────────────────────────────────────*/ +Vnodes: arg $v; do v=1 for words($v); y=word($v, v) + if \datatype(y, 'W') then call err "node isn't a whole number: " y + y=y/1 /*normalize the Y integer: no LZ, dot*/ + if top==. then do; LO=y; top=y; HI=y; L.=; @.=; maxL=1; end + LO=min(LO, y); HI=max(HI, y) + if @.y\==. & @.y\=='' then call err "node is already defined: " y + end /*v*/ + return diff --git a/Task/Penneys-game/Factor/penneys-game.factor b/Task/Penneys-game/Factor/penneys-game.factor new file mode 100644 index 0000000000..ebbbe320d1 --- /dev/null +++ b/Task/Penneys-game/Factor/penneys-game.factor @@ -0,0 +1,88 @@ +USING: arrays ascii io kernel math prettyprint random sequences +strings ; +IN: rosetta-code.penneys-game + +! Generate a random boolean. +: t|f ( -- t/f ) + 1 random-bits 0 = ; + +! Checks whether the sequence chosen by the human is valid. +: valid-input? ( seq -- ? ) + [ [ CHAR: H = ] [ CHAR: T = ] bi or ] filter length 3 = ; + +! Prompt the human player for a sequence. +: input-seq ( -- seq ) + "Please input a 3-long sequence of H or T (heads or tails)." + print "Example: HTH" print "> " write readln >upper >array ; + +! Get the human player's input sequence with error checking. +: get-input ( -- seq ) + t [ drop input-seq dup valid-input? not ] loop ; + +! Add a random coin flip to a vector. +: flip-coin ( vector -- vector' ) + t|f CHAR: H CHAR: T ? over push ; + +! Generate a random 3-long sequence of coin flips. +: rand-seq ( -- seq ) + V{ } clone 3 [ flip-coin ] times ; + +! Generate the optimal sequence response to a given sequence. +: optimal ( seq1 -- seq2 ) + [ second dup CHAR: H = [ CHAR: T ] [ CHAR: H ] if ] + [ first ] [ second ] tri 3array nip dup + "The computer chose " write >string write "." print ; + +! Choose a random sequence for the computer and report what +! was chosen. +: computer-first ( -- seq ) + "The computer picks a sequence first and chooses " write + rand-seq dup >string write "." print >array ; + +! The human is prompted to choose any sequence with no +! restrictions. +: human-first ( -- seq ) + "You get to go first." print get-input ; + +! Forbid the player from choosing the same sequence as the +! computer. +: human-second ( cseq -- cseq hseq ) + get-input [ 2dup = not ] + [ drop + "You may not choose the same sequence as the computer." + print get-input + ] until ; + +! Display a message introducing the game. +: welcome ( -- ) + "Welcome to Penney's Game. The computer or the player" print + "will be randomly selected to choose a sequence of" print + "three coin tosses. The sequence will be shown to the" print + "opponent, and then he will choose a sequence." print nl + "Then, a coin will be flipped until the sequence" print + "matches the last three coin flips, and a winner" print + "announced." print nl ; + +! Check for human victory. +: human-won? ( cseq hseq coin-flips -- ? ) + 3 tail* >array = nip ; + +! Check for computer victory. +: computer-won? ( cseq hseq coin-flips -- ? ) + 3 tail* >array pick = 2nip ; + +! Flip a coin until a victory is detected. Then, inform the +! player who won. +: flip-coins ( cseq hseq -- ) + "Flipping coins..." print + rand-seq [ 3dup [ human-won? ] [ computer-won? ] 3bi or ] + [ flip-coin ] until dup >string print human-won? + [ "You won!" print ] [ "The computer won." print ] if ; + +! Randomly choose a player to choose their sequence first. +! Then play a full round of Penney's Game. +: start-game ( -- ) + welcome t|f [ human-first dup optimal swap ] + [ computer-first human-second ] if flip-coins ; + +start-game diff --git a/Task/Penneys-game/Kotlin/penneys-game.kotlin b/Task/Penneys-game/Kotlin/penneys-game.kotlin new file mode 100644 index 0000000000..73f0986340 --- /dev/null +++ b/Task/Penneys-game/Kotlin/penneys-game.kotlin @@ -0,0 +1,69 @@ +// version 1.2.10 + +import java.util.Random + +val rand = Random() + +val optimum = mapOf( + "HHH" to "THH", "HHT" to "THH", "HTH" to "HHT", "HTT" to "HHT", + "THH" to "TTH", "THT" to "TTH", "TTH" to "HTT", "TTT" to "HTT" +) + +fun getUserSequence(): String { + println("A sequence of three H or T should be entered") + var userSeq: String + do { + print("Enter your sequence: ") + userSeq = readLine()!!.toUpperCase() + } + while (userSeq.length != 3 || userSeq.any { it != 'H' && it != 'T' }) + return userSeq +} + +fun getComputerSequence(userSeq: String = ""): String { + val compSeq = if(userSeq == "") + String(CharArray(3) { if (rand.nextInt(2) == 0) 'T' else 'H' }) + else + optimum[userSeq]!! + println("Computer's sequence: $compSeq") + return compSeq +} + +fun main(args: Array) { + var userSeq: String + var compSeq: String + val r = rand.nextInt(2) + if (r == 0) { + println("You go first") + userSeq = getUserSequence() + println() + compSeq = getComputerSequence(userSeq) + } + else { + println("Computer goes first") + compSeq = getComputerSequence() + println() + userSeq = getUserSequence() + } + + println() + val coins = StringBuilder() + while (true) { + val coin = if (rand.nextInt(2) == 0) 'H' else 'T' + coins.append(coin) + println("Coins flipped: $coins") + val len = coins.length + if (len >= 3) { + val seq = coins.substring(len - 3, len) + if (seq == userSeq) { + println("\nYou win!") + return + } + else if (seq == compSeq) { + println("\nComputer wins!") + return + } + } + Thread.sleep(2000) // wait two seconds for next flip + } +} diff --git a/Task/Penneys-game/Perl-6/penneys-game.pl6 b/Task/Penneys-game/Perl-6/penneys-game.pl6 index a7a5a04604..710c632447 100644 --- a/Task/Penneys-game/Perl-6/penneys-game.pl6 +++ b/Task/Penneys-game/Perl-6/penneys-game.pl6 @@ -32,7 +32,7 @@ repeat until prompt("Wanna play again? ").lc ~~ /^n/ { my @mine; if $flip == $mefirst { - print "{Yay.pick}! I get to choose first, and I choose: "; sleep 2; say @mine = Coin.roll(3); + print "{Yay.pick}! I get to choose first, and I choose: "; sleep 2; say @mine = |Coin.roll(3); @yours = your-choice("Now you gotta choose: "); while @yours eqv @mine { say "{Bozo.pick}! We'd both win at the same time if you pick that!"; @@ -43,7 +43,7 @@ repeat until prompt("Wanna play again? ").lc ~~ /^n/ { else { @yours = your-choice("{Boo.pick}! First you choose: "); say "OK, you'll win if we see: ", @yours; - print "In that case, I'll just randomly choose: "; sleep 2; say @mine = Coin(+!@yours[1]), @yours[0,1]; + print "In that case, I'll just randomly choose: "; sleep 2; say @mine = Coin(+!@yours[1]), |@yours[0,1]; } sub check($a,$b,$c) { @@ -65,7 +65,7 @@ repeat until prompt("Wanna play again? ").lc ~~ /^n/ { "Can I borrow that coin again?").pick; sleep 1; print "Here we go!\n\t"; - for Coin.roll(3), &check ...^ :!defined { + for |Coin.roll(3), &check ...^ :!defined { flipping; print "$_ "; } diff --git a/Task/Penneys-game/PicoLisp/penneys-game.l b/Task/Penneys-game/PicoLisp/penneys-game.l new file mode 100644 index 0000000000..a9fd27d6d1 --- /dev/null +++ b/Task/Penneys-game/PicoLisp/penneys-game.l @@ -0,0 +1,45 @@ +(seed (in "/dev/urandom" (rd 8))) + +(setq *S (list 0 0)) + +(de toss (N) + (make + (do N + (link (if (rand T) "T" "H")) ) ) ) + +(de comp (A Lst) + (or + (for ((I . L) Lst (cddr L) (cdr L)) + (T (fully = A L) I) ) + T ) ) + +(de score NIL + (prinl) + (prinl "Total score:") + (prinl "^Iuser: " (car *S)) + (prinl "^Icomp: " (cadr *S)) ) + +(de play NIL + (let (C (toss 3) Lst (toss (rand 5 12)) U) + (prinl) + (prin "Select toss: ") + (setq U (in NIL (skip) (line))) + (prinl "Comp toss: " C) + (prinl "Toss: " Lst) + (setq @ (comp U Lst) @@ (comp C Lst) ) + (cond + ((< @ @@) (prinl "User win.") (inc *S)) + ((> @ @@) (prinl "Comp win.") (inc (cdr *S))) + (T (prinl "Draw, lets play again.")) ) + (score) ) ) + +(de go NIL + (loop + (play) + (T + (prog + (prinl) + (prin "Want play again? Y/N: ") + (= "N" (uppc (in NIL (char)))) ) ) ) ) + +(go) diff --git a/Task/Penneys-game/VBA/penneys-game.vba b/Task/Penneys-game/VBA/penneys-game.vba new file mode 100644 index 0000000000..fc8cd91580 --- /dev/null +++ b/Task/Penneys-game/VBA/penneys-game.vba @@ -0,0 +1,81 @@ +Option Explicit + +Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) +Private Const HT As String = "H T" + +Public Sub PenneysGame() +Dim S$, YourSeq$, ComputeSeq$, i&, Seq$, WhoWin$, flag As Boolean + + Do + S = WhoWillBeFirst(Choice("Who will be first")) + If S = "ABORT" Then Exit Do + Debug.Print S; " start" + YourSeq = Choice("Your sequence", 3) + If YourSeq Like "*ABORT*" Then Exit Do + Debug.Print "Your sequence : " & YourSeq + ComputeSeq = vbNullString + For i = 1 To 3 + ComputeSeq = ComputeSeq & Random + Next i + Debug.Print "Computer sequence : " & ComputeSeq + Seq = vbNullString + Do + Seq = Seq & Random + Debug.Print Seq + Sleep 1000 + Loop While Not Winner(ComputeSeq, YourSeq, Seq, WhoWin) + Debug.Print WhoWin; " win" + If MsgBox(WhoWin & " win" & vbCrLf & "Play again?", vbYesNo) = vbNo Then flag = True + Debug.Print "" + Loop While Not flag + Debug.Print "Game over" +End Sub + +Private Function WhoWillBeFirst(YourChoice As String) As String +Dim S$ + S = Random + Select Case YourChoice + Case "ABORT": WhoWillBeFirst = YourChoice + Case Else: + WhoWillBeFirst = IIf(S = YourChoice, "You", "Computer") + End Select +End Function + +Private Function Choice(Title As String, Optional Seq As Integer) As String +Dim S$, i&, t$ + If Seq = 0 Then Seq = 1 + t = Title + For i = 1 To Seq + S = vbNullString + Do + S = InputBox("Choose between H or T : ", t) + If StrPtr(S) = 0 Then S = "Abort" + S = UCase(S) + Loop While S <> "H" And S <> "T" And S <> "ABORT" + Choice = Choice & S + t = Title & " " & Choice + If Choice Like "*ABORT*" Then Exit For + Next i +End Function + +Private Function Random() As String +Randomize Timer + Random = Split(HT, " ")(CInt(Rnd)) +End Function + +Private Function Winner(Cs$, Ys$, S$, W$) As Boolean + If Len(S) < 3 Then + Winner = False + Else + If Right(S, 3) = Cs And Right(S, 3) = Ys Then + Winner = True + W = "Computer & you" + ElseIf Right(S, 3) = Cs And Right(S, 3) <> Ys Then + Winner = True + W = "Computer" + ElseIf Right(S, 3) = Ys And Right(S, 3) <> Cs Then + Winner = True + W = "You" + End If + End If +End Function diff --git a/Task/Percentage-difference-between-images/Go/percentage-difference-between-images-1.go b/Task/Percentage-difference-between-images/Go/percentage-difference-between-images-1.go index 524a3026ea..7932a88e52 100644 --- a/Task/Percentage-difference-between-images/Go/percentage-difference-between-images-1.go +++ b/Task/Percentage-difference-between-images/Go/percentage-difference-between-images-1.go @@ -4,61 +4,63 @@ import ( "fmt" "image/jpeg" "os" + "log" + "image" ) +func loadJpeg(filename string) (image.Image, error) { + f, err := os.Open(filename) + if err != nil { + return nil, err + } + defer f.Close() + + img, err := jpeg.Decode(f) + if err != nil { + return nil, err + } + + return img, nil +} + +func diff(a, b uint32) int64 { + if a > b { + return int64(a - b) + } + return int64(b - a) +} + func main() { - f, err := os.Open("Lenna50.jpg") + i50, err := loadJpeg("Lenna50.jpg") if err != nil { - fmt.Println(err) - return + log.Fatal(err) } - defer f.Close() - i50, err := jpeg.Decode(f) + + i100, err := loadJpeg("Lenna100.jpg") if err != nil { - fmt.Println(err) - return - } - if f, err = os.Open("Lenna100.jpg"); err != nil { - fmt.Println(err) - return - } - defer f.Close() - i100, err := jpeg.Decode(f) - if err != nil { - fmt.Println(err) - return + log.Fatal(err) } + if i50.ColorModel() != i100.ColorModel() { - fmt.Println("different color models") - return + log.Fatal("different color models") } + b := i50.Bounds() if !b.Eq(i100.Bounds()) { - fmt.Println("different image sizes") - return + log.Fatal("different image sizes") } + var sum int64 for y := b.Min.Y; y < b.Max.Y; y++ { for x := b.Min.X; x < b.Max.X; x++ { r1, g1, b1, _ := i50.At(x, y).RGBA() r2, g2, b2, _ := i100.At(x, y).RGBA() - if r1 > r2 { - sum += int64(r1 - r2) - } else { - sum += int64(r2 - r1) - } - if g1 > g2 { - sum += int64(g1 - g2) - } else { - sum += int64(g2 - g1) - } - if b1 > b2 { - sum += int64(b1 - b2) - } else { - sum += int64(b2 - b1) - } + sum += diff(r1, r2) + sum += diff(g1, g2) + sum += diff(b1, b2) } } + nPixels := (b.Max.X - b.Min.X) * (b.Max.Y - b.Min.Y) fmt.Printf("Image difference: %f%%\n", float64(sum*100)/(float64(nPixels)*0xffff*3)) diff --git a/Task/Percentage-difference-between-images/Java/percentage-difference-between-images.java b/Task/Percentage-difference-between-images/Java/percentage-difference-between-images.java index 13ec00741b..3ec737389e 100644 --- a/Task/Percentage-difference-between-images/Java/percentage-difference-between-images.java +++ b/Task/Percentage-difference-between-images/Java/percentage-difference-between-images.java @@ -1,48 +1,48 @@ import java.awt.image.BufferedImage; -import javax.imageio.ImageIO; +import java.io.File; import java.io.IOException; -import java.net.URL; +import javax.imageio.ImageIO; -public class ImgDiffPercent -{ - public static void main(String args[]) - { - BufferedImage img1 = null; - BufferedImage img2 = null; - try { - URL url1 = new URL("http://rosettacode.org/mw/images/3/3c/Lenna50.jpg"); - URL url2 = new URL("http://rosettacode.org/mw/images/b/b6/Lenna100.jpg"); - img1 = ImageIO.read(url1); - img2 = ImageIO.read(url2); - } catch (IOException e) { - e.printStackTrace(); +public enum ImgDiffPercent { + ; + + public static void main(String[] args) throws IOException { + // https://rosettacode.org/mw/images/3/3c/Lenna50.jpg + // https://rosettacode.org/mw/images/b/b6/Lenna100.jpg + BufferedImage img1 = ImageIO.read(new File("Lenna50.jpg")); + BufferedImage img2 = ImageIO.read(new File("Lenna100.jpg")); + + double p = getDifferencePercent(img1, img2); + System.out.println("diff percent: " + p); } - int width1 = img1.getWidth(null); - int width2 = img2.getWidth(null); - int height1 = img1.getHeight(null); - int height2 = img2.getHeight(null); - if ((width1 != width2) || (height1 != height2)) { - System.err.println("Error: Images dimensions mismatch"); - System.exit(1); + + private static double getDifferencePercent(BufferedImage img1, BufferedImage img2) { + int width = img1.getWidth(); + int height = img1.getHeight(); + int width2 = img2.getWidth(); + int height2 = img2.getHeight(); + if (width != width2 || height != height2) { + throw new IllegalArgumentException(String.format("Images must have the same dimensions: (%d,%d) vs. (%d,%d)", width, height, width2, height2)); + } + + long diff = 0; + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + diff += pixelDiff(img1.getRGB(x, y), img2.getRGB(x, y)); + } + } + long maxDiff = 3L * 255 * width * height; + + return 100.0 * diff / maxDiff; } - long diff = 0; - for (int y = 0; y < height1; y++) { - for (int x = 0; x < width1; x++) { - int rgb1 = img1.getRGB(x, y); - int rgb2 = img2.getRGB(x, y); + + private static int pixelDiff(int rgb1, int rgb2) { int r1 = (rgb1 >> 16) & 0xff; int g1 = (rgb1 >> 8) & 0xff; - int b1 = (rgb1 ) & 0xff; + int b1 = rgb1 & 0xff; int r2 = (rgb2 >> 16) & 0xff; int g2 = (rgb2 >> 8) & 0xff; - int b2 = (rgb2 ) & 0xff; - diff += Math.abs(r1 - r2); - diff += Math.abs(g1 - g2); - diff += Math.abs(b1 - b2); - } + int b2 = rgb2 & 0xff; + return Math.abs(r1 - r2) + Math.abs(g1 - g2) + Math.abs(b1 - b2); } - double n = width1 * height1 * 3; - double p = diff / n / 255.0; - System.out.println("diff percent: " + (p * 100.0)); - } } diff --git a/Task/Percentage-difference-between-images/Julia/percentage-difference-between-images.julia b/Task/Percentage-difference-between-images/Julia/percentage-difference-between-images.julia new file mode 100644 index 0000000000..0569d5eb19 --- /dev/null +++ b/Task/Percentage-difference-between-images/Julia/percentage-difference-between-images.julia @@ -0,0 +1,17 @@ +using Images, FileIO + +absdiff(a::RGB{T}, b::RGB{T}) where T = sum(abs(col(a) - col(b)) for col in (red, green, blue)) +function pctdiff(A::Matrix{Color{T}}, B::Matrix{Color{T}}) where T + size(A) != size(B) && throw(ArgumentError("images must be same-size")) + s = zero(T) + for (a, b) in zip(A, B) + s += absdiff(a, b) + end + return 100s / 3prod(size(A)) +end + +img50 = load("data/lenna50.jpg") |> Matrix{RGB{Float64}}; +img100 = load("data/lenna100.jpg") |> Matrix{RGB{Float64}}; + +d = pctdiff(img50, img100) +@printf("Percentage difference: %.4f%%\n", d) diff --git a/Task/Percentage-difference-between-images/Kotlin/percentage-difference-between-images.kotlin b/Task/Percentage-difference-between-images/Kotlin/percentage-difference-between-images.kotlin new file mode 100644 index 0000000000..1f1a4c6f0a --- /dev/null +++ b/Task/Percentage-difference-between-images/Kotlin/percentage-difference-between-images.kotlin @@ -0,0 +1,43 @@ +// version 1.2.10 + +import java.awt.image.BufferedImage +import java.io.File +import javax.imageio.ImageIO +import kotlin.math.abs + +fun getDifferencePercent(img1: BufferedImage, img2: BufferedImage): Double { + val width = img1.width + val height = img1.height + val width2 = img2.width + val height2 = img2.height + if (width != width2 || height != height2) { + val f = "(%d,%d) vs. (%d,%d)".format(width, height, width2, height2) + throw IllegalArgumentException("Images must have the same dimensions: $f") + } + var diff = 0L + for (y in 0 until height) { + for (x in 0 until width) { + diff += pixelDiff(img1.getRGB(x, y), img2.getRGB(x, y)) + } + } + val maxDiff = 3L * 255 * width * height + return 100.0 * diff / maxDiff +} + +fun pixelDiff(rgb1: Int, rgb2: Int): Int { + val r1 = (rgb1 shr 16) and 0xff + val g1 = (rgb1 shr 8) and 0xff + val b1 = rgb1 and 0xff + val r2 = (rgb2 shr 16) and 0xff + val g2 = (rgb2 shr 8) and 0xff + val b2 = rgb2 and 0xff + return abs(r1 - r2) + abs(g1 - g2) + abs(b1 - b2) +} + +fun main(args: Array) { + val img1 = ImageIO.read(File("Lenna50.jpg")) + val img2 = ImageIO.read(File("Lenna100.jpg")) + + val p = getDifferencePercent(img1, img2) + println("The percentage difference is ${"%.6f".format(p)}%") +} diff --git a/Task/Percentage-difference-between-images/Python/percentage-difference-between-images-1.py b/Task/Percentage-difference-between-images/Python/percentage-difference-between-images-1.py new file mode 100644 index 0000000000..269586e419 --- /dev/null +++ b/Task/Percentage-difference-between-images/Python/percentage-difference-between-images-1.py @@ -0,0 +1,16 @@ +import Image + +i1 = Image.open("image1.jpg") +i2 = Image.open("image2.jpg") +assert i1.mode == i2.mode, "Different kinds of images." +assert i1.size == i2.size, "Different sizes." + +pairs = zip(i1.getdata(), i2.getdata()) +if len(i1.getbands()) == 1: + # for gray-scale jpegs + dif = sum(abs(p1-p2) for p1,p2 in pairs) +else: + dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2)) + +ncomponents = i1.size[0] * i1.size[1] * 3 +print "Difference (percentage):", (dif / 255.0 * 100) / ncomponents diff --git a/Task/Percentage-difference-between-images/Python/percentage-difference-between-images.py b/Task/Percentage-difference-between-images/Python/percentage-difference-between-images-2.py similarity index 100% rename from Task/Percentage-difference-between-images/Python/percentage-difference-between-images.py rename to Task/Percentage-difference-between-images/Python/percentage-difference-between-images-2.py diff --git a/Task/Percolation-Bond-percolation/Go/percolation-bond-percolation.go b/Task/Percolation-Bond-percolation/Go/percolation-bond-percolation.go index d6711d7fd6..968fbe6514 100644 --- a/Task/Percolation-Bond-percolation/Go/percolation-bond-percolation.go +++ b/Task/Percolation-Bond-percolation/Go/percolation-bond-percolation.go @@ -1,9 +1,9 @@ package main import ( - "bytes" "fmt" "math/rand" + "strings" "time" ) @@ -67,7 +67,7 @@ var ( ) func (g *grid) String() string { - var buf bytes.Buffer + var buf strings.Builder // Don't really need to call Grow but it helps avoid multiple // reallocations if the size is large. buf.Grow((len(g.cell) + 1) * len(g.cell[0]) * 7) diff --git a/Task/Percolation-Bond-percolation/Julia/percolation-bond-percolation.julia b/Task/Percolation-Bond-percolation/Julia/percolation-bond-percolation.julia new file mode 100644 index 0000000000..91e3d7f921 --- /dev/null +++ b/Task/Percolation-Bond-percolation/Julia/percolation-bond-percolation.julia @@ -0,0 +1,93 @@ +using Distributions + +struct Grid + cells::BitArray{2} + hwall::BitArray{2} + vwall::BitArray{2} +end +function Grid(p::AbstractFloat, m::Integer=10, n::Integer=10) + cells = fill(false, m, n) + hwall = rand(Bernoulli(p), m + 1, n) + vwall = rand(Bernoulli(p), m, n + 1) + vwall[:, 1] = true + vwall[:, end] = true + return Grid(cells, hwall, vwall) +end + +function Base.show(io::IO, g::Grid) + H = (" .", " _") + V = (":", "|") + C = (" ", "#") + ind = findfirst(g.cells[end, :] .& .!g.hwall[end, :]) + percolated = !iszero(ind) + println(io, "$(size(g.cells, 1))×$(size(g.cells, 2)) $(percolated ? "Percolated" : "Not percolated") grid") + for r in 1:size(g.cells, 1) + println(io, " ", join(H[w+1] for w in g.hwall[r, :])) + println(io, " $(r % 10)) ", join(V[w+1] * C[c+1] for (w, c) in zip(g.vwall[r, :], g.cells[r, :]))) + end + println(io, " ", join(H[w+1] for w in g.hwall[end, :])) + if percolated + println(io, " !) ", " " ^ (ind - 1), '#') + end +end + +function floodfill!(m::Integer, n::Integer, cells::AbstractMatrix{<:Integer}, + hwall::AbstractMatrix{<:Integer}, vwall::AbstractMatrix{<:Integer}) + # fill cells + cells[m, n] = true + percolated = false + # bottom + if m < size(cells, 1) && !hwall[m+1, n] && !cells[m+1, n] + percolated = percolated || floodfill!(m + 1, n, cells, hwall, vwall) + # The Bottom + elseif m == size(cells, 1) && !hwall[m+1, n] + return true + end + # left + if n > 1 && !vwall[m, n] && !cells[m, n-1] + percolated = percolated || floodfill!(m, n - 1, cells, hwall, vwall) + end + # right + if n < size(cells, 2) && !vwall[m, n+1] && !cells[m, n+1] + percolated = percolated || floodfill!(m, n + 1, cells, hwall, vwall) + end + # top + if m > 1 && !hwall[m, n] && !cells[m-1, n] + percolated = percolated || floodfill!(m - 1, n, cells, hwall, vwall) + end + return percolated +end +function pourontop!(g::Grid) + m, n = 1, 1 + percolated = false + while !percolated && n ≤ size(g.cells, 2) + percolated = !g.hwall[m, n] && floodfill!(m, n, g.cells, g.hwall, g.vwall) + n += 1 + end + return percolated +end + +function main(probs, nrep::Integer=1000) + sampleprinted = false + pcount = zeros(Int, size(probs)) + for (i, p) in enumerate(probs), _ in 1:nrep + g = Grid(p) + percolated = pourontop!(g) + if percolated + pcount[i] += 1 + if !sampleprinted + println(g) + sampleprinted = true + end + end + end + return pcount ./ nrep +end + +probs = collect(10:-1:0) ./ 10 +percprobs = main(probs) + +println("Fraction of 1000 tries that percolate through:") +for (pr, pp) in zip(probs, percprobs) + @printf("\tp = %.3f ⇒ freq. = %5.3f\n", pr, pp) +end diff --git a/Task/Percolation-Bond-percolation/Kotlin/percolation-bond-percolation.kotlin b/Task/Percolation-Bond-percolation/Kotlin/percolation-bond-percolation.kotlin new file mode 100644 index 0000000000..44b2d1250b --- /dev/null +++ b/Task/Percolation-Bond-percolation/Kotlin/percolation-bond-percolation.kotlin @@ -0,0 +1,91 @@ +// version 1.2.10 + +import java.util.Random + +val rand = Random() +const val RAND_MAX = 32767 + +// cell states +const val FILL = 1 +const val RWALL = 2 // right wall +const val BWALL = 4 // bottom wall + +val x = 10 +val y = 10 +var grid = IntArray(x * (y + 2)) +var cells = 0 +var end = 0 +var m = 0 +var n = 0 + +fun makeGrid(p: Double) { + val thresh = (p * RAND_MAX).toInt() + m = x + n = y + grid.fill(0) // clears grid + for (i in 0 until m) grid[i] = BWALL or RWALL + cells = m + end = m + for (i in 0 until y) { + for (j in x - 1 downTo 1) { + val r1 = rand.nextInt(RAND_MAX + 1) + val r2 = rand.nextInt(RAND_MAX + 1) + grid[end++] = (if (r1 < thresh) BWALL else 0) or + (if (r2 < thresh) RWALL else 0) + } + val r3 = rand.nextInt(RAND_MAX + 1) + grid[end++] = RWALL or (if (r3 < thresh) BWALL else 0) + } +} + +fun showGrid() { + for (j in 0 until m) print("+--") + println("+") + + for (i in 0..n) { + print(if (i == n) " " else "|") + for (j in 0 until m) { + print(if ((grid[i * m + j + cells] and FILL) != 0) "[]" else " ") + print(if ((grid[i * m + j + cells] and RWALL) != 0) "|" else " ") + } + println() + if (i == n) return + for (j in 0 until m) { + print(if ((grid[i * m + j + cells] and BWALL) != 0) "+--" else "+ ") + } + println("+") + } +} + +fun fill(p: Int): Boolean { + if ((grid[p] and FILL) != 0) return false + grid[p] = grid[p] or FILL + if (p >= end) return true // success: reached bottom row + return (((grid[p + 0] and BWALL) == 0) && fill(p + m)) || + (((grid[p + 0] and RWALL) == 0) && fill(p + 1)) || + (((grid[p - 1] and RWALL) == 0) && fill(p - 1)) || + (((grid[p - m] and BWALL) == 0) && fill(p - m)) +} + +fun percolate(): Boolean { + var i = 0 + while (i < m && !fill(cells + i)) i++ + return i < m +} + +fun main(args: Array) { + makeGrid(0.5) + percolate() + showGrid() + + println("\nrunning $x x $y grids 10,000 times for each p:") + for (p in 1..9) { + var cnt = 0 + val pp = p / 10.0 + for (i in 0 until 10_000) { + makeGrid(pp) + if (percolate()) cnt++ + } + println("p = %3g: %.4f".format(pp, cnt.toDouble() / 10_000)) + } +} diff --git a/Task/Percolation-Mean-cluster-density/Julia/percolation-mean-cluster-density.julia b/Task/Percolation-Mean-cluster-density/Julia/percolation-mean-cluster-density.julia new file mode 100644 index 0000000000..76d42ea321 --- /dev/null +++ b/Task/Percolation-Mean-cluster-density/Julia/percolation-mean-cluster-density.julia @@ -0,0 +1,51 @@ +using Distributions + +newgrid(p::Float64, r::Int, c::Int=r) = rand(Bernoulli(p), r, c) + +function walkmaze!(grid::Matrix{Int}, r::Int, c::Int, indx::Int) + NOT_CLUSTERED = 1 # const + N, M = size(grid) + dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]] + # fill cell + grid[r, c] = indx + # check for each direction + for d in dirs + rr, cc = (r, c) .+ d + if checkbounds(Bool, grid, rr, cc) && grid[rr, cc] == NOT_CLUSTERED + walkmaze!(grid, rr, cc, indx) + end + end +end + +function clustercount!(grid::Matrix{Int}) + NOT_CLUSTERED = 1 # const + walkind = 1 + for r in 1:size(grid, 1), c in 1:size(grid, 2) + if grid[r, c] == NOT_CLUSTERED + walkind += 1 + walkmaze!(grid, r, c, walkind) + end + end + return walkind - 1 +end +clusterdensity(p::Float64, n::Int) = clustercount!(newgrid(p, n)) / n ^ 2 + +function printgrid(G::Matrix{Int}) + LETTERS = vcat(' ', '#', 'A':'Z', 'a':'z') + for r in 1:size(G, 1) + println(r % 10, ") ", join(LETTERS[G[r, :] .+ 1], ' ')) + end +end + +G = newgrid(0.5, 15) +@printf("Found %i clusters in this %i×%i grid\n\n", clustercount!(G), size(G, 1), size(G, 2)) +printgrid(G) +println() + +const nrange = 2 .^ (4:2:12) +const p = 0.5 +const nrep = 5 +for n in nrange + sim = mean(clusterdensity(p, n) for _ in 1:nrep) + @printf("nrep = %2i p = %.2f dim = %-13s sim = %.5f\n", nrep, p, "$n × $n", sim) +end diff --git a/Task/Percolation-Mean-cluster-density/Kotlin/percolation-mean-cluster-density.kotlin b/Task/Percolation-Mean-cluster-density/Kotlin/percolation-mean-cluster-density.kotlin new file mode 100644 index 0000000000..17d77cfb69 --- /dev/null +++ b/Task/Percolation-Mean-cluster-density/Kotlin/percolation-mean-cluster-density.kotlin @@ -0,0 +1,80 @@ +// version 1.2.10 + +import java.util.Random + +val rand = Random() +const val RAND_MAX = 32767 + +lateinit var map: IntArray +var w = 0 +var ww = 0 + +const val ALPHA = "+.ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" +const val ALEN = ALPHA.length - 3 + +fun makeMap(p: Double) { + val thresh = (p * RAND_MAX).toInt() + ww = w * w + var i = ww + map = IntArray(i) + while (i-- != 0) { + val r = rand.nextInt(RAND_MAX + 1) + if (r < thresh) map[i] = -1 + } +} + +fun showCluster() { + var k = 0 + for (i in 0 until w) { + for (j in 0 until w) { + val s = map[k++] + val c = if (s < ALEN) ALPHA[1 + s] else '?' + print(" $c") + } + println() + } +} + +fun recur(x: Int, v: Int) { + if ((x in 0 until ww) && map[x] == -1) { + map[x] = v + recur(x - w, v) + recur(x - 1, v) + recur(x + 1, v) + recur(x + w, v) + } +} + +fun countClusters(): Int { + var cls = 0 + for (i in 0 until ww) { + if (map[i] != -1) continue + recur(i, ++cls) + } + return cls +} + +fun tests(n: Int, p: Double): Double { + var k = 0.0 + for (i in 0 until n) { + makeMap(p) + k += countClusters().toDouble() / ww + } + return k / n +} + +fun main(args: Array) { + w = 15 + makeMap(0.5) + val cls = countClusters() + println("width = 15, p = 0.5, $cls clusters:") + showCluster() + + println("\np = 0.5, iter = 5:") + w = 1 shl 2 + while (w <= 1 shl 13) { + val t = tests(5, 0.5) + println("%5d %9.6f".format(w, t)) + w = w shl 1 + } +} diff --git a/Task/Percolation-Mean-run-density/Julia/percolation-mean-run-density.julia b/Task/Percolation-Mean-run-density/Julia/percolation-mean-run-density.julia new file mode 100644 index 0000000000..4be788452c --- /dev/null +++ b/Task/Percolation-Mean-run-density/Julia/percolation-mean-run-density.julia @@ -0,0 +1,20 @@ +using Distributions, IterTools + +newv(n::Int, p::Float64) = rand(Bernoulli(p), n) +runs(v::Vector{Int}) = sum((a & ~b) for (a, b) in zip(v, IterTools.chain(v[2:end], v[1]))) + +mrd(n::Int, p::Float64) = runs(newv(n, p)) / n + +nrep = 500 + +for p in 0.1:0.2:1 + lim = p * (1 - p) + + println() + for ex in 10:2:14 + n = 2 ^ ex + sim = mean(mrd.(n, p) for _ in 1:nrep) + @printf("nrep = %3i\tp = %4.2f\tn = %5i\np · (1 - p) = %5.3f\tsim = %5.3f\tΔ = %3.1f%%\n", + nrep, p, n, lim, sim, lim > 0 ? abs(sim - lim) / lim * 100 : sim * 100) + end +end diff --git a/Task/Percolation-Mean-run-density/Kotlin/percolation-mean-run-density.kotlin b/Task/Percolation-Mean-run-density/Kotlin/percolation-mean-run-density.kotlin new file mode 100644 index 0000000000..5a0b597f02 --- /dev/null +++ b/Task/Percolation-Mean-run-density/Kotlin/percolation-mean-run-density.kotlin @@ -0,0 +1,40 @@ +// version 1.2.10 + +import java.util.Random + +val rand = Random() +const val RAND_MAX = 32767 + +// just generate 0s and 1s without storing them +fun runTest(p: Double, len: Int, runs: Int): Double { + var cnt = 0 + val thresh = (p * RAND_MAX).toInt() + for (r in 0 until runs) { + var x = 0 + var i = len + while (i-- > 0) { + val y = if (rand.nextInt(RAND_MAX + 1) < thresh) 1 else 0 + if (x < y) cnt++ + x = y + } + } + return cnt.toDouble() / runs / len +} + +fun main(args: Array) { + println("running 1000 tests each:") + println(" p\t n\tK\tp(1-p)\t diff") + println("------------------------------------------------") + val fmt = "%.1f\t%6d\t%.4f\t%.4f\t%+.4f (%+.2f%%)" + for (ip in 1..9 step 2) { + val p = ip / 10.0 + val p1p = p * (1.0 - p) + var n = 100 + while (n <= 100_000) { + val k = runTest(p, n, 1000) + println(fmt.format(p, n, k, p1p, k - p1p, (k - p1p) / p1p * 100)) + n *= 10 + } + println() + } +} diff --git a/Task/Percolation-Site-percolation/Julia/percolation-site-percolation.julia b/Task/Percolation-Site-percolation/Julia/percolation-site-percolation.julia new file mode 100644 index 0000000000..4863f43b1e --- /dev/null +++ b/Task/Percolation-Site-percolation/Julia/percolation-site-percolation.julia @@ -0,0 +1,75 @@ +using Distributions + +newgrid(p::Float64, M::Int=15, N::Int=15) = rand(Bernoulli(p), M, N) + +function walkmaze!(grid::Matrix{Int}, r::Int, c::Int, indx::Int) + NOT_VISITED = 1 # const + N, M = size(grid) + dirs = [[1, 0], [-1, 0], [0, 1], [1, 0]] + # fill cell + grid[r, c] = indx + + # is the bottom line? + rst = r == N + + # for each direction, if has not reached the bottom yet and can continue go to that direction + for d in dirs + rr, cc = (r, c) .+ d + if !rst && checkbounds(Bool, grid, rr, cc) && grid[rr, cc] == NOT_VISITED + rst = walkmaze!(grid, rr, cc, indx) + end + end + return rst +end + +function checkpath!(grid::Matrix{Int}) + NOT_VISITED = 1 # const + N, M = size(grid) + walkind = 1 + for m in 1:M + if grid[1, m] == NOT_VISITED + walkind += 1 + if walkmaze!(grid, 1, m, walkind) + return true + end + end + end + return false +end + +function printgrid(G::Matrix{Int}) + LETTERS = vcat(' ', '#', 'A':'Z') + for r in 1:size(G, 1) + println(r % 10, ") ", join(LETTERS[G[r, :] .+ 1], ' ')) + end + if any(G[end, :] .> 1) + println("!) ", join((ifelse(c > 1, LETTERS[c+1], ' ') for c in G[end, :]), ' ')) + end +end + +const nrep = 1000 # const +sampleprinted = false + +p = collect(0.0:0.1:1.0) +f = similar(p) +for i in linearindices(f) + c = 0 + for _ in 1:nrep + G = newgrid(p[i]) + perc = checkpath!(G) + if perc + c += 1 + if !sampleprinted + @printf("Sample percolation, %i×%i grid, p = %.2f\n\n", size(G, 1), size(G, 2), p[i]) + printgrid(G) + sampleprinted = true + end + end + end + f[i] = c / nrep +end + +println("\nFrequencies for $nrep tries that percolate through\n") +for (pi, fi) in zip(p, f) + @printf("p = %.1f ⇛ f = %.3f\n", pi, fi) +end diff --git a/Task/Percolation-Site-percolation/Kotlin/percolation-site-percolation.kotlin b/Task/Percolation-Site-percolation/Kotlin/percolation-site-percolation.kotlin new file mode 100644 index 0000000000..e9c9b5583b --- /dev/null +++ b/Task/Percolation-Site-percolation/Kotlin/percolation-site-percolation.kotlin @@ -0,0 +1,67 @@ +// version 1.2.10 + +import java.util.Random + +val rand = Random() +const val RAND_MAX = 32767 +const val NUL = '\u0000' + +val x = 15 +val y = 15 +var grid = StringBuilder((x + 1) * (y + 1) + 1) +var cell = 0 +var end = 0 +var m = 0 +var n = 0 + +fun makeGrid(p: Double) { + val thresh = (p * RAND_MAX).toInt() + m = x + n = y + grid.setLength(0) // clears grid + grid.setLength(m + 1) // sets first (m + 1) chars to NUL + end = m + 1 + cell = m + 1 + for (i in 0 until n) { + for (j in 0 until m) { + val r = rand.nextInt(RAND_MAX + 1) + grid.append(if (r < thresh) '+' else '.') + end++ + } + grid.append('\n') + end++ + } + grid[end - 1] = NUL + end -= ++m // end is the index of the first cell of bottom row +} + +fun ff(p: Int): Boolean { // flood fill + if (grid[p] != '+') return false + grid[p] = '#' + return p >= end || ff(p + m) || ff(p + 1) || ff(p - 1) || ff(p - m) +} + +fun percolate(): Boolean { + var i = 0 + while (i < m && !ff(cell + i)) i++ + return i < m +} + +fun main(args: Array) { + makeGrid(0.5) + percolate() + + println("$x x $y grid:") + println(grid) + + println("\nrunning 10,000 tests for each case:") + for (ip in 0..10) { + val p = ip / 10.0 + var cnt = 0 + for (i in 0 until 10_000) { + makeGrid(p) + if (percolate()) cnt++ + } + println("p = %.1f: %.4f".format(p, cnt / 10000.0)) + } +} diff --git a/Task/Perfect-numbers/Julia/perfect-numbers.julia b/Task/Perfect-numbers/Julia/perfect-numbers.julia index 4527ce6a2d..df3550345d 100644 --- a/Task/Perfect-numbers/Julia/perfect-numbers.julia +++ b/Task/Perfect-numbers/Julia/perfect-numbers.julia @@ -1,3 +1,4 @@ -function isperfect(n) - n == sum([n % i == 0 ? i : 0 for i = 1:n-1]) -end +isperfect(n::Integer) = n == sum([n % i == 0 ? i : 0 for i = 1:(n - 1)]) +perfects(n::Integer) = filter(isperfect, 1:n) + +@show perfects(10000) diff --git a/Task/Perfect-numbers/Modula-2/perfect-numbers.mod2 b/Task/Perfect-numbers/Modula-2/perfect-numbers.mod2 new file mode 100644 index 0000000000..e5e7165723 --- /dev/null +++ b/Task/Perfect-numbers/Modula-2/perfect-numbers.mod2 @@ -0,0 +1,43 @@ +MODULE PerfectNumbers; + +FROM SWholeIO IMPORT + WriteCard; +FROM STextIO IMPORT + WriteLn; +FROM RealMath IMPORT + sqrt; + +VAR + N: CARDINAL; + +PROCEDURE IsPerfect(N: CARDINAL): BOOLEAN; +VAR + S, I: CARDINAL; + SqrtN: REAL; +BEGIN + S := 1; + SqrtN := sqrt(FLOAT(N)); + IF N REM 2 = 0 THEN + S := S + 2 + N / 2; + END; + I := 3; + WHILE FLOAT(I) <= SqrtN - 1.0 DO + IF N REM I = 0 THEN + S := S + I + N / I; + END; + I := I + 1; + END; + IF I * I = N THEN + S := S + I; + END; + RETURN (N = S); +END IsPerfect; + +BEGIN + FOR N := 2 TO 10000 BY 2 DO + IF IsPerfect(N) THEN + WriteCard(N, 5); + WriteLn; + END; + END; +END PerfectNumbers. diff --git a/Task/Perfect-numbers/Perl-6/perfect-numbers.pl6 b/Task/Perfect-numbers/Perl-6/perfect-numbers.pl6 index 80433532f6..f03fdd510e 100644 --- a/Task/Perfect-numbers/Perl-6/perfect-numbers.pl6 +++ b/Task/Perfect-numbers/Perl-6/perfect-numbers.pl6 @@ -1 +1,4 @@ -sub perf($n) { $n == [+] grep $n %% *, 1 .. $n div 2 } +sub is-perf($n) { $n == [+] grep $n %% *, 1 .. $n div 2 } + +# used as +put (grep {.&is-perf}, 1..Inf)[^4]; diff --git a/Task/Permutation-test/Java/permutation-test.java b/Task/Permutation-test/Java/permutation-test.java new file mode 100644 index 0000000000..8879f4446e --- /dev/null +++ b/Task/Permutation-test/Java/permutation-test.java @@ -0,0 +1,30 @@ +public class PermutationTest { + private static final int[] data = new int[]{ + 85, 88, 75, 66, 25, 29, 83, 39, 97, + 68, 41, 10, 49, 16, 65, 32, 92, 28, 98 + }; + + private static int pick(int at, int remain, int accu, int treat) { + if (remain == 0) return (accu > treat) ? 1 : 0; + return pick(at - 1, remain - 1, accu + data[at - 1], treat) + + ((at > remain) ? pick(at - 1, remain, accu, treat) : 0); + } + + public static void main(String[] args) { + int treat = 0; + double total = 1.0; + for (int i = 0; i <= 8; ++i) { + treat += data[i]; + } + for (int i = 19; i >= 11; --i) { + total *= i; + } + for (int i = 9; i >= 1; --i) { + total /= i; + } + int gt = pick(19, 9, 0, treat); + int le = (int) (total - gt); + System.out.printf("<= : %f%% %d\n", 100.0 * le / total, le); + System.out.printf(" > : %f%% %d\n", 100.0 * gt / total, gt); + } +} diff --git a/Task/Permutation-test/Julia/permutation-test-1.julia b/Task/Permutation-test/Julia/permutation-test-1.julia index 4841ff5aa4..f9d88b1f34 100644 --- a/Task/Permutation-test/Julia/permutation-test-1.julia +++ b/Task/Permutation-test/Julia/permutation-test-1.julia @@ -1,27 +1,28 @@ -delta_mean{T<:Real}(a::Array{T,1}, b::Array{T,1}) = mean(a) - mean(b) +using Combinatorics -function bifurcate{T<:Integer}(a::AbstractVector, sel::Array{T,1}) - x = a[sel] - asel = trues(length(a)) +meandiff(a::Vector{T}, b::Vector{T}) where T <: Real = mean(a) - mean(b) + +function bifurcate(a::AbstractVector, sel::Vector{T}) where T <: Integer + x = a[sel] + asel = trues(length(a)) asel[sel] = false - y = a[asel] - return (x, y) + y = a[asel] + return x, y end -function perm_sig_test{T<:Real}(treat::Array{T,1}, control::Array{T,1}) - base_effect = delta_mean(treat, control) - pool = [treat, control] - tlen = length(treat) - plen = length(pool) - better = 0 - worse = 0 - for s in combinations(1:plen, tlen) - (t, c) = bifurcate(pool, s) - if base_effect < delta_mean(t, c) +function permutation_test(treated::Vector{T}, control::Vector{T}) where T <: Real + effect0 = meandiff(treated, control) + pool = vcat(treated, control) + tlen = length(treated) + plen = length(pool) + better = worse = 0 + for subset in combinations(1:plen, tlen) + t, c = bifurcate(pool, subset) + if effect0 < meandiff(t, c) better += 1 else worse += 1 end end - return (better, worse) + return better, worse end diff --git a/Task/Permutation-test/Julia/permutation-test-2.julia b/Task/Permutation-test/Julia/permutation-test-2.julia index b3ef8745e7..6812de7eae 100644 --- a/Task/Permutation-test/Julia/permutation-test-2.julia +++ b/Task/Permutation-test/Julia/permutation-test-2.julia @@ -1,17 +1,13 @@ -treat = [85, 88, 75, 66, 25, 29, 83, 39, 97] -control = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98] +const treated = [85, 88, 75, 66, 25, 29, 83, 39, 97] +const control = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98] -(better, worse) = perm_sig_test(treat, control) +(better, worse) = permutation_test(treated, control) tot = better + worse println("Permutation test using the following data:") -println("Treated: ", treat) +println("Treated: ", treated) println("Control: ", control) - -println() -println("There are ", tot, " different permuted groups of these data.") -print(@sprintf("%8d, %5.2f%% ", better, 100better/tot)) -println("showed better than actual results.") -print(@sprintf("%8d, %5.2f%% ", worse, 100worse/tot)) -println("showed equalivalent or worse results.") +println("\nThere are $tot different permuted groups of these data.") +@printf("%8d, %5.2f%% showed better than actual results.\n", better, 100 * better / tot) +print(@sprintf("%8d, %5.2f%% showed equalivalent or worse results.", worse, 100 * worse / tot)) diff --git a/Task/Permutations-Derangements/Perl-6/permutations-derangements.pl6 b/Task/Permutations-Derangements/Perl-6/permutations-derangements.pl6 index eb2c0d7a36..c2b759c9e5 100644 --- a/Task/Permutations-Derangements/Perl-6/permutations-derangements.pl6 +++ b/Task/Permutations-Derangements/Perl-6/permutations-derangements.pl6 @@ -1,24 +1,15 @@ -sub is-derangement(List $l) { - return not grep { $l[$_] == $_ }, 0..($l.elems - 1); +sub derangements(@l) { + @l.permutations.grep(-> @p { none(@p Zeqv @l) }) } -# task 1 -sub derangements(Range $x) { - $x.permutations.grep( *.&is-derangement ) +sub prefix:(Int $n) { + (1, 0, 1, -> $a, $b { ($++ + 2) × ($b + $a) } ... *)[$n] } -# task 2 -.say for (0..4).&derangements; +say 'derangements([1, 2, 3, 4])'; +say derangements([1, 2, 3, 4]), "\n"; -# task 3 -sub prefix:(Int $x) { - return +derangements(^$x); -} - -# task 4 -for ^9 -> $n { - say "number: " ~ $n; - say "count: " ~ !$n; - say "derangements: "; - .say for (0..$n-1).&derangements; +say 'n == !n == derangements(^n).elems'; +for 0 .. 9 -> $n { + say "!$n == { !$n } == { derangements(^$n).elems }" } diff --git a/Task/Permutations-Derangements/Perl/permutations-derangements.pl b/Task/Permutations-Derangements/Perl/permutations-derangements-1.pl similarity index 100% rename from Task/Permutations-Derangements/Perl/permutations-derangements.pl rename to Task/Permutations-Derangements/Perl/permutations-derangements-1.pl diff --git a/Task/Permutations-Derangements/Perl/permutations-derangements-2.pl b/Task/Permutations-Derangements/Perl/permutations-derangements-2.pl new file mode 100644 index 0000000000..f582416516 --- /dev/null +++ b/Task/Permutations-Derangements/Perl/permutations-derangements-2.pl @@ -0,0 +1,25 @@ +use ntheory ":all"; + +# Count derangements using derangement iterator +sub countderange { + my($n,$s) = (shift,0); + forderange { $s++ } $n; + $s; +} +# Count derangements using inclusion-exclusion +sub subfactorial1 { + my $n = shift; + vecsum(map{ vecprod((-1)**($n-$_),binomial($n,$_),factorial($_)) }0..$n); +} +# Count derangements using simple recursion without special functions +sub subfactorial2 { + my $n = shift; + use bigint; no warnings 'recursion'; + ($n < 1) ? 1 : $n * subfactorial2($n-1) + (-1)**$n; +} + +print "Derangements of 4 items:\n"; +forderange { print "@_\n" } 4; +printf "\n%3s %15s %15s\n","N","List count","!N"; +printf "%3d %15d %15d %15d\n",$_,countderange($_),subfactorial1($_),subfactorial2($_) for 0..9; +printf "%3d %15s %s\n",$_,"",subfactorial2($_) for 20,200; diff --git a/Task/Permutations-Derangements/REXX/permutations-derangements.rexx b/Task/Permutations-Derangements/REXX/permutations-derangements.rexx index 7868f0cc15..a7940f7bb5 100644 --- a/Task/Permutations-Derangements/REXX/permutations-derangements.rexx +++ b/Task/Permutations-Derangements/REXX/permutations-derangements.rexx @@ -1,43 +1,42 @@ -/*REXX pgm generates all permutations of N derangements & subfactorial #*/ -numeric digits 1000 /*be able to handle big subfacts.*/ -parse arg N .; if N=='' then N=4 /*Not specified? Assume default*/ -d=derangementsSet(N) /*go & build the derangements set*/ -say d 'derangements for' N "items are:" +/*REXX program generates all permutations of N derangements and subfactorial # */ +numeric digits 1000 /*be able to handle large subfactorials*/ +parse arg N .; if N=='' | N=="," then N=4 /*Not specified? Then use the default.*/ +d= derangeSet(N) /*go and build the derangements set. */ +say d 'derangements for' N "items are:" say - do i=1 for d /*show derangements for N items.*/ - say right('derangement',22) right(i,length(d)) '───►' $.i + do i=1 for d /*display the derangements for N items.*/ + say right('derangement', 22) right(i, length(d) ) '───►' $.i end /*i*/ -say /* [↓] count and calculate !L. */ - do L=0 to 9; d=derangementsSet(L) - say L 'items: derangement count='right(d,6)", !"L'='right(!s(L),6) +say /* [↓] count and calculate subfact !L.*/ + do L=0 to 2; d= derangeSet(L) + say L 'items: derangement count='right(d, 6)", !"L'='right( !s(L), 6) end /*L*/ say -say right('!20=' , 40) !s( 20) -say right('!100=', 40) !s(100) -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────!S subroutine───────────────────────*/ -!s: _=1; do j=1 for arg(1);if j//2 then _=-1+j*_;else _=1+j*_;end;return _ -/*──────────────────────────────────DERANGEMENTSSET subroutine──────────*/ -derangementsSet: procedure expose $.; parse arg x; $.=; #=0; p=x-1 -if x==0 then return 1; if x==1 then return 0 - /*populate the first derangement.*/ -@.1=2; @.2=1; do i=3 to x; @.i=i; end -parse value @.p @.x with @.x @.p; call .buildD x /*swap & build.*/ - /*build others.*/ - do while .nextD(x,0); call .buildD x; end -return # -/*──────────────────────────────────.BUILDD subroutine──────────────────*/ -.buildD: do j=1 for arg(1); if @.j==j then return; end -#=#+1; do j=1 for arg(1); $.#=$.# @.j; end; return -/*──────────────────────────────────.NEXTD subroutine───────────────────*/ -.nextD: procedure expose @.; parse arg n,i; nm=n-1 +say right('!20=' , 22) !s( 20) +say right('!200=', 22) !s(200) +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +!s: _=1; do j=1 for arg(1); if j//2 then _= j*_ - 1; else _=j*_ + 1 + end /*j*/; return _ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +derangeSet: procedure expose $.; parse arg x; $.=; #=0; p=x-1 + if x==0 then return 1; if x==1 then return 0 + @.1=2; @.2=1 /*populate 1st derangement.*/ + do i=3 to x; @.i=i; end /*i*/ /* " the rest of 'em.*/ + parse value @.p @.x with @.x @.p; call .buildD x /*swap & build.*/ + /*build others.*/ + do while .nextD(x, 0); call .buildD x; end; return # +/*──────────────────────────────────────────────────────────────────────────────────────*/ +.buildD: do j=1 for arg(1); if @.j==j then return; end + #=#+1; do j=1 for arg(1); $.#= $.# @.j; end; return +/*──────────────────────────────────────────────────────────────────────────────────────*/ +.nextD: procedure expose @.; parse arg n,i - do k=nm by -1 for nm; kp=k+1; if @.k<@.kp then do; i=k; leave; end - end /*k*/ + do k=n-1 by -1 for n-1; kp=k+1; if @.k<@.kp then do; i=k; leave; end + end /*k*/ - do j=i+1 while j [@perm] --> %2d\n", $k, $rank; +} +print "\n"; + +print " Four 12-object random permutations using ranks\n"; +print join(" ", numtoperm(12,urandomm(factorial(12)))), "\n" for 1..4; +print "\n"; +print " Four 12-object random permutations using randperm\n"; +print join(" ", randperm(12)),"\n" for 1..4; +print "\n"; +print " Four 4-object random permutations of 100k objects using randperm\n"; +print join(" ", randperm(100000,4)),"\n" for 1..4; diff --git a/Task/Permutations-Rank-of-a-permutation/REXX/permutations-rank-of-a-permutation.rexx b/Task/Permutations-Rank-of-a-permutation/REXX/permutations-rank-of-a-permutation.rexx index b4b5ac5fa8..c380ec47cb 100644 --- a/Task/Permutations-Rank-of-a-permutation/REXX/permutations-rank-of-a-permutation.rexx +++ b/Task/Permutations-Rank-of-a-permutation/REXX/permutations-rank-of-a-permutation.rexx @@ -1,38 +1,35 @@ /*REXX program displays permutations of N number of objects (1, 2, 3, ···). */ -parse arg N seed . /*obtain optional arguments from the CL*/ -if N=='' | N=="," then N=4 /*Not specified? Then use the default.*/ +parse arg N y seed . /*obtain optional arguments from the CL*/ +if N=='' | N=="," then N= 4 /*Not specified? Then use the default.*/ +if y=='' | y=="," then y=17 /* " " " " " " */ if datatype(seed,'W') then call random ,,seed /*can make RANDOM numbers repeatable. */ -permutes=permSets(N) /*returns N! (number of permutations).*/ -w=length(permutes) /*used for aligning the SAY output. */ - - do what=0 to permutes-1 /*traipse through each of the permutes.*/ - z=permSets(N, what) /*get which of the permutation it is.*/ - say N 'items, permute' right(what,w) "=" z ' rank=' permSets(N,,z) - end /*what*/ -say -N=12 - do 4; ?=random(0, N**4) /*REXX has a 100k RANDOM range. */ - say N 'items, permute' right(?,6) " is " permSets(N,?) - end /*rand*/ +permutes= permSets(N) /*returns N! (number of permutations).*/ +w= length(permutes) /*used for aligning the SAY output. */ +@.= + do p=0 to permutes-1 /*traipse through each of the permutes.*/ + z=permSets(N, p) /*get which of the permutation it is.*/ + say 'for' N "items, permute rank" right(p,w) 'is: ' z + @.p=z /*define a rank permutation in @ array.*/ + end /*p*/ +say /* [↓] displays a particular perm rank*/ +say ' the permutation rank of' y "is: " @.y /*display a particular permuation rank.*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -permSets: procedure expose @. #; #=0; parse arg x,r,c; c=space(c); xm=x-1 - - do j=1 for x; @.j=j-1; end /*j*/ - _=0; do u=2 for xm; _=_ @.u; end /*u*/ - if r==# then return _; if c==_ then return # - - do while .permSets(x,0); #=#+1; _=@.1 - do v=2 for xm; _=_ @.v; end /*v*/ - if r==# then return _; if c==_ then return # - end /*while···*/ - return #+1 +permSets: procedure expose @. #; #=0; parse arg x,r,c; c=space(c); xm=x -1 + do j=1 for x; @.j=j-1; end /*j*/ + _=0; do u=2 for xm; _=_ @.u; end /*u*/ + if r==# then return _; if c==_ then return # + do while .permSets(x,0); #=#+1; _=@.1 + do v=2 for xm; _=_ @.v; end /*v*/ + if r==# then return _; if c==_ then return # + end /*while···*/ + return #+1 /*──────────────────────────────────────────────────────────────────────────────────────*/ .permSets: procedure expose @.; parse arg p,q; pm=p-1 do k=pm by -1 for pm; kp=k+1; if @.k<@.kp then do; q=k; leave; end end /*k*/ - do j=q+1 while j + +list = [0, 1, 2, 3] +for perm = 0 to 23 + str = "" + for i = 1 to len(list) + str = str + list[i] + ", " + next + see nl + str = left(str, len(str)-2) + see "(" + str + ") -> " + perm + nextPermutation(list) +next + +func nextPermutation(a) + elementcount = len(a) + if elementcount < 1 then return ok + pos = elementcount-1 + while a[pos] >= a[pos+1] + pos -= 1 + if pos <= 0 permutationReverse(a, 1, elementcount) + return + ok + end + last = elementcount + while a[last] <= a[pos] + last -= 1 + end + temp = a[pos] + a[pos] = a[last] + a[last] = temp + permutationReverse(a, pos+1, elementcount) + + func permutationReverse(a, first, last) + while first < last + temp = a[first] + a[first] = a[last] + a[last] = temp + first = first + 1 + last = last - 1 + end diff --git a/Task/Permutations-by-swapping/00DESCRIPTION b/Task/Permutations-by-swapping/00DESCRIPTION index e72104ddbb..1aa1cf3bd5 100644 --- a/Task/Permutations-by-swapping/00DESCRIPTION +++ b/Task/Permutations-by-swapping/00DESCRIPTION @@ -17,7 +17,7 @@ Note: The Steinhaus–Johnson–Trotter algorithm generates successive permutati * [http://www.gutenberg.org/files/18567/18567-h/18567-h.htm#ch7] Tintinnalogia -;Related task: +;Related tasks: *   [[Matrix arithmetic]] *   [[Gray code]]

diff --git a/Task/Permutations-by-swapping/C/permutations-by-swapping.c b/Task/Permutations-by-swapping/C/permutations-by-swapping.c new file mode 100644 index 0000000000..a232b547ca --- /dev/null +++ b/Task/Permutations-by-swapping/C/permutations-by-swapping.c @@ -0,0 +1,69 @@ +/*Abhishek Ghosh, 25th October 2017*/ + +#include +#include +#include + +int flag = 1; + +void heapPermute(int n, int arr[],int arrLen){ + int temp; + int i; + + if(n==1){ + printf("\n["); + + for(i=0;i",argV[0]); + else{ + while(argV[1][i]!=00){ + if(argV[1][i++]==',') + count++; + } + + arr = (int*)malloc(count*sizeof(int)); + + i = 0; + + token = strtok(argV[1],","); + + while(token!=NULL){ + arr[i++] = atoi(token); + token = strtok(NULL,","); + } + + heapPermute(i,arr,count); + } + + return 0; +} diff --git a/Task/Permutations-by-swapping/Clojure/permutations-by-swapping-1.clj b/Task/Permutations-by-swapping/Clojure/permutations-by-swapping-1.clj index 1a055e0fb8..f0ffd0a3a4 100644 --- a/Task/Permutations-by-swapping/Clojure/permutations-by-swapping-1.clj +++ b/Task/Permutations-by-swapping/Clojure/permutations-by-swapping-1.clj @@ -1,5 +1,37 @@ -(defn permutations [a-set] - (cond (empty? a-set) '(()) - (empty? (rest a-set)) (list (apply list a-set)) - :else (for [x a-set y (permutations (remove #{x} a-set))] - (cons x y)))) +(defn permutation-swaps + "List of swap indexes to generate all permutations of n elements" + [n] + (if (= n 2) `((0 1)) + (let [old-swaps (permutation-swaps (dec n)) + swaps-> (partition 2 1 (range n)) + swaps<- (reverse swaps->)] + (mapcat (fn [old-swap side] + (case side + :first swaps<- + :right (conj swaps<- old-swap) + :left (conj swaps-> (map inc old-swap)))) + (conj old-swaps nil) + (cons :first (cycle '(:left :right))))))) + + +(defn swap [v [i j]] + (-> v + (assoc i (nth v j)) + (assoc j (nth v i)))) + + +(defn permutations [n] + (let [permutations (reduce + (fn [all-perms new-swap] + (conj all-perms (swap (last all-perms) + new-swap))) + (vector (vec (range n))) + (permutation-swaps n)) + output (map vector + permutations + (cycle '(1 -1)))] + output)) + + +(doseq [n [2 3 4]] + (dorun (map println (permutations n)))) diff --git a/Task/Permutations-by-swapping/Julia/permutations-by-swapping-1.julia b/Task/Permutations-by-swapping/Julia/permutations-by-swapping-1.julia new file mode 100644 index 0000000000..cc4abfda73 --- /dev/null +++ b/Task/Permutations-by-swapping/Julia/permutations-by-swapping-1.julia @@ -0,0 +1,58 @@ +function johnsontrottermove!(ints, isleft) + len = length(ints) + function ismobile(pos) + if isleft[pos] && (pos > 1) && (ints[pos-1] < ints[pos]) + return true + elseif !isleft[pos] && (pos < len) && (ints[pos+1] < ints[pos]) + return true + end + false + end + function maxmobile() + arr = [ints[pos] for pos in 1:len if ismobile(pos)] + if isempty(arr) + 0, 0 + else + maxmob = maximum(arr) + maxmob, findfirst(x -> x == maxmob, ints) + end + end + function directedswap(pos) + tmp = ints[pos] + tmpisleft = isleft[pos] + if isleft[pos] + ints[pos] = ints[pos-1]; ints[pos-1] = tmp + isleft[pos] = isleft[pos-1]; isleft[pos-1] = tmpisleft + else + ints[pos] = ints[pos+1]; ints[pos+1] = tmp + isleft[pos] = isleft[pos+1]; isleft[pos+1] = tmpisleft + end + end + (moveint, movepos) = maxmobile() + if movepos > 0 + directedswap(movepos) + for (i, val) in enumerate(ints) + if val > moveint + isleft[i] = !isleft[i] + end + end + ints, isleft, true + else + ints, isleft, false + end +end +function johnsontrotter(low, high) + ints = collect(low:high) + isleft = [true for i in ints] + firstconfig = copy(ints) + iters = 0 + while true + iters += 1 + println("$ints $(iters & 1 == 1 ? "+1" : "-1")") + if johnsontrottermove!(ints, isleft)[3] == false + break + end + end + println("There were $iters iterations.") +end +johnsontrotter(1,4) diff --git a/Task/Permutations-by-swapping/Julia/permutations-by-swapping-2.julia b/Task/Permutations-by-swapping/Julia/permutations-by-swapping-2.julia new file mode 100644 index 0000000000..5c062fa03a --- /dev/null +++ b/Task/Permutations-by-swapping/Julia/permutations-by-swapping-2.julia @@ -0,0 +1,23 @@ +function johnsontrotter(low, high) + function permutelevel(vec) + if length(vec) < 2 + return [vec] + end + sequences = [] + endint = vec[end] + smallersequences = permutelevel(vec[1:end-1]) + leftward = true + for seq in smallersequences + for pos in (leftward ? (length(seq)+1:-1:1): (1:length(seq)+1)) + push!(sequences, insert!(copy(seq), pos, endint)) + end + leftward = !leftward + end + sequences + end + permutelevel(collect(low:high)) +end + +for (i, sequence) in enumerate(johnsontrotter(1,4)) + println("""$sequence, $(i & 1 == 1 ? "+1" : "-1")""") +end diff --git a/Task/Permutations-by-swapping/Lua/permutations-by-swapping.lua b/Task/Permutations-by-swapping/Lua/permutations-by-swapping-1.lua similarity index 100% rename from Task/Permutations-by-swapping/Lua/permutations-by-swapping.lua rename to Task/Permutations-by-swapping/Lua/permutations-by-swapping-1.lua diff --git a/Task/Permutations-by-swapping/Lua/permutations-by-swapping-2.lua b/Task/Permutations-by-swapping/Lua/permutations-by-swapping-2.lua new file mode 100644 index 0000000000..2dedc826e6 --- /dev/null +++ b/Task/Permutations-by-swapping/Lua/permutations-by-swapping-2.lua @@ -0,0 +1,21 @@ +local wrap, yield = coroutine.wrap, coroutine.yield +local function perm(n) + local r = {} + for i=1,n do r[i]=i end + local sign = 1 + return wrap(function() + local function swap(m) + if m==0 then + sign = -sign, yield(sign,r) + else + for i=m,1,-1 do + r[i],r[m]=r[m],r[i] + swap(m-1) + r[i],r[m]=r[m],r[i] + end + end + end + swap(n) + end) +end +for sign,r in perm(3) do print(sign,table.unpack(r))end diff --git a/Task/Permutations-by-swapping/REXX/permutations-by-swapping.rexx b/Task/Permutations-by-swapping/REXX/permutations-by-swapping.rexx index a8792aa6f7..171b8a5553 100644 --- a/Task/Permutations-by-swapping/REXX/permutations-by-swapping.rexx +++ b/Task/Permutations-by-swapping/REXX/permutations-by-swapping.rexx @@ -1,52 +1,46 @@ -/*REXX program generates all permutations of N different objects by swapping. */ -parse arg things bunch . /*get optional arguments from the C.L. */ -things = p(things 4) /*should use the default for THINGS ? */ -bunch = p(bunch things) /* " " " " " BUNCH ? */ +/*REXX program generates all permutations of N different objects by swapping. */ +parse arg things bunch . /*obtain optional arguments from the CL*/ +if things=='' | things=="," then things=4 /*Not specified? Then use the default.*/ +if bunch =='' | bunch =="," then bunch =things /* " " " " " " */ call permSets things, bunch /*invoke permutations by swapping sub. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -!: procedure; !=1; do j=2 to arg(1); !=!*j; end /*j*/; return ! -c: return substr(arg(1), arg(2), 1) /*pick a single character from a string*/ -p: return word(arg(1), 1) /*pick 1st word (or number) from a list*/ +!: procedure; !=1; do j=2 to arg(1); !=!*j; end; return ! /*──────────────────────────────────────────────────────────────────────────────────────*/ permSets: procedure; parse arg x,y /*take X things Y at a time. */ - !.=0; pad=left('',x*y) /*Note: X can't be > length(@0abcs). */ - @abc = 'abcdefghijklmnopqrstuvwxyz'; @abcU=@abc; upper @abcU /*build symbols*/ - @abcS= @abcU || @abc; @0abcS=123456789 || @abcS /* ··· and more*/ - z= /*define Z to be a null value for start*/ - do i=1 for x /*build list of (permutation) symbols. */ - z=z || c(@0abcS, i) /*append the char to the symbol list. */ - end /*i*/ + !.=0; pad=left('', x*y) /*X can't be > length of below str (62)*/ + z=left('123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', x); q=z #=1 /*the number of permutations (so far).*/ - !.z=1; q=z; s=1; times=!(x)% !(x-y) /*calculate (#) TIMES using factorial.*/ - w=max(length(z), length('permute')) /*maximum width of Z and also PERMUTE.*/ + !.z=1; s=1; times=!(x) % !(x-y) /*calculate (#) TIMES using factorial.*/ + w=max(length(z), length('permute') ) /*maximum width of Z and also PERMUTE.*/ say center('permutations for ' x ' things taken ' y " at a time",60,'═') say - say pad 'permutation' center("permute", w, '─') "sign" - say pad '───────────' center("───────", w, '─') "────" - say pad center(#, 11) center(z , w) right(s, 4-1) + say pad 'permutation' center("permute", w, '─') "sign" + say pad '───────────' center("───────", w, '─') "────" + say pad center(#, 11) center(z , w) right(s, 4-1) - do $=1 until #==times /*perform permutation until # of times.*/ - do k=1 for x-1 /*step thru things for things-1 times.*/ - do m=k+1 to x; ?= /*this method doesn't use adjacency. */ - do n=1 for x /*build the new permutation by swapping*/ - if n\==k & n\==m then ? = ? || c(z, n) - else if n==k then ? = ? || c(z, m) - else ? = ? || c(z, k) - end /*n*/ - z=? /*save this permutation for next swap. */ - if !.? then iterate m /*if defined before, then try next one.*/ - _=0 /* [↓] count number of swapped symbols*/ - do d=1 for x while $\==1; _=_+(c(?,d)\==c(prev,d)); end /*d*/ - if _>2 then do; _=z - a=$//x+1; q=q+_ /* [← ↓] this swapping tries adjacency*/ - b=q//x+1; if b==a then b=a+1; if b>x then b=a-1 - z=overlay(c(z, b), overlay(c(z, a), _, b), a) - iterate $ /*now, try this particular permutation.*/ - end - #=#+1; s=-s; say pad center(#,11) center(?,w) right(s,4-1) - !.?=1; prev=?; iterate $ /*now, try another swapped permutation.*/ - end /*m*/ - end /*k*/ - end /*$*/ + do $=1 until #==times /*perform permutation until # of times.*/ + do k=1 for x-1 /*step thru things for things-1 times.*/ + do m=k+1 to x; ?= /*this method doesn't use adjacency. */ + do n=1 for x /*build the new permutation by swapping*/ + if n\==k & n\==m then ? = ? || substr(z, n, 1) + else if n==k then ? = ? || substr(z, m, 1) + else ? = ? || substr(z, k, 1) + end /*n*/ + z=? /*save this permutation for next swap. */ + if !.? then iterate m /*if defined before, then try next one.*/ + _=0 /* [↓] count number of swapped symbols*/ + do d=1 for x while $\==1; _= _ + (substr(?,d,1)\==substr(prev,d,1)) + end /*d*/ + if _>2 then do; _=z + a=$//x+1; q=q + _ /* [← ↓] this swapping tries adjacency*/ + b=q//x+1; if b==a then b=a + 1; if b>x then b=a - 1 + z=overlay( substr(z,b,1), overlay( substr(z,a,1), _, b), a) + iterate $ /*now, try this particular permutation.*/ + end + #=#+1; s= -s; say pad center(#, 11) center(?, w) right(s, 4-1) + !.?=1; prev=?; iterate $ /*now, try another swapped permutation.*/ + end /*m*/ + end /*k*/ + end /*$*/ return /*we're all finished with permutating. */ diff --git a/Task/Permutations-by-swapping/Scala/permutations-by-swapping.scala b/Task/Permutations-by-swapping/Scala/permutations-by-swapping.scala new file mode 100644 index 0000000000..2fa0f0780e --- /dev/null +++ b/Task/Permutations-by-swapping/Scala/permutations-by-swapping.scala @@ -0,0 +1,36 @@ +object JohnsonTrotter extends App { + + private def perm(n: Int): Unit = { + val p = new Array[Int](n) // permutation + val pi = new Array[Int](n) // inverse permutation + val dir = new Array[Int](n) // direction = +1 or -1 + + def perm(n: Int, p: Array[Int], pi: Array[Int], dir: Array[Int]): Unit = { + if (n >= p.length) for (aP <- p) print(aP) + else { + perm(n + 1, p, pi, dir) + for (i <- 0 until n) { // swap + printf(" (%d %d)\n", pi(n), pi(n) + dir(n)) + val z = p(pi(n) + dir(n)) + p(pi(n)) = z + p(pi(n) + dir(n)) = n + pi(z) = pi(n) + pi(n) = pi(n) + dir(n) + perm(n + 1, p, pi, dir) + } + dir(n) = -dir(n) + } + } + + for (i <- 0 until n) { + dir(i) = -1 + p(i) = i + pi(i) = i + } + perm(0, p, pi, dir) + print(" (0 1)\n") + } + + perm(4) + +} diff --git a/Task/Permutations/Fortran/permutations-3.f b/Task/Permutations/Fortran/permutations-3.f index 9aca8ed593..7185cb2466 100644 --- a/Task/Permutations/Fortran/permutations-3.f +++ b/Task/Permutations/Fortran/permutations-3.f @@ -1,41 +1,361 @@ - program nptest - integer n,i,a - logical nextp - external nextp - parameter(n=4) - dimension a(n) - do i=1,n - a(i)=i - enddo - 10 print *,(a(i),i=1,n) - if(nextp(n,a)) go to 10 - end + program testing_permutation_algorithms + + implicit none + integer :: nmax + integer, dimension(:),allocatable :: ida + logical :: mtc + logical :: even + integer :: i + integer(8) :: ic + integer :: clock_rate, clock_max, t1, t2 + real(8) :: dt + integer :: pos_min, pos_max +! +! +! Beginning: +! + write(*,*) 'INPUT N:' + read *, nmax + write(*,*) 'N =', nmax + allocate ( ida(1:nmax) ) +! +! +! (1) Starting: +! + do i = 1, nmax + ida(i) = i + enddo +! + ic = 0 + call system_clock ( t1, clock_rate, clock_max ) +! + mtc = .false. +! + do + call subnexper ( nmax, ida, mtc, even ) +! +! 1) counting the number of permutatations +! + ic = ic + 1 +! +! 2) writing out the result: +! +! do i = 1, nmax +! write (100,"(i3,',')",advance = "no") ida(i) +! enddo +! write(100,*) +! +! repeat if not being finished yet, otherwise exit. +! + if (mtc) then + cycle + else + exit + endif +! + enddo +! + call system_clock ( t2, clock_rate, clock_max ) + dt = ( dble(t2) - dble(t1) )/ dble(clock_rate) +! +! Finishing (1) +! + write(*,*) "1) subnexper:" + write(*,*) 'Total permutations :', ic + write(*,*) 'Total time elapsed :', dt +! +! +! (2) Starting: +! + do i = 1, nmax + ida(i) = i + enddo +! + pos_min = 1 + pos_max = nmax +! + ic = 0 + call system_clock ( t1, clock_rate, clock_max ) +! + call generate ( pos_min ) +! + call system_clock ( t2, clock_rate, clock_max ) + dt = ( dble(t2) - dble(t1) )/ dble(clock_rate) +! +! Finishing (2) +! + write(*,*) "2) generate:" + write(*,*) 'Total permutations :', ic + write(*,*) 'Total time elapsed :', dt +! +! +! (3) Starting: +! + do i = 1, nmax + ida(i) = i + enddo +! + ic = 0 + call system_clock ( t1, clock_rate, clock_max ) +! + i = 1 + call perm ( i ) +! + call system_clock ( t2, clock_rate, clock_max ) + dt = ( dble(t2) - dble(t1) )/ dble(clock_rate) +! +! Finishing (3) +! + write(*,*) "3) perm:" + write(*,*) 'Total permutations :', ic + write(*,*) 'Total time elapsed :', dt +! +! +! (4) Starting: +! + do i = 1, nmax + ida(i) = i + enddo +! + ic = 0 + call system_clock ( t1, clock_rate, clock_max ) +! + do +! +! 1) counting the number of permutatations +! + ic = ic + 1 +! +! 2) writing out the result: +! +! do i = 1, nmax +! write (100,"(i3,',')",advance = "no") ida(i) +! enddo +! write(100,*) +! +! repeat if not being finished yet, otherwise exit. +! + if ( nextp(nmax,ida) ) then + cycle + else + exit + endif +! + enddo +! + call system_clock ( t2, clock_rate, clock_max ) + dt = ( dble(t2) - dble(t1) )/ dble(clock_rate) +! +! Finishing (4) +! + write(*,*) "4) nextp:" + write(*,*) 'Total permutations :', ic + write(*,*) 'Total time elapsed :', dt +! +! +! What's else? +! ... +! +!== + deallocate(ida) +! + stop +!== + contains +!== +! Modified version of SUBROUTINE NEXPER from the book of +! Albert Nijenhuis and Herbert S. Wilf, "Combinatorial +! Algorithms For Computers and Calculators", 2nd Ed, p.59. +! + subroutine subnexper ( n, a, mtc, even ) + implicit none + integer,intent(in) :: n + integer,dimension(n),intent(inout) :: a + logical,intent(inout) :: mtc, even +! +! local varialbes: +! + integer,save :: nm3 + integer :: ia, i, s, d, i1, l, j, m +! + if (mtc) goto 10 + + nm3 = n-3 + + do i = 1,n + a(i) = i + enddo + + mtc = .true. +5 even = .true. + + if ( n .eq. 1 ) goto 8 + +6 if ( a(n) .ne. 1 .or. a(1) .ne. 2+mod(n,2) ) return + + if ( n .le. 3 ) goto 8 + + do i = 1,nm3 + if( a(i+1) .ne. a(i)+1 ) return + enddo + +8 mtc = .false. - function nextp(n,a) - integer n,a,i,j,k,t - logical nextp - dimension a(n) - i=n-1 - 10 if(a(i).lt.a(i+1)) go to 20 - i=i-1 - if(i.eq.0) go to 20 - go to 10 - 20 j=i+1 - k=n - 30 t=a(j) - a(j)=a(k) - a(k)=t - j=j+1 - k=k-1 - if(j.lt.k) go to 30 - j=i - if(j.ne.0) go to 40 - nextp=.false. return - 40 j=j+1 - if(a(j).lt.a(i)) go to 40 - t=a(i) - a(i)=a(j) - a(j)=t - nextp=.true. - end + +10 if ( n .eq. 1 ) goto 27 + + if( .not. even ) goto 20 + + ia = a(1) + a(1) = a(2) + a(2) = ia + even = .false. + + goto 6 + +20 s = 0 + + do i1 = 2,n + ia = a(i1) + i = i1-1 + d = 0 + do j = 1,i + if ( a(j) .gt. ia ) d = d+1 + enddo + s = d+s + if ( d .ne. i*mod(s,2) ) goto 35 + enddo + +27 a(1) = 0 + + goto 8 + +35 m = mod(s+1,2)*(n+1) + + do j = 1,i + if(isign(1,a(j)-ia) .eq. isign(1,a(j)-m)) cycle + m = a(j) + l = j + enddo + + a(l) = ia + a(i1) = m + even = .true. + + return + end subroutine +!===== +! +! http://rosettacode.org/wiki/Permutations#Fortran +! + recursive subroutine generate (pos) + + implicit none + integer,intent(in) :: pos + integer :: val + + if (pos > pos_max) then +! +! 1) counting the number of permutatations +! + ic = ic + 1 +! +! 2) writing out the result: +! +! write (*,*) permutation +! + else + do val = 1, nmax + if (.not. any (ida( : pos-1) == val)) then + ida(pos) = val + call generate (pos + 1) + endif + enddo + endif + + end subroutine +!===== +! +! http://rosettacode.org/wiki/Permutations#Fortran +! + recursive subroutine perm (i) + implicit none + integer,intent(inout) :: i +! + integer :: j, t, ip1 +! + if (i == nmax) then +! +! 1) couting the number of permutatations +! + ic = ic + 1 +! +! 2) writing out the result: +! +! write (*,*) a +! + else + ip1 = i+1 + do j = i, nmax + t = ida(i) + ida(i) = ida(j) + ida(j) = t + call perm ( ip1 ) + t = ida(i) + ida(i) = ida(j) + ida(j) = t + enddo + endif + return + end subroutine +!===== +! +! http://rosettacode.org/wiki/Permutations#Fortran +! + function nextp ( n, a ) + logical :: nextp + integer,intent(in) :: n + integer,dimension(n),intent(inout) :: a +! +! local variables: +! + integer i,j,k,t +! + i = n-1 + 10 if ( a(i) .lt. a(i+1) ) goto 20 + i = i-1 + if ( i .eq. 0 ) goto 20 + goto 10 + 20 j = i+1 + k = n + 30 t = a(j) + a(j) = a(k) + a(k) = t + j = j+1 + k = k-1 + if ( j .lt. k ) goto 30 + j = i + if (j .ne. 0 ) goto 40 +! + nextp = .false. +! + return +! + 40 j = j+1 + if ( a(j) .lt. a(i) ) goto 40 + t = a(i) + a(i) = a(j) + a(j) = t +! + nextp = .true. +! + return + end function +!===== +! +! What's else ? +! ... + +!===== + end program diff --git a/Task/Permutations/Fortran/permutations-4.f b/Task/Permutations/Fortran/permutations-4.f new file mode 100644 index 0000000000..9aca8ed593 --- /dev/null +++ b/Task/Permutations/Fortran/permutations-4.f @@ -0,0 +1,41 @@ + program nptest + integer n,i,a + logical nextp + external nextp + parameter(n=4) + dimension a(n) + do i=1,n + a(i)=i + enddo + 10 print *,(a(i),i=1,n) + if(nextp(n,a)) go to 10 + end + + function nextp(n,a) + integer n,a,i,j,k,t + logical nextp + dimension a(n) + i=n-1 + 10 if(a(i).lt.a(i+1)) go to 20 + i=i-1 + if(i.eq.0) go to 20 + go to 10 + 20 j=i+1 + k=n + 30 t=a(j) + a(j)=a(k) + a(k)=t + j=j+1 + k=k-1 + if(j.lt.k) go to 30 + j=i + if(j.ne.0) go to 40 + nextp=.false. + return + 40 j=j+1 + if(a(j).lt.a(i)) go to 40 + t=a(i) + a(i)=a(j) + a(j)=t + nextp=.true. + end diff --git a/Task/Permutations/Julia/permutations.julia b/Task/Permutations/Julia/permutations.julia index de66009352..a35ec1a1fc 100644 --- a/Task/Permutations/Julia/permutations.julia +++ b/Task/Permutations/Julia/permutations.julia @@ -1,3 +1,5 @@ +using Combinatorics + term = "RCode" i = 0 pcnt = factorial(length(term)) diff --git a/Task/Permutations/Rust/permutations-1.rust b/Task/Permutations/Rust/permutations-1.rust index b7a7432add..fd14838331 100644 --- a/Task/Permutations/Rust/permutations-1.rust +++ b/Task/Permutations/Rust/permutations-1.rust @@ -1,34 +1,40 @@ -struct QuickPerm { +pub fn permutations(size: usize) -> Permutations { + Permutations { idxs: (0..size).collect(), swaps: vec![0; size], i: 0 } +} + +pub struct Permutations { idxs: Vec, - elems: Vec, - idx: usize, + swaps: Vec, + i: usize, } -impl QuickPerm { - fn new(elems: Vec) -> Self { - QuickPerm { idxs: (0..elems.len()+1).collect(), elems: elems, idx: 1 } - } -} +impl Iterator for Permutations { + type Item = Vec; -impl Iterator for QuickPerm { - type Item = Vec; fn next(&mut self) -> Option { - if self.idx == self.elems.len() { return None; } - - self.idxs[self.idx] -= 1; - let other = if self.idx % 2 == 1 { self.idxs[self.idx] } else { 0 }; - self.elems.swap(self.idx, other); - self.idx = 1; - while self.idxs[self.idx] == 0 { - self.idxs[self.idx] = self.idx; - self.idx += 1; + if self.i > 0 { + loop { + if self.i >= self.swaps.len() { return None; } + if self.swaps[self.i] < self.i { break; } + self.swaps[self.i] = 0; + self.i += 1; + } + self.idxs.swap(self.i, (self.i & 1) * self.swaps[self.i]); + self.swaps[self.i] += 1; } - Some(self.elems.clone()) + self.i = 1; + Some(self.idxs.clone()) } } fn main() { - for perm in QuickPerm::new(vec![1,2,3]) { - println!("{:?}", perm); - } + let perms = permutations(3).collect::>(); + assert_eq!(perms, vec![ + vec![0, 1, 2], + vec![1, 0, 2], + vec![2, 0, 1], + vec![0, 2, 1], + vec![1, 2, 0], + vec![2, 1, 0], + ]); } diff --git a/Task/Permutations/Rust/permutations-2.rust b/Task/Permutations/Rust/permutations-2.rust index ce7f859b9e..c542c01cd7 100644 --- a/Task/Permutations/Rust/permutations-2.rust +++ b/Task/Permutations/Rust/permutations-2.rust @@ -1,4 +1,5 @@ use std::collections::VecDeque; + fn permute(used: &mut Vec, unused: &mut VecDeque, action: &F) { if unused.is_empty() { action(used); @@ -11,15 +12,7 @@ fn permute(used: &mut Vec, unused: &mut VecDeque, action: } } -// Same as the vec! macro, but for VecDeques as well -macro_rules! vec_deque { - ($($item:expr),*) => {{ - let mut deque = ::std::collections::VecDeque::new(); - $(deque.push_back($item);)* - deque - }} -} - fn main() { - permute(&mut Vec::new(), &mut vec_deque![1,2,3], &|perm| println!("{:?}", perm)); + let mut queue = (1..4).collect::>(); + permute(&mut Vec::new(), &mut queue, &|perm| println!("{:?}", perm)); } diff --git a/Task/Permutations/Smalltalk/permutations.st b/Task/Permutations/Smalltalk/permutations-1.st similarity index 100% rename from Task/Permutations/Smalltalk/permutations.st rename to Task/Permutations/Smalltalk/permutations-1.st diff --git a/Task/Permutations/Smalltalk/permutations-2.st b/Task/Permutations/Smalltalk/permutations-2.st new file mode 100644 index 0000000000..a1a1ee753a --- /dev/null +++ b/Task/Permutations/Smalltalk/permutations-2.st @@ -0,0 +1,27 @@ +ArrayedCollection extend [ + + permuteAndDo: aBlock + ["Permute receiver in-place, and call aBlock. + Requires integer keys." + self permuteUpto: self size andDo: aBlock] + + permuteUpto: n andDo: aBlock + [n = 0 ifTrue: [^aBlock value]. + 1 to: n do: + [:i | + self swap: i with: n. + self permuteUpto: n-1 andDo: aBlock. + self swap: i with: n]] +] + +SequenceableCollection extend [ + + permutations + ["Answer a ReadStream of permuted shallow copies of receiver." + | c | + c := MappedCollection + collection: self + map: self keys asArray. + ^Generator on: + [:g | + c map permuteAndDo: [g yield: (c copyFrom: 1 to: c size)]]] diff --git a/Task/Permutations/Smalltalk/permutations-3.st b/Task/Permutations/Smalltalk/permutations-3.st new file mode 100644 index 0000000000..59a30c3b38 --- /dev/null +++ b/Task/Permutations/Smalltalk/permutations-3.st @@ -0,0 +1,2 @@ +st> 'Abc' permutations contents +('bcA' 'cbA' 'cAb' 'Acb' 'bAc' 'Abc' ) diff --git a/Task/Permutations/Stata/permutations-2.stata b/Task/Permutations/Stata/permutations-2.stata index 9aaec3a281..4c1a1239f7 100644 --- a/Task/Permutations/Stata/permutations-2.stata +++ b/Task/Permutations/Stata/permutations-2.stata @@ -22,23 +22,15 @@ void genperm() { p = 1 do { a[p++, .] = u - i = n for (i = n; i > 1; i--) { if (u[i-1] < u[i]) break } if (i > 1) { j = i k = n - while (j < k) { - s = u[j] - u[j] = u[k] - u[k] = s - j++ - k-- - } + while (j < k) u[(j++, k--)] = u[(k, j)] s = u[i-1] - j = i for (j = i; u[j] < s; j++) { } u[i-1] = u[j] diff --git a/Task/Pernicious-numbers/00DESCRIPTION b/Task/Pernicious-numbers/00DESCRIPTION index d473a4dfbd..2ea809bf46 100644 --- a/Task/Pernicious-numbers/00DESCRIPTION +++ b/Task/Pernicious-numbers/00DESCRIPTION @@ -1,4 +1,6 @@ -A   [[wp:Pernicious number|pernicious number]]   is a positive integer whose   [[population count]]   is a prime.   The population count is the number of ones in the binary representation of a non-negative integer. +A   [[wp:Pernicious number|pernicious number]]   is a positive integer whose   [[population count]]   is a prime. + +The population count is the number of   ''ones''   in the binary representation of a non-negative integer. ;Example @@ -6,7 +8,7 @@ A   [[wp:Pernicious number|pernicious number]]   is a positive integer ;Task -* display the first   '''25'''   pernicious numbers. +* display the first   '''25'''   pernicious numbers   (in decimal). * display all pernicious numbers between   '''888,888,877'''   and   '''888,888,888'''   (inclusive). * display each list of integers on one line   (which may or may not include a title). diff --git a/Task/Pernicious-numbers/AWK/pernicious-numbers.awk b/Task/Pernicious-numbers/AWK/pernicious-numbers.awk new file mode 100644 index 0000000000..64d852055d --- /dev/null +++ b/Task/Pernicious-numbers/AWK/pernicious-numbers.awk @@ -0,0 +1,54 @@ +# syntax: GAWK -f PERNICIOUS_NUMBERS.AWK +BEGIN { + pernicious(25) + pernicious(888888877,888888888) + exit(0) +} +function pernicious(x,y, count,n) { + if (y == "") { # print first X pernicious numbers + while (count < x) { + if (is_prime(pop_count(++n)) == 1) { + printf("%d ",n) + count++ + } + } + } + else { # print pernicious numbers in X-Y range + for (n=x; n<=y; n++) { + if (is_prime(pop_count(n)) == 1) { + printf("%d ",n) + } + } + } + print("") +} +function dec2bin(n, str) { + while (n) { + if (n%2 == 0) { + str = "0" str + } + else { + str = "1" str + } + n = int(n/2) + } + if (str == "") { + str = "0" + } + return(str) +} +function is_prime(x, i) { + if (x <= 1) { + return(0) + } + for (i=2; i<=int(sqrt(x)); i++) { + if (x % i == 0) { + return(0) + } + } + return(1) +} +function pop_count(n) { + n = dec2bin(n) + return gsub(/1/,"&",n) +} diff --git a/Task/Pernicious-numbers/Factor/pernicious-numbers.factor b/Task/Pernicious-numbers/Factor/pernicious-numbers.factor new file mode 100644 index 0000000000..30976c19e2 --- /dev/null +++ b/Task/Pernicious-numbers/Factor/pernicious-numbers.factor @@ -0,0 +1,6 @@ +USING: lists lists.lazy math.bits math.primes math.ranges ; + +: pernicious? ( n -- ? ) make-bits [ t = ] count prime? ; + +0 lfrom [ pernicious? ] lfilter 25 swap ltake list>array . ! print first 25 pernicious numbers +888,888,877 888,888,888 [a,b] [ pernicious? ] filter . ! print pernicious numbers in range diff --git a/Task/Pernicious-numbers/Haskell/pernicious-numbers.hs b/Task/Pernicious-numbers/Haskell/pernicious-numbers-1.hs similarity index 100% rename from Task/Pernicious-numbers/Haskell/pernicious-numbers.hs rename to Task/Pernicious-numbers/Haskell/pernicious-numbers-1.hs diff --git a/Task/Pernicious-numbers/Haskell/pernicious-numbers-2.hs b/Task/Pernicious-numbers/Haskell/pernicious-numbers-2.hs new file mode 100644 index 0000000000..ff49d714b5 --- /dev/null +++ b/Task/Pernicious-numbers/Haskell/pernicious-numbers-2.hs @@ -0,0 +1,26 @@ +import Data.List (unfoldr) +import Data.Tuple (swap) + +isPernicious :: Int -> Bool +isPernicious = isPrime . popCount + +popCount :: Int -> Int +popCount = + sum . unfoldr ((flip if_ Nothing . (0 ==)) <*> (Just . swap . flip quotRem 2)) + +isPrime :: Int -> Bool +isPrime = + (==) <$> (\n -> [1 .. n] >>= flip ((if_ . (0 ==) . mod n) <*> return) []) <*> + ((1 :) . return) + +if_ :: Bool -> a -> a -> a +if_ True x _ = x +if_ False _ y = y + +main :: IO () +main = + mapM_ + print + [ take 25 $ filter isPernicious [1 ..] + , filter isPernicious [888888877 .. 888888888] + ] diff --git a/Task/Pernicious-numbers/Julia/pernicious-numbers.julia b/Task/Pernicious-numbers/Julia/pernicious-numbers.julia index eea1d0f55e..cf206efec1 100644 --- a/Task/Pernicious-numbers/Julia/pernicious-numbers.julia +++ b/Task/Pernicious-numbers/Julia/pernicious-numbers.julia @@ -1,19 +1,16 @@ -ispernicious(n::Int) = isprime(count_ones(n)) +using Primes -pcnt = 0 -i = 0 -print(" ") -while pcnt < 25 - i += 1 - ispernicious(i) || continue - pcnt += 1 - print(i, " ") +ispernicious(n::Integer) = isprime(count_ones(n)) +nextpernicious(n::Integer) = begin n += 1; while !ispernicious(n) n += 1 end; return n end +function perniciouses(n::Int) + rst = Vector{Int}(n) + rst[1] = 3 + for i in 2:n + rst[i] = nextpernicious(rst[i-1]) + end + return rst end -println() +perniciouses(a::Integer, b::Integer) = filter(ispernicious, a:b) -print(" ") -for i in 888888877:888888888 - ispernicious(i) || continue - print(i, " ") -end -println() +println("First 25 pernicious numbers: ", join(perniciouses(25), ", ")) +println("Perniciouses in [888888877, 888888888]: ", join(perniciouses(888888877, 888888888), ", ")) diff --git a/Task/Pernicious-numbers/Modula-2/pernicious-numbers.mod2 b/Task/Pernicious-numbers/Modula-2/pernicious-numbers.mod2 new file mode 100644 index 0000000000..123802639a --- /dev/null +++ b/Task/Pernicious-numbers/Modula-2/pernicious-numbers.mod2 @@ -0,0 +1,50 @@ +MODULE Pernicious; +FROM FormatString IMPORT FormatString; +FROM Terminal IMPORT WriteString,WriteLn,ReadChar; + +PROCEDURE IsPrime(x : LONGINT) : BOOLEAN; +VAR i : LONGINT; +BEGIN + IF x<2 THEN RETURN FALSE END; + FOR i:=2 TO x-1 DO + IF x MOD i = 0 THEN RETURN FALSE END + END; + RETURN TRUE +END IsPrime; + +PROCEDURE BitCount(x : LONGINT) : LONGINT; +VAR count : LONGINT; +BEGIN + count := 0; + WHILE x>0 DO + x := x BAND (x-1); + INC(count) + END; + RETURN count +END BitCount; + +VAR + buf : ARRAY[0..63] OF CHAR; + i,n : LONGINT; +BEGIN + i := 1; + n := 0; + WHILE n<25 DO + IF IsPrime(BitCount(i)) THEN + FormatString("%l ", buf, i); + WriteString(buf); + INC(n) + END; + INC(i) + END; + WriteLn; + + FOR i:=888888877 TO 888888888 DO + IF IsPrime(BitCount(i)) THEN + FormatString("%l ", buf, i); + WriteString(buf) + END; + END; + + ReadChar +END Pernicious. diff --git a/Task/Pernicious-numbers/Ring/pernicious-numbers.ring b/Task/Pernicious-numbers/Ring/pernicious-numbers.ring new file mode 100644 index 0000000000..79fbc1293e --- /dev/null +++ b/Task/Pernicious-numbers/Ring/pernicious-numbers.ring @@ -0,0 +1,42 @@ +# Project : Pernicious numbers +# Date : 2017/10/01 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +see "The first 25 pernicious numbers:" + nl +nr = 0 +for n=1 to 50 + sum = 0 + str = decimaltobase(n, 2) + for m=1 to len(str) + if str[m] = "1" + sum = sum + 1 + ok + next + if isprime(sum) + nr = nr + 1 + see "" + n + " " + ok + if nr = 25 + exit + ok +next + +func decimaltobase(nr, base) + binary = 0 + i = 1 + while(nr != 0) + remainder = nr % base + nr = floor(nr/base) + binary= binary + (remainder*i) + i = i*10 + end + return string(binary) + +func isprime num + if (num <= 1) return 0 ok + if (num % 2 = 0 and num != 2) return 0 ok + for i = 3 to floor(num / 2) -1 step 2 + if (num % i = 0) return 0 ok + next + return 1 diff --git a/Task/Phrase-reversals/Elena/phrase-reversals.elena b/Task/Phrase-reversals/Elena/phrase-reversals.elena new file mode 100644 index 0000000000..344b3b179f --- /dev/null +++ b/Task/Phrase-reversals/Elena/phrase-reversals.elena @@ -0,0 +1,17 @@ +import extensions. +import system'routines. + +program = +[ + var reverse := (:s)(s toArray; sequenceReverse; summarize(String new)). + + var phrase := "rosetta code phrase reversal". + console printLine(phrase). + + //Reverse the string + console printLine(reverse(phrase)). + //Reverse each individual word in the string, maintaining original string order. + console printLine(phrase split by:" "; selectBy(:s)(reverse(s) add(" ")); summarize(String new)). + //Reverse the order of each word of the phrase, maintaining the order of characters in each word. + console printLine(reverse(phrase split by:" "; selectBy(:s)(s + " "))). +]. diff --git a/Task/Phrase-reversals/Factor/phrase-reversals.factor b/Task/Phrase-reversals/Factor/phrase-reversals.factor new file mode 100644 index 0000000000..4aa50f42bb --- /dev/null +++ b/Task/Phrase-reversals/Factor/phrase-reversals.factor @@ -0,0 +1,9 @@ +USE: splitting + +: splitp ( str -- seq ) " " split ; +: printp ( seq -- ) " " join print ; +: reverse-string ( str -- ) reverse print ; +: reverse-words ( str -- ) splitp [ reverse ] map printp ; +: reverse-phrase ( str -- ) splitp reverse printp ; + +"rosetta code phrase reversal" [ reverse-string ] [ reverse-words ] [ reverse-phrase ] tri diff --git a/Task/Phrase-reversals/Perl-6/phrase-reversals.pl6 b/Task/Phrase-reversals/Perl-6/phrase-reversals.pl6 index 8d02db3d7c..36bcf3c12c 100644 --- a/Task/Phrase-reversals/Perl-6/phrase-reversals.pl6 +++ b/Task/Phrase-reversals/Perl-6/phrase-reversals.pl6 @@ -1,6 +1,6 @@ my $s = 'rosetta code phrase reversal'; -say 'Input : ', $s; -say 'String reversed : ', $s.flip; -say 'Each word reversed : ', $s.words».flip; -say 'Word-order reversed : ', $s.words.reverse; +put 'Input : ', $s; +put 'String reversed : ', $s.flip; +put 'Each word reversed : ', $s.words».flip; +put 'Word-order reversed : ', $s.words.reverse; diff --git a/Task/Phrase-reversals/VBA/phrase-reversals.vba b/Task/Phrase-reversals/VBA/phrase-reversals.vba new file mode 100644 index 0000000000..8299c9a599 --- /dev/null +++ b/Task/Phrase-reversals/VBA/phrase-reversals.vba @@ -0,0 +1,32 @@ +Option Explicit + +Sub Main_Phrase_Reversals() +Const PHRASE As String = "rosetta code phrase reversal" + Debug.Print "Original String : " & PHRASE + Debug.Print "Reverse String : " & Reverse_String(PHRASE) + Debug.Print "Reverse each individual word : " & Reverse_each_individual_word(PHRASE) + Debug.Print "Reverse order of each word : " & Reverse_the_order_of_each_word(PHRASE) +End Sub + +Function Reverse_String(strPhrase As String) As String + Reverse_String = StrReverse(strPhrase) +End Function + +Function Reverse_each_individual_word(strPhrase As String) As String +Dim Words, i&, strTemp$ + Words = Split(strPhrase, " ") + For i = 0 To UBound(Words) + Words(i) = Reverse_String(CStr(Words(i))) + Next i + Reverse_each_individual_word = Join(Words, " ") +End Function + +Function Reverse_the_order_of_each_word(strPhrase As String) As String +Dim Words, i&, strTemp$ + + Words = Split(strPhrase, " ") + For i = UBound(Words) To 0 Step -1 + strTemp = strTemp & " " & Words(i) + Next i + Reverse_the_order_of_each_word = Trim(strTemp) +End Function diff --git a/Task/Pi/Fortran/pi-1.f b/Task/Pi/Fortran/pi-1.f index c6c54d9fd0..ade41af3eb 100644 --- a/Task/Pi/Fortran/pi-1.f +++ b/Task/Pi/Fortran/pi-1.f @@ -1,15 +1,20 @@ -Coded by Stanley Rabinowitz, 12 Vine Brook Road, Westford MA, 01886-4212. - INTEGER VECT(3350),BUFFER(201) - DATA VECT/3350*2/,MORE/0/ - DO 2 N = 1,201 - KARRAY = 0 - DO 3 L = 3350,1,-1 - NUM = 100000*VECT(L) + KARRAY*L - KARRAY = NUM/(2*L - 1) - 3 VECT(L) = NUM - KARRAY*(2*L - 1) - K = KARRAY/100000 - BUFFER(N) = MORE + K - 2 MORE = KARRAY - K*100000 - WRITE (*,100) BUFFER - 100 FORMAT (I2,"."/(1X,10I5.5)) - END +program pi + implicit none + integer,dimension(3350) :: vect + integer,dimension(201) :: buffer + integer :: more,karray,num,k,l,n + more = 0 + vect = 2 + do n = 1,201 + karray = 0 + do l = 3350,1,-1 + num = 100000*vect(l) + karray*l + karray = num/(2*l - 1) + vect(l) = num - karray*(2*l - 1) + end do + k = karray/100000 + buffer(n) = more + k + more = karray - k*100000 + end do + write (*,'(i2,"."/(1x,10i5.5))') buffer +end program pi diff --git a/Task/Pi/JavaScript/pi-1.js b/Task/Pi/JavaScript/pi-1.js new file mode 100644 index 0000000000..babf88f68a --- /dev/null +++ b/Task/Pi/JavaScript/pi-1.js @@ -0,0 +1,25 @@ +var BigInteger = require('jsbn').BigInteger; +var bi = function(n, b) { return new BigInteger(n.toString(), b ? b : 10); }; +function calcPi() { + var q=bi(1), r=bi(0), t=bi(1), k=bi(1), n=bi(3), l=bi(3); + var one=bi(1), two=bi(2), three=bi(3), four=bi(4), seven=bi(7), ten=bi(10); + while (true) { + if (q.multiply(four).add(r).subtract(t).compareTo(n.multiply(t)) < 0) { + process.stdout.write(n.toString()); + nr = (r.subtract(n.multiply(t))).multiply(ten); + n = (q.multiply(three).add(r)).multiply(ten).divide(t).subtract(n.multiply(ten)); + q = q.multiply(ten); + r = nr; + } else { + nr = q.shiftLeft(1).add(r).multiply(l); + nn = q.multiply(k).multiply(seven).add(two).add(r.multiply(l)).divide(t.multiply(l)); + q = q.multiply(k); + t = t.multiply(l); + l = l.add(two); + k = k.add(one); + n = nn; + r = nr; + } + } +} +calcPi(); diff --git a/Task/Pi/JavaScript/pi-2.js b/Task/Pi/JavaScript/pi-2.js new file mode 100644 index 0000000000..7bd8b3fc92 --- /dev/null +++ b/Task/Pi/JavaScript/pi-2.js @@ -0,0 +1,44 @@ + +... + + diff --git a/Task/Pi/JavaScript/pi.js b/Task/Pi/JavaScript/pi-3.js similarity index 100% rename from Task/Pi/JavaScript/pi.js rename to Task/Pi/JavaScript/pi-3.js diff --git a/Task/Pick-random-element/BASIC/pick-random-element.basic b/Task/Pick-random-element/BASIC/pick-random-element-1.basic similarity index 100% rename from Task/Pick-random-element/BASIC/pick-random-element.basic rename to Task/Pick-random-element/BASIC/pick-random-element-1.basic diff --git a/Task/Pick-random-element/BASIC/pick-random-element-2.basic b/Task/Pick-random-element/BASIC/pick-random-element-2.basic new file mode 100644 index 0000000000..26fc63e422 --- /dev/null +++ b/Task/Pick-random-element/BASIC/pick-random-element-2.basic @@ -0,0 +1,8 @@ +10 DIM A$(9) +20 FOR I=0 TO 9 : READ A$(I) : NEXT +30 X = RND(-TI) : REM 'PLANT A RANDOM SEED' +40 X = INT(RND(1)*10) +50 PRINT A$(X) +60 END +100 DATA ALPHA, BRAVO, CHARLIE, DELTA, ECHO +110 DATA FOXTROT, GOLF, HOTEL, INDIA, JULIETT diff --git a/Task/Pick-random-element/Haskell/pick-random-element-1.hs b/Task/Pick-random-element/Haskell/pick-random-element-1.hs index 8f5cd09c30..006f728127 100644 --- a/Task/Pick-random-element/Haskell/pick-random-element-1.hs +++ b/Task/Pick-random-element/Haskell/pick-random-element-1.hs @@ -3,4 +3,4 @@ import System.Random (randomRIO) pick :: [a] -> IO a pick xs = fmap (xs !!) $ randomRIO (0, length xs - 1) -x <- pick [1 2 3] +x <- pick [1, 2, 3] diff --git a/Task/Pick-random-element/Haskell/pick-random-element-2.hs b/Task/Pick-random-element/Haskell/pick-random-element-2.hs index 0a663f8928..4d11ee83b3 100644 --- a/Task/Pick-random-element/Haskell/pick-random-element-2.hs +++ b/Task/Pick-random-element/Haskell/pick-random-element-2.hs @@ -1,5 +1,2 @@ import Data.Random -import Data.Random.Source.DevRandom -import Data.Random.Extras - -x <- runRVar (choice [1 2 3]) DevRandom +sample $ randomElement [1, 2, 3] diff --git a/Task/Pick-random-element/Haskell/pick-random-element-3.hs b/Task/Pick-random-element/Haskell/pick-random-element-3.hs index d2fe54c046..d8be702bd4 100644 --- a/Task/Pick-random-element/Haskell/pick-random-element-3.hs +++ b/Task/Pick-random-element/Haskell/pick-random-element-3.hs @@ -1,3 +1,3 @@ -import Test.QuickCheck (generate, elements) - -x <- (generate . elements) [1, 2, 3] +do + x <- sample $ randomElement [1, 2, 3] + print x diff --git a/Task/Pick-random-element/Kotlin/pick-random-element.kotlin b/Task/Pick-random-element/Kotlin/pick-random-element.kotlin index 2666869a4c..6f6827060a 100644 --- a/Task/Pick-random-element/Kotlin/pick-random-element.kotlin +++ b/Task/Pick-random-element/Kotlin/pick-random-element.kotlin @@ -1,13 +1,30 @@ -// version 1.0.6 +// version 1.2.10 + +import java.util.Random + +/** + * Extension function on any list that will return a random element from index 0 + * to the last index + */ +fun List.getRandomElement() = this[Random().nextInt(this.size)] + +/** + * Extension function on any list that will return a list of unique random picks + * from the list. If the specified number of elements you want is larger than the + * number of elements in the list it returns null + */ +fun List.getRandomElements(numberOfElements: Int): List? { + if (numberOfElements > this.size) { + return null + } + return this.shuffled().take(numberOfElements) +} fun main(args: Array) { val list = listOf(1, 16, 3, 7, 17, 24, 34, 23, 11, 2) - println("The list consists of the following numbers:") - println(list) - val chosen = mutableSetOf() - println("\nFive elements chosen at random without duplication are:") - while (chosen.size < 5) { - val r = list[(Math.random() * list.size).toInt()] - if (chosen.add(r)) println(r) - } + println("The list consists of the following numbers:\n${list}") + + // notice we can call our extension functions as if they were regular member functions of List + println("\nA randomly selected element from the list is ${list.getRandomElement()}") + println("\nA random sequence of 5 elements from the list is ${list.getRandomElements(5)}") } diff --git a/Task/Pick-random-element/Nim/pick-random-element.nim b/Task/Pick-random-element/Nim/pick-random-element.nim index 1f0418618f..c32b669104 100644 --- a/Task/Pick-random-element/Nim/pick-random-element.nim +++ b/Task/Pick-random-element/Nim/pick-random-element.nim @@ -1,14 +1,4 @@ -import math randomize() -proc random[T](a: openarray[T]): T = - a[random(a.low..a.len)] - let ls = @["foo", "bar", "baz"] -echo ls.random() - -var xs: array[10..14, string] -for i in 10..14: - xs[i] = "foo: " & $i - -echo xs.random() +echo ls.rand() diff --git a/Task/Pick-random-element/Perl-6/pick-random-element-2.pl6 b/Task/Pick-random-element/Perl-6/pick-random-element-2.pl6 index 5654731e2e..a620bc1c55 100644 --- a/Task/Pick-random-element/Perl-6/pick-random-element-2.pl6 +++ b/Task/Pick-random-element/Perl-6/pick-random-element-2.pl6 @@ -1,3 +1,3 @@ -(1..6).roll; # return 1 random value in the range 1 through 6 -(1..6).roll(3); # return a list of 3 random values in the range 1 through 6 -(1..6).roll(*); # return a lazy infinite list of random values in the range 1 through 6 +say (1..6).roll; # return 1 random value in the range 1 through 6 +say (1..6).roll(3); # return a list of 3 random values in the range 1 through 6 +say (1..6).roll(*)[^100]; # return first 100 values from a lazy infinite list of random values in the range 1 through 6 diff --git a/Task/Pick-random-element/Perl-6/pick-random-element-3.pl6 b/Task/Pick-random-element/Perl-6/pick-random-element-3.pl6 index 99da7334f3..d4aa49ca95 100644 --- a/Task/Pick-random-element/Perl-6/pick-random-element-3.pl6 +++ b/Task/Pick-random-element/Perl-6/pick-random-element-3.pl6 @@ -1,5 +1,5 @@ # define the deck my @deck = <2 3 4 5 6 7 8 9 J Q K A> X~ <♠ ♣ ♥ ♦>; -@deck.pick; # Pick a card -@deck.pick(5); # Draw 5 -@deck.pick(*); # Get a shuffled deck +say @deck.pick; # Pick a card +say @deck.pick(5); # Draw 5 +say @deck.pick(*); # Get a shuffled deck diff --git a/Task/Pick-random-element/Red/pick-random-element.red b/Task/Pick-random-element/Red/pick-random-element.red new file mode 100644 index 0000000000..57560ddbf9 --- /dev/null +++ b/Task/Pick-random-element/Red/pick-random-element.red @@ -0,0 +1 @@ +>> random/only collect [repeat i 10 [keep i]] diff --git a/Task/Pick-random-element/Ring/pick-random-element.ring b/Task/Pick-random-element/Ring/pick-random-element.ring index 7d039c384d..33258c12f0 100644 --- a/Task/Pick-random-element/Ring/pick-random-element.ring +++ b/Task/Pick-random-element/Ring/pick-random-element.ring @@ -1,6 +1,6 @@ aList = "abcdefghij" for i = 1 to 10 - letter = random(10) + letter = random(9) + 1 if letter > 0 see aList[letter] + nl ok diff --git a/Task/Pick-random-element/Ruby/pick-random-element.rb b/Task/Pick-random-element/Ruby/pick-random-element.rb index ccab5f1694..6574e4ccfb 100644 --- a/Task/Pick-random-element/Ruby/pick-random-element.rb +++ b/Task/Pick-random-element/Ruby/pick-random-element.rb @@ -1,4 +1,2 @@ -irb(main):001:0> %w(north east south west).sample -=> "west" -irb(main):002:0> (1..100).to_a.sample(2) -=> [17, 79] +%w(north east south west).sample # => "west" +(1..100).to_a.sample(2) # => [17, 79] diff --git a/Task/Pick-random-element/Rust/pick-random-element.rust b/Task/Pick-random-element/Rust/pick-random-element.rust index 1e958ef156..f9a01483bc 100644 --- a/Task/Pick-random-element/Rust/pick-random-element.rust +++ b/Task/Pick-random-element/Rust/pick-random-element.rust @@ -1,6 +1,10 @@ extern crate rand; + use rand::Rng; + fn main() { let array = [5,1,2,5,6,7,8,1,2,4,5]; - println!("{}", rand::thread_rng().choose(&array).unwrap()); + let mut rng = rand::thread_rng(); + + println!("{}", rng.choose(&array).unwrap()); } diff --git a/Task/Pick-random-element/VBA/pick-random-element.vba b/Task/Pick-random-element/VBA/pick-random-element.vba new file mode 100644 index 0000000000..fcc15c54dd --- /dev/null +++ b/Task/Pick-random-element/VBA/pick-random-element.vba @@ -0,0 +1,10 @@ +Option Explicit + +Sub Main_Pick_Random_Element() + Debug.Print Pick_Random_Element(Array(1, 2, 3, 4, 5, #11/24/2017#, "azerty")) +End Sub + +Function Pick_Random_Element(myArray) + Randomize Timer + Pick_Random_Element = myArray(Int((Rnd * (UBound(myArray) - LBound(myArray) + 1) + LBound(myArray)))) +End Function diff --git a/Task/Pig-the-dice-game/Ring/pig-the-dice-game.ring b/Task/Pig-the-dice-game/Ring/pig-the-dice-game.ring new file mode 100644 index 0000000000..4cfc2af858 --- /dev/null +++ b/Task/Pig-the-dice-game/Ring/pig-the-dice-game.ring @@ -0,0 +1,31 @@ +# Project : Pig the dice game +# Date : 2017/10/31 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +numPlayers = 2 +maxScore = 100 +safescore = list(numPlayers) + +while true + rolling = "" + for player = 1 to numPlayers + score = 0 + while safeScore[player] < maxScore + see "Player " + player + " Rolling? (Y) " + give rolling + if upper(rolling) = "Y" + rolled = random(5) + 1 + see "Player " + player + " rolled " + rolled + nl + if rolled = 1 + see "Bust! you lose player " + player + " but still keep your previous score of " + safeScore[player] + nl + exit + ok + score = score + rolled + else + safeScore[player] = safeScore[player] + score + ok + end + next +end +see "Player " + player + " wins with a score of " + safeScore[player] diff --git a/Task/Pig-the-dice-game/VBA/pig-the-dice-game.vba b/Task/Pig-the-dice-game/VBA/pig-the-dice-game.vba new file mode 100644 index 0000000000..1233fd7198 --- /dev/null +++ b/Task/Pig-the-dice-game/VBA/pig-the-dice-game.vba @@ -0,0 +1,50 @@ +Option Explicit + +Sub Main_Pig() +Dim Scs() As Byte, Ask As Integer, Np As Boolean, Go As Boolean +Dim Cp As Byte, Rd As Byte, NbP As Byte, ScBT As Byte + 'You can adapt these Const, but don't touch the "¤¤¤¤" + Const INPTXT As String = "Enter number of players : " + Const INPTITL As String = "Numeric only" + Const ROL As String = "Player ¤¤¤¤ rolls the die." + Const MSG As String = "Do you want to ""hold"" : " + Const TITL As String = "Total if you keep : " + Const RES As String = "The die give you : ¤¤¤¤ points." + Const ONE As String = "The die give you : 1 point. Sorry!" & vbCrLf & "Next player." + Const WIN As String = "Player ¤¤¤¤ win the Pig Dice Game!" + Const STW As Byte = 100 + + Randomize Timer + NbP = Application.InputBox(INPTXT, INPTITL, 2, Type:=1) + ReDim Scs(1 To NbP) + Cp = 1 + Do + ScBT = 0 + Do + MsgBox Replace(ROL, "¤¤¤¤", Cp) + Rd = Int((Rnd * 6) + 1) + If Rd > 1 Then + MsgBox Replace(RES, "¤¤¤¤", Rd) + ScBT = ScBT + Rd + If Scs(Cp) + ScBT >= STW Then + Go = True + Exit Do + End If + Ask = MsgBox(MSG & ScBT, vbYesNo, TITL & Scs(Cp) + ScBT) + If Ask = vbYes Then + Scs(Cp) = Scs(Cp) + ScBT + Np = True + End If + Else + MsgBox ONE + Np = True + End If + Loop Until Np + If Not Go Then + Np = False + Cp = Cp + 1 + If Cp > NbP Then Cp = 1 + End If + Loop Until Go + MsgBox Replace(WIN, "¤¤¤¤", Cp) +End Sub diff --git a/Task/Pinstripe-Display/Julia/pinstripe-display.julia b/Task/Pinstripe-Display/Julia/pinstripe-display.julia new file mode 100644 index 0000000000..2e03810ce3 --- /dev/null +++ b/Task/Pinstripe-Display/Julia/pinstripe-display.julia @@ -0,0 +1,20 @@ +using Luxor + +function drawbars(w, h, sections, dk, lt) + Drawing(w,h) + background("white") + width = 1 + height = h/sections + for y in 0:height:h-1 + setline(width) + for x in 0:w/width + sethue(x % 2 == 0 ? dk: lt) + line(Point(x*width,y), Point(x*width,y+height), :stroke) + end + width += 1 + end +end + +drawbars(1920, 1080, 4, "black", "white") +finish() +preview() diff --git a/Task/Pinstripe-Display/Ring/pinstripe-display.ring b/Task/Pinstripe-Display/Ring/pinstripe-display.ring new file mode 100644 index 0000000000..0349ea65bd --- /dev/null +++ b/Task/Pinstripe-Display/Ring/pinstripe-display.ring @@ -0,0 +1,64 @@ +# Project : Pinstripe/Display +# Date : 2018/01/13 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +load "guilib.ring" + +paint = null + +new qapp + { + win1 = new qwidget() { + setwindowtitle("Pinstripe/Display") + setgeometry(100,100,500,600) + label1 = new qlabel(win1) { + setgeometry(10,10,400,400) + settext("") + } + new qpushbutton(win1) { + setgeometry(150,500,100,30) + settext("draw") + setclickevent("draw()") + } + show() + } + exec() + } + +func draw + p1 = new qpicture() + color = new qcolor() { + setrgb(0,0,255,255) + } + pen = new qpen() { + setcolor(color) + setwidth(1) + } + paint = new qpainter() { + begin(p1) + setpen(pen) + + xscreen = 100 + yscreen = 100 + color = new qcolor() + color.setrgb(0,0,0,255) + mybrush = new qbrush() {setstyle(1) setcolor(color)} + setbrush(mybrush) + for x = 0 to xscreen*4-4 step 4 + drawrect(x,yscreen*3/2,2,yscreen/2) + next + for x = 0 to xscreen*4-8 step 8 + drawrect(x,yscreen*2/2,4,yscreen/2) + next + for x = 0 to xscreen*4-12 step 12 + drawrect(x,yscreen*1/2,6,yscreen/2) + next + for x = 0 to xscreen*4-16 step 16 + drawrect(x,yscreen*0/2,8,yscreen/2) + next + + endpaint() + } + label1 { setpicture(p1) show() } + return diff --git a/Task/Pinstripe-Display/Sinclair-ZX81-BASIC/pinstripe-display.sinclair b/Task/Pinstripe-Display/Sinclair-ZX81-BASIC/pinstripe-display.sinclair new file mode 100644 index 0000000000..b2f124c825 --- /dev/null +++ b/Task/Pinstripe-Display/Sinclair-ZX81-BASIC/pinstripe-display.sinclair @@ -0,0 +1,9 @@ +10 FOR W=1 TO 4 +20 FOR I=0 TO 63 STEP 2*W +30 FOR J=1 TO W +40 FOR K=43-11*(W-1) TO 33-11*(W-1) STEP -1 +50 PLOT I+J,K +60 NEXT K +70 NEXT J +80 NEXT I +90 NEXT W diff --git a/Task/Playing-cards/Factor/playing-cards.factor b/Task/Playing-cards/Factor/playing-cards.factor new file mode 100644 index 0000000000..8e23848f19 --- /dev/null +++ b/Task/Playing-cards/Factor/playing-cards.factor @@ -0,0 +1,19 @@ +USING: formatting grouping io kernel math qw random sequences +vectors ; +IN: rosetta-code.playing-cards + +CONSTANT: pips qw{ A 2 3 4 5 6 7 8 9 10 J Q K } +CONSTANT: suits qw{ ♥ ♣ ♦ ♠ } + +: ( -- vec ) 52 iota >vector ; + +: card>str ( n -- str ) + 13 /mod [ suits nth ] [ pips nth ] bi* prepend ; + +: print-deck ( seq -- ) + 13 group [ [ card>str "%-4s" printf ] each nl ] each ; + + ! make new deck +randomize ! shuffle the deck +dup pop drop ! deal from the deck (and discard) +print-deck ! print the deck diff --git a/Task/Playing-cards/Smalltalk/playing-cards.st b/Task/Playing-cards/Smalltalk/playing-cards-1.st similarity index 100% rename from Task/Playing-cards/Smalltalk/playing-cards.st rename to Task/Playing-cards/Smalltalk/playing-cards-1.st diff --git a/Task/Playing-cards/Smalltalk/playing-cards-2.st b/Task/Playing-cards/Smalltalk/playing-cards-2.st new file mode 100644 index 0000000000..ebfb14e488 --- /dev/null +++ b/Task/Playing-cards/Smalltalk/playing-cards-2.st @@ -0,0 +1,37 @@ +Object subclass: Deck [ + + | cards | + + Deck class >> of: aCardClass + [^self new + initializeWith: aCardClass; + yourself] + + initializeWith: aCardClass + [cards := OrderedCollection from: aCardClass standardSet] + + displayOn: aStream + [cards + do: [:each | each displayOn: aStream] + separatedBy: [aStream space]] + + shuffle + [1 to: cards size - 1 do: + [:a || b | + b := Random between: a and: cards size. + cards swap: a with: b]] + + deal + [^cards removeLast] +] + +Object subclass: Card [ + + Card class >> standardSet + [^#( + '2d' '3d' '4d' '5d' '6d' '7d' '8d' '9d' 'Td' 'Jd' 'Qd' 'Kd' 'Ad' + '2s' '3s' '4s' '5s' '6s' '7s' '8s' '9s' 'Ts' 'Js' 'Qs' 'Ks' 'As' + '2h' '3h' '4h' '5h' '6h' '7h' '8h' '9h' 'Th' 'Jh' 'Qh' 'Kh' 'Ah' + '2c' '3c' '4c' '5c' '6c' '7c' '8c' '9c' 'Tc' 'Jc' 'Qc' 'Kc' 'Ac' + ) deepCopy] +] diff --git a/Task/Playing-cards/Smalltalk/playing-cards-3.st b/Task/Playing-cards/Smalltalk/playing-cards-3.st new file mode 100644 index 0000000000..10c95b1e3a --- /dev/null +++ b/Task/Playing-cards/Smalltalk/playing-cards-3.st @@ -0,0 +1,14 @@ +st> myDeck := Deck of: Card +a Deck +st> myDeck displayNl +2d 3d 4d 5d 6d 7d 8d 9d Td Jd Qd Kd Ad 2s 3s 4s 5s 6s 7s 8s 9s Ts Js Qs Ks As 2h 3h 4h 5h 6h 7h 8h 9h Th Jh Qh Kh Ah 2c 3c 4c 5c 6c 7c 8c 9c Tc Jc Qc Kc Ac +st> myDeck shuffle +a Deck +st> myDeck displayNl +6c 7d Ac 4c 9s 2s Tc 9c Jh 3h Kh 7h 3s 5s 3d Kd Jc Qs As Qd 3c Kc Qh 2d 9h 4h 8c 7s Ah 9d Js 6h 8s 8h 5c 2c 4s 8d 5d Ts 4d Qc Td 7c 2h 5h 6s 6d Th Ks Jd Ad +st> myHand := OrderedCollection new +OrderedCollection () +st> 5 timesRepeat: [myHand add: myDeck deal] +5 +st> myHand +OrderedCollection ('Ad' 'Jd' 'Ks' 'Th' '6d' ) diff --git a/Task/Plot-coordinate-pairs/Julia/plot-coordinate-pairs.julia b/Task/Plot-coordinate-pairs/Julia/plot-coordinate-pairs.julia index 13d836ffa8..34860287e4 100644 --- a/Task/Plot-coordinate-pairs/Julia/plot-coordinate-pairs.julia +++ b/Task/Plot-coordinate-pairs/Julia/plot-coordinate-pairs.julia @@ -1,6 +1,8 @@ -using PyPlot +using Plots +plotlyjs() x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0] -plot(x,y, "bo") -savefig("qsort-range-10-9.png") + +p = scatter(x, y) +savefig(p, "/tmp/testplot.png") diff --git a/Task/Plot-coordinate-pairs/Kotlin/plot-coordinate-pairs.kotlin b/Task/Plot-coordinate-pairs/Kotlin/plot-coordinate-pairs.kotlin new file mode 100644 index 0000000000..9627b8efe2 --- /dev/null +++ b/Task/Plot-coordinate-pairs/Kotlin/plot-coordinate-pairs.kotlin @@ -0,0 +1,39 @@ +// Version 1.2.31 + +import org.jfree.chart.ChartFactory +import org.jfree.chart.ChartPanel +import org.jfree.data.xy.XYSeries +import org.jfree.data.xy.XYSeriesCollection +import org.jfree.chart.plot.PlotOrientation +import javax.swing.JFrame +import javax.swing.SwingUtilities +import java.awt.BorderLayout + +fun main(args: Array) { + val x = intArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) + val y = doubleArrayOf( + 2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0 + ) + val series = XYSeries("plots") + (0 until x.size).forEach { series.add(x[it], y[it]) } + val labels = arrayOf("Plot Demo", "X", "Y") + val data = XYSeriesCollection(series) + val options = booleanArrayOf(false, true, false) + val orient = PlotOrientation.VERTICAL + val chart = ChartFactory.createXYLineChart( + labels[0], labels[1], labels[2], data, orient, options[0], options[1], options[2] + ) + val chartPanel = ChartPanel(chart) + SwingUtilities.invokeLater { + val f = JFrame() + with(f) { + defaultCloseOperation = JFrame.EXIT_ON_CLOSE + add(chartPanel, BorderLayout.CENTER) + title = "Plot coordinate pairs" + isResizable = false + pack() + setLocationRelativeTo(null) + isVisible = true + } + } +} diff --git a/Task/Plot-coordinate-pairs/Perl-6/plot-coordinate-pairs.pl6 b/Task/Plot-coordinate-pairs/Perl-6/plot-coordinate-pairs.pl6 index 0e52516f4b..166bc33f62 100644 --- a/Task/Plot-coordinate-pairs/Perl-6/plot-coordinate-pairs.pl6 +++ b/Task/Plot-coordinate-pairs/Perl-6/plot-coordinate-pairs.pl6 @@ -1,16 +1,15 @@ use SVG; use SVG::Plot; -my @x = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9); +my @x = 0..9; my @y = (2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0); -my $svg = SVG::Plot.new( +say SVG.serialize: SVG::Plot.new( width => 512, height => 512, x => @x, x-tick-step => { 1 }, - values => [@y], + min-y-axis => 0, + values => [@y,], title => 'Coordinate Pairs', ).plot(:xy-lines); - -say SVG.serialize($svg); diff --git a/Task/Plot-coordinate-pairs/Ring/plot-coordinate-pairs.ring b/Task/Plot-coordinate-pairs/Ring/plot-coordinate-pairs.ring new file mode 100644 index 0000000000..2596618e7d --- /dev/null +++ b/Task/Plot-coordinate-pairs/Ring/plot-coordinate-pairs.ring @@ -0,0 +1,78 @@ +# Project : Plot coordinate pairs +# Date : 2018/01/11 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +load "guilib.ring" + +paint = null + +new qapp + { + win1 = new qwidget() { + setwindowtitle("Plot coordinate pairs") + setgeometry(100,100,1024,900) + label1 = new qlabel(win1) { + setgeometry(10,10,1024,900) + settext("") + } + new qpushbutton(win1) { + setgeometry(50,50,100,30) + settext("draw") + setclickevent("draw()") + } + show() + } + exec() + } + +func draw + p1 = new qpicture() + color = new qcolor() { + setrgb(0,0,255,255) + } + pen = new qpen() { + setcolor(color) + setwidth(1) + } + paint = new qpainter() { + begin(p1) + setpen(pen) + + old = 0 + yold = 0 + xnew = 0 + ynew = 0 + x2 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + y2 = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0] + + for x = 1 to 9 + drawline(100*x,720,100*x,0) + drawtext(100*x,750,string(x)) + next + + for y = 20 to 180 step 20 + drawline(900,4*y,0,4*y) + drawtext(0,720-4*y,string(y)) + next + + drawline(0,0,0,720) + drawline(0,0,900,0) + + for i = 1 to 10 + if i=1 + xold = 100*x2[i] + yold = 720-4*y2[i] + else + xnew = 100*x2[i] + ynew = 720-4*y2[i] + drawline(xold,yold,xnew,ynew) + xold = xnew + yold = ynew + ok + next + + endpaint() + } + label1 { setpicture(p1) show() } + return diff --git a/Task/Polymorphic-copy/Elena/polymorphic-copy.elena b/Task/Polymorphic-copy/Elena/polymorphic-copy.elena new file mode 100644 index 0000000000..3ff02a5c59 --- /dev/null +++ b/Task/Polymorphic-copy/Elena/polymorphic-copy.elena @@ -0,0 +1,24 @@ +import extensions. + +class T +{ + Name = "T". + + clone = T new. +} + +class S :: T +{ + Name = "S". + + clone = S new. +} + +program = +[ + type original := S new. + type clone := original clone. + + console printLine(original Name). + console printLine(clone Name). +]. diff --git a/Task/Polymorphic-copy/Scala/polymorphic-copy.scala b/Task/Polymorphic-copy/Scala/polymorphic-copy.scala new file mode 100644 index 0000000000..f1bcae54b7 --- /dev/null +++ b/Task/Polymorphic-copy/Scala/polymorphic-copy.scala @@ -0,0 +1,21 @@ +object PolymorphicCopy { + + def main(args: Array[String]) { + val a: Animal = Dog("Rover", 3, "Terrier") + val b: Animal = a.copy() // calls Dog.copy() because runtime type of 'a' is Dog + println(s"Dog 'a' = $a") // implicitly calls Dog.toString() + println(s"Dog 'b' = $b") // ditto + println(s"Dog 'a' is ${if (a == b) "" else "not"} the same object as Dog 'b'") + } + + case class Animal(name: String, age: Int) { + + override def toString = s"Name: $name, Age: $age" + } + + case class Dog(override val name: String, override val age: Int, breed: String) extends Animal(name, age) { + + override def toString = super.toString() + s", Breed: $breed" + } + +} diff --git a/Task/Polymorphism/Elena/polymorphism.elena b/Task/Polymorphism/Elena/polymorphism.elena new file mode 100644 index 0000000000..fac37a6748 --- /dev/null +++ b/Task/Polymorphism/Elena/polymorphism.elena @@ -0,0 +1,46 @@ +import extensions. + +class Point +{ + int prop X :: _x. + int prop Y :: _y. + + constructor new(IntNumber x, IntNumber y) + [ + _x := x. + _y := y. + ] + + constructor new + <= new(0,0). + + print [ console printLine("Point") ] +} + +class Circle :: Point +{ + int prop R :: _r. + + constructor new + <= new(0). + + constructor new(IntNumber r) + <= new(0, 0, r). + + constructor new(IntNumber x, IntNumber y, IntNumber r) + <= new(x, y); + [ + _r := r. + ] + + print [ console printLine("Circle") ] +} + +program = +[ + var p := Point new. + var c := Circle new. + + p print. + c print. +]. diff --git a/Task/Polymorphism/Julia/polymorphism.julia b/Task/Polymorphism/Julia/polymorphism.julia index 470e508927..d60059f73b 100644 --- a/Task/Polymorphism/Julia/polymorphism.julia +++ b/Task/Polymorphism/Julia/polymorphism.julia @@ -1,30 +1,28 @@ -import Base.print - -type Point +mutable struct Point x::Float64 y::Float64 end -print(p::Point) = println("Point($(p.x), $(p.y))") +Base.show(io::IO, p::Point) = print(io, "Point($(p.x), $(p.y))") -x(p::Point) = p.x -y(p::Point) = p.y +getx(p::Point) = p.x +gety(p::Point) = p.y setx(p::Point, x) = (p.x = x) sety(p::Point, y) = (p.y = y) -type Circle +mutable struct Circle x::Float64 y::Float64 r::Float64 end -x(c::Circle) = c.x -y(c::Circle) = c.y -r(c::Circle) = c.r +getx(c::Circle) = c.x +gety(c::Circle) = c.y +getr(c::Circle) = c.r setx(c::Circle, x) = (c.x = x) sety(c::Circle, y) = (c.y = y) setr(c::Circle, r) = (c.r = r) -print(c::Circle) = println("Circle($(c.x), $(c.y), $(c.r))") +Base.show(io::IO, c::Circle) = print(io, "Circle($(c.x), $(c.y), $(c.r))") diff --git a/Task/Polynomial-long-division/APL/polynomial-long-division.apl b/Task/Polynomial-long-division/APL/polynomial-long-division.apl new file mode 100644 index 0000000000..317403e516 --- /dev/null +++ b/Task/Polynomial-long-division/APL/polynomial-long-division.apl @@ -0,0 +1,8 @@ +div←{ + { + q r d←⍵ + (≢d) > n←≢r : q r + c ← (⊃⌽r) ÷ ⊃⌽d + ∇ (c,q) ((¯1↓r) - c × ¯1↓(-n)↑d) d + } ⍬ ⍺ ⍵ +} diff --git a/Task/Polynomial-long-division/Clojure/polynomial-long-division.clj b/Task/Polynomial-long-division/Clojure/polynomial-long-division.clj new file mode 100644 index 0000000000..1140c8fce0 --- /dev/null +++ b/Task/Polynomial-long-division/Clojure/polynomial-long-division.clj @@ -0,0 +1,95 @@ +(defn grevlex [term1 term2] + (let [grade1 (reduce +' term1) + grade2 (reduce +' term2) + comp (- grade2 grade1)] ;; total degree + (if (not= 0 comp) + comp + (loop [term1 term1 + term2 term2] + (if (empty? term1) + 0 + (let [grade1 (last term1) + grade2 (last term2) + comp (- grade1 grade2)] ;; differs from grlex because terms are flipped from above + (if (not= 0 comp) + comp + (recur (pop term1) + (pop term2))))))))) + +(defn mul + ;; transducer + ([poly1] ;; completion + (fn + ([] poly1) + ([poly2] (mul poly1 poly2)) + ([poly2 & more] (mul poly1 poly2 more)))) + ([poly1 poly2] + (let [product (atom (transient (sorted-map-by grevlex)))] + (doall ;; `for` is lazy so must to be forced for side-effects + (for [term1 poly1 + term2 poly2 + :let [vars (mapv +' (key term1) (key term2)) + coeff (* (val term1) (val term2))]] + (if (contains? @product vars) + (swap! product assoc! vars (+ (get @product vars) coeff)) + (swap! product assoc! vars coeff)))) + (->> product + (deref) + (persistent!) + (denull)))) + ([poly1 poly2 & more] + (reduce mul (mul poly1 poly2) more))) + +(defn compl [term1 term2] + (map (fn [x y] + (cond + (and (zero? x) (not= 0 y)) nil + (< x y) nil + (>= x y) (- x y))) + term1 + term2)) + +(defn s-poly [f g] + (let [f-vars (first f) + g-vars (first g) + lcm (compl f-vars g-vars)] + (if (not-any? nil? lcm) + {(vec lcm) + (/ (second f) (second g))}))) + +(defn divide [f g] + (loop [f f + g g + result (transient {}) + remainder {}] + (if (empty? f) + (list (persistent! result) + (->> remainder + (filter #(not (nil? %))) + (into (sorted-map-by grevlex)))) + (let [term1 (first f) + term2 (first g) + s-term (s-poly term1 term2)] + (if (nil? s-term) + (recur (dissoc f (first term1)) + (dissoc g (first term2)) + result + (conj remainder term1)) + (recur (sub f (mul g s-term)) + g + (conj! result s-term) + remainder)))))) + +(deftest divide-tests + (is (= (divide {[1 1] 2, [1 0] 3, [0 1] 5, [0 0] 7} + {[1 1] 2, [1 0] 3, [0 1] 5, [0 0] 7}) + '({[0 0] 1} {}))) + (is (= (divide {[1 1] 2, [1 0] 3, [0 1] 5, [0 0] 7} + {[0 0] 1}) + '({[1 1] 2, [1 0] 3, [0 1] 5, [0 0] 7} {}))) + (is (= (divide {[1 1] 2, [1 0] 10, [0 1] 3, [0 0] 15} + {[0 1] 1, [0 0] 5}) + '({[1 0] 2, [0 0] 3} {}))) + (is (= (divide {[1 1] 2, [1 0] 10, [0 1] 3, [0 0] 15} + {[1 0] 2, [0 0] 3}) + '({[0 1] 1, [0 0] 5} {})))) diff --git a/Task/Polynomial-long-division/Java/polynomial-long-division.java b/Task/Polynomial-long-division/Java/polynomial-long-division.java new file mode 100644 index 0000000000..37b3ee292e --- /dev/null +++ b/Task/Polynomial-long-division/Java/polynomial-long-division.java @@ -0,0 +1,118 @@ +import java.util.Arrays; + +public class PolynomialLongDivision { + private static class Solution { + double[] quotient, remainder; + + Solution(double[] q, double[] r) { + this.quotient = q; + this.remainder = r; + } + } + + private static int polyDegree(double[] p) { + for (int i = p.length - 1; i >= 0; --i) { + if (p[i] != 0.0) return i; + } + return Integer.MIN_VALUE; + } + + private static double[] polyShiftRight(double[] p, int places) { + if (places <= 0) return p; + int pd = polyDegree(p); + if (pd + places >= p.length) { + throw new IllegalArgumentException("The number of places to be shifted is too large"); + } + double[] d = Arrays.copyOf(p, p.length); + for (int i = pd; i >= 0; --i) { + d[i + places] = d[i]; + d[i] = 0.0; + } + return d; + } + + private static void polyMultiply(double[] p, double m) { + for (int i = 0; i < p.length; ++i) { + p[i] *= m; + } + } + + private static void polySubtract(double[] p, double[] s) { + for (int i = 0; i < p.length; ++i) { + p[i] -= s[i]; + } + } + + private static Solution polyLongDiv(double[] n, double[] d) { + if (n.length != d.length) { + throw new IllegalArgumentException("Numerator and denominator vectors must have the same size"); + } + int nd = polyDegree(n); + int dd = polyDegree(d); + if (dd < 0) { + throw new IllegalArgumentException("Divisor must have at least one one-zero coefficient"); + } + if (nd < dd) { + throw new IllegalArgumentException("The degree of the divisor cannot exceed that of the numerator"); + } + double[] n2 = Arrays.copyOf(n, n.length); + double[] q = new double[n.length]; + while (nd >= dd) { + double[] d2 = polyShiftRight(d, nd - dd); + q[nd - dd] = n2[nd] / d2[nd]; + polyMultiply(d2, q[nd - dd]); + polySubtract(n2, d2); + nd = polyDegree(n2); + } + return new Solution(q, n2); + } + + private static void polyShow(double[] p) { + int pd = polyDegree(p); + for (int i = pd; i >= 0; --i) { + double coeff = p[i]; + if (coeff == 0.0) continue; + if (coeff == 1.0) { + if (i < pd) { + System.out.print(" + "); + } + } else if (coeff == -1.0) { + if (i < pd) { + System.out.print(" - "); + } else { + System.out.print("-"); + } + } else if (coeff < 0.0) { + if (i < pd) { + System.out.printf(" - %.1f", -coeff); + } else { + System.out.print(coeff); + } + } else { + if (i < pd) { + System.out.printf(" + %.1f", coeff); + } else { + System.out.print(coeff); + } + } + if (i > 1) System.out.printf("x^%d", i); + else if (i == 1) System.out.print("x"); + } + System.out.println(); + } + + public static void main(String[] args) { + double[] n = new double[]{-42.0, 0.0, -12.0, 1.0}; + double[] d = new double[]{-3.0, 1.0, 0.0, 0.0}; + System.out.print("Numerator : "); + polyShow(n); + System.out.print("Denominator : "); + polyShow(d); + System.out.println("-------------------------------------"); + Solution sol = polyLongDiv(n, d); + System.out.print("Quotient : "); + polyShow(sol.quotient); + System.out.print("Remainder : "); + polyShow(sol.remainder); + } +} diff --git a/Task/Polynomial-long-division/Kotlin/polynomial-long-division.kotlin b/Task/Polynomial-long-division/Kotlin/polynomial-long-division.kotlin new file mode 100644 index 0000000000..ce88220987 --- /dev/null +++ b/Task/Polynomial-long-division/Kotlin/polynomial-long-division.kotlin @@ -0,0 +1,90 @@ +// version 1.1.51 + +typealias IAE = IllegalArgumentException + +data class Solution(val quotient: DoubleArray, val remainder: DoubleArray) + +fun polyDegree(p: DoubleArray): Int { + for (i in p.size - 1 downTo 0) { + if (p[i] != 0.0) return i + } + return Int.MIN_VALUE +} + +fun polyShiftRight(p: DoubleArray, places: Int): DoubleArray { + if (places <= 0) return p + val pd = polyDegree(p) + if (pd + places >= p.size) { + throw IAE("The number of places to be shifted is too large") + } + val d = p.copyOf() + for (i in pd downTo 0) { + d[i + places] = d[i] + d[i] = 0.0 + } + return d +} + +fun polyMultiply(p: DoubleArray, m: Double) { + for (i in 0 until p.size) p[i] *= m +} + +fun polySubtract(p: DoubleArray, s: DoubleArray) { + for (i in 0 until p.size) p[i] -= s[i] +} + +fun polyLongDiv(n: DoubleArray, d: DoubleArray): Solution { + if (n.size != d.size) { + throw IAE("Numerator and denominator vectors must have the same size") + } + var nd = polyDegree(n) + val dd = polyDegree(d) + if (dd < 0) { + throw IAE("Divisor must have at least one one-zero coefficient") + } + if (nd < dd) { + throw IAE("The degree of the divisor cannot exceed that of the numerator") + } + val n2 = n.copyOf() + val q = DoubleArray(n.size) // all elements zero by default + while (nd >= dd) { + val d2 = polyShiftRight(d, nd - dd) + q[nd - dd] = n2[nd] / d2[nd] + polyMultiply(d2, q[nd - dd]) + polySubtract(n2, d2) + nd = polyDegree(n2) + } + return Solution(q, n2) +} + +fun polyShow(p: DoubleArray) { + val pd = polyDegree(p) + for (i in pd downTo 0) { + val coeff = p[i] + if (coeff == 0.0) continue + print (when { + coeff == 1.0 -> if (i < pd) " + " else "" + coeff == -1.0 -> if (i < pd) " - " else "-" + coeff < 0.0 -> if (i < pd) " - ${-coeff}" else "$coeff" + else -> if (i < pd) " + $coeff" else "$coeff" + }) + if (i > 1) print("x^$i") + else if (i == 1) print("x") + } + println() +} + +fun main(args: Array) { + val n = doubleArrayOf(-42.0, 0.0, -12.0, 1.0) + val d = doubleArrayOf( -3.0, 1.0, 0.0, 0.0) + print("Numerator : ") + polyShow(n) + print("Denominator : ") + polyShow(d) + println("-------------------------------------") + val (q, r) = polyLongDiv(n, d) + print("Quotient : ") + polyShow(q) + print("Remainder : ") + polyShow(r) +} diff --git a/Task/Polynomial-long-division/REXX/polynomial-long-division.rexx b/Task/Polynomial-long-division/REXX/polynomial-long-division.rexx new file mode 100644 index 0000000000..eb9247cc54 --- /dev/null +++ b/Task/Polynomial-long-division/REXX/polynomial-long-division.rexx @@ -0,0 +1,44 @@ +/* REXX needed by some... */ +z='1 -12 0 -42' /* Numerator */ +n='1 -3' /* Denominator */ +zx=z +nx=n copies('0 ',words(z)-words(n)) +qx='' /* Quotient */ +Do Until words(zx)1 Then fact='*x**'d + When d=1 Then fact='*x' + Otherwise fact='' + End + Select + When word(poly,i)=0 Then p='' + When word(poly,i)=1 Then p='+'substr(fact,2) + When word(poly,i)=-1 Then p='-'substr(fact,2) + When word(poly,i)<0 Then p=word(poly,i)||fact + Otherwise p='+'word(poly,i)||fact + End + res=res p + d=d-1 + End +Return strip(space(res,0),'L','+') diff --git a/Task/Polynomial-regression/D/polynomial-regression.d b/Task/Polynomial-regression/D/polynomial-regression.d new file mode 100644 index 0000000000..d1f45524d3 --- /dev/null +++ b/Task/Polynomial-regression/D/polynomial-regression.d @@ -0,0 +1,47 @@ +import std.algorithm; +import std.range; +import std.stdio; + +auto average(R)(R r) { + auto t = r.fold!("a+b", "a+1")(0, 0); + return cast(double) t[0] / t[1]; +} + +void polyRegression(int[] x, int[] y) { + auto n = x.length; + auto r = iota(0, n).array; + auto xm = x.average(); + auto ym = y.average(); + auto x2m = r.map!"a*a".average(); + auto x3m = r.map!"a*a*a".average(); + auto x4m = r.map!"a*a*a*a".average(); + auto xym = x.zip(y).map!"a[0]*a[1]".average(); + auto x2ym = x.zip(y).map!"a[0]*a[0]*a[1]".average(); + + auto sxx = x2m - xm * xm; + auto sxy = xym - xm * ym; + auto sxx2 = x3m - xm * x2m; + auto sx2x2 = x4m - x2m * x2m; + auto sx2y = x2ym - x2m * ym; + + auto b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2); + auto c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2); + auto a = ym - b * xm - c * x2m; + + real abc(int xx) { + return a + b * xx + c * xx * xx; + } + + writeln("y = ", a, " + ", b, "x + ", c, "x^2"); + writeln(" Input Approximation"); + writeln(" x y y1"); + foreach (i; 0..n) { + writefln("%2d %3d %5.1f", x[i], y[i], abc(x[i])); + } +} + +void main() { + auto x = iota(0, 11).array; + auto y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]; + polyRegression(x, y); +} diff --git a/Task/Polynomial-regression/Java/polynomial-regression.java b/Task/Polynomial-regression/Java/polynomial-regression.java new file mode 100644 index 0000000000..282aaa39b9 --- /dev/null +++ b/Task/Polynomial-regression/Java/polynomial-regression.java @@ -0,0 +1,50 @@ +import java.util.Arrays; +import java.util.function.IntToDoubleFunction; +import java.util.stream.IntStream; + +public class PolynomialRegression { + private static void polyRegression(int[] x, int[] y) { + int n = x.length; + int[] r = IntStream.range(0, n).toArray(); + double xm = Arrays.stream(x).average().orElse(Double.NaN); + double ym = Arrays.stream(y).average().orElse(Double.NaN); + double x2m = Arrays.stream(r).map(a -> a * a).average().orElse(Double.NaN); + double x3m = Arrays.stream(r).map(a -> a * a * a).average().orElse(Double.NaN); + double x4m = Arrays.stream(r).map(a -> a * a * a * a).average().orElse(Double.NaN); + double xym = 0.0; + for (int i = 0; i < x.length && i < y.length; ++i) { + xym += x[i] * y[i]; + } + xym /= Math.min(x.length, y.length); + double x2ym = 0.0; + for (int i = 0; i < x.length && i < y.length; ++i) { + x2ym += x[i] * x[i] * y[i]; + } + x2ym /= Math.min(x.length, y.length); + + double sxx = x2m - xm * xm; + double sxy = xym - xm * ym; + double sxx2 = x3m - xm * x2m; + double sx2x2 = x4m - x2m * x2m; + double sx2y = x2ym - x2m * ym; + + double b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2); + double c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2); + double a = ym - b * xm - c * x2m; + + IntToDoubleFunction abc = (int xx) -> a + b * xx + c * xx * xx; + + System.out.println("y = " + a + " + " + b + "x + " + c + "x^2"); + System.out.println(" Input Approximation"); + System.out.println(" x y y1"); + for (int i = 0; i < n; ++i) { + System.out.printf("%2d %3d %5.1f\n", x[i], y[i], abc.applyAsDouble(x[i])); + } + } + + public static void main(String[] args) { + int[] x = IntStream.range(0, 11).toArray(); + int[] y = new int[]{1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321}; + polyRegression(x, y); + } +} diff --git a/Task/Polynomial-regression/Julia/polynomial-regression.julia b/Task/Polynomial-regression/Julia/polynomial-regression.julia index b397000990..e50fa10a86 100644 --- a/Task/Polynomial-regression/Julia/polynomial-regression.julia +++ b/Task/Polynomial-regression/Julia/polynomial-regression.julia @@ -1,4 +1,5 @@ -function polyfit(x, y, n) - A = [ float(x[i])^p for i = 1:length(x), p = 0:n ] - A \ y -end +polyfit(x::Vector, y::Vector, deg::Int) = collect(v ^ p for v in x, p in 0:deg) \ y + +x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +y = [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321] +@show polyfit(x, y, 2) diff --git a/Task/Polynomial-regression/Kotlin/polynomial-regression.kotlin b/Task/Polynomial-regression/Kotlin/polynomial-regression.kotlin new file mode 100644 index 0000000000..5ac47050a5 --- /dev/null +++ b/Task/Polynomial-regression/Kotlin/polynomial-regression.kotlin @@ -0,0 +1,38 @@ +// version 1.1.51 + +fun polyRegression(x: IntArray, y: IntArray) { + val n = x.size + val r = 0 until n + val xm = x.average() + val ym = y.average() + val x2m = r.map { it * it }.average() + val x3m = r.map { it * it * it }.average() + val x4m = r.map { it * it * it * it }.average() + val xym = x.zip(y).map { it.first * it.second }.average() + val x2ym = x.zip(y).map { it.first * it.first * it.second }.average() + + val sxx = x2m - xm * xm + val sxy = xym - xm * ym + val sxx2 = x3m - xm * x2m + val sx2x2 = x4m - x2m * x2m + val sx2y = x2ym - x2m * ym + + val b = (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2) + val c = (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2) + val a = ym - b * xm - c * x2m + + fun abc(xx: Int) = a + b * xx + c * xx * xx + + println("y = $a + ${b}x + ${c}x^2\n") + println(" Input Approximation") + println(" x y y1") + for (i in 0 until n) { + System.out.printf("%2d %3d %5.1f\n", x[i], y[i], abc(x[i])) + } +} + +fun main(args: Array) { + val x = IntArray(11) { it } + val y = intArrayOf(1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321) + polyRegression(x, y) +} diff --git a/Task/Polynomial-regression/Modula-2/polynomial-regression.mod2 b/Task/Polynomial-regression/Modula-2/polynomial-regression.mod2 new file mode 100644 index 0000000000..69f53801e9 --- /dev/null +++ b/Task/Polynomial-regression/Modula-2/polynomial-regression.mod2 @@ -0,0 +1,87 @@ +MODULE PolynomialRegression; +FROM FormatString IMPORT FormatString; +FROM RealStr IMPORT RealToStr; +FROM Terminal IMPORT WriteString,WriteLn,ReadChar; + +PROCEDURE Eval(a,b,c,x : REAL) : REAL; +BEGIN + RETURN a + b*x + c*x*x; +END Eval; + +PROCEDURE Regression(x,y : ARRAY OF INTEGER); +VAR + n,i : INTEGER; + xm,x2m,x3m,x4m : REAL; + ym : REAL; + xym,x2ym : REAL; + sxx,sxy,sxx2,sx2x2,sx2y : REAL; + a,b,c : REAL; + buf : ARRAY[0..63] OF CHAR; +BEGIN + n := SIZE(x)/SIZE(INTEGER); + + xm := 0.0; + ym := 0.0; + x2m := 0.0; + x3m := 0.0; + x4m := 0.0; + xym := 0.0; + x2ym := 0.0; + FOR i:=0 TO n-1 DO + xm := xm + FLOAT(x[i]); + ym := ym + FLOAT(y[i]); + x2m := x2m + FLOAT(x[i]) * FLOAT(x[i]); + x3m := x3m + FLOAT(x[i]) * FLOAT(x[i]) * FLOAT(x[i]); + x4m := x4m + FLOAT(x[i]) * FLOAT(x[i]) * FLOAT(x[i]) * FLOAT(x[i]); + xym := xym + FLOAT(x[i]) * FLOAT(y[i]); + x2ym := x2ym + FLOAT(x[i]) * FLOAT(x[i]) * FLOAT(y[i]); + END; + xm := xm / FLOAT(n); + ym := ym / FLOAT(n); + x2m := x2m / FLOAT(n); + x3m := x3m / FLOAT(n); + x4m := x4m / FLOAT(n); + xym := xym / FLOAT(n); + x2ym := x2ym / FLOAT(n); + + sxx := x2m - xm * xm; + sxy := xym - xm * ym; + sxx2 := x3m - xm * x2m; + sx2x2 := x4m - x2m * x2m; + sx2y := x2ym - x2m * ym; + + b := (sxy * sx2x2 - sx2y * sxx2) / (sxx * sx2x2 - sxx2 * sxx2); + c := (sx2y * sxx - sxy * sxx2) / (sxx * sx2x2 - sxx2 * sxx2); + a := ym - b * xm - c * x2m; + + WriteString("y = "); + RealToStr(a, buf); + WriteString(buf); + WriteString(" + "); + RealToStr(b, buf); + WriteString(buf); + WriteString("x + "); + RealToStr(c, buf); + WriteString(buf); + WriteString("x^2"); + WriteLn; + + FOR i:=0 TO n-1 DO + FormatString("%2i %3i ", buf, x[i], y[i]); + WriteString(buf); + RealToStr(Eval(a,b,c,FLOAT(x[i])), buf); + WriteString(buf); + WriteLn; + END; +END Regression; + +TYPE R = ARRAY[0..10] OF INTEGER; +VAR + x,y : R; +BEGIN + x := R{0,1,2,3,4,5,6,7,8,9,10}; + y := R{1,6,17,34,57,86,121,162,209,262,321}; + Regression(x,y); + + ReadChar; +END PolynomialRegression. diff --git a/Task/Polynomial-regression/Ruby/polynomial-regression-1.rb b/Task/Polynomial-regression/Ruby/polynomial-regression-1.rb index 65e8020258..cfff811f2f 100644 --- a/Task/Polynomial-regression/Ruby/polynomial-regression-1.rb +++ b/Task/Polynomial-regression/Ruby/polynomial-regression-1.rb @@ -1,10 +1,10 @@ require 'matrix' def regress x, y, degree - x_data = x.map { |xi| (0..degree).map { |pow| (xi**pow).to_f } } + x_data = x.map { |xi| (0..degree).map { |pow| (xi**pow).to_r } } mx = Matrix[*x_data] my = Matrix.column_vector(y) - ((mx.t * mx).inv * mx.t * my).transpose.to_a[0] + ((mx.t * mx).inv * mx.t * my).transpose.to_a[0].map(&:to_f) end diff --git a/Task/Polynomial-regression/Ruby/polynomial-regression-2.rb b/Task/Polynomial-regression/Ruby/polynomial-regression-2.rb index c742b60fa3..b9183be208 100644 --- a/Task/Polynomial-regression/Ruby/polynomial-regression-2.rb +++ b/Task/Polynomial-regression/Ruby/polynomial-regression-2.rb @@ -1,5 +1,3 @@ -betas = regress [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], - [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321], - 2 - -p betas +p regress([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + [1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321], + 2) diff --git a/Task/Power-set/Clojure/power-set-2.clj b/Task/Power-set/Clojure/power-set-2.clj index 093f1f627a..59922e4cd5 100644 --- a/Task/Power-set/Clojure/power-set-2.clj +++ b/Task/Power-set/Clojure/power-set-2.clj @@ -1,9 +1,6 @@ (defn powerset [coll] (reduce (fn [a x] - (->> a - (map #(set (concat #{x} %))) - (concat a) - set)) + (into a (map #(conj % x)) a)) #{#{}} coll)) (powerset #{1 2 3}) diff --git a/Task/Power-set/Go/power-set.go b/Task/Power-set/Go/power-set.go index 25b6f6c094..eaaf4f6420 100644 --- a/Task/Power-set/Go/power-set.go +++ b/Task/Power-set/Go/power-set.go @@ -1,9 +1,9 @@ package main import ( - "bytes" "fmt" "strconv" + "strings" ) // types needed to implement general purpose sets are element and set @@ -85,7 +85,7 @@ func (s set) String() string { if len(s) == 0 { return "∅" } - var buf bytes.Buffer + var buf strings.Builder buf.WriteRune('{') for i, e := range s { if i > 0 { @@ -104,7 +104,7 @@ func (s set) powerSet() set { var u set for _, er := range r { er := er.(set) - u = append(u, append(er[:len(er):len(er)], es)) + u = append(u, append(er[:len(er):len(er)], es)) } r = append(r, u...) } diff --git a/Task/Power-set/PARI-GP/power-set.pari b/Task/Power-set/PARI-GP/power-set-1.pari similarity index 100% rename from Task/Power-set/PARI-GP/power-set.pari rename to Task/Power-set/PARI-GP/power-set-1.pari diff --git a/Task/Power-set/PARI-GP/power-set-2.pari b/Task/Power-set/PARI-GP/power-set-2.pari new file mode 100644 index 0000000000..3f80fa8d0f --- /dev/null +++ b/Task/Power-set/PARI-GP/power-set-2.pari @@ -0,0 +1,2 @@ +S=["a","b","c"] +forsubset(#S,s,print1(vecextract(S,s)" ")) diff --git a/Task/Power-set/Perl/power-set-10.pl b/Task/Power-set/Perl/power-set-10.pl index a7e912522e..3d2864f0fb 100644 --- a/Task/Power-set/Perl/power-set-10.pl +++ b/Task/Power-set/Perl/power-set-10.pl @@ -1,21 +1,8 @@ -use strict; -use warnings; -sub powerset(&@) { - my $callback = shift; - my $bitmask = ''; - my $bytes = @_/8; - { - my @indices = grep vec($bitmask, $_, 1), 0..$#_; - $callback->( @_[@indices] ); - ++vec($bitmask, $_, 8) and last for 0 .. $bytes; - redo if @indices != @_; - } +my @set = (1, 2, 3); +my @powerset = powerset(@set); + +sub set_to_string { + "{" . join(", ", map { ref $_ ? set_to_string(@$_) : $_ } @_) . "}" } -print "powerset of empty set:\n"; -powerset { print "[@_]\n" }; -print "powerset of set {1,2,3,4}:\n"; -powerset { print "[@_]\n" } 1..4; -my $i = 0; -powerset { ++$i } 1..9; -print "The powerset of a nine element set contains $i elements.\n"; +print set_to_string(@powerset), "\n"; diff --git a/Task/Power-set/Perl/power-set-11.pl b/Task/Power-set/Perl/power-set-11.pl new file mode 100644 index 0000000000..a7e912522e --- /dev/null +++ b/Task/Power-set/Perl/power-set-11.pl @@ -0,0 +1,21 @@ +use strict; +use warnings; +sub powerset(&@) { + my $callback = shift; + my $bitmask = ''; + my $bytes = @_/8; + { + my @indices = grep vec($bitmask, $_, 1), 0..$#_; + $callback->( @_[@indices] ); + ++vec($bitmask, $_, 8) and last for 0 .. $bytes; + redo if @indices != @_; + } +} + +print "powerset of empty set:\n"; +powerset { print "[@_]\n" }; +print "powerset of set {1,2,3,4}:\n"; +powerset { print "[@_]\n" } 1..4; +my $i = 0; +powerset { ++$i } 1..9; +print "The powerset of a nine element set contains $i elements.\n"; diff --git a/Task/Power-set/Perl/power-set-2.pl b/Task/Power-set/Perl/power-set-2.pl index 53adc449dd..42eac087e9 100644 --- a/Task/Power-set/Perl/power-set-2.pl +++ b/Task/Power-set/Perl/power-set-2.pl @@ -1,4 +1,4 @@ -use ntheory "vecextract"; -my @S=("a","b","c"); -my @PS = map { "[".join(" ",vecextract(\@S,$_))."]" } 0..2**scalar(@S)-1; -say join(" ",@PS); +use ntheory "forcomb"; +my @S = qw/a b c/; +forcomb { print "[@S[@_]] " } scalar(@S); +print "\n"; diff --git a/Task/Power-set/Perl/power-set-3.pl b/Task/Power-set/Perl/power-set-3.pl index 99b1aed6e7..d6fe1146ce 100644 --- a/Task/Power-set/Perl/power-set-3.pl +++ b/Task/Power-set/Perl/power-set-3.pl @@ -1,5 +1,5 @@ use ntheory "forcomb"; -my @S=("a","b","c"); +my @S = qw/a b c/; for $k (0..@S) { # Iterate over each $#S+1,$k combination. forcomb { print "[@S[@_]] " } @S,$k; diff --git a/Task/Power-set/Perl/power-set-4.pl b/Task/Power-set/Perl/power-set-4.pl index 9a53bbc995..c6f50eb71c 100644 --- a/Task/Power-set/Perl/power-set-4.pl +++ b/Task/Power-set/Perl/power-set-4.pl @@ -1,14 +1,4 @@ -use Set::Object qw(set); - -sub powerset { - my $p = Set::Object->new( set() ); - foreach my $i (shift->elements) { - $p->insert( map { set($_->elements, $i) } $p->elements ); - } - return $p; -} - -my $set = set(1, 2, 3); -my $powerset = powerset($set); - -print $powerset->as_string, "\n"; +use ntheory "vecextract"; +my @S = qw/a b c/; +my @PS = map { "[".join(" ",vecextract(\@S,$_))."]" } 0..2**scalar(@S)-1; +say join(" ",@PS); diff --git a/Task/Power-set/Perl/power-set-5.pl b/Task/Power-set/Perl/power-set-5.pl index 14835dd1be..9a53bbc995 100644 --- a/Task/Power-set/Perl/power-set-5.pl +++ b/Task/Power-set/Perl/power-set-5.pl @@ -1,6 +1,14 @@ -package Set { - sub new { bless { map {$_ => undef} @_[1..$#_] }, shift; } - sub elements { sort keys %{shift()} } - sub as_string { 'Set(' . join(' ', sort keys %{shift()}) . ')' } - # ...more set methods could be defined here... +use Set::Object qw(set); + +sub powerset { + my $p = Set::Object->new( set() ); + foreach my $i (shift->elements) { + $p->insert( map { set($_->elements, $i) } $p->elements ); + } + return $p; } + +my $set = set(1, 2, 3); +my $powerset = powerset($set); + +print $powerset->as_string, "\n"; diff --git a/Task/Power-set/Perl/power-set-6.pl b/Task/Power-set/Perl/power-set-6.pl index fc22e29c83..14835dd1be 100644 --- a/Task/Power-set/Perl/power-set-6.pl +++ b/Task/Power-set/Perl/power-set-6.pl @@ -1,11 +1,6 @@ -use List::Util qw(reduce); - -sub powerset { - @{( reduce { [@$a, map { Set->new($_->elements, $b) } @$a ] } - [Set->new()], shift->elements )}; +package Set { + sub new { bless { map {$_ => undef} @_[1..$#_] }, shift; } + sub elements { sort keys %{shift()} } + sub as_string { 'Set(' . join(' ', sort keys %{shift()}) . ')' } + # ...more set methods could be defined here... } - -my $set = Set->new(1, 2, 3); -my @subsets = powerset($set); - -print $_->as_string, "\n" for @subsets; diff --git a/Task/Power-set/Perl/power-set-7.pl b/Task/Power-set/Perl/power-set-7.pl index 90f5ed87c2..fc22e29c83 100644 --- a/Task/Power-set/Perl/power-set-7.pl +++ b/Task/Power-set/Perl/power-set-7.pl @@ -1,3 +1,11 @@ +use List::Util qw(reduce); + sub powerset { - @_ ? map { $_, [$_[0], @$_] } powerset(@_[1..$#_]) : []; + @{( reduce { [@$a, map { Set->new($_->elements, $b) } @$a ] } + [Set->new()], shift->elements )}; } + +my $set = Set->new(1, 2, 3); +my @subsets = powerset($set); + +print $_->as_string, "\n" for @subsets; diff --git a/Task/Power-set/Perl/power-set-8.pl b/Task/Power-set/Perl/power-set-8.pl index f9cea5d06c..90f5ed87c2 100644 --- a/Task/Power-set/Perl/power-set-8.pl +++ b/Task/Power-set/Perl/power-set-8.pl @@ -1,5 +1,3 @@ -use List::Util qw(reduce); - sub powerset { - @{( reduce { [@$a, map([@$_, $b], @$a)] } [[]], @_ )} + @_ ? map { $_, [$_[0], @$_] } powerset(@_[1..$#_]) : []; } diff --git a/Task/Power-set/Perl/power-set-9.pl b/Task/Power-set/Perl/power-set-9.pl index 3d2864f0fb..f9cea5d06c 100644 --- a/Task/Power-set/Perl/power-set-9.pl +++ b/Task/Power-set/Perl/power-set-9.pl @@ -1,8 +1,5 @@ -my @set = (1, 2, 3); -my @powerset = powerset(@set); +use List::Util qw(reduce); -sub set_to_string { - "{" . join(", ", map { ref $_ ? set_to_string(@$_) : $_ } @_) . "}" +sub powerset { + @{( reduce { [@$a, map([@$_, $b], @$a)] } [[]], @_ )} } - -print set_to_string(@powerset), "\n"; diff --git a/Task/Power-set/Ring/power-set.ring b/Task/Power-set/Ring/power-set.ring new file mode 100644 index 0000000000..e0d4196f75 --- /dev/null +++ b/Task/Power-set/Ring/power-set.ring @@ -0,0 +1,23 @@ +# Project : Power set +# Date : 2018/01/13 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +list = ["1", "2", "3", "4"] +see powerset(list) + +func powerset(list) + s = "{" + for i = 1 to (2 << len(list)) - 1 step 2 + s = s + "{" + for j = 1 to len(list) + if i & (1 << j) + s = s + list[j] + "," + ok + next + if right(s,1) = "," + s = left(s,len(s)-1) + ok + s = s + "}," + next + return left(s,len(s)-1) + "}" diff --git a/Task/Power-set/Swift/power-set-1.swift b/Task/Power-set/Swift/power-set-1.swift new file mode 100644 index 0000000000..742e27d09e --- /dev/null +++ b/Task/Power-set/Swift/power-set-1.swift @@ -0,0 +1,15 @@ +func powersetFrom(_ elements: Set) -> Set> { + guard elements.count > 0 else { + return [[]] + } + var powerset: Set> = [[]] + for element in elements { + for subset in powerset { + powerset.insert(subset.union([element])) + } + } + return powerset +} + +// Example: +powersetFrom([1, 2, 4]) diff --git a/Task/Power-set/Swift/power-set-2.swift b/Task/Power-set/Swift/power-set-2.swift new file mode 100644 index 0000000000..932ae330ba --- /dev/null +++ b/Task/Power-set/Swift/power-set-2.swift @@ -0,0 +1,2 @@ +//Example: +powersetFrom(["a", "b", "d"]) diff --git a/Task/Pragmatic-directives/C/pragmatic-directives.c b/Task/Pragmatic-directives/C/pragmatic-directives.c new file mode 100644 index 0000000000..facbc441a9 --- /dev/null +++ b/Task/Pragmatic-directives/C/pragmatic-directives.c @@ -0,0 +1,41 @@ +/*Abhishek Ghosh, 7th October 2017*/ + +/*Almost every C program has the below line, +the #include preprocessor directive is used to +instruct the compiler which files to load before compiling the program. + +All preprocessor commands begin with # +*/ +#include + +/*The #define preprocessor directive is often used to create abbreviations for code segments*/ +#define Hi printf("Hi There."); + +/*It can be used, or misused, for rather innovative uses*/ + +#define start int main(){ +#define end return 0;} + +start + +Hi + +/*And here's the nice part, want your compiler to talk to you ? +Just use the #warning pragma if you are using a C99 compliant compiler +like GCC*/ +#warning "Don't you have anything better to do ?" + +#ifdef __unix__ +#warning "What are you doing still working on Unix ?" +printf("\nThis is an Unix system."); +#elif _WIN32 +#warning "You couldn't afford a 64 bit ?" +printf("\nThis is a 32 bit Windows system."); +#elif _WIN64 +#warning "You couldn't afford an Apple ?" +printf("\nThis is a 64 bit Windows system."); +#endif + +end + +/*Enlightened ?*/ diff --git a/Task/Pragmatic-directives/Scala/pragmatic-directives.scala b/Task/Pragmatic-directives/Scala/pragmatic-directives.scala new file mode 100644 index 0000000000..3df4fa3e6c --- /dev/null +++ b/Task/Pragmatic-directives/Scala/pragmatic-directives.scala @@ -0,0 +1,2 @@ +@inline +@tailrec diff --git a/Task/Price-fraction/Gambas/price-fraction.gambas b/Task/Price-fraction/Gambas/price-fraction.gambas new file mode 100644 index 0000000000..90c68d7a12 --- /dev/null +++ b/Task/Price-fraction/Gambas/price-fraction.gambas @@ -0,0 +1,14 @@ +Public Sub Main() +Dim byValue As Byte[] = [10, 18, 26, 32, 38, 44, 50, 54, 58, 62, 66, 70, 74, 78, 82, 86, 90, 94, 98, 100] +Dim byLimit As Byte[] = [6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61, 66, 71, 76, 81, 86, 91, 96] +Dim byCount, byCheck As Byte + +For byCount = 0 To 100 + For byCheck = 0 To byLimit.Max + If byCount < byLimit[byCheck] Then Break + Next + Print Format(byCount / 100, "0.00") & " = " & Format(byValue[byCheck] / 100, "0.00") & gb.Tab; + If byCount Mod 5 = 0 Then Print +Next + +End diff --git a/Task/Price-fraction/VBA/price-fraction.vba b/Task/Price-fraction/VBA/price-fraction.vba new file mode 100644 index 0000000000..d613038085 --- /dev/null +++ b/Task/Price-fraction/VBA/price-fraction.vba @@ -0,0 +1,18 @@ +Option Explicit + +Sub Main() +Dim test, i As Long + test = Array(0.34, 0.070145, 0.06, 0.05, 0.50214, 0.56, 1#, 0.99, 0#, 0.7388727) + For i = 0 To UBound(test) + Debug.Print test(i) & " := " & Price_Fraction(CSng(test(i))) + Next i +End Sub + +Private Function Price_Fraction(n As Single) As Single +Dim Vin, Vout, i As Long + Vin = Array(0.06, 0.11, 0.16, 0.21, 0.26, 0.31, 0.36, 0.41, 0.46, 0.51, 0.56, 0.61, 0.66, 0.71, 0.76, 0.81, 0.86, 0.91, 0.96, 1.01) + Vout = Array(0.1, 0.18, 0.26, 0.32, 0.38, 0.44, 0.5, 0.54, 0.58, 0.62, 0.66, 0.7, 0.74, 0.78, 0.82, 0.86, 0.9, 0.94, 0.98, 1#) + For i = 0 To UBound(Vin) + If n < Vin(i) Then Price_Fraction = Vout(i): Exit For + Next i +End Function diff --git a/Task/Primality-by-trial-division/Clojure/primality-by-trial-division-2.clj b/Task/Primality-by-trial-division/Clojure/primality-by-trial-division-2.clj index 1c04af6669..08cc88e6aa 100644 --- a/Task/Primality-by-trial-division/Clojure/primality-by-trial-division-2.clj +++ b/Task/Primality-by-trial-division/Clojure/primality-by-trial-division-2.clj @@ -4,4 +4,4 @@ (and (< 1 x) (odd? x) (not-any? (partial divides? x) - (range 3 (math/sqrt x) 2))))) + (range 3 (inc (Math/sqrt x)) 2))))) diff --git a/Task/Primality-by-trial-division/Clojure/primality-by-trial-division-3.clj b/Task/Primality-by-trial-division/Clojure/primality-by-trial-division-3.clj index 42f41ae18b..f33bb384d1 100644 --- a/Task/Primality-by-trial-division/Clojure/primality-by-trial-division-3.clj +++ b/Task/Primality-by-trial-division/Clojure/primality-by-trial-division-3.clj @@ -7,4 +7,4 @@ (and (integer? x) (< 1 x) (not-any? (partial divides? x) - (take-while (partial > (math/sqrt x)) primes))))) + (take-while (partial >= (Math/sqrt x)) primes))))) diff --git a/Task/Primality-by-trial-division/Common-Lisp/primality-by-trial-division.lisp b/Task/Primality-by-trial-division/Common-Lisp/primality-by-trial-division-1.lisp similarity index 100% rename from Task/Primality-by-trial-division/Common-Lisp/primality-by-trial-division.lisp rename to Task/Primality-by-trial-division/Common-Lisp/primality-by-trial-division-1.lisp diff --git a/Task/Primality-by-trial-division/Common-Lisp/primality-by-trial-division-2.lisp b/Task/Primality-by-trial-division/Common-Lisp/primality-by-trial-division-2.lisp new file mode 100644 index 0000000000..16b3948044 --- /dev/null +++ b/Task/Primality-by-trial-division/Common-Lisp/primality-by-trial-division-2.lisp @@ -0,0 +1,15 @@ +;; Project : Primality by trial division +;; Date : 2018/03/06 +;; Author : Gal Zsolt [~ CalmoSoft ~] +;; Email : + +(defun prime(n) + (setq flag 0) + (loop for i from 2 to (- n 1) do + (if (= (mod n i) 0) + (setq flag 1))) + (if (= flag 0) + (format t "~d is a prime number" n) + (format t "~d is not a prime number" n))) +(prime 7) +(prime 8) diff --git a/Task/Primality-by-trial-division/Lingo/primality-by-trial-division-1.lingo b/Task/Primality-by-trial-division/Lingo/primality-by-trial-division-1.lingo new file mode 100644 index 0000000000..c783a7e9f5 --- /dev/null +++ b/Task/Primality-by-trial-division/Lingo/primality-by-trial-division-1.lingo @@ -0,0 +1,8 @@ +on isPrime (n) + if n<=1 or (n>2 and n mod 2=0) then return FALSE + sq = sqrt(n) + repeat with i = 3 to sq + if n mod i = 0 then return FALSE + end repeat + return TRUE +end diff --git a/Task/Primality-by-trial-division/Lingo/primality-by-trial-division-2.lingo b/Task/Primality-by-trial-division/Lingo/primality-by-trial-division-2.lingo new file mode 100644 index 0000000000..647143f950 --- /dev/null +++ b/Task/Primality-by-trial-division/Lingo/primality-by-trial-division-2.lingo @@ -0,0 +1,5 @@ +primes = [] +repeat with i = 0 to 100 + if isPrime(i) then primes.add(i) +end repeat +put primes diff --git a/Task/Primality-by-trial-division/Sidef/primality-by-trial-division.sidef b/Task/Primality-by-trial-division/Sidef/primality-by-trial-division-1.sidef similarity index 100% rename from Task/Primality-by-trial-division/Sidef/primality-by-trial-division.sidef rename to Task/Primality-by-trial-division/Sidef/primality-by-trial-division-1.sidef diff --git a/Task/Primality-by-trial-division/Sidef/primality-by-trial-division-2.sidef b/Task/Primality-by-trial-division/Sidef/primality-by-trial-division-2.sidef new file mode 100644 index 0000000000..7215a09b0d --- /dev/null +++ b/Task/Primality-by-trial-division/Sidef/primality-by-trial-division-2.sidef @@ -0,0 +1,8 @@ +func is_prime(n) { + return (n >= 2) if (n < 4) + return false if (n%%2 || n%%3) + for k in (5 .. n.isqrt -> by(6)) { + return false if (n%%k || n%%(k+2)) + } + return true +} diff --git a/Task/Primality-by-trial-division/VBA/primality-by-trial-division.vba b/Task/Primality-by-trial-division/VBA/primality-by-trial-division.vba new file mode 100644 index 0000000000..ec9d859ee7 --- /dev/null +++ b/Task/Primality-by-trial-division/VBA/primality-by-trial-division.vba @@ -0,0 +1,27 @@ +Option Explicit + +Sub FirstTwentyPrimes() +Dim count As Integer, i As Long, t(19) As String + Do + i = i + 1 + If IsPrime(i) Then + t(count) = i + count = count + 1 + End If + Loop While count <= UBound(t) + Debug.Print Join(t, ", ") +End Sub + +Function IsPrime(Nb As Long) As Boolean + If Nb = 2 Then + IsPrime = True + ElseIf Nb < 2 Or Nb Mod 2 = 0 Then + Exit Function + Else + Dim i As Long + For i = 3 To Sqr(Nb) Step 2 + If Nb Mod i = 0 Then Exit Function + Next + IsPrime = True + End If +End Function diff --git a/Task/Prime-decomposition/Erlang/prime-decomposition.erl b/Task/Prime-decomposition/Erlang/prime-decomposition.erl index a826a4fb40..7f7d56bb45 100644 --- a/Task/Prime-decomposition/Erlang/prime-decomposition.erl +++ b/Task/Prime-decomposition/Erlang/prime-decomposition.erl @@ -4,6 +4,7 @@ factors(N) -> factors(N,2,[]). factors(1,_,Acc) -> Acc; +factors(N,K,Acc) when N < K*K -> [N|Acc]; factors(N,K,Acc) when N rem K == 0 -> factors(N div K,K, [K|Acc]); factors(N,K,Acc) -> diff --git a/Task/Prime-decomposition/Ring/prime-decomposition.ring b/Task/Prime-decomposition/Ring/prime-decomposition.ring index f6ddafa019..d4e39c1674 100644 --- a/Task/Prime-decomposition/Ring/prime-decomposition.ring +++ b/Task/Prime-decomposition/Ring/prime-decomposition.ring @@ -13,7 +13,7 @@ next func isPrime num if (num <= 1) return 0 ok - if (num % 2 = 0) return 0 ok + if (num % 2 = 0) and num != 2 return 0 ok for i = 3 to floor(num / 2) -1 step 2 if (num % i = 0) return 0 ok next diff --git a/Task/Prime-decomposition/Sidef/prime-decomposition-1.sidef b/Task/Prime-decomposition/Sidef/prime-decomposition-1.sidef index 958ff17ca0..8f02775fca 100644 --- a/Task/Prime-decomposition/Sidef/prime-decomposition-1.sidef +++ b/Task/Prime-decomposition/Sidef/prime-decomposition-1.sidef @@ -1,4 +1 @@ -require('ntheory') -func prime_factors(n) { - [%S.factor(n.to_s)] -} +say factor(536870911) #=> [233, 1103, 2089] diff --git a/Task/Prime-decomposition/Sidef/prime-decomposition-2.sidef b/Task/Prime-decomposition/Sidef/prime-decomposition-2.sidef index 855ed5d951..2ff6858375 100644 --- a/Task/Prime-decomposition/Sidef/prime-decomposition-2.sidef +++ b/Task/Prime-decomposition/Sidef/prime-decomposition-2.sidef @@ -1,18 +1,18 @@ func prime_factors(n) { - var p = 3; - var out = []; - return out if (n < 1); - while (!(n & 1)) { - n >>= 1; - out << 2; - } - while ((n > 1) && (p*p <= n)) { - while (n %% p) { - n /= p; - out << p; + return [] if (n < 1) + gather { + while (!(n & 1)) { + n >>= 1 + take(2) } - p += 2; + var p = 3 + while ((n > 1) && (p*p <= n)) { + while (n %% p) { + n //= p + take(p) + } + p += 2 + } + take(n) if (n > 1) } - out << n if (n > 1); - return out; } diff --git a/Task/Prime-decomposition/Sidef/prime-decomposition-3.sidef b/Task/Prime-decomposition/Sidef/prime-decomposition-3.sidef index a1175bde94..924665b724 100644 --- a/Task/Prime-decomposition/Sidef/prime-decomposition-3.sidef +++ b/Task/Prime-decomposition/Sidef/prime-decomposition-3.sidef @@ -1 +1 @@ -say prime_factors(536870911); +say prime_factors(536870911) #=> [233, 1103, 2089] diff --git a/Task/Prime-decomposition/Stata/prime-decomposition.stata b/Task/Prime-decomposition/Stata/prime-decomposition.stata new file mode 100644 index 0000000000..f862d6eff2 --- /dev/null +++ b/Task/Prime-decomposition/Stata/prime-decomposition.stata @@ -0,0 +1,26 @@ +function factor(n_) { + n = n_ + a = J(0,2,.) + if (n<2) { + return(a) + } + else if (n<4) { + return((n,1)) + } + else { + if (mod(n,2)==0) { + for (i=0; mod(n,2)==0; i++) n = floor(n/2) + a = a\(2,i) + } + + for (k=3; k*k<=n; k=k+2) { + if (mod(n,k)==0) { + for (i=0; mod(n,k)==0; i++) n = floor(n/k) + a = a\(k,i) + } + } + + if (n>1) a = a\(n,1) + return(a) + } +} diff --git a/Task/Priority-queue/C/priority-queue.c b/Task/Priority-queue/C/priority-queue.c index 00a7acebad..fab0de35f9 100644 --- a/Task/Priority-queue/C/priority-queue.c +++ b/Task/Priority-queue/C/priority-queue.c @@ -35,11 +35,14 @@ char *pop (heap_t *h) { return NULL; } char *data = h->nodes[1].data; + h->nodes[1] = h->nodes[h->len]; + h->len--; + i = 1; - while (1) { - k = i; + while (i!=h->len+1) { + k = h->len+1; j = 2 * i; if (j <= h->len && h->nodes[j].priority < h->nodes[k].priority) { k = j; @@ -47,13 +50,9 @@ char *pop (heap_t *h) { if (j + 1 <= h->len && h->nodes[j + 1].priority < h->nodes[k].priority) { k = j + 1; } - if (k == i) { - break; - } h->nodes[i] = h->nodes[k]; i = k; } - h->nodes[i] = h->nodes[h->len + 1]; return data; } diff --git a/Task/Priority-queue/Nim/priority-queue-2.nim b/Task/Priority-queue/Nim/priority-queue-2.nim index cd816c9b06..d1405d151b 100644 --- a/Task/Priority-queue/Nim/priority-queue-2.nim +++ b/Task/Priority-queue/Nim/priority-queue-2.nim @@ -1,18 +1,12 @@ -import tables +import HeapQueue -var - pq = initTable[int, string]() +var pq = newHeapQueue[(int, string)]() -proc main() = - pq.add(3, "Clear drains") - pq.add(4, "Feed cat") - pq.add(5, "Make tea") - pq.add(1, "Solve RC tasks") - pq.add(2, "Tax return") +pq.push((3, "Clear drains")) +pq.push((4, "Feed cat")) +pq.push((5, "Make tea")) +pq.push((1, "Solve RC tasks")) +pq.push((2, "Tax return")) - for i in countUp(1,5): - if pq.hasKey(i): - echo i, ": ", pq[i] - pq.del(i) - -main() +while pq.len() > 0: + echo pq.pop() diff --git a/Task/Priority-queue/Nim/priority-queue-3.nim b/Task/Priority-queue/Nim/priority-queue-3.nim new file mode 100644 index 0000000000..cd816c9b06 --- /dev/null +++ b/Task/Priority-queue/Nim/priority-queue-3.nim @@ -0,0 +1,18 @@ +import tables + +var + pq = initTable[int, string]() + +proc main() = + pq.add(3, "Clear drains") + pq.add(4, "Feed cat") + pq.add(5, "Make tea") + pq.add(1, "Solve RC tasks") + pq.add(2, "Tax return") + + for i in countUp(1,5): + if pq.hasKey(i): + echo i, ": ", pq[i] + pq.del(i) + +main() diff --git a/Task/Priority-queue/REXX/priority-queue-1.rexx b/Task/Priority-queue/REXX/priority-queue-1.rexx index 5f7dcde330..747420b9a2 100644 --- a/Task/Priority-queue/REXX/priority-queue-1.rexx +++ b/Task/Priority-queue/REXX/priority-queue-1.rexx @@ -1,5 +1,5 @@ -/*REXX program implements a priority queue; with insert/display/delete the top task. */ -#=0; @.= /*0 tasks; nullify the priority queue.*/ +/*REXX program implements a priority queue with insert/display/delete the top task.*/ +#=0; @.= /*0 tasks; nullify the priority queue.*/ say '══════ inserting tasks.'; call .ins 3 "Clear drains" call .ins 4 "Feed cat" call .ins 5 "Make tea" @@ -11,16 +11,12 @@ say '══════ showing tasks.'; call .show say '══════ deletes top task.'; say .del() /*delete the top task. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -.del: procedure expose @. #; parse arg p; if p=='' then p=.top(); x=@.p; @.p=; return x - /*delete the top task entry. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ +.del: procedure expose @. #; arg p; if p='' then p=.top(); y=@.p; @.p=; return y .ins: procedure expose @. #; #=#+1; @.#=arg(1); return # /*entry, P, task.*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -.show: procedure expose @. #; do j=1 for #; _=@.j; if _=='' then iterate; say _; end - return /* [↑] show whole list or just one. */ +.show: procedure expose @. #; do j=1 for #; _=@.j; if _\=='' then say _; end; return /*──────────────────────────────────────────────────────────────────────────────────────*/ .top: procedure expose @. #; top=; top#= - do j=1 for #; _=word(@.j,1); if _=='' then iterate - if top=='' | _>top then do; top=_; top#=j; end + do j=1 for #; _=word(@.j, 1); if _=='' then iterate + if top=='' | _>top then do; top=_; top#=j; end end /*j*/ return top# diff --git a/Task/Priority-queue/XLISP/priority-queue-1.xlisp b/Task/Priority-queue/XLISP/priority-queue-1.xlisp new file mode 100644 index 0000000000..d9e82eb357 --- /dev/null +++ b/Task/Priority-queue/XLISP/priority-queue-1.xlisp @@ -0,0 +1,35 @@ +(define-class priority-queue + (instance-variables queue lowest-priority most-urgent) ) + +(define-method (priority-queue 'initialize limit) + (defun setup (x) + (vector-set! queue x nil) + (if (< x limit) + (setup (+ x 1)) ) ) + (setq lowest-priority limit) + (setq most-urgent limit) + (setq queue (make-vector (+ limit 1))) + (setup 0) + self ) + +(define-method (priority-queue 'push item priority) + (if (and (integerp priority) (>= priority 0) (<= priority lowest-priority)) + (progn + (setq most-urgent (min priority most-urgent)) + (vector-set! queue priority (nconc (vector-ref queue priority) (cons item nil))) ) ) ) + +(define-method (priority-queue 'pop) + (defun find-next (q) + (if (or (= q lowest-priority) (not (null (vector-ref queue q)))) + q + (find-next (+ q 1)) ) ) + (define item (car (vector-ref queue most-urgent))) + (vector-set! queue most-urgent (cdr (vector-ref queue most-urgent))) + (setq most-urgent (find-next most-urgent)) + item ) + +(define-method (priority-queue 'peek) + (car (vector-ref queue most-urgent)) ) + +(define-method (priority-queue 'emptyp) + (and (= most-urgent lowest-priority) (null (vector-ref queue most-urgent))) ) diff --git a/Task/Priority-queue/XLISP/priority-queue-10.xlisp b/Task/Priority-queue/XLISP/priority-queue-10.xlisp new file mode 100644 index 0000000000..1f7ac18771 --- /dev/null +++ b/Task/Priority-queue/XLISP/priority-queue-10.xlisp @@ -0,0 +1,3 @@ +[13] (pq 'pop) + +() diff --git a/Task/Priority-queue/XLISP/priority-queue-2.xlisp b/Task/Priority-queue/XLISP/priority-queue-2.xlisp new file mode 100644 index 0000000000..a7304744fd --- /dev/null +++ b/Task/Priority-queue/XLISP/priority-queue-2.xlisp @@ -0,0 +1,7 @@ +(define pq (priority-queue 'new 5)) + +(pq 'push "Clear drains" 3) +(pq 'push "Feed cat" 4) +(pq 'push "Make tea" 5) +(pq 'push "Solve RC tasks" 1) +(pq 'push "Tax return" 2) diff --git a/Task/Priority-queue/XLISP/priority-queue-3.xlisp b/Task/Priority-queue/XLISP/priority-queue-3.xlisp new file mode 100644 index 0000000000..1d8808b2e3 --- /dev/null +++ b/Task/Priority-queue/XLISP/priority-queue-3.xlisp @@ -0,0 +1,6 @@ +[1] (pq 'pop) + +"Solve RC tasks" +[2] (pq 'pop) + +"Tax return" diff --git a/Task/Priority-queue/XLISP/priority-queue-4.xlisp b/Task/Priority-queue/XLISP/priority-queue-4.xlisp new file mode 100644 index 0000000000..4140d8cafb --- /dev/null +++ b/Task/Priority-queue/XLISP/priority-queue-4.xlisp @@ -0,0 +1,3 @@ +[3] (pq 'push "Answer emails" 4) + +("Feed cat" "Answer emails") diff --git a/Task/Priority-queue/XLISP/priority-queue-5.xlisp b/Task/Priority-queue/XLISP/priority-queue-5.xlisp new file mode 100644 index 0000000000..acba4bedad --- /dev/null +++ b/Task/Priority-queue/XLISP/priority-queue-5.xlisp @@ -0,0 +1,3 @@ +[4] (pq 'push "Weed garden" 17) + +() diff --git a/Task/Priority-queue/XLISP/priority-queue-6.xlisp b/Task/Priority-queue/XLISP/priority-queue-6.xlisp new file mode 100644 index 0000000000..7f681c5289 --- /dev/null +++ b/Task/Priority-queue/XLISP/priority-queue-6.xlisp @@ -0,0 +1,3 @@ +[5] (pq 'emptyp) + +() diff --git a/Task/Priority-queue/XLISP/priority-queue-7.xlisp b/Task/Priority-queue/XLISP/priority-queue-7.xlisp new file mode 100644 index 0000000000..8f71cb0e48 --- /dev/null +++ b/Task/Priority-queue/XLISP/priority-queue-7.xlisp @@ -0,0 +1,3 @@ +[6] (pq 'peek) + +"Clear drains" diff --git a/Task/Priority-queue/XLISP/priority-queue-8.xlisp b/Task/Priority-queue/XLISP/priority-queue-8.xlisp new file mode 100644 index 0000000000..94cd885afc --- /dev/null +++ b/Task/Priority-queue/XLISP/priority-queue-8.xlisp @@ -0,0 +1,8 @@ +[7] (pq 'show) + +Object is #, Class is # +Instance variables: + QUEUE = #(() () () ("Clear drains") ("Feed cat" "Answer emails") ("Make tea")) + LOWEST-PRIORITY = 5 + MOST-URGENT = 3 +# diff --git a/Task/Priority-queue/XLISP/priority-queue-9.xlisp b/Task/Priority-queue/XLISP/priority-queue-9.xlisp new file mode 100644 index 0000000000..64d77e6532 --- /dev/null +++ b/Task/Priority-queue/XLISP/priority-queue-9.xlisp @@ -0,0 +1,15 @@ +[8] (pq 'pop) + +"Clear drains" +[9] (pq 'pop) + +"Feed cat" +[10] (pq 'pop) + +"Answer emails" +[11] (pq 'pop) + +"Make tea" +[12] (pq 'emptyp) + +#T diff --git a/Task/Probabilistic-choice/REXX/probabilistic-choice.rexx b/Task/Probabilistic-choice/REXX/probabilistic-choice.rexx index 88b19523c3..3865fbe211 100644 --- a/Task/Probabilistic-choice/REXX/probabilistic-choice.rexx +++ b/Task/Probabilistic-choice/REXX/probabilistic-choice.rexx @@ -4,27 +4,30 @@ if trials=='' | trials=="," then trials=1000000 /*Not specified? Then use the if digs=='' | digs=="," then digs=15 /* " " " " " " */ if datatype(seed, 'W') then call random ,,seed /*allows repeatability for RANDOM nums.*/ numeric digits digs /*use a specific number of decimal digs*/ -names= 'aleph beth gimel daleth he waw zayin heth ───totals───►' /*names of cells.*/ -#= words(names) - 1; s=0 -HI=100000 - do n=1 for #-1; prob.n=1 / (n+4); Hprob.n=prob.n * HI; s=s + prob.n +names= 'aleph beth gimel daleth he waw zayin heth ───totals───►' /*names of the cells.*/ +HI=100000 /*max REXX RANDOM num*/ +z=words(names); #=z - 1 /*#≡the number of actual/useable names.*/ +$=0 /*initialize sum of the probabilities. */ + do n=1 for #; prob.n=1 / (n+4); if n==# then prob.n= 1759 / 27720 + $=$ + prob.n; Hprob.n=prob.n * HI end /*n*/ -!.=0 -prob.#=1759/27720; !.9=trials; Hprob.#=prob.# * HI; s=s + prob.# -prob.9=s - do j=1 for trials; r=random(1, HI) /*generate X number of random numbers.*/ +prob.z=$ /*define the value of the ───totals───.*/ +@.=0 /*initialize all counters in the range.*/ +@.z=trials /*define the last counter of " " */ + do j=1 for trials; r=random(HI) /*gen TRIAL number of random numbers.*/ do k=1 for # /*for each cell, compute percentages. */ - if r<=Hprob.k then !.k=!.k + 1 /* " " " range, bump the counter*/ + if r<=Hprob.k then @.k=@.k + 1 /* " " " range, bump the counter*/ end /*k*/ end /*j*/ -@= '═' /*@: a literal used for CENTER BIF pad*/ -w=digs +6 /*W: display width for the percentages*/ +_= '═' /*_: a literal used for CENTER BIF pad*/ +w=digs + 6 /*W: display width for the percentages*/ d=4 + max( length(trials), length('count') ) /* [↓] display a formatted top header.*/ -say center('name',15,@) center('count',d,@) center('target %',w,@) center('actual %',w,@) +say center('name',15,_) center('count',d,_) center('target %',w,_) center('actual %',w,_) - do i=1 for #+1 /*display each of the cells and totals.*/ - say ' ' left( word(names, i), 13) right(!.i, d-2) " ", - left( format( prob.i * 100, d), w-2), - left( format( !.i/trials * 100, d), w-2) - if i==# then say center(@,15,@) center(@,d,@) center(@,w,@) center(@,w,@) - end /*i*/ /*stick a fork in it, we are all done.*/ + do cell=1 for z /*display each of the cells and totals.*/ + say ' ' left( word(names, cell), 13) right(@.cell, d-2) " ", + left( format( prob.cell * 100, d), w-2), + left( format( @.cell/trials * 100, d), w-2) + if cell==# then say center(_,15,_) center(_,d,_) center(_,w,_) center(_,w,_) + end /*c*/ /* [↑] display a formatted foot header*/ + /*stick a fork in it, we are all done.*/ diff --git a/Task/Probabilistic-choice/Ring/probabilistic-choice.ring b/Task/Probabilistic-choice/Ring/probabilistic-choice.ring new file mode 100644 index 0000000000..a032b5a7a3 --- /dev/null +++ b/Task/Probabilistic-choice/Ring/probabilistic-choice.ring @@ -0,0 +1,25 @@ +# Project : Probabilistic choice +# Date : 2017/10/01 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +cnt = list(8) +item = ["aleph","beth","gimel","daleth","he","waw","zayin","heth"] +prob = [1/5.0, 1/6.0, 1/7.0, 1/8.0, 1/9.0, 1/10.0, 1/11.0, 1759/27720] + +for trial = 1 to 1000000 + r = random(10)/10 + p = 0 + for i = 1 to len(prob) + p = p + prob[i] + if r < p + cnt[i] = cnt[i] + 1 + loop + ok + next +next + +see "item actual theoretical" + nl +for i = 1 to len(item) + see "" + item[i] + " " + cnt[i]/1000000 + " " + prob[i] + nl +next diff --git a/Task/Probabilistic-choice/Rust/probabilistic-choice.rust b/Task/Probabilistic-choice/Rust/probabilistic-choice.rust new file mode 100644 index 0000000000..d43470c17f --- /dev/null +++ b/Task/Probabilistic-choice/Rust/probabilistic-choice.rust @@ -0,0 +1,127 @@ +extern crate rand; + +use rand::distributions::{IndependentSample, Sample, Weighted, WeightedChoice}; +use rand::{weak_rng, Rng}; + +const DATA: [(&str, f64); 8] = [ + ("aleph", 1.0 / 5.0), + ("beth", 1.0 / 6.0), + ("gimel", 1.0 / 7.0), + ("daleth", 1.0 / 8.0), + ("he", 1.0 / 9.0), + ("waw", 1.0 / 10.0), + ("zayin", 1.0 / 11.0), + ("heth", 1759.0 / 27720.0), +]; + +const SAMPLES: usize = 1_000_000; + +/// Generate a mapping to be used by `WeightedChoice` +fn gen_mapping() -> Vec> { + DATA.iter() + .enumerate() + .map(|(i, &(_, p))| Weighted { + // `WeightedChoice` requires `u32` weights rather than raw probabilities. For each + // probability, we convert it to a `u32` weight, and associate it with an index. We + // multiply by a constant because small numbers such as 0.2 when casted to `u32` + // become `0`. This conversion decreases the accuracy of the mapping, which is why we + // provide an implementation which uses `f64`s for the best accuracy. + weight: (p * 1_000_000_000.0) as u32, + item: i, + }) + .collect() +} + +/// Generate a mapping of the raw probabilities +fn gen_mapping_float() -> Vec { + // This does the work of `WeightedChoice::new`, splitting a number into various ranges. The + // `item` of `Weighted` is represented here merely by the probability's position in the `Vec`. + let mut running_total = 0.0; + DATA.iter() + .map(|&(_, p)| { + running_total += p; + running_total + }) + .collect() +} + +/// An implementation of `WeightedChoice` which uses probabilities rather than weights. Refer to +/// the `WeightedChoice` source for serious usage. +struct WcFloat { + mapping: Vec, +} + +impl WcFloat { + fn new(mapping: &[f64]) -> Self { + Self { + mapping: mapping.to_vec(), + } + } + + // This is roughly the same logic as `WeightedChoice::ind_sample` (though is likely slower) + fn search(&self, sample_prob: f64) -> usize { + let idx = self.mapping + .binary_search_by(|p| p.partial_cmp(&sample_prob).unwrap()); + match idx { + Ok(i) | Err(i) => i, + } + } +} + +impl IndependentSample for WcFloat { + fn ind_sample(&self, rng: &mut R) -> usize { + // Because we know the total is exactly 1.0, we can merely use a raw float value. + // Otherwise caching `Range::new(0.0, running_total)` and sampling with + // `range.ind_sample(&mut rng)` is recommended. + let sample_prob = rng.next_f64(); + self.search(sample_prob) + } +} + +impl Sample for WcFloat { + fn sample(&mut self, rng: &mut R) -> usize { + self.ind_sample(rng) + } +} + +fn take_samples(rng: &mut R, wc: &T) -> [usize; 8] +where + T: IndependentSample, +{ + let mut counts = [0; 8]; + for _ in 0..SAMPLES { + let sample = wc.ind_sample(rng); + counts[sample] += 1; + } + counts +} + +fn print_mapping(counts: &[usize]) { + println!("Item | Expected | Actual "); + println!("-------+----------+----------"); + for (&(name, expected), &count) in DATA.iter().zip(counts.iter()) { + let real = count as f64 / SAMPLES as f64; + println!("{:6} | {:.6} | {:.6}", name, expected, real); + } +} + +fn main() { + let mut rng = weak_rng(); + + println!(" ~~~ U32 METHOD ~~~"); + let mut mapping = gen_mapping(); + let wc = WeightedChoice::new(&mut mapping); + + let counts = take_samples(&mut rng, &wc); + print_mapping(&counts); + + println!(); + + println!(" ~~~ FLOAT METHOD ~~~"); + // initialize the float version of `WeightedChoice` + let mapping = gen_mapping_float(); + let wc = WcFloat::new(&mapping); + + let counts = take_samples(&mut rng, &wc); + print_mapping(&counts); +} diff --git a/Task/Probabilistic-choice/Stata/probabilistic-choice.stata b/Task/Probabilistic-choice/Stata/probabilistic-choice.stata new file mode 100644 index 0000000000..46bb343f0c --- /dev/null +++ b/Task/Probabilistic-choice/Stata/probabilistic-choice.stata @@ -0,0 +1,8 @@ +clear +mata +letters="aleph","beth","gimel","daleth","he","waw","zayin","heth" +a=letters[rdiscrete(10000,1,(1/5,1/6,1/7,1/8,1/9,1/10,1/11,1759/27720))]' +st_addobs(10000) +st_addvar("str10","a") +st_sstore(.,.,a) +end diff --git a/Task/Problem-of-Apollonius/Julia/problem-of-apollonius-1.julia b/Task/Problem-of-Apollonius/Julia/problem-of-apollonius-1.julia new file mode 100644 index 0000000000..d952ac4b83 --- /dev/null +++ b/Task/Problem-of-Apollonius/Julia/problem-of-apollonius-1.julia @@ -0,0 +1,51 @@ +module ApolloniusProblems + +using Polynomials +export Circle + +struct Point{T<:Real} + x::T + y::T +end + +xcoord(p::Point) = p.x +ycoord(p::Point) = p.y + +struct Circle{T<:Real} + c::Point{T} + r::T +end +Circle(x::T, y::T, r::T) where T<:Real = Circle(Point(x, y), r) + +radius(c::Circle) = c.r +center(c::Circle) = c.c +xcenter(c::Circle) = xcoord(center(c)) +ycenter(c::Circle) = ycoord(center(c)) + +Base.show(io::IO, c::Circle) = + @printf(io, "centered at (%0.4f, %0.4f) with radius %0.4f", + xcenter(c), ycenter(c), radius(c)) + +function solve(ap::Vector{Circle{T}}, enc=()) where T<:Real + length(ap) == 3 || error("This Apollonius problem needs 3 circles.") + x = @. xcenter(ap) + y = @. ycenter(ap) + r = map(u -> ifelse(u ∈ enc, -1, 1), 1:3) .* radius.(ap) + @views begin + a = 2x[1] .- 2x[2:3] + b = 2y[1] .- 2y[2:3] + c = 2r[1] .- 2r[2:3] + d = (x[1] ^ 2 + y[1] ^ 2 - r[1] ^ 2) .- (x[2:3] .^ 2 .+ y[2:3] .^ 2 .- r[2:3] .^ 2) + end + u = Poly([-det([b d]), det([b c])] ./ det([a b])) + v = Poly([det([a d]), -det([a c])] ./ det([a b])) + w = Poly([r[1], 1.0]) ^ 2 + s = (u - x[1]) ^ 2 + (v - y[1]) ^ 2 - w + r = filter(x -> iszero(imag(x)) && x > zero(x), roots(s)) + length(r) < 2 || error("The solution is not unique.") + length(r) == 1 || error("There is no solution.") + r = r[1] + return Circle(polyval(u, r), polyval(v, r), r) +end + +end # module ApolloniusProblem diff --git a/Task/Problem-of-Apollonius/Julia/problem-of-apollonius-2.julia b/Task/Problem-of-Apollonius/Julia/problem-of-apollonius-2.julia new file mode 100644 index 0000000000..a93714bd2a --- /dev/null +++ b/Task/Problem-of-Apollonius/Julia/problem-of-apollonius-2.julia @@ -0,0 +1,8 @@ +include("module.jl") +using ApolloniusProblems + +let test = [Circle(0.0, 0.0, 1.0), Circle(4.0, 0.0, 1.0), Circle(2.0, 4.0, 2.0)] + println("The defining circles are: \n - ", join(test, "\n - ")) + println("The internal circle is:\n\t", ApolloniusProblems.solve(test)) + println("The external circle is:\n\t", ApolloniusProblems.solve(test, 1:3)) +end diff --git a/Task/Problem-of-Apollonius/Julia/problem-of-apollonius.julia b/Task/Problem-of-Apollonius/Julia/problem-of-apollonius.julia deleted file mode 100644 index b50064af21..0000000000 --- a/Task/Problem-of-Apollonius/Julia/problem-of-apollonius.julia +++ /dev/null @@ -1,55 +0,0 @@ -using Polynomials - -immutable Point{T<:Real} - x::T - y::T -end - -immutable Circle{T<:Real} - c::Point{T} - r::T -end -Circle{T<:Real}(x::T, y::T, r::T) = Circle(Point(x,y), r) - -function apollonius{T<:Real}(ap::Array{Circle{T},1}, - enc::Array{Int,1}=Int[]) - length(ap) == 3 || error("This Apollonius problem needs 3 circles.") - x = map(u->u.c.x, ap) - y = map(u->u.c.y, ap) - r = map(u->u in enc ? -1 : 1, 1:3) .* map(u->u.r, ap) - a = 2x[1] - 2x[2:3] - b = 2y[1] - 2y[2:3] - c = 2r[1] - 2r[2:3] - d = (x[1]^2 + y[1]^2 - r[1]^2) - d -= (map(u->u^2, x) + map(u->u^2, y) - map(u->u^2, r))[2:3] - u = Poly([-det(hcat(b,d)), det(hcat(b,c))]/det(hcat(a,b))) - v = Poly([det(hcat(a,d)), -det(hcat(a,c))]/det(hcat(a,b))) - w = Poly([r[1], 1.0])^2 - s = (u - x[1])^2 + (v - y[1])^2 - w - r = filter(x->imag(x)==0 && 0
diff --git a/Task/Pythagorean-triples/360-Assembly/pythagorean-triples.360 b/Task/Pythagorean-triples/360-Assembly/pythagorean-triples.360 new file mode 100644 index 0000000000..34af874616 --- /dev/null +++ b/Task/Pythagorean-triples/360-Assembly/pythagorean-triples.360 @@ -0,0 +1,127 @@ +* Pythagorean triples - 12/06/2018 +PYTHTRI CSECT + USING PYTHTRI,R13 base register + B 72(R15) skip savearea + DC 17F'0' savearea + SAVE (14,12) save previous context + ST R13,4(R15) link backward + ST R15,8(R13) link forward + LR R13,R15 set addressability + MVC PMAX,=F'1' pmax=1 + LA R6,1 i=1 + DO WHILE=(C,R6,LE,=F'6') do i=1 to 6 + L R5,PMAX pmax + MH R5,=H'10' *10 + ST R5,PMAX pmax=pmax*10 + MVC PRIM,=F'0' prim=0 + MVC COUNT,=F'0' count=0 + L R1,PMAX pmax + BAL R14,ISQRT isqrt(pmax) + SRA R0,1 /2 + ST R0,NMAX nmax=isqrt(pmax)/2 + LA R7,1 n=1 + DO WHILE=(C,R7,LE,NMAX) do n=1 to nmax + LA R9,1(R7) m=n+1 + LR R5,R9 m + AR R5,R7 +n + MR R4,R9 *m + SLA R5,1 *2 + LR R8,R5 p=2*m*(m+n) + DO WHILE=(C,R8,LE,PMAX) do while p<=pmax + LR R1,R9 m + LR R2,R7 n + BAL R14,GCD gcd(m,n) + IF C,R0,EQ,=F'1' THEN if gcd(m,n)=1 then + L R2,PRIM prim + LA R2,1(R2) +1 + ST R2,PRIM prim=prim+1 + L R4,PMAX pmax + SRDA R4,32 ~ + DR R4,R8 /p + A R5,COUNT +count + ST R5,COUNT count=count+pmax/p + ENDIF , endif + LA R9,2(R9) m=m+2 + LR R5,R9 m + AR R5,R7 +n + MR R4,R9 *m + SLA R5,1 *2 + LR R8,R5 p=2*m*(m+n) + ENDDO , enddo n + LA R7,1(R7) n++ + ENDDO , enddo n + L R1,PMAX pmax + XDECO R1,XDEC edit pmax + MVC PG+15(9),XDEC+3 output pmax + L R1,COUNT count + XDECO R1,XDEC edit count + MVC PG+33(9),XDEC+3 output count + L R1,PRIM prim + XDECO R1,XDEC edit prim + MVC PG+55(9),XDEC+3 output prim + XPRNT PG,L'PG print + LA R6,1(R6) i++ + ENDDO , enddo i + L R13,4(0,R13) restore previous savearea pointer + RETURN (14,12),RC=0 restore registers from calling sav +NMAX DS F nmax +PMAX DS F pmax +COUNT DS F count +PRIM DS F prim +PG DC CL80'Max Perimeter: ........., Total: ........., Primitive:' +XDEC DS CL12 +GCD EQU * --------------- function gcd(a,b) + STM R2,R7,GCDSA save context + LR R3,R1 c=a + LR R4,R2 d=b +GCDLOOP LR R6,R3 c + SRDA R6,32 ~ + DR R6,R4 /d + LTR R6,R6 if c mod d=0 + BZ GCDELOOP then leave loop + LR R5,R6 e=c mod d + LR R3,R4 c=d + LR R4,R5 d=e + B GCDLOOP loop +GCDELOOP LR R0,R4 return(d) + LM R2,R7,GCDSA restore context + BR R14 return +GCDSA DS 6A context store +ISQRT EQU * --------------- function isqrt(n) + STM R3,R10,ISQRTSA save context + LR R6,R1 n=r1 + LR R10,R6 sqrtn=n + SRA R10,1 sqrtn=n/2 + IF LTR,R10,Z,R10 THEN if sqrtn=0 then + LA R10,1 sqrtn=1 + ELSE , else + LA R9,0 snm2=0 + LA R8,0 snm1=0 + LA R7,0 sn=0 + LA R3,0 okexit=0 + DO UNTIL=(C,R3,EQ,=A(1)) do until okexit=1 + AR R10,R7 sqrtn=sqrtn+sn + LR R9,R8 snm2=snm1 + LR R8,R7 snm1=sn + LR R4,R6 n + SRDA R4,32 ~ + DR R4,R10 /sqrtn + SR R5,R10 -sqrtn + SRA R5,1 /2 + LR R7,R5 sn=(n/sqrtn-sqrtn)/2 + IF C,R7,EQ,=F'0',OR,CR,R7,EQ,R9 THEN if sn=0 or sn=snm2 then + LA R3,1 okexit=1 + ENDIF , endif + ENDDO , enddo until + ENDIF , endif + LR R5,R10 sqrtn + MR R4,R10 *sqrtn + IF CR,R5,GT,R6 THEN if sqrtn*sqrtn>n then + BCTR R10,0 sqrtn=sqrtn-1 + ENDIF , endif + LR R0,R10 return(sqrtn) + LM R3,R10,ISQRTSA restore context + BR R14 return +ISQRTSA DS 8A context store + YREGS + END PYTHTRI diff --git a/Task/Pythagorean-triples/JavaScript/pythagorean-triples-1.js b/Task/Pythagorean-triples/JavaScript/pythagorean-triples-1.js index b1de50ddea..802a19943b 100644 --- a/Task/Pythagorean-triples/JavaScript/pythagorean-triples-1.js +++ b/Task/Pythagorean-triples/JavaScript/pythagorean-triples-1.js @@ -1,43 +1,55 @@ (() => { - - // concatMap :: (a -> [b]) -> [a] -> [b] - const concatMap = (f, xs) => [].concat.apply([], xs.map(f)); - - // range :: Int -> Int -> [Int] - const range = (m, n) => - Array.from({ - length: Math.floor(n - m) + 1 - }, (_, i) => m + i); - - // gcd :: Integral a => a -> a -> a - const gcd = (x, y) => { - const _gcd = (a, b) => (b === 0 ? a : _gcd(b, a % b)), - abs = Math.abs; - return _gcd(abs(x), abs(y)); - } + 'use strict'; // Arguments: predicate, maximum perimeter // pythTripleCount :: ((Int, Int, Int) -> Bool) -> Int -> Int const pythTripleCount = (p, maxPerim) => { - const xs = range(1, Math.floor(maxPerim / 2)); + const xs = enumFromTo(1, Math.floor(maxPerim / 2)); return concatMap(x => concatMap(y => concatMap(z => - ( (x + y + z <= maxPerim ) && - (x * x + y * y === z * z ) && - p(x, y, z) ) ? [ - [x, y, z] - ] : [ ], // concatMap eliminates empty lists - xs.slice(y)), xs.slice(x)), xs - ) - .length; + ((x + y + z <= maxPerim) && + (x * x + y * y === z * z) && + p(x, y, z)) ? [ + [x, y, z] + ] : [], // (Empty lists disappear under concatenation) + xs.slice(y)), xs.slice(x)), xs + ) + .length; }; + // GENERIC FUNCTIONS -------------------------------------- + + // concatMap :: (a -> [b]) -> [a] -> [b] + const concatMap = (f, xs) => + xs.length > 0 ? [].concat.apply([], xs.map(f)) : []; + + // enumFromTo :: Enum a => a -> a -> [a] + const enumFromTo = (m, n) => + (typeof m !== 'number' ? ( + enumFromToChar + ) : enumFromToInt) + .apply(null, [m, n]); + + // enumFromToInt :: Int -> Int -> [Int] + const enumFromToInt = (m, n) => + n >= m ? Array.from({ + length: Math.floor(n - m) + 1 + }, (_, i) => m + i) : []; + + // gcd :: Int -> Int -> Int + const gcd = (x, y) => { + const _gcd = (a, b) => (b === 0 ? a : _gcd(b, a % b)); + return _gcd(Math.abs(x), Math.abs(y)); + }; + + // MAIN --------------------------------------------------- return [10, 100, 1000] .map(n => ({ maxPerimeter: n, triples: pythTripleCount(x => true, n), primitives: pythTripleCount((x, y, _) => gcd(x, y) === 1, n) })); + })(); diff --git a/Task/Pythagorean-triples/Rust/pythagorean-triples.rust b/Task/Pythagorean-triples/Rust/pythagorean-triples.rust new file mode 100644 index 0000000000..138ab757b7 --- /dev/null +++ b/Task/Pythagorean-triples/Rust/pythagorean-triples.rust @@ -0,0 +1,46 @@ +use std::thread; + +fn f1 (a : u64, b : u64, c : u64, d : u64) -> u64 { + let mut primitive_count = 0; + for triangle in [[a - 2*b + 2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c], + [a + 2*b + 2*c, 2*a + b + 2*c, 2*a + 2*b + 3*c], + [2*b + 2*c - a, b + 2*c - 2*a, 2*b + 3*c - 2*a]] .iter() { + let l = triangle[0] + triangle[1] + triangle[2]; + if l > d { continue; } + primitive_count += 1 + f1(triangle[0], triangle[1], triangle[2], d); + } + primitive_count +} + +fn f2 (a : u64, b : u64, c : u64, d : u64) -> u64 { + let mut triplet_count = 0; + for triangle in [[a - 2*b + 2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c], + [a + 2*b + 2*c, 2*a + b + 2*c, 2*a + 2*b + 3*c], + [2*b + 2*c - a, b + 2*c - 2*a, 2*b + 3*c - 2*a]] .iter() { + let l = triangle[0] + triangle[1] + triangle[2]; + if l > d { continue; } + triplet_count += (d/l) + f2(triangle[0], triangle[1], triangle[2], d); + } + triplet_count +} + +fn main () { + let new_th_1 = thread::Builder::new().stack_size(32 * 1024 * 1024).spawn (move || { + let mut i = 100; + while i <= 100_000_000_000 { + println!(" Primitive triples below {} : {}", i, f1(3, 4, 5, i) + 1); + i *= 10; + } + }).unwrap(); + + let new_th_2 =thread::Builder::new().stack_size(32 * 1024 * 1024).spawn (move || { + let mut i = 100; + while i <= 100_000_000_000 { + println!(" Triples below {} : {}", i, f2(3, 4, 5, i) + i/12); + i *= 10; + } + }).unwrap(); + + new_th_1.join().unwrap(); + new_th_2.join().unwrap(); +} diff --git a/Task/QR-decomposition/C/qr-decomposition.c b/Task/QR-decomposition/C/qr-decomposition.c index 97aba43826..cf63ca5f7a 100644 --- a/Task/QR-decomposition/C/qr-decomposition.c +++ b/Task/QR-decomposition/C/qr-decomposition.c @@ -10,7 +10,7 @@ typedef struct { mat matrix_new(int m, int n) { mat x = malloc(sizeof(mat_t)); - x->v = malloc(sizeof(double) * m); + x->v = malloc(sizeof(double*) * m); x->v[0] = calloc(sizeof(double), m * n); for (int i = 0; i < m; i++) x->v[i] = x->v[0] + n * i; diff --git a/Task/Quaternion-type/Elena/quaternion-type.elena b/Task/Quaternion-type/Elena/quaternion-type.elena new file mode 100644 index 0000000000..8e942bcb5f --- /dev/null +++ b/Task/Quaternion-type/Elena/quaternion-type.elena @@ -0,0 +1,87 @@ +import system'math. +import extensions. + +struct Quaternion :: BaseValue +{ + real rprop A :: a. + real rprop B :: b. + real rprop C :: c. + real rprop D :: d. + + constructor new(object a, object b, object c, object d) + <= new(a real, b real, c real, d real). + + constructor new(real a, real b, real c, real d) + [ + @a := a. + @b := b. + @c := c. + @d := d. + ] + + stacksafe explicit(Real r) + [ + a := r. + b := 0.0r. + c := 0.0r. + d := 0.0r. + ] + + real Norm = (a*a + b*b + c*c + d*d) sqrt. + + type negative = Quaternion new(a negative,b negative,c negative,d negative). + + type Conjugate = Quaternion new(a,b negative,c negative,d negative). + + type add(Quaternion q) + = Quaternion new(a + q A, b + q B, c + q C, d + q D). + + type multiply(Quaternion q) + = Quaternion new( + a * q A - b * q B - c * q C - d * q D, + a * q B + b * q A + c * q D - d * q C, + a * q C - b * q D + c * q A + d * q B, + a * q D + b * q C - c * q B + d * q A). + + type add(real r) + <= add(Quaternion new(r,0,0,0)). + + type multiply(real r) + <= multiply(Quaternion new(r,0,0,0)). + + bool equal(Quaternion q) + = (a == q A) && (b == q B) && (c == q C) && (d == q D). + + literal + = String writeFormatted("Q({0}, {1}, {2}, {3})",a,b,c,d). +} + +program = +[ + var q := Quaternion new(1,2,3,4). + var q1 := Quaternion new(2,3,4,5). + var q2 := Quaternion new(3,4,5,6). + real r := 7. + + console printLine("q = ", q). + console printLine("q1 = ", q1). + console printLine("q2 = ", q2). + console printLine("r = ", r). + + console printLine("q.Norm() = ", q Norm). + console printLine("q1.Norm() = ", q1 Norm). + console printLine("q2.Norm() = ", q2 Norm). + + console printLine("-q = ", q negative). + console printLine("q.Conjugate() = ", q Conjugate). + + console printLine("q + r = ", q + r). + console printLine("q1 + q2 = ", q1 + q2). + console printLine("q2 + q1 = ", q2 + q1). + + console printLine("q * r = ", q * r). + console printLine("q1 * q2 = ", q1 * q2). + console printLine("q2 * q1 = ", q2 * q1). + + console printLineFormatted("q1*q2 {0} q2*q1", ((q1 * q2) == (q2 * q1)) iif("==","!=")). +]. diff --git a/Task/Quaternion-type/Rust/quaternion-type.rust b/Task/Quaternion-type/Rust/quaternion-type.rust new file mode 100644 index 0000000000..1a12b16296 --- /dev/null +++ b/Task/Quaternion-type/Rust/quaternion-type.rust @@ -0,0 +1,173 @@ +use std::fmt::{Display, Error, Formatter}; +use std::ops::{Add, Mul, Neg}; + +#[derive(Clone,Copy,Debug)] +struct Quaternion { + a: f64, + b: f64, + c: f64, + d: f64 +} + +impl Quaternion { + pub fn new(a: f64, b: f64, c: f64, d: f64) -> Quaternion { + Quaternion { + a: a, + b: b, + c: c, + d: d + } + } + + pub fn norm(&self) -> f64 { + (self.a.powi(2) + self.b.powi(2) + self.c.powi(2) + self.d.powi(2)).sqrt() + } + + pub fn conjugate(&self) -> Quaternion { + Quaternion { + a: self.a, + b: -self.b, + c: -self.c, + d: -self.d + } + } +} + +impl Add for Quaternion { + type Output = Quaternion; + + #[inline] + fn add(self, other: Quaternion) -> Self::Output { + Quaternion { + a: self.a + other.a, + b: self.b + other.b, + c: self.c + other.c, + d: self.d + other.d + } + } +} + +impl Add for Quaternion { + type Output = Quaternion; + + #[inline] + fn add(self, other: f64) -> Self::Output { + Quaternion { + a: self.a + other, + b: self.b, + c: self.c, + d: self.d + } + } +} + +impl Add for f64 { + type Output = Quaternion; + + #[inline] + fn add(self, other: Quaternion) -> Self::Output { + Quaternion { + a: other.a + self, + b: other.b, + c: other.c, + d: other.d + } + } +} + +impl Display for Quaternion { + fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { + write!(f, "({} + {}i + {}j + {}k)", self.a, self.b, self.c, self.d) + } +} + +impl Mul for Quaternion { + type Output = Quaternion; + + #[inline] + fn mul(self, rhs: Quaternion) -> Self::Output { + Quaternion { + a: self.a * rhs.a - self.b * rhs.b - self.c * rhs.c - self.d * rhs.d, + b: self.a * rhs.b + self.b * rhs.a + self.c * rhs.d - self.d * rhs.c, + c: self.a * rhs.c - self.b * rhs.d + self.c * rhs.a + self.d * rhs.b, + d: self.a * rhs.d + self.b * rhs.c - self.c * rhs.b + self.d * rhs.a, + } + } +} + +impl Mul for Quaternion { + type Output = Quaternion; + + #[inline] + fn mul(self, other: f64) -> Self::Output { + Quaternion { + a: self.a * other, + b: self.b * other, + c: self.c * other, + d: self.d * other + } + } +} + +impl Mul for f64 { + type Output = Quaternion; + + #[inline] + fn mul(self, other: Quaternion) -> Self::Output { + Quaternion { + a: other.a * self, + b: other.b * self, + c: other.c * self, + d: other.d * self + } + } +} + +impl Neg for Quaternion { + type Output = Quaternion; + + #[inline] + fn neg(self) -> Self::Output { + Quaternion { + a: -self.a, + b: -self.b, + c: -self.c, + d: -self.d + } + } +} + +fn main() { + let q0 = Quaternion { a: 1., b: 2., c: 3., d: 4. }; + let q1 = Quaternion::new(2., 3., 4., 5.); + let q2 = Quaternion::new(3., 4., 5., 6.); + let r: f64 = 7.; + + println!("q0 = {}", q0); + println!("q1 = {}", q1); + println!("q2 = {}", q2); + println!("r = {}", r); + println!(); + println!("-q0 = {}", -q0); + println!("conjugate of q0 = {}", q0.conjugate()); + println!(); + println!("r + q0 = {}", r + q0); + println!("q0 + r = {}", q0 + r); + println!(); + println!("r * q0 = {}", r * q0); + println!("q0 * r = {}", q0 * r); + println!(); + println!("q0 + q1 = {}", q0 + q1); + println!("q0 * q1 = {}", q0 * q1); + println!(); + println!("q0 * (conjugate of q0) = {}", q0 * q0.conjugate()); + println!(); + println!(" q0 + q1 * q2 = {}", q0 + q1 * q2); + println!("(q0 + q1) * q2 = {}", (q0 + q1) * q2); + println!(); + println!(" q0 * q1 * q2 = {}", q0 *q1 * q2); + println!("(q0 * q1) * q2 = {}", (q0 * q1) * q2); + println!(" q0 * (q1 * q2) = {}", q0 * (q1 * q2)); + println!(); + println!("normal of q0 = {}", q0.norm()); +} diff --git a/Task/Queue-Definition/Elena/queue-definition.elena b/Task/Queue-Definition/Elena/queue-definition.elena new file mode 100644 index 0000000000..3a5249ee62 --- /dev/null +++ b/Task/Queue-Definition/Elena/queue-definition.elena @@ -0,0 +1,62 @@ +import extensions. + +template queue :: type +{ + array theArray. + int theTop. + int theTale. + + explicit + [ + theArray := type<>(8). + theTop := 0. + theTale := 0. + ] + + bool empty + = theTop == theTale. + + push type:anObject + [ + if (theTale > theArray length) + [ + theArray := theArray reallocate(theTale). + ]. + + theArray[theTale] := anObject. + + theTale += 1. + ] + + type pop + [ + if (theTale == theTop) + [ InvalidOperationException new:"Queue is empty"; raise ]. + + type item := theArray[theTop]. + + theTop += 1. + + ^ item + ] +} + +program = +[ + queue q := queue(). + q push(1). + q push(2). + q push(3). + console printLine(q pop). + console printLine(q pop). + console printLine(q pop). + console printLine("a queue is ", q empty; iif("empty","not empty")). + console print("Trying to pop:"). + try(q pop) + { + on(Exception e) + [ + console printLine(e message) + ] + } +]. diff --git a/Task/Queue-Definition/Perl-6/queue-definition.pl6 b/Task/Queue-Definition/Perl-6/queue-definition.pl6 new file mode 100644 index 0000000000..a2e112674f --- /dev/null +++ b/Task/Queue-Definition/Perl-6/queue-definition.pl6 @@ -0,0 +1,31 @@ +role FIFO { + method enqueue ( *@values ) { # Add values to queue, returns the number of values added. + self.push: @values; + return @values.elems; + } + method dequeue ( ) { # Remove and return the first value from the queue. + # Return Nil if queue is empty. + return self.elems ?? self.shift !! Nil; + } + method is-empty ( ) { # Check to see if queue is empty. Returns Boolean value. + return self.elems == 0; + } +} + +# Example usage: + +my @queue does FIFO; + +say @queue.is-empty; # -> Bool::True +for
-> $i { say @queue.enqueue: $i } # 1 \n 1 \n 1 +say @queue.enqueue: Any; # -> 1 +say @queue.enqueue: 7, 8; # -> 2 +say @queue.is-empty; # -> Bool::False +say @queue.dequeue; # -> A +say @queue.elems; # -> 4 +say @queue.dequeue; # -> B +say @queue.is-empty; # -> Bool::False +say @queue.enqueue('OHAI!'); # -> 1 +say @queue.dequeue until @queue.is-empty; # -> C \n Any() \n [7 8] \n OHAI! +say @queue.is-empty; # -> Bool::True +say @queue.dequeue; # -> diff --git a/Task/Queue-Usage/Astro/queue-usage.astro b/Task/Queue-Usage/Astro/queue-usage.astro index 05f46159e8..0e2ab25d31 100644 --- a/Task/Queue-Usage/Astro/queue-usage.astro +++ b/Task/Queue-Usage/Astro/queue-usage.astro @@ -1,7 +1,7 @@ -let myQueue = Queue() +let myQueue = Queue[Str]() myQueue.push 'foo' myQueue.push 'bar' myQueue.push 'baz' -print myQueue.pop() # => 'foo' -print myQueue.pop() # => 'bar' -print myQueue.pop() # => 'baz' +print myQueue.pop() # 'foo' +print myQueue.pop() # 'bar' +print myQueue.pop() # 'baz' diff --git a/Task/Queue-Usage/Julia/queue-usage.julia b/Task/Queue-Usage/Julia/queue-usage.julia new file mode 100644 index 0000000000..2589d2f634 --- /dev/null +++ b/Task/Queue-Usage/Julia/queue-usage.julia @@ -0,0 +1,7 @@ +using DataStructures + +queue = Queue(String) +@show enqueue!(queue, "foo") +@show enqueue!(queue, "bar") +@show dequeue!(queue) # -> foo +@show dequeue!(queue) # -> bar diff --git a/Task/Quickselect-algorithm/Julia/quickselect-algorithm.julia b/Task/Quickselect-algorithm/Julia/quickselect-algorithm.julia new file mode 100644 index 0000000000..1aad7a1d4e --- /dev/null +++ b/Task/Quickselect-algorithm/Julia/quickselect-algorithm.julia @@ -0,0 +1,2 @@ +v = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] +@show v select(v, 1:10) diff --git a/Task/Quickselect-algorithm/Maple/quickselect-algorithm.maple b/Task/Quickselect-algorithm/Maple/quickselect-algorithm.maple new file mode 100644 index 0000000000..a53875be3a --- /dev/null +++ b/Task/Quickselect-algorithm/Maple/quickselect-algorithm.maple @@ -0,0 +1,36 @@ +part := proc(arr, left, right, pivot) + local val,safe,i: + val := arr[pivot]: + arr[pivot], arr[right] := arr[right], arr[pivot]: + safe := left: + for i from left to right do + if arr[i] < val then + arr[safe], arr[i] := arr[i], arr[safe]: + safe := safe + 1: + end if: + end do: + arr[right], arr[safe] := arr[safe], arr[right]: + return safe: +end proc: + +quickselect := proc(arr,k) + local pivot,left,right: + left,right := 1,numelems(arr): + while(true)do + if left = right then return arr[left]: end if: + pivot := trunc((left+right)/2); + pivot := part(arr, left, right, pivot): + if k = pivot then + return arr[k]: + elif k < pivot then + right := pivot-1: + else + left := pivot+1: + end if: + end do: +end proc: +roll := rand(1..20): +demo := Array([seq(roll(), i=1..20)]); +map(x->printf("%d ", x), demo): +print(quickselect(demo,7)): +print(quickselect(demo,14)): diff --git a/Task/Quickselect-algorithm/Ring/quickselect-algorithm.ring b/Task/Quickselect-algorithm/Ring/quickselect-algorithm.ring index bd0d15b1a7..c4a7828392 100644 --- a/Task/Quickselect-algorithm/Ring/quickselect-algorithm.ring +++ b/Task/Quickselect-algorithm/Ring/quickselect-algorithm.ring @@ -2,19 +2,19 @@ aList = [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] see partition(aList, 9, 4, 2) + nl func partition list, left, right, pivotIndex - pivotValue = list[pivotIndex] - temp = list[pivotIndex] - list[pivotIndex] = list[right] - list[right] = temp - storeIndex = left - for i = left to right-1 - if list[i] < pivotValue - temp = list[storeIndex] - list[storeIndex] = list[i] - list[i] = temp - storeIndex++ ok - temp = list[right] - list[right] = list[storeIndex] - list[storeIndex] = temp - next - return storeIndex + pivotValue = list[pivotIndex] + temp = list[pivotIndex] + list[pivotIndex] = list[right] + list[right] = temp + storeIndex = left + for i = left to right-1 + if list[i] < pivotValue + temp = list[storeIndex] + list[storeIndex] = list[i] + list[i] = temp + storeIndex++ ok + temp = list[right] + list[right] = list[storeIndex] + list[storeIndex] = temp + next + return storeIndex diff --git a/Task/Quine/JavaScript/quine-4.js b/Task/Quine/JavaScript/quine-4.js index bb3945e6e1..4ab4691499 100644 --- a/Task/Quine/JavaScript/quine-4.js +++ b/Task/Quine/JavaScript/quine-4.js @@ -1 +1 @@ -var a=function () {var b="var a="+a.toString()+"\;a()";alert(b)};a() +q=`%3Bconsole.log(%60q%3D%5C%60%24%7Bq%7D%5C%60%60%2BdecodeURIComponent(q))`;console.log(`q=\`${q}\``+decodeURIComponent(q)) diff --git a/Task/Quine/JavaScript/quine-5.js b/Task/Quine/JavaScript/quine-5.js index 2890fb95bf..bb3945e6e1 100644 --- a/Task/Quine/JavaScript/quine-5.js +++ b/Task/Quine/JavaScript/quine-5.js @@ -1,5 +1 @@ -(function f() { - - return '(' + f.toString() + ')();'; - -})(); +var a=function () {var b="var a="+a.toString()+"\;a()";alert(b)};a() diff --git a/Task/Quine/JavaScript/quine-7.js b/Task/Quine/JavaScript/quine-7.js index 4291e29f30..2890fb95bf 100644 --- a/Task/Quine/JavaScript/quine-7.js +++ b/Task/Quine/JavaScript/quine-7.js @@ -1,5 +1,5 @@ (function f() { - console.log('(' + f.toString() + ')();'); + return '(' + f.toString() + ')();'; })(); diff --git a/Task/Quine/JavaScript/quine-8.js b/Task/Quine/JavaScript/quine-8.js new file mode 100644 index 0000000000..4291e29f30 --- /dev/null +++ b/Task/Quine/JavaScript/quine-8.js @@ -0,0 +1,5 @@ +(function f() { + + console.log('(' + f.toString() + ')();'); + +})(); diff --git a/Task/Quine/MATLAB/quine-1.m b/Task/Quine/MATLAB/quine-1.m index 34101a0b09..bbd8cfc11e 100644 --- a/Task/Quine/MATLAB/quine-1.m +++ b/Task/Quine/MATLAB/quine-1.m @@ -1,7 +1 @@ - function quine() - fid = fopen([mfilename,'.m']); - while ~feof(fid) - printf('%s\n',fgetl(fid)); - end; - fclose(fid); - end; +x='{>\(y>(((-y-(((<(^= Vec::new(); /* ooer */ let mut x=r-1; let mut y=0; + let mut k=1;let mut j=1;let mut e=k -(r<<1);while x>=y{b.push((r+x,r+y));b.push((r+y,r+x)); b.push((r-y,r+x) + );b.push((r-x, r+y));b.push((r-x,r-y));b.push((r-y,r-x)); b.push((r+y,r-x));b.push((r+x,r-y)); if e<=0{ + y+=1;e+=j;j+=2;}if e>0 {x-=1;k+=2;e+=k-(r<<1);}}let mut t=q.iter();'o:for y in 1..r*2 { let l: Vec + = b.iter().filter(|x| x.1==y).map(|x| x.0).collect(); let x = l.iter().cloned().fold(0, + i32::max); let n =l.iter().cloned().fold(999, i32::min);let m=x-n; for _ in 0..n { print! + (" ");}for _ in 0..m{ if let Some(v) = t.next() {print!("{:02},",v);} else{ break + 'o; }} print!("\n"); } for n in q.iter() { print!("{}", (if *n==32{10} else + {*n+32}) as char);}print!("\n");} // github.com/kirjavascript diff --git a/Task/RIPEMD-160/Julia/ripemd-160.julia b/Task/RIPEMD-160/Julia/ripemd-160.julia index 3ca8c08da9..51bcf6de89 100644 --- a/Task/RIPEMD-160/Julia/ripemd-160.julia +++ b/Task/RIPEMD-160/Julia/ripemd-160.julia @@ -1,53 +1,24 @@ using Nettle -function ripemdsum(s::String) - bytes2hex(ripemd160_hash(s)) +labels = ["\"\" (empty string)", "\"a\"", "\"abc\"", + "\"message digest\"", "\"a...z\"", + "\"abcdbcde...nopq\"", "\"A...Za...z0...9\"", + "8 times \"1234567890\"", "1 million times \"a\""] +texts = ["", "a", "abc", "message digest", "abcdefghijklmnopqrstuvwxyz", + "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", + "1234567890" ^ 8, "a" ^ 1_000_000] +expects = ["9c1185a5c5e9fc54612808977ee8f548b2258d31", + "0bdc9d2d256b3ee9daae347be6f4dc835a467ffe", + "8eb208f7e05d987a9b044a8e98c6b087f15a0bfc", + "5d0689ef49d2fae572b881b123a85ffa21595f36", + "f71c27109c692c1b56bbdceb5b9d2865b3708dbc", + "12a053384a9c0c88e405a06c27dcf49ada62eb2b", + "b0e20b6e3116640286ed3a87a5713079b21f5189", + "9b752e45573d4b39f4dbd3323cab82bf63326bfb", + "52783243c1697bdbe16d37f97f68f08325dc1528"] + +for (lab, text, expect) in zip(labels, texts, expects) + digest = hexdigest("ripemd160", text) + println("# $lab\n -> digest: $digest\n -> expect: $expect") end - -mes = ["", "a", "abc", "message digest", "abcdefghijklmnopqrstuvwxyz", - "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"] - -h = ASCIIString[] -for s in mes - push!(h, ripemdsum(s)) -end -push!(h, ripemdsum("1234567890"^8)) -push!(h, ripemdsum("a"^10^6)) - -t = ["9c1185a5c5e9fc54612808977ee8f548b2258d31", - "0bdc9d2d256b3ee9daae347be6f4dc835a467ffe", - "8eb208f7e05d987a9b044a8e98c6b087f15a0bfc", - "5d0689ef49d2fae572b881b123a85ffa21595f36", - "f71c27109c692c1b56bbdceb5b9d2865b3708dbc", - "12a053384a9c0c88e405a06c27dcf49ada62eb2b", - "b0e20b6e3116640286ed3a87a5713079b21f5189", - "9b752e45573d4b39f4dbd3323cab82bf63326bfb", - "52783243c1697bdbe16d37f97f68f08325dc1528"] - -lab = ["\"\" (empty string)", "\"a\"", "\"abc\"", - "\"message digest\"", "\"a...z\"", - "\"abcdbcde...nopq\"", "\"A...Za...z0...9\"", - "8 times \"1234567890\"", "1 million times \"a\""] - -isok = t .== h - -println("Testing Julia's RIPEMD-160 hash against its test vectors.") -for i in 1:length(h) - print(@sprintf(" %20s => ", lab[i]), h[i], " ") - if isok[i] - println('\u263a') - else - println('\u26a0') - end -end - -if all(isok) - println("The function passes for all test vectors.\n") -else - println("The function fid not pass for all test vectors.\n") -end - -msg = "Rosetta Code" -h = ripemdsum(msg) -println(msg, " => ", h) diff --git a/Task/RSA-code/Java/rsa-code.java b/Task/RSA-code/Java/rsa-code.java new file mode 100644 index 0000000000..ec527ec23f --- /dev/null +++ b/Task/RSA-code/Java/rsa-code.java @@ -0,0 +1,27 @@ +public static void main(String[] args) { + /* + This is probably not the best method...or even the most optimized way...however it works since n and d are too big to be ints or longs + This was also only tested with 'Rosetta Code' and 'Hello World' + It's also pretty limited on plainText size (anything bigger than the above will fail) + */ + BigInteger n = new BigInteger("9516311845790656153499716760847001433441357"); + BigInteger e = new BigInteger("65537"); + BigInteger d = new BigInteger("5617843187844953170308463622230283376298685"); + Charset c = Charsets.UTF_8; + String plainText = "Rosetta Code"; + System.out.println("PlainText : " + plainText); + byte[] bytes = plainText.getBytes(); + BigInteger plainNum = new BigInteger(bytes); + System.out.println("As number : " + plainNum); + BigInteger Bytes = new BigInteger(bytes); + if (Bytes.compareTo(n) == 1) { + System.out.println("Plaintext is too long"); + return; + } + BigInteger enc = plainNum.modPow(e, n); + System.out.println("Encoded: " + enc); + BigInteger dec = enc.modPow(d, n); + System.out.println("Decoded: " + dec); + String decText = new String(dec.toByteArray(), c); + System.out.println("As text: " + decText); +} diff --git a/Task/RSA-code/Julia/rsa-code.julia b/Task/RSA-code/Julia/rsa-code.julia new file mode 100644 index 0000000000..aff7f460cf --- /dev/null +++ b/Task/RSA-code/Julia/rsa-code.julia @@ -0,0 +1,18 @@ +function rsaencode(clearmsg::AbstractString, nmod::Integer, expub::Integer) + bytes = parse(BigInt, "0x" * bytes2hex(collect(UInt8, clearmsg))) + return powermod(bytes, expub, nmod) +end + +function rsadecode(cryptmsg::Integer, nmod::Integer, dsecr::Integer) + decoded = powermod(encoded, dsecr, nmod) + return join(Char.(hex2bytes(hex(decoded)))) +end + +msg = "Rosetta Code." +nmod = big"9516311845790656153499716760847001433441357" +expub = 65537 +dsecr = big"5617843187844953170308463622230283376298685" + +encoded = rsaencode(msg, nmod, expub) +decoded = rsadecode(encoded, nmod, dsecr) +println("\n# $msg\n -> ENCODED: $encoded\n -> DECODED: $decoded") diff --git a/Task/Random-number-generator--device-/D/random-number-generator--device-.d b/Task/Random-number-generator--device-/D/random-number-generator--device-.d new file mode 100644 index 0000000000..dd5406cbd8 --- /dev/null +++ b/Task/Random-number-generator--device-/D/random-number-generator--device-.d @@ -0,0 +1,10 @@ +import std.stdio; +import std.random; + +void main() +{ + Mt19937 gen; + gen.seed(unpredictableSeed); + auto n = gen.front; + writeln(n); +} diff --git a/Task/Random-number-generator--device-/Rust/random-number-generator--device-.rust b/Task/Random-number-generator--device-/Rust/random-number-generator--device-.rust index 507a1263a9..57b01e073c 100644 --- a/Task/Random-number-generator--device-/Rust/random-number-generator--device-.rust +++ b/Task/Random-number-generator--device-/Rust/random-number-generator--device-.rust @@ -1,13 +1,14 @@ extern crate rand; -use rand::{Rng, OsRng}; +use rand::{OsRng, Rng}; fn main() { + // because `OsRng` opens files, it may fail let mut rng = match OsRng::new() { Ok(v) => v, Err(e) => panic!("Failed to obtain OS RNG: {}", e) }; - let rand_num:u32 = rng.next_u32(); - println!("{}",rand_num); + let rand_num: u32 = rng.gen(); + println!("{}", rand_num); } diff --git a/Task/Random-number-generator--device-/Scala/random-number-generator--device-.scala b/Task/Random-number-generator--device-/Scala/random-number-generator--device-.scala new file mode 100644 index 0000000000..8caa1730d9 --- /dev/null +++ b/Task/Random-number-generator--device-/Scala/random-number-generator--device-.scala @@ -0,0 +1,9 @@ +import java.security.SecureRandom + +object RandomExample extends App { + new SecureRandom { + val newSeed: Long = this.nextInt().toLong * this.nextInt() + this.setSeed(newSeed) // reseed using the previous 2 random numbers + println(this.nextInt()) // get random 32-bit number and print it + } +} diff --git a/Task/Random-number-generator--included-/Elena/random-number-generator--included-.elena b/Task/Random-number-generator--included-/Elena/random-number-generator--included-.elena new file mode 100644 index 0000000000..f760f5cc21 --- /dev/null +++ b/Task/Random-number-generator--included-/Elena/random-number-generator--included-.elena @@ -0,0 +1,7 @@ +import extensions. + +program = +[ + console printLine(randomGenerator nextReal). + console printLine(randomGenerator eval(0,100)). +]. diff --git a/Task/Random-numbers/Elena/random-numbers.elena b/Task/Random-numbers/Elena/random-numbers.elena new file mode 100644 index 0000000000..80767a4097 --- /dev/null +++ b/Task/Random-numbers/Elena/random-numbers.elena @@ -0,0 +1,32 @@ +import extensions. +import extensions'math. + +randomNormal = [ ^ mathControl cos(2 * pi_value * randomGenerator nextReal) + * mathControl sqrt(-2 * mathControl ln(randomGenerator nextReal)) ]. + +program = +[ + array a := real<>(1000). + + real tAvg := 0. + 0 till(a length) do(:x) + [ + a[x] := randomNormal() / 2 + 1. + tAvg += a[x]. + ]. + + tAvg /= a length. + console printLine("Average: ", tAvg). + + real s := 0. + 0 till(a length) do(:x) + [ + s += mathControl power(a[x] - tAvg, 2) + ]. + + s := mathControl sqrt(s / 1000). + + console printLine("Standard Deviation: ", s). + + console readChar. +]. diff --git a/Task/Random-numbers/Factor/random-numbers.factor b/Task/Random-numbers/Factor/random-numbers.factor index c9bf94312d..c00fed054f 100644 --- a/Task/Random-numbers/Factor/random-numbers.factor +++ b/Task/Random-numbers/Factor/random-numbers.factor @@ -1 +1,2 @@ +USING: random ; 1000 [ 1.0 0.5 normal-random-float ] replicate diff --git a/Task/Random-numbers/Go/random-numbers.go b/Task/Random-numbers/Go/random-numbers.go index a939a0eb8d..e563437edb 100644 --- a/Task/Random-numbers/Go/random-numbers.go +++ b/Task/Random-numbers/Go/random-numbers.go @@ -1,17 +1,46 @@ package main import ( + "fmt" + "math" "math/rand" + "strings" "time" ) const mean = 1.0 const stdv = .5 +const n = 1000 func main() { - var list [1000]float64 + var list [n]float64 rand.Seed(time.Now().UnixNano()) for i := range list { list[i] = mean + stdv*rand.NormFloat64() } + // show computed mean and stdv of list + var s, sq float64 + for _, v := range list { + s += v + } + cm := s / n + for _, v := range list { + d := v - cm + sq += d * d + } + fmt.Printf("mean %.3f, stdv %.3f\n", cm, math.Sqrt(sq/(n-1))) + // show histogram by hdiv divisions per stdv over +/-hrange stdv + const hdiv = 3 + const hrange = 2 + var h [1 + 2*hrange*hdiv]int + for _, v := range list { + bin := hrange*hdiv + int(math.Floor((v-mean)/stdv*hdiv+.5)) + if bin >= 0 && bin < len(h) { + h[bin]++ + } + } + const hscale = 10 + for _, c := range h { + fmt.Println(strings.Repeat("*", (c+hscale/2)/hscale)) + } } diff --git a/Task/Random-numbers/Haskell/random-numbers.hs b/Task/Random-numbers/Haskell/random-numbers-1.hs similarity index 100% rename from Task/Random-numbers/Haskell/random-numbers.hs rename to Task/Random-numbers/Haskell/random-numbers-1.hs diff --git a/Task/Random-numbers/Haskell/random-numbers-2.hs b/Task/Random-numbers/Haskell/random-numbers-2.hs new file mode 100644 index 0000000000..3672a0680d --- /dev/null +++ b/Task/Random-numbers/Haskell/random-numbers-2.hs @@ -0,0 +1 @@ +replicateM 1000 $ normal 1 0.5 diff --git a/Task/Random-numbers/Haskell/random-numbers-3.hs b/Task/Random-numbers/Haskell/random-numbers-3.hs new file mode 100644 index 0000000000..109bb32031 --- /dev/null +++ b/Task/Random-numbers/Haskell/random-numbers-3.hs @@ -0,0 +1,9 @@ +import Data.Random +import Control.Monad + +thousandRandomNumbers :: RVar [Double] +thousandRandomNumbers = replicateM 1000 $ normal 1 0.5 + +main = do + x <- sample thousandRandomNumbers + print x diff --git a/Task/Random-numbers/Lingo/random-numbers-1.lingo b/Task/Random-numbers/Lingo/random-numbers-1.lingo new file mode 100644 index 0000000000..872af0806e --- /dev/null +++ b/Task/Random-numbers/Lingo/random-numbers-1.lingo @@ -0,0 +1,5 @@ +-- Returns a random float value in range 0..1 +on randf () + n = random(the maxinteger)-1 + return n / float(the maxinteger-1) +end diff --git a/Task/Random-numbers/Lingo/random-numbers-2.lingo b/Task/Random-numbers/Lingo/random-numbers-2.lingo new file mode 100644 index 0000000000..6a1b5f8080 --- /dev/null +++ b/Task/Random-numbers/Lingo/random-numbers-2.lingo @@ -0,0 +1,4 @@ +normal = [] +repeat with i = 1 to 1000 + normal.add(1 + sqrt(-2 * log(randf())) * cos(2 * PI * randf()) / 2) +end repeat diff --git a/Task/Random-numbers/Scala/random-numbers.scala b/Task/Random-numbers/Scala/random-numbers-1.scala similarity index 100% rename from Task/Random-numbers/Scala/random-numbers.scala rename to Task/Random-numbers/Scala/random-numbers-1.scala diff --git a/Task/Random-numbers/Scala/random-numbers-2.scala b/Task/Random-numbers/Scala/random-numbers-2.scala new file mode 100644 index 0000000000..a027e1a19c --- /dev/null +++ b/Task/Random-numbers/Scala/random-numbers-2.scala @@ -0,0 +1,25 @@ +val distrubution = { + def randomNormal = 1.0 + 0.5 * scala.util.Random.nextGaussian + + def normalDistribution(a: Double): Stream[Double] = a #:: normalDistribution(randomNormal) + + normalDistribution(randomNormal) +} + +/* + * Let's test it + */ + def calcAvgAndStddev[T](ts: Iterable[T])(implicit num: Fractional[T]): (T, Double) = { + val mean: T = + num.div(ts.sum, num.fromInt(ts.size)) // Leaving with type of function T + + // Root of mean diffs + val stdDev = sqrt(ts.map { x => + val diff = num.toDouble(num.minus(x, mean)) + diff * diff + }.sum / ts.size) + + (mean, stdDev) + } + +println(calcAvgAndStddev(distrubution.take(1000))) // e.g. (1.0061433267806525,0.5291834867560893) diff --git a/Task/Random-numbers/Standard-ML/random-numbers-3.ml b/Task/Random-numbers/Standard-ML/random-numbers-3.ml new file mode 100644 index 0000000000..19fee754e8 --- /dev/null +++ b/Task/Random-numbers/Standard-ML/random-numbers-3.ml @@ -0,0 +1,36 @@ +val urandomlist = fn seed => fn n => +let + val uniformdeviate = fn seed => + let + val in31m = (Real.fromInt o Int32.toInt ) (getOpt (Int32.maxInt,0) ); + val in31 = in31m +1.0; + val s1 = 41160.0; + val s2 = 950665216.0; + val v = Real.realFloor seed; + val val1 = v*s1; + val val2 = v*s2; + val next1 = Real.fromLargeInt (Real.toLargeInt IEEEReal.TO_NEGINF (val1/in31)) ; + val next2 = Real.rem(Real.realFloor(val2/in31) , in31m ); + val valt = val1+val2 - (next1+next2)*in31m; + val nextt = Real.realFloor(valt/in31m); + val valt = valt - nextt*in31m; + in + (valt/in31m,valt) + end; +val store = ref (0.0,0.0); +val rec u = fn S => fn 0 => [] | n=> (store:=uniformdeviate S; (#1 (!store)):: (u (#2 (!store)) (n-1))) ; +in + u seed n +end; + +local + open Math +in + val bmconv = fn urand => fn vrand => 1.0+0.5*(sqrt(~2.0*ln urand)*cos (2.0*pi*vrand) ) +end; + +val rec makeNormals = fn once => fn u::v::[] => [once u v] | + u::v::rm => (once u v )::(makeNormals once rm ); + +val anyrealseed=1009.0 ; +makeNormals bmconv (urandomlist anyrealseed 2000); diff --git a/Task/Random-numbers/Stata/random-numbers.stata b/Task/Random-numbers/Stata/random-numbers-1.stata similarity index 100% rename from Task/Random-numbers/Stata/random-numbers.stata rename to Task/Random-numbers/Stata/random-numbers-1.stata diff --git a/Task/Random-numbers/Stata/random-numbers-2.stata b/Task/Random-numbers/Stata/random-numbers-2.stata new file mode 100644 index 0000000000..c0cd7a0006 --- /dev/null +++ b/Task/Random-numbers/Stata/random-numbers-2.stata @@ -0,0 +1 @@ +a = rnormal(1000,1,1,0.5) diff --git a/Task/Range-expansion/Ring/range-expansion.ring b/Task/Range-expansion/Ring/range-expansion.ring new file mode 100644 index 0000000000..a1c7147d6c --- /dev/null +++ b/Task/Range-expansion/Ring/range-expansion.ring @@ -0,0 +1,44 @@ +# Project : Range expansion +# Date : 2017/11/08 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : + +int = "-6,-3--1,3-5,7-11,14,15,17-20" +int = str2list(substr(int, ",", nl)) +newint = [] +for n=1 to len(int) + nrint = substr(int[n], "-") + nrint2 = substr(int[n], "--") + if nrint2 > 0 + temp1 = left(int[n], nrint2 -1) + temp2 = right(int[n], len(int[n]) - nrint2) + add(newint, [temp1,temp2]) + else + if len(int[n]) <= 2 + add(newint, [int[n], ""]) + else + if nrint > 0 and nrint2 = 0 + temp1 = left(int[n], nrint - 1) + temp2 = right(int[n], len(int[n]) - nrint) + add(newint, [temp1,temp2]) + ok + ok + ok +next +showarray(newint) + +func showarray(vect) + see "[" + svect = "" + for n = 1 to len(vect) + if newint[n][2] != "" + for nr = newint[n][1] to newint[n][2] + svect = svect +"" + nr + ", " + next + else + svect = svect +"" + newint[n][1] + ", " + ok + next + svect = left(svect, len(svect) - 2) + see svect + see "]" + nl diff --git a/Task/Range-extraction/Clojure/range-extraction.clj b/Task/Range-extraction/Clojure/range-extraction.clj new file mode 100644 index 0000000000..91f63c1ae4 --- /dev/null +++ b/Task/Range-extraction/Clojure/range-extraction.clj @@ -0,0 +1,16 @@ +(use '[flatland.useful.seq :only (partition-between)]) + +(defn nonconsecutive? [[x y]] + (not= (inc x) y)) + +(defn string-ranges [coll] + (let [left (first coll) + size (count coll)] + (cond + (> size 2) (str left "-" (last coll)) + (= size 2) (str left "," (last coll)) + :else (str left)))) + +(defn format-with-ranges [coll] + (println (clojure.string/join "," + (map string-ranges (partition-between nonconsecutive? coll))))) diff --git a/Task/Range-extraction/Factor/range-extraction.factor b/Task/Range-extraction/Factor/range-extraction.factor new file mode 100644 index 0000000000..04cd8b173f --- /dev/null +++ b/Task/Range-extraction/Factor/range-extraction.factor @@ -0,0 +1,18 @@ +USING: formatting io kernel math math.parser sequences +splitting.monotonic ; +IN: rosetta-code.range-extraction + +: make-range ( seq -- str ) + [ first ] [ last ] bi "%d-%d" sprintf ; + +: make-atomic ( seq -- str ) [ number>string ] map "," join ; + +: extract-range ( seq -- str ) + [ - -1 = ] monotonic-split + [ dup length 2 > [ make-range ] [ make-atomic ] if ] map + "," join ; + +{ + 0 1 2 4 6 7 8 11 12 14 15 16 17 18 19 20 21 22 + 23 24 25 27 28 29 30 31 32 33 35 36 37 38 39 +} extract-range print diff --git a/Task/Range-extraction/Ring/range-extraction.ring b/Task/Range-extraction/Ring/range-extraction.ring new file mode 100644 index 0000000000..95bccc3895 --- /dev/null +++ b/Task/Range-extraction/Ring/range-extraction.ring @@ -0,0 +1,46 @@ +# Project : Range extraction +# Date : 2017/11/08 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : + +int = "0,1,2,4,6,7,8,11,12,14,15,16,17,18,19,20,21,22,23,24,25,27,28,29,30,31,32,33,35,36,37,38,39" +int = str2list(substr(int, ",", nl)) +sumint = [] +intnew = 1 +for n=1 to len(int) + flag = 0 + nr = 0 + intnew = 0 + for m=n to len(int)-1 + if int[m] = int[m+1] - 1 + intnew = m+1 + flag = 1 + nr = nr + 1 + else + exit + ok + next + if flag = 1 and nr > 1 + if intnew != 0 + add(sumint, [n,intnew]) + n = m + ok + else + add(sumint, [n,""]) + ok +next +showarray(sumint) + +func showarray(vect) + see "[" + svect = "" + for n = 1 to len(vect) + if vect[n][2] != "" + svect = svect +"" + int[vect[n][1]] + "-" + int[vect[n][2]] + ", " + else + svect = svect +"" + int[vect[n][1]] + ", " + ok + next + svect = left(svect, len(svect) - 2) + see svect + see "]" + nl diff --git a/Task/Range-extraction/Rust/range-extraction-1.rust b/Task/Range-extraction/Rust/range-extraction-1.rust index 621ebeeae3..71324b4363 100644 --- a/Task/Range-extraction/Rust/range-extraction-1.rust +++ b/Task/Range-extraction/Rust/range-extraction-1.rust @@ -6,7 +6,7 @@ struct RangeFinder<'a, T: 'a> { arr: &'a [T], } -impl<'a, T> Iterator for RangeFinder<'a, T> where T: PartialEq + Add + Copy { +impl<'a, T> Iterator for RangeFinder<'a, T> where T: PartialEq + Add + Copy { type Item = (T, Option); fn next(&mut self) -> Option { if self.index == self.length { @@ -40,10 +40,12 @@ impl<'a, T> RangeFinder<'a, T> { } fn main() { - let n = [0,1,2,3]; - - for (i, (lo, hi)) in RangeFinder::new(&n).enumerate() { - if i > 0 {print!(", ")} + let input_numbers : &[i8] = &[0, 1, 2, 4, 6, 7, 8, 11, 12, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, + 37, 38, 39]; + for (i, (lo, hi)) in RangeFinder::new(&input_numbers).enumerate() { + if i > 0 {print!(",")} print!("{}", lo); if hi.is_some() {print!("-{}", hi.unwrap())} } diff --git a/Task/Range-extraction/Rust/range-extraction-3.rust b/Task/Range-extraction/Rust/range-extraction-3.rust index 00e96f973f..ce3afda70e 100644 --- a/Task/Range-extraction/Rust/range-extraction-3.rust +++ b/Task/Range-extraction/Rust/range-extraction-3.rust @@ -1 +1 @@ - impl<'a, T> Iterator for RangeFinder<'a, T> where T: PartialEq + Add + Copy { + impl<'a, T> Iterator for RangeFinder<'a, T> where T: PartialEq + Add + Copy { diff --git a/Task/Ranking-methods/C/ranking-methods.c b/Task/Ranking-methods/C/ranking-methods.c new file mode 100644 index 0000000000..e48fa469a7 --- /dev/null +++ b/Task/Ranking-methods/C/ranking-methods.c @@ -0,0 +1,119 @@ +/*Abhishek Ghosh, 5th November 2017*/ + +#include +#include + +typedef struct{ + int score; + char name[100]; +}entry; + +void ordinalRanking(entry* list,int len){ + + int i; + + printf("\n\nOrdinal Ranking\n---------------"); + + for(i=0;i"); + else + processFile(argV[1]); + return 0; +} diff --git a/Task/Ranking-methods/D/ranking-methods.d b/Task/Ranking-methods/D/ranking-methods.d new file mode 100644 index 0000000000..7f68dfcb72 --- /dev/null +++ b/Task/Ranking-methods/D/ranking-methods.d @@ -0,0 +1,167 @@ +import std.algorithm; +import std.stdio; + +void main() { + immutable scores = [ + "Solomon": 44, + "Jason": 42, + "Errol": 42, + "Garry": 41, + "Bernard": 41, + "Barry": 41, + "Stephen": 39 + ]; + + scores.standardRank; + scores.modifiedRank; + scores.denseRank; + scores.ordinalRank; + scores.fractionalRank; +} + +/* +Standard ranking +1 44 Solomon +2 42 Jason +2 42 Errol +4 41 Garry +4 41 Bernard +4 41 Barry +7 39 Stephen +*/ +void standardRank(const int[string] data) { + writeln("Standard Rank"); + + int rank = 1; + foreach (value; data.values.dup.sort!"a>b".uniq) { + int temp = rank; + foreach(k,v; data) { + if (v==value) { + writeln(temp, " ", v, " ", k); + rank++; + } + } + } + + writeln; +} + +/* +Modified ranking +1 44 Solomon +3 42 Jason +3 42 Errol +6 41 Garry +6 41 Bernard +6 41 Barry +7 39 Stephen +*/ +void modifiedRank(const int[string] data) { + writeln("Modified Rank"); + + int rank = 0; + foreach (value; data.values.dup.sort!"a>b".uniq) { + foreach(k,v; data) { + if (v==value) { + rank++; + } + } + foreach(k,v; data) { + if (v==value) { + writeln(rank, " ", v, " ", k); + } + } + } + + writeln; +} + +/* +Dense ranking +1 44 Solomon +2 42 Jason +2 42 Errol +3 41 Garry +3 41 Bernard +3 41 Barry +4 39 Stephen +*/ +void denseRank(const int[string] data) { + writeln("Dense Rank"); + + int rank = 1; + foreach (value; data.values.dup.sort!"a>b".uniq) { + foreach(k,v; data) { + if (v==value) { + writeln(rank, " ", v, " ", k); + } + } + rank++; + } + + writeln; +} + +/* +Ordinal ranking +1 44 Solomon +2 42 Jason +3 42 Errol +4 41 Garry +5 41 Bernard +6 41 Barry +7 39 Stephen +*/ +void ordinalRank(const int[string] data) { + writeln("Ordinal Rank"); + + int rank = 1; + foreach (value; data.values.dup.sort!"a>b".uniq) { + foreach(k,v; data) { + if (v==value) { + writeln(rank, " ", v, " ", k); + rank++; + } + } + } + + writeln; +} + +/* +Fractional ranking +1,0 44 Solomon +2,5 42 Jason +2,5 42 Errol +5,0 41 Garry +5,0 41 Bernard +5,0 41 Barry +7,0 39 Stephen +*/ +void fractionalRank(const int[string] data) { + writeln("Fractional Rank"); + + int rank = 0; + foreach (value; data.values.dup.sort!"a>b".uniq) { + real avg = 0; + int cnt; + + foreach(k,v; data) { + if (v==value) { + rank++; + cnt++; + avg+=rank; + } + } + avg /= cnt; + + foreach(k,v; data) { + if (v==value) { + writef("%0.1f ", avg); + writeln(v, " ", k); + } + } + } + + writeln; +} diff --git a/Task/Rate-counter/D/rate-counter.d b/Task/Rate-counter/D/rate-counter.d new file mode 100644 index 0000000000..7fb934e336 --- /dev/null +++ b/Task/Rate-counter/D/rate-counter.d @@ -0,0 +1,20 @@ +import std.stdio; +import std.conv; +import std.datetime.stopwatch; + +int a; +void f0() {} +void f1() { auto b = a; } +void f2() { auto b = to!string(a); } + + +void main() +{ + auto r = benchmark!(f0, f1, f2)(10_000); + + writeln("Time fx took to run 10,000 times:\n"); + writeln("f0: ", r[0]); + writeln("f1: ", r[1]); + writeln("f2: ", r[2]); + +} diff --git a/Task/Ray-casting-algorithm/00DESCRIPTION b/Task/Ray-casting-algorithm/00DESCRIPTION index 07d41afbd2..a0dedd38cb 100644 --- a/Task/Ray-casting-algorithm/00DESCRIPTION +++ b/Task/Ray-casting-algorithm/00DESCRIPTION @@ -47,7 +47,7 @@ An algorithm for the previous speech could be (if P is a point, Px is its x coor '''end''' '''if''' '''if''' Py < Ay '''or''' Py > By '''then''' '''return''' false - '''else''' '''if''' Px > max(Ax, Bx) '''then''' + '''else''' '''if''' Px >= max(Ax, Bx) '''then''' '''return''' false '''else''' '''if''' Px < min(Ax, Bx) '''then''' diff --git a/Task/Ray-casting-algorithm/Java/ray-casting-algorithm.java b/Task/Ray-casting-algorithm/Java/ray-casting-algorithm.java index aa2e3185f8..45d1dbcd94 100644 --- a/Task/Ray-casting-algorithm/Java/ray-casting-algorithm.java +++ b/Task/Ray-casting-algorithm/Java/ray-casting-algorithm.java @@ -9,7 +9,7 @@ public class RayCasting { if (P[1] == A[1] || P[1] == B[1]) P[1] += 0.0001; - if (P[1] > B[1] || P[1] < A[1] || P[0] > max(A[0], B[0])) + if (P[1] > B[1] || P[1] < A[1] || P[0] >= max(A[0], B[0])) return false; if (P[0] < min(A[0], B[0])) diff --git a/Task/Ray-casting-algorithm/Julia/ray-casting-algorithm-1.julia b/Task/Ray-casting-algorithm/Julia/ray-casting-algorithm-1.julia new file mode 100644 index 0000000000..38aa4f5ed5 --- /dev/null +++ b/Task/Ray-casting-algorithm/Julia/ray-casting-algorithm-1.julia @@ -0,0 +1,45 @@ +module RayCastings + +export Point + +struct Point{T} + x::T + y::T +end +Base.show(io::IO, p::Point) = print(io, "($(p.x), $(p.y))") + +const Edge = Tuple{Point{T}, Point{T}} where T +Base.show(io::IO, e::Edge) = print(io, "$(e[1]) ∘-∘ $(e[2])") + +function rayintersectseg(p::Point{T}, edge::Edge{T}) where T + a, b = edge + if a.y > b.y + a, b = b, a + end + if p.y ∈ (a.y, b.y) + p = Point(p.x, p.y + eps(p.y)) + end + + rst = false + if (p.y > b.y || p.y < a.y) || (p.x > max(a.x, b.x)) + return false + end + + if p.x < min(a.x, b.x) + rst = true + else + mred = (b.y - a.y) / (b.x - a.x) + mblu = (p.y - a.y) / (p.x - a.x) + rst = mblu ≥ mred + end + + return rst +end + +isinside(poly::Vector{Tuple{Point{T}, Point{T}}}, p::Point{T}) where T = + isodd(count(edge -> rayintersectseg(p, edge), poly)) + +connect(a::Point{T}, b::Point{T}...) where T = + [(a, b) for (a, b) in zip(vcat(a, b...), vcat(b..., a))] + +end # module RayCastings diff --git a/Task/Ray-casting-algorithm/Julia/ray-casting-algorithm-2.julia b/Task/Ray-casting-algorithm/Julia/ray-casting-algorithm-2.julia new file mode 100644 index 0000000000..0e6355da3b --- /dev/null +++ b/Task/Ray-casting-algorithm/Julia/ray-casting-algorithm-2.julia @@ -0,0 +1,31 @@ +let A = Point(0.0, 0.0), + B = Point(0.0, 10.0), + C = Point(10.0, 10.0), + D = Point(10.0, 0.0), + E = Point(2.5, 2.5), + F = Point(2.5, 7.5), + G = Point(7.5, 7.5), + H = Point(7.5, 2.5), + I = Point(3.0, 0.0), + J = Point(7.0, 0.0), + K = Point(10.0, 5.0), + L = Point(7.0, 10.0), + M = Point(3.0, 10.0), + N = Point(0.0, 5.0), + testpts = (Point(5.0, 5.0), Point(5.0, 8.0), Point(-10.0, 5.0), Point(0.0, 5.0), + Point(10.0, 5.0), Point(8.0, 5.0), Point(10.0, 10.0)) + + square = RayCastings.connect(A, B, C, D) + square_withhole = vcat(square, RayCastings.connect(E, F, G, H)) + strange = RayCastings.connect(A, E, B, F, G, C, D, E) + exagon = RayCastings.connect(I, J, K, L, M, N) + + println("\n# TESTING WHETHER POINTS ARE WITHIN POLYGONS") + for poly in (square, square_withhole, strange, exagon) + println("\nEdges: \n - ", join(poly, "\n - ")) + println("Inside/outside:") + for p in testpts + @printf(" - %-12s is %s\n", p, RayCastings.isinside(poly, p) ? "inside" : "outside") + end + end +end diff --git a/Task/Ray-casting-algorithm/REXX/ray-casting-algorithm.rexx b/Task/Ray-casting-algorithm/REXX/ray-casting-algorithm.rexx index 3c3baaf861..c72f9ca161 100644 --- a/Task/Ray-casting-algorithm/REXX/ray-casting-algorithm.rexx +++ b/Task/Ray-casting-algorithm/REXX/ray-casting-algorithm.rexx @@ -7,45 +7,44 @@ call poly 0 0, A A, 0 10, A B, B B, 10 10, 10 0 ; call test 'ir call poly 3 0, 7 0, 10 5, 7 10, 3 10, 0 5 ; call test 'hexagon' exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -in$out: procedure expose point. poly.; parse arg p; #=0 - do side=1 to poly.0 by 2; #=#+intersect(p,side); end /*side*/ +in$out: procedure expose point. poly.; parse arg p; #=0 + do side=1 to poly.0 by 2; #=# +intersect(p, side); end /*side*/ return # // 2 /*ODD is inside. EVEN is outside.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ -intersect: procedure expose point. poly.; parse arg ?,s; sp=s+1 - epsilon='1e' || (-digits()%2); infinity="1e" || (digits() *2) - Px=point.?.x; Ax=poly.s.x; Ay=poly.s.y - Py=point.?.y; Bx=poly.sp.x; By=poly.sp.y /* [↓] do a swap.*/ +intersect: procedure expose point. poly.; parse arg ?,s; sp=s + 1 + epsilon= '1e' || (-digits() %2); infinity= "1e" || (digits() *2) + Px=point.?.x; Ax=poly.s.x; Bx=poly.sp.x + Py=point.?.y; Ay=poly.s.y; By=poly.sp.y /* [↓] do a vertex swap*/ if Ay>By then parse value Ax Ay Bx By with Bx By Ax Ay if Py=Ay | Py=By then Py=Py + epsilon - if PyBy | Px>max(Ax,Bx) then return 0 - if Px= m_red + if PyBy | Px>max(Ax, Bx) then return 0 + if Px= red + return 1 /*──────────────────────────────────────────────────────────────────────────────────────*/ -points: wx=0; wy=0; do j=1 for arg(); parse value arg(j) with xx yy - wx=max(wx, length(xx) ); call value 'POINT.'j".X", xx - wy=max(wy, length(yy) ); call value 'POINT.'j".Y", yy +points: wx=0; wy=0; do j=1 for arg(); parse value arg(j) with xx yy + wx=max(wx, length(xx) ); call value 'POINT.'j".X", xx + wy=max(wy, length(yy) ); call value 'POINT.'j".Y", yy end /*j*/ call value point.0, j-1 /*define the number of points. */ - return + return /* [↑] adjust J (for DO loop)*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ -poly: @='POLY.'; parse arg Fx Fy /* [↓] process the X,Y points.*/ +poly: @= 'POLY.'; parse arg Fx Fy /* [↓] process the X,Y points.*/ n=0 - do j=1 for arg(); n=n+1; parse value arg(j) with xx yy - call value @ || n'.X', xx ; call value @ || n".Y", yy - if n//2 then iterate; n=n+1 - call value @ || n'.X', xx ; call value @ || n".Y", yy + do j=1 for arg(); n=n + 1; parse value arg(j) with xx yy + call value @ || n'.X', xx ; call value @ || n".Y", yy + if n//2 then iterate; n=n + 1 /*Inside? Then skip this point.*/ + call value @ || n'.X', xx ; call value @ || n".Y", yy end /*j*/ - n=n+1 - call value @ || n'.X', Fx; call value @ || n".Y", Fy; call value @'0',n - return /*POLY.0 is # segments(sides).*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -test: say; do k=1 for point.0; w=wx+wy+2 - say right(' ['arg(1)"] point:", 30), - right( right(point.k.x, wx)', 'right(point.k.y, wy), w) " is ", - right( word('outside inside', in$out(k)+1), 7) - end /*k*/ + n=n + 1 /*POLY.0 is # segments(sides).*/ + call value @ || n'.X', Fx; call value @ || n".Y", Fy; call value @'0', n return +/*──────────────────────────────────────────────────────────────────────────────────────*/ +test: say; do k=1 for point.0; w=wx + wy + 2 /*W, WX, WY ≡are various widths*/ + say right(' ['arg(1)"] point:", 30), + right( right(point.k.x, wx)', 'right(point.k.y, wy), w) " is ", + right( word('outside inside', in$out(k) + 1), 7) + end /*k*/ + return /* [↑] format the output nicely*/ diff --git a/Task/Ray-casting-algorithm/Racket/ray-casting-algorithm.rkt b/Task/Ray-casting-algorithm/Racket/ray-casting-algorithm.rkt index f7c3e63219..3c34c7341a 100644 --- a/Task/Ray-casting-algorithm/Racket/ray-casting-algorithm.rkt +++ b/Task/Ray-casting-algorithm/Racket/ray-casting-algorithm.rkt @@ -11,7 +11,7 @@ boolean?)])) (struct point (x y) #:transparent) - (struct seg (Ax Ay Bx By)) + (struct seg (Ax Ay Bx By) #:transparent) (define ε 0.000001) (define (neq? x y) (not (eq? x y))) @@ -23,17 +23,23 @@ (eq? Pyo By)) ε 0))]) - (cond [(or (< Py Ay) (> Py By)) #f] + (define Ax2 (if (< Ay By) Ax Bx)) + (define Ay2 (if (< Ay By) Ay By)) + (define Bx2 (if (< Ay By) Bx Ax)) + (define By2 (if (< Ay By) By Ay)) + + (cond [(or (> Py (max Ay By)) (< Py (min Ay By))) #f] [(> Px (max Ax Bx)) #f] - [(< Px (min Ax Bx)) #t] - [else - (let ([red (if (neq? Ax Px) - (/ (- By Ay) (- Bx Ax)) - +inf.0)] - [blue (if (neq? Ax Px) - (/ (- Py Ax) (- Px Ax)) - +inf.0)]) - (if (>= blue red) #t #f))]))) + [else (cond + [(< Px (min Ax Bx)) #t] + [else + (let ([red (if (neq? Ax2 Bx2) + (/ (- By2 Ay2) (- Bx2 Ax2)) + +inf.0)] + [blue (if (neq? Ax2 Px) + (/ (- Py Ay2) (- Px Ax2)) + +inf.0)]) + (if (>= blue red) #t #f))])]))) (define (point-in-polygon? point polygon) (odd? diff --git a/Task/Ray-casting-algorithm/Rust/ray-casting-algorithm.rust b/Task/Ray-casting-algorithm/Rust/ray-casting-algorithm.rust index f6f5f85d88..077d4fd52b 100644 --- a/Task/Ray-casting-algorithm/Rust/ray-casting-algorithm.rust +++ b/Task/Ray-casting-algorithm/Rust/ray-casting-algorithm.rust @@ -1,71 +1,83 @@ use std::f64; -use std::clone::Clone; const _EPS: f64 = 0.00001; const _MIN: f64 = f64::MIN_POSITIVE; const _MAX: f64 = f64::MAX; -#[derive(Debug, Clone)] +#[derive(Clone)] struct Point { x: f64, - y: f64 + y: f64, } -#[derive(Debug, Clone)] +#[derive(Clone)] struct Edge { pt1: Point, - pt2: Point + pt2: Point, } impl Edge { fn new(pt1: (f64, f64), pt2: (f64, f64)) -> Edge { - Edge { pt1: Point {x: pt1.0, y: pt1.1}, pt2: Point {x: pt2.0, y: pt2.1} } + Edge { + pt1: Point { x: pt1.0, y: pt1.1 }, + pt2: Point { x: pt2.0, y: pt2.1 }, + } } } -#[derive(Debug)] -struct Polygon{ - edges: Vec // Polygon has to be created with counter-clockwise coordinates +struct Polygon { + edges: Vec, // Polygon has to be created with counter-clockwise coordinates } fn pt_in_polygon(pt: &Point, poly: &Polygon) -> bool { - poly.edges.iter() - .map(|edge| ray_intersect_seg(pt, edge)) - .fold(0u8, |sum, val| sum + (val as u8)) % 2 == 1 + let count = poly.edges + .iter() + .filter(|edge| ray_intersect_seg(pt, edge)) + .count(); + + count % 2 == 1 } fn ray_intersect_seg(p: &Point, edge: &Edge) -> bool { let mut pt = p.clone(); let (mut a, mut b): (&Point, &Point) = (&edge.pt1, &edge.pt2); if a.y > b.y { - let t = a; a = b; b = t; + std::mem::swap(&mut a, &mut b); } if pt.y == a.y || pt.y == b.y { - pt = Point {x: pt.x, y: pt.y + _EPS}; + pt.y += _EPS; } + if (pt.y > b.y || pt.y < a.y) || pt.x > a.x.max(b.x) { - return false; - } - if pt.x < a.x.min(b.x) { - return true; + false + } else if pt.x < a.x.min(b.x) { + true } else { - let m_red = if (a.x - b.x).abs() > _MIN { (b.y - a.y) / (b.x - a.x) } else { _MAX }; - let m_blue = if (a.x - pt.x).abs() > _MIN { (pt.y - a.y) / (pt.x - a.x) } else { _MAX }; - return m_blue >= m_red; + let m_red = if (a.x - b.x).abs() > _MIN { + (b.y - a.y) / (b.x - a.x) + } else { + _MAX + }; + let m_blue = if (a.x - pt.x).abs() > _MIN { + (pt.y - a.y) / (pt.x - a.x) + } else { + _MAX + }; + m_blue >= m_red } } -fn main(){ - let p = |x,y| Point {x: x, y: y}; - let testpoints = vec![p(5.0, 5.0), p(5.0, 8.0), p(-10.0, 5.0), p(0.0, 5.0), p(10.0, 5.0), p(8.0, 5.0), p(10.0, 10.0)]; +fn main() { + let p = |x, y| Point { x, y }; + let testpoints = [p(5.0, 5.0), p(5.0, 8.0), p(-10.0, 5.0), p(0.0, 5.0), p(10.0, 5.0), p(8.0, 5.0), p(10.0, 10.0)]; let poly_square = Polygon { edges: vec![ Edge::new((0.0, 0.0), (10.0, 0.0)), Edge::new((10.0, 0.0), (10.0, 10.0)), Edge::new((10.0, 10.0), (0.0, 10.0)), - Edge::new((0.0, 10.0), (0.0, 0.0)) - ] - }; + Edge::new((0.0, 10.0), (0.0, 0.0)), + ], + }; let poly_square_hole = Polygon { edges: vec![ Edge::new((0.0, 0.0), (10.0, 0.0)), @@ -75,8 +87,8 @@ fn main(){ Edge::new((2.5, 2.5), (7.5, 2.5)), Edge::new((7.5, 2.5), (7.5, 7.5)), Edge::new((7.5, 7.5), (2.5, 7.5)), - Edge::new((2.5, 7.5), (2.5, 2.5)) - ] + Edge::new((2.5, 7.5), (2.5, 2.5)), + ], }; let poly_strange = Polygon { edges: vec![ @@ -86,8 +98,8 @@ fn main(){ Edge::new((2.5, 7.5), (7.5, 7.5)), Edge::new((7.5, 7.5), (10.0, 10.0)), Edge::new((10.0, 10.0), (10.0, 0.0)), - Edge::new((10.0, 0.0), (2.5, 2.5)) - ] + Edge::new((10.0, 0.0), (2.5, 2.5)), + ], }; let poly_hexagon = Polygon { edges: vec![ @@ -96,24 +108,24 @@ fn main(){ Edge::new((10.0, 5.0), (7.0, 10.0)), Edge::new((7.0, 10.0), (3.0, 10.0)), Edge::new((3.0, 10.0), (0.0, 5.0)), - Edge::new((0.0, 5.0), (3.0, 0.0)) - ] - }; + Edge::new((0.0, 5.0), (3.0, 0.0)), + ], + }; print!("\nSquare :"); - for pt in testpoints.iter() { + for pt in &testpoints { print!(" {:?}", pt_in_polygon(pt, &poly_square)); } print!("\nSquare with hole:"); - for pt in testpoints.iter() { + for pt in &testpoints { print!(" {:?}", pt_in_polygon(pt, &poly_square_hole)); } print!("\nStrange polygon :"); - for pt in testpoints.iter() { + for pt in &testpoints { print!(" {:?}", pt_in_polygon(pt, &poly_strange)); } print!("\nHexagon :"); - for pt in testpoints.iter() { + for pt in &testpoints { print!(" {:?}", pt_in_polygon(pt, &poly_hexagon)); } - print!("\n"); + println!(); } diff --git a/Task/Ray-casting-algorithm/Visual-Basic-.NET/ray-casting-algorithm.visual b/Task/Ray-casting-algorithm/Visual-Basic-.NET/ray-casting-algorithm.visual new file mode 100644 index 0000000000..58731d1c2f --- /dev/null +++ b/Task/Ray-casting-algorithm/Visual-Basic-.NET/ray-casting-algorithm.visual @@ -0,0 +1,47 @@ +Imports System.Math + +Module RayCasting + + Private square As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}} + Private squareHole As Integer()() = {New Integer() {0, 0}, New Integer() {20, 0}, New Integer() {20, 20}, New Integer() {0, 20}, New Integer() {5, 5}, New Integer() {15, 5}, New Integer() {15, 15}, New Integer() {5, 15}} + Private strange As Integer()() = {New Integer() {0, 0}, New Integer() {5, 5}, New Integer() {0, 20}, New Integer() {5, 15}, New Integer() {15, 15}, New Integer() {20, 20}, New Integer() {20, 0}} + Private hexagon As Integer()() = {New Integer() {6, 0}, New Integer() {14, 0}, New Integer() {20, 10}, New Integer() {14, 20}, New Integer() {6, 20}, New Integer() {0, 10}} + Private shapes As Integer()()() = {square, squareHole, strange, hexagon} + + Public Sub Main() + Dim testPoints As Double()() = {New Double() {10, 10}, New Double() {10, 16}, New Double() {-20, 10}, New Double() {0, 10}, New Double() {20, 10}, New Double() {16, 10}, New Double() {20, 20}} + + For Each shape As Integer()() In shapes + For Each point As Double() In testPoints + Console.Write(String.Format("{0} ", Contains(shape, point).ToString.PadLeft(7))) + Next + Console.WriteLine() + Next + End Sub + + Private Function Contains(shape As Integer()(), point As Double()) As Boolean + + Dim inside As Boolean = False + Dim length As Integer = shape.Length + + For i As Integer = 0 To length - 1 + If Intersects(shape(i), shape((i + 1) Mod length), point) Then + inside = Not inside + End If + Next + + Return inside + End Function + + Private Function Intersects(a As Integer(), b As Integer(), p As Double()) As Boolean + + If a(1) > b(1) Then Return Intersects(b, a, p) + If p(1) = a(1) Or p(1) = b(1) Then p(1) += 0.0001 + If p(1) > b(1) Or p(1) < a(1) Or p(0) > Max(a(0), b(0)) Then Return False + If p(0) < Min(a(0), b(0)) Then Return True + Dim red As Double = (p(1) - a(1)) / (p(0) - a(0)) + Dim blue As Double = (b(1) - a(1)) / (b(0) - a(0)) + + Return red >= blue + End Function +End Module diff --git a/Task/Read-a-configuration-file/00DESCRIPTION b/Task/Read-a-configuration-file/00DESCRIPTION index 6b58c94121..6119b26bcf 100644 --- a/Task/Read-a-configuration-file/00DESCRIPTION +++ b/Task/Read-a-configuration-file/00DESCRIPTION @@ -1,4 +1,4 @@ -The task is to read a configuration file in standard configuration file, +The task is to read a configuration file in standard configuration file format, and set variables accordingly. For this task, we have a configuration file as follows: diff --git a/Task/Read-a-configuration-file/Aime/read-a-configuration-file.aime b/Task/Read-a-configuration-file/Aime/read-a-configuration-file.aime index c77973a49f..a793fb671a 100644 --- a/Task/Read-a-configuration-file/Aime/read-a-configuration-file.aime +++ b/Task/Read-a-configuration-file/Aime/read-a-configuration-file.aime @@ -6,60 +6,53 @@ text an, d, k; an = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; -f_affix(f, "tmp/config"); +f.affix("tmp/config"); -while ((c = f_peek(f)) ^ -1) { +while ((c = f.peek) ^ -1) { integer removed; - f_side(f, " \t\r"); - c = f_peek(f); + f.side(" \t\r"); + c = f.peek; removed = c == ';'; if (removed) { - f_pick(f); - f_side(f, " \t\r"); - c = f_peek(f); + f.pick; + f.side(" \t\r"); + c = f.peek; } - c = index(an, c); + c = place(an, c); if (-1 < c && c < 52) { - f_near(f, an, k); + f.near(an, k); if (removed) { r[k] = "false"; } else { - data b; - - f_side(f, " \t\r"); - if (f_peek(f) == '=') { - f_pick(f); - f_side(f, " \t\r"); + f.side(" \t\r"); + if (f.peek == '=') { + f.pick; + f.side(" \t\r"); } - f_ever(f, ",#\n", d); - b = d; - bb_drop(b, " \r\t"); - d = b_string(b); - if (f_peek(f) != ',') { - r[k] = length(d) ? d : "true"; + f.ever(",#\n", d); + d = bb_drop(d, " \r\t"); + if (f.peek != ',') { + r[k] = ~d ? d : "true"; } else { - f_news(f, l, 0, 0, ","); + f.news(l, 0, 0, ","); lf_push(l, d); for (c, d in l) { - b = d; - bb_drop(b, " \r\t"); - bf_drop(b, " \r\t"); - l[c] = b_string(b); + l[c] = bb_drop(d, " \r\t").bf_drop(" \r\t").string; } - r_put(s, k, l); - f_seek(f, -1, SEEK_CURRENT); + s.put(k, l); + f.seek(-1, SEEK_CURRENT); } } } - f_slip(f); + f.slip; } -r_wcall(r, o_, 0, 2, ": ", "\n"); +r.wcall(o_, 0, 2, ": ", "\n"); for (k, l in s) { o_(k, ": "); - l_ucall(l, o_, 0, ", "); + l.ucall(o_, 0, ", "); o_("\n"); } diff --git a/Task/Read-a-configuration-file/C/read-a-configuration-file.c b/Task/Read-a-configuration-file/C/read-a-configuration-file.c new file mode 100644 index 0000000000..17a77b0818 --- /dev/null +++ b/Task/Read-a-configuration-file/C/read-a-configuration-file.c @@ -0,0 +1,171 @@ +#include +#include +#include +#include + +#define rosetta_uint8_t unsigned char + +#define FALSE 0 +#define TRUE 1 + +#define CONFIGS_TO_READ 5 +#define INI_ARRAY_DELIMITER ',' + +/* Assume that the config file represent a struct containing all the parameters to load */ +struct configs { + char *fullname; + char *favouritefruit; + rosetta_uint8_t needspeeling; + rosetta_uint8_t seedsremoved; + char **otherfamily; + size_t otherfamily_len; + size_t _configs_left_; +}; + +static char ** make_array (size_t * arrlen, const char * src, const size_t buffsize, IniFormat ini_format) { + + /* Allocate a new array of strings and populate it from the stringified source */ + *arrlen = ini_array_get_length(src, INI_ARRAY_DELIMITER, ini_format); + char ** const dest = *arrlen ? (char **) malloc(*arrlen * sizeof(char *) + buffsize) : NULL; + if (!dest) { return NULL; } + memcpy(dest + *arrlen, src, buffsize); + char * iter = (char *) (dest + *arrlen); + for (size_t idx = 0; idx < *arrlen; idx++) { + dest[idx] = ini_array_release(&iter, INI_ARRAY_DELIMITER, ini_format); + ini_string_parse(dest[idx], ini_format); + } + return dest; + +} + +static int configs_member_handler (IniDispatch *this, void *v_confs) { + + struct configs *confs = (struct configs *) v_confs; + + if (this->type != INI_KEY) { + + return 0; + + } + + if (ini_string_match_si("FULLNAME", this->data, this->format)) { + + if (confs->fullname) { return 0; } + this->v_len = ini_string_parse(this->value, this->format); /* Remove all quotes, if any */ + confs->fullname = strndup(this->value, this->v_len); + confs->_configs_left_--; + + } else if (ini_string_match_si("FAVOURITEFRUIT", this->data, this->format)) { + + if (confs->favouritefruit) { return 0; } + this->v_len = ini_string_parse(this->value, this->format); /* Remove all quotes, if any */ + confs->favouritefruit = strndup(this->value, this->v_len); + confs->_configs_left_--; + + } else if (ini_string_match_si("NEEDSPEELING", this->data, this->format)) { + + if (~confs->needspeeling & 0x80) { return 0; } + confs->needspeeling = ini_get_bool(this->value, TRUE); + confs->_configs_left_--; + + } else if (ini_string_match_si("SEEDSREMOVED", this->data, this->format)) { + + if (~confs->seedsremoved & 0x80) { return 0; } + confs->seedsremoved = ini_get_bool(this->value, TRUE); + confs->_configs_left_--; + + } else if (!confs->otherfamily && ini_string_match_si("OTHERFAMILY", this->data, this->format)) { + + if (confs->otherfamily) { return 0; } + this->v_len = ini_array_collapse(this->value, INI_ARRAY_DELIMITER, this->format); /* Save memory (not strictly needed) */ + confs->otherfamily = make_array(&confs->otherfamily_len, this->value, this->v_len + 1, this->format); + confs->_configs_left_--; + + } + + /* Optimization: stop reading the INI file when we have all we need */ + return !confs->_configs_left_; + +} + +static int populate_configs (struct configs * confs) { + + /* Define the format of the configuration file */ + IniFormat config_format = { + .delimiter_symbol = INI_ANY_SPACE, + .case_sensitive = FALSE, + .semicolon_marker = INI_IGNORE, + .hash_marker = INI_IGNORE, + .multiline_nodes = INI_NO_MULTILINE, + .section_paths = INI_NO_SECTIONS, + .no_single_quotes = FALSE, + .no_double_quotes = FALSE, + .no_spaces_in_names = TRUE, + .implicit_is_not_empty = TRUE, + .do_not_collapse_values = FALSE, + .preserve_empty_quotes = FALSE, + .no_disabled_after_space = FALSE, + .disabled_can_be_implicit = FALSE + }; + + *confs = (struct configs) { NULL, NULL, 0x80, 0x80, NULL, 0, CONFIGS_TO_READ }; + + if (load_ini_path("rosetta.conf", config_format, NULL, configs_member_handler, confs) & CONFINI_ERROR) { + + fprintf(stderr, "Sorry, something went wrong :-(\n"); + return 1; + + } + + confs->needspeeling &= 0x7F; + confs->seedsremoved &= 0x7F; + + return 0; + +} + +int main () { + + struct configs confs; + + ini_global_set_implicit_value("YES", 0); + + if (populate_configs(&confs)) { + + return 1; + + } + + /* Print the configurations parsed */ + + printf( + + "Full name: %s\n" + "Favorite fruit: %s\n" + "Need spelling: %s\n" + "Seeds removed: %s\n", + + confs.fullname, + confs.favouritefruit, + confs.needspeeling ? "True" : "False", + confs.seedsremoved ? "True" : "False" + + ); + + for (size_t idx = 0; idx < confs.otherfamily_len; idx++) { + + printf("Other family[%d]: %s\n", idx, confs.otherfamily[idx]); + + } + + /* Free the allocated memory */ + + #define FREE_NON_NULL(PTR) if (PTR) { free(PTR); } + + FREE_NON_NULL(confs.fullname); + FREE_NON_NULL(confs.favouritefruit); + FREE_NON_NULL(confs.otherfamily); + + return 0; + +} diff --git a/Task/Read-a-configuration-file/Clojure/read-a-configuration-file.clj b/Task/Read-a-configuration-file/Clojure/read-a-configuration-file.clj index 8d075afccc..d7ad9d47c5 100644 --- a/Task/Read-a-configuration-file/Clojure/read-a-configuration-file.clj +++ b/Task/Read-a-configuration-file/Clojure/read-a-configuration-file.clj @@ -1,2 +1,48 @@ -(let [cfg (read-string (slurp "config.edn"))] - (clojure.pprint/pprint cfg)) +(ns read-conf-file.core + (:require [clojure.java.io :as io] + [clojure.string :as str]) + (:gen-class)) + +(def conf-keys ["fullname" + "favouritefruit" + "needspeeling" + "seedsremoved" + "otherfamily"]) + +(defn get-lines + "Read file returning vec of lines." + [file] + (try + (with-open [rdr (io/reader file)] + (into [] (line-seq rdr))) + (catch Exception e (.getMessage e)))) + +(defn parse-line + "Parse passed line returning vec: token, vec of values." + [line] + (if-let [[_ k v] (re-matches #"(?i)^\s*([a-z]+)(?:\s+|=)?(.+)?$" line)] + (let [k (str/lower-case k)] + (if v + [k (str/split v #",\s*")] + [k [true]])))) + +(defn mk-conf + "Build configuration map from lines." + [lines] + (->> (map parse-line lines) + (filter (comp not nil?)) + (reduce (fn + [m [k v]] + (assoc m k v)) {}))) + +(defn output + [conf-keys conf] + (doseq [k conf-keys] + (let [v (get conf k)] + (if v + (println (format "%s = %s" k (str/join ", " v))) + (println (format "%s = %s" k "false")))))) + +(defn -main + [filename] + (output conf-keys (mk-conf (get-lines filename)))) diff --git a/Task/Read-a-configuration-file/Common-Lisp/read-a-configuration-file-1.lisp b/Task/Read-a-configuration-file/Common-Lisp/read-a-configuration-file-1.lisp index 69179b972d..1b600a304a 100644 --- a/Task/Read-a-configuration-file/Common-Lisp/read-a-configuration-file-1.lisp +++ b/Task/Read-a-configuration-file/Common-Lisp/read-a-configuration-file-1.lisp @@ -1,10 +1,40 @@ -;config-file.txt -;lisp comments works normally as it would in lisp -#S(config-file -:fullname "Foo Barber" -:favoritefruit "banana" -:needspeeling t -:seedsremoved nil -:otherfamily '("Rhu Barber" "Harry Barber") -;:will "not be read" -) +(ql:quickload :parser-combinators) + +(defpackage :read-config + (:use :cl :parser-combinators)) + +(in-package :read-config) + +(defun trim-space (string) + (string-trim '(#\space #\tab) string)) + +(defun any-but1? (except) + (named-seq? (<- res (many1? (except? (item) except))) + (coerce res 'string))) + +(defun values? () + (named-seq? (<- values (sepby? (any-but1? #\,) #\,)) + (mapcar 'trim-space values))) + +(defun key-values? () + (named-seq? (<- key (word?)) + (opt? (many? (whitespace?))) + (opt? #\=) + (<- values (values?)) + (cons key (or (if (cdr values) values (car values)) t)))) + +(defun parse-line (line) + (setf line (trim-space line)) + (if (or (string= line "") (member (char line 0) '(#\# #\;))) + :comment + (parse-string* (key-values?) line))) + +(defun parse-config (stream) + (let ((hash (make-hash-table :test 'equal))) + (loop for line = (read-line stream nil nil) + while line + do (let ((parsed (parse-line line))) + (cond ((eq parsed :comment)) + ((eq parsed nil) (error "config parser error: ~a" line)) + (t (setf (gethash (car parsed) hash) (cdr parsed)))))) + hash)) diff --git a/Task/Read-a-configuration-file/Common-Lisp/read-a-configuration-file-2.lisp b/Task/Read-a-configuration-file/Common-Lisp/read-a-configuration-file-2.lisp index c0b04865a9..befdf401fe 100644 --- a/Task/Read-a-configuration-file/Common-Lisp/read-a-configuration-file-2.lisp +++ b/Task/Read-a-configuration-file/Common-Lisp/read-a-configuration-file-2.lisp @@ -1,9 +1,12 @@ -;config-file.lisp -(defstruct config-file :fullname :favoritefruit :needspeeling :seedsremoved :otherfamily) -(with-open-file (in "config-file.txt") - (defvar contents (read in)) - (format t "~a~%" contents) - ;reading the config-file into a structure gives us - ;some helper functions to access individualy each element - (format t "Fullname: ~a~%" (config-file-fullname contents)) - (format t "Contents is a config-file? ~a~%" (config-file-p contents))) +READ-CONFIG> (with-open-file (s "test.cfg") (parse-config s)) +# +READ-CONFIG> (maphash (lambda (k v) (print (list k v))) *) + +("FULLNAME" "Foo Barber") +("FAVOURITEFRUIT" "banana") +("NEEDSPEELING" T) +("OTHERFAMILY" ("Rhu Barber" "Harry Barber")) +NIL +READ-CONFIG> (gethash "SEEDSREMOVED" **) +NIL +NIL diff --git a/Task/Read-a-configuration-file/Julia/read-a-configuration-file.julia b/Task/Read-a-configuration-file/Julia/read-a-configuration-file.julia new file mode 100644 index 0000000000..b648e9ec65 --- /dev/null +++ b/Task/Read-a-configuration-file/Julia/read-a-configuration-file.julia @@ -0,0 +1,24 @@ +function readconf(file) + vars = Dict() + for line in eachline(file) + line = strip(line) + if !isempty(line) && !startswith(line, '#') && !startswith(line, ';') + fspace = searchindex(line, " ") + if fspace == 0 + vars[Symbol(lowercase(line))] = true + else + vname, line = Symbol(lowercase(line[1:fspace-1])), line[fspace+1:end] + value = ',' ∈ line ? strip.(split(line, ',')) : line + vars[vname] = value + end + end + end + for (vname, value) in vars + eval(:($vname = $value)) + end + return vars +end + +readconf("test.conf") + +@show fullname favouritefruit needspeeling otherfamily diff --git a/Task/Read-a-configuration-file/Perl-6/read-a-configuration-file.pl6 b/Task/Read-a-configuration-file/Perl-6/read-a-configuration-file.pl6 index fe23f90c37..4d215ac672 100644 --- a/Task/Read-a-configuration-file/Perl-6/read-a-configuration-file.pl6 +++ b/Task/Read-a-configuration-file/Perl-6/read-a-configuration-file.pl6 @@ -17,7 +17,7 @@ grammar ConfFile { [ \n || { die "Parse failed at line $*linenum" } ] } - proto token line() {{*}} + proto token line() {*} token line:misc { {} (\S+) { die "Unrecognized word: $0" } } diff --git a/Task/Read-a-configuration-file/PowerShell/read-a-configuration-file-4.psh b/Task/Read-a-configuration-file/PowerShell/read-a-configuration-file-4.psh new file mode 100644 index 0000000000..61367e8171 --- /dev/null +++ b/Task/Read-a-configuration-file/PowerShell/read-a-configuration-file-4.psh @@ -0,0 +1,88 @@ +Function Read-ConfigurationFile { + [CmdletBinding()] + [OutputType([Collections.Specialized.OrderedDictionary])] + Param ( + [Parameter( + Mandatory=$true, + Position=0 + ) + ] + [Alias('LiteralPath')] + [ValidateScript({ + Test-Path -LiteralPath $PSItem -PathType 'Leaf' + }) + ] + [String] + $_LiteralPath + ) + + Begin { + Function Houdini-Value ([String]$_Text) { + $__Aux = $_Text.Trim() + If ($__Aux.Length -eq 0) { + $__Aux = $true + } ElseIf ($__Aux.Contains(',')) { + $__Aux = $__Aux.Split(',') | + ForEach-Object { + If ($PSItem.Trim().Length -ne 0) { + $PSItem.Trim() + } + } + } + Return $__Aux + } + } + + Process { + $__Configuration = [Ordered]@{} + # Config equivalent pattern + # Select-String -Pattern '^\s*[^\s;#=]+.*\s*$' -LiteralPath '.\filename.cfg' + Switch -Regex -File $_LiteralPath { + + '^\s*[;#=]|^\s*$' { + Write-Verbose -Message "v$(' '*20)ignored" + Write-Verbose -Message $Matches[0] + Continue + } + + '^([^=]+)=(.*)$' { + Write-Verbose -Message '↓← ← ← ← ← ← ← ← ← ← equal pattern' + Write-Verbose -Message $Matches[0] + $__Name,$__Value = $Matches[1..2] + $__Configuration[$__Name.Trim()] = Houdini-Value($__Value) + Continue + } + + '^\s*([^\s;#=]+)(.*)(\s*)$' { + Write-Verbose -Message '↓← ← ← ← ← ← ← ← ← ← space or tab pattern or only name' + Write-Verbose -Message $Matches[0] + $__Name,$__Value = $Matches[1..2] + $__Configuration[$__Name.Trim()] = Houdini-Value($__Value) + Continue + } + + } + Return $__Configuration + } +} + +Function Show-Value ([Collections.Specialized.OrderedDictionary]$_Dictionary, $_Index, $_SubIndex) { + $__Aux = $_Index + ' = ' + If ($_Dictionary[$_Index] -eq $null) { + $__Aux += $false + } ElseIf ($_Dictionary[$_Index].Count -gt 1) { + If ($_SubIndex -eq $null) { + $__Aux += $_Dictionary[$_Index] -join ',' + } Else { + $__Aux = $_Index + '(' + $_SubIndex + ') = ' + If ($_Dictionary[$_Index][$_SubIndex] -eq $null) { + $__Aux += $false + } Else { + $__Aux += $_Dictionary[$_Index][$_SubIndex] + } + } + } Else { + $__Aux += $_Dictionary[$_Index] + } + Return $__Aux +} diff --git a/Task/Read-a-configuration-file/PowerShell/read-a-configuration-file-5.psh b/Task/Read-a-configuration-file/PowerShell/read-a-configuration-file-5.psh new file mode 100644 index 0000000000..1eacbba80d --- /dev/null +++ b/Task/Read-a-configuration-file/PowerShell/read-a-configuration-file-5.psh @@ -0,0 +1 @@ +$Configuration = Read-ConfigurationFile -LiteralPath '.\config.cfg' diff --git a/Task/Read-a-configuration-file/PowerShell/read-a-configuration-file-6.psh b/Task/Read-a-configuration-file/PowerShell/read-a-configuration-file-6.psh new file mode 100644 index 0000000000..5c08d16192 --- /dev/null +++ b/Task/Read-a-configuration-file/PowerShell/read-a-configuration-file-6.psh @@ -0,0 +1 @@ +$Configuration diff --git a/Task/Read-a-configuration-file/PowerShell/read-a-configuration-file-7.psh b/Task/Read-a-configuration-file/PowerShell/read-a-configuration-file-7.psh new file mode 100644 index 0000000000..b96da687ef --- /dev/null +++ b/Task/Read-a-configuration-file/PowerShell/read-a-configuration-file-7.psh @@ -0,0 +1,8 @@ +Show-Value $Configuration 'fullname' +Show-Value $Configuration 'favouritefruit' +Show-Value $Configuration 'needspeeling' +Show-Value $Configuration 'seedsremoved' +Show-Value $Configuration 'otherfamily' +Show-Value $Configuration 'otherfamily' 0 +Show-Value $Configuration 'otherfamily' 1 +Show-Value $Configuration 'otherfamily' 2 diff --git a/Task/Read-a-configuration-file/PowerShell/read-a-configuration-file-8.psh b/Task/Read-a-configuration-file/PowerShell/read-a-configuration-file-8.psh new file mode 100644 index 0000000000..75656ae118 --- /dev/null +++ b/Task/Read-a-configuration-file/PowerShell/read-a-configuration-file-8.psh @@ -0,0 +1,45 @@ +'$Configuration[''fullname'']' +$Configuration['fullname'] +'$Configuration.''fullname''' +$Configuration.'fullname' +'$Configuration.Item(''fullname'')' +$Configuration.Item('fullname') +'$Configuration[0]' +$Configuration[0] +'$Configuration.Item(0)' +$Configuration.Item(0) +' ' +'=== $Configuration[''otherfamily''] ===' +$Configuration['otherfamily'] +'=== $Configuration[''otherfamily''][0] ===' +$Configuration['otherfamily'][0] +'=== $Configuration[''otherfamily''][1] ===' +$Configuration['otherfamily'][1] +' ' +'=== $Configuration.''otherfamily'' ===' +$Configuration.'otherfamily' +'=== $Configuration.''otherfamily''[0] ===' +$Configuration.'otherfamily'[0] +'=== $Configuration.''otherfamily''[1] ===' +$Configuration.'otherfamily'[1] +' ' +'=== $Configuration.Item(''otherfamily'') ===' +$Configuration.Item('otherfamily') +'=== $Configuration.Item(''otherfamily'')[0] ===' +$Configuration.Item('otherfamily')[0] +'=== $Configuration.Item(''otherfamily'')[1] ===' +$Configuration.Item('otherfamily')[1] +' ' +'=== $Configuration[3] ===' +$Configuration[3] +'=== $Configuration[3][0] ===' +$Configuration[3][0] +'=== $Configuration[3][1] ===' +$Configuration[3][1] +' ' +'=== $Configuration.Item(3) ===' +$Configuration.Item(3) +'=== $Configuration.Item(3).Item(0) ===' +$Configuration.Item(3).Item(0) +'=== $Configuration.Item(3).Item(1) ===' +$Configuration.Item(3).Item(1) diff --git a/Task/Read-a-configuration-file/Rust/read-a-configuration-file.rust b/Task/Read-a-configuration-file/Rust/read-a-configuration-file.rust new file mode 100644 index 0000000000..043e43660d --- /dev/null +++ b/Task/Read-a-configuration-file/Rust/read-a-configuration-file.rust @@ -0,0 +1,80 @@ +use std::fs::File; +use std::io::BufRead; +use std::io::BufReader; +use std::iter::FromIterator; +use std::path::Path; + +fn main() { + let path = String::from("file.conf"); + let cfg = config_from_file(path); + println!("{:?}", cfg); +} + +fn config_from_file(path: String) -> Config { + let path = Path::new(&path); + let file = File::open(path).expect("File not found or cannot be opened"); + let content = BufReader::new(&file); + let mut cfg = Config::new(); + + for line in content.lines() { + let line = line.expect("Could not read the line"); + // Remove whitespaces at the beginning and end + let line = line.trim(); + + // Ignore comments and empty lines + if line.starts_with("#") || line.starts_with(";") || line.is_empty() { + continue; + } + + // Split line into parameter name and rest tokens + let tokens = Vec::from_iter(line.split_whitespace()); + let name = tokens.first().unwrap(); + let tokens = tokens.get(1..).unwrap(); + + // Remove the equal signs + let tokens = tokens.iter().filter(|t| !t.starts_with("=")); + // Remove comment after the parameters + let tokens = tokens.take_while(|t| !t.starts_with("#") && !t.starts_with(";")); + + // Concat back the parameters into one string to split for separated parameters + let mut parameters = String::new(); + tokens.for_each(|t| { parameters.push_str(t); parameters.push(' '); }); + // Splits the parameters and trims + let parameters = parameters.split(',').map(|s| s.trim()); + // Converts them from Vec<&str> into Vec + let parameters: Vec = parameters.map(|s| s.to_string()).collect(); + + // Setting the config parameters + match name.to_lowercase().as_str() { + "fullname" => cfg.full_name = parameters.get(0).cloned(), + "favouritefruit" => cfg.favourite_fruit = parameters.get(0).cloned(), + "needspeeling" => cfg.needs_peeling = true, + "seedsremoved" => cfg.needs_peeling = true, + "otherfamily" => cfg.other_family = Some(parameters), + _ => (), + } + } + + cfg +} + +#[derive(Clone, Debug)] +struct Config { + full_name: Option, + favourite_fruit: Option, + needs_peeling: bool, + seeds_removed: bool, + other_family: Option>, +} + +impl Config { + fn new() -> Config { + Config { + full_name: None, + favourite_fruit: None, + needs_peeling: false, + seeds_removed: false, + other_family: None, + } + } +} diff --git a/Task/Read-a-file-line-by-line/Aime/read-a-file-line-by-line.aime b/Task/Read-a-file-line-by-line/Aime/read-a-file-line-by-line.aime index 8160c335a7..7e525c5b75 100644 --- a/Task/Read-a-file-line-by-line/Aime/read-a-file-line-by-line.aime +++ b/Task/Read-a-file-line-by-line/Aime/read-a-file-line-by-line.aime @@ -1,9 +1,9 @@ file f; text s; -f_affix(f, "src/aime.c"); +f.affix("src/aime.c"); -while (f_line(f, s) != -1) { +while (f.line(s) != -1) { o_text(s); o_byte('\n'); } diff --git a/Task/Read-a-file-line-by-line/Astro/read-a-file-line-by-line.astro b/Task/Read-a-file-line-by-line/Astro/read-a-file-line-by-line.astro index be1ea06913..27ec5a587d 100644 --- a/Task/Read-a-file-line-by-line/Astro/read-a-file-line-by-line.astro +++ b/Task/Read-a-file-line-by-line/Astro/read-a-file-line-by-line.astro @@ -1,2 +1,3 @@ -try f <- open('foobar.txt'): - print line for line in f +try f = open('foobar.txt'): + for line in lines f: + print line diff --git a/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-1.c b/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-1.c index 4e9dd77577..92a9d5b1ee 100644 --- a/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-1.c +++ b/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-1.c @@ -15,7 +15,7 @@ int main(void) exit(EXIT_FAILURE); while ((read = getline(&line, &len, stream)) != -1) { - printf("Retrieved line of length %zu :\n", read); + printf("Retrieved line of length %u :\n", read); printf("%s", line); } diff --git a/Task/Read-a-file-line-by-line/Maple/read-a-file-line-by-line.maple b/Task/Read-a-file-line-by-line/Maple/read-a-file-line-by-line.maple new file mode 100644 index 0000000000..e437a6ff84 --- /dev/null +++ b/Task/Read-a-file-line-by-line/Maple/read-a-file-line-by-line.maple @@ -0,0 +1,6 @@ +path := "file.txt": +while (true) do + input := readline(path): + if input = 0 then break; end if: + #The line is stored in input +end do: diff --git a/Task/Read-a-specific-line-from-a-file/Aime/read-a-specific-line-from-a-file.aime b/Task/Read-a-specific-line-from-a-file/Aime/read-a-specific-line-from-a-file.aime index 2e121586fe..c4d2bf4099 100644 --- a/Task/Read-a-specific-line-from-a-file/Aime/read-a-specific-line-from-a-file.aime +++ b/Task/Read-a-specific-line-from-a-file/Aime/read-a-specific-line-from-a-file.aime @@ -3,28 +3,24 @@ read_line(text &line, text path, integer n) { file f; - f_affix(f, path); + f.affix(path); - while (n) { - n -= 1; - f_slip(f); - } + call_n(n, f_slip, f); - f_line(f, line); + f.line(line); } integer main(void) { - if (2 < argc()) { - text line; + if (1 < argc()) { + text line; - read_line(line, argv(1), 6); + read_line(line, argv(1), 6); - o_text(line); - o_byte('\n'); + o_("7th line is:\n", line, "\n"); } - return 0; + 0; } diff --git a/Task/Read-a-specific-line-from-a-file/Red/read-a-specific-line-from-a-file.red b/Task/Read-a-specific-line-from-a-file/Red/read-a-specific-line-from-a-file.red new file mode 100644 index 0000000000..8d02f3d49e --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/Red/read-a-specific-line-from-a-file.red @@ -0,0 +1,7 @@ +>> x: pick read/lines %file.txt 7 + +case [ + x = none [print "File has less than seven lines"] + (length? x) = 0 [print "Line 7 is empty"] + (length? x) > 0 [print append "Line seven = " x] +] diff --git a/Task/Read-a-specific-line-from-a-file/Rust/read-a-specific-line-from-a-file-1.rust b/Task/Read-a-specific-line-from-a-file/Rust/read-a-specific-line-from-a-file-1.rust new file mode 100644 index 0000000000..4ca52fe91f --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/Rust/read-a-specific-line-from-a-file-1.rust @@ -0,0 +1,19 @@ +use std::fs::File; +use std::io::BufRead; +use std::io::BufReader; +use std::io::Error; +use std::path::Path; + +fn main() { + let path = Path::new("file.txt"); + let line_num = 7usize; + let line = get_line_at(&path, line_num - 1); + println!("{}", line.unwrap()); +} + +fn get_line_at(path: &Path, line_num: usize) -> Result { + let file = File::open(path).expect("File not found or cannot be opened"); + let content = BufReader::new(&file); + let mut lines = content.lines(); + lines.nth(line_num).expect("No line found at that position") +} diff --git a/Task/Read-a-specific-line-from-a-file/Rust/read-a-specific-line-from-a-file-2.rust b/Task/Read-a-specific-line-from-a-file/Rust/read-a-specific-line-from-a-file-2.rust new file mode 100644 index 0000000000..757a899864 --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/Rust/read-a-specific-line-from-a-file-2.rust @@ -0,0 +1,32 @@ +use std::env; +use std::fs::File; +use std::io::BufRead; +use std::io::BufReader; +use std::path::Path; + +fn main() { + if env::args().len() <= 1 { + println!("At least a path to a file is needed: No file path given"); + return; + } else { + let path = &env::args().nth(1).expect("could not parse the path"); + let path = Path::new(&path); + let mut line_num = 1usize; + if let Some(arg) = env::args().nth(2) { + line_num = arg.parse::().expect("Parsing line number failed"); + } + print_line_at(&path, line_num); + } +} + +fn print_line_at(path: &Path, line_num: usize) { + if line_num < 1 { + panic!("Line number has to be > 0"); + } + let line_num = line_num - 1; + let file = File::open(path).expect("File not found or cannot be opened"); + let content = BufReader::new(&file); + let mut lines = content.lines(); + let line = lines.nth(line_num).expect("No line found at given position"); + println!("{}", line.expect("None line")); +} diff --git a/Task/Read-entire-file/Julia/read-entire-file-1.julia b/Task/Read-entire-file/Julia/read-entire-file-1.julia index 6d32ab1a8c..142458266e 100644 --- a/Task/Read-entire-file/Julia/read-entire-file-1.julia +++ b/Task/Read-entire-file/Julia/read-entire-file-1.julia @@ -1,2 +1,2 @@ -readall("/devel/myfile.txt") # read file into a string -open(readbytes, "/devel/myfile.txt") # read file into an array of bytes +readstring("/devel/myfile.txt") # read file into a string +read("/devel/myfile.txt", filesize("/devel/myfile.txt")) # read file into an array of bytes diff --git a/Task/Read-entire-file/Julia/read-entire-file-2.julia b/Task/Read-entire-file/Julia/read-entire-file-2.julia index 96339a82f6..c837e3d8cb 100644 --- a/Task/Read-entire-file/Julia/read-entire-file-2.julia +++ b/Task/Read-entire-file/Julia/read-entire-file-2.julia @@ -1,2 +1 @@ -f = open("/devel/myfile.txt", "r") -A = mmap_array(Uint8, (filesize("/devel/myfile.txt"),), f) +A = Mmap.mmap(open("/devel/myfile.txt"), Array{UInt8,1}) diff --git a/Task/Real-constants-and-functions/Perl/real-constants-and-functions.pl b/Task/Real-constants-and-functions/Perl/real-constants-and-functions.pl index 35610128b4..b5079c0134 100644 --- a/Task/Real-constants-and-functions/Perl/real-constants-and-functions.pl +++ b/Task/Real-constants-and-functions/Perl/real-constants-and-functions.pl @@ -9,3 +9,9 @@ abs($x); # absolute value floor($x); # floor ceil($x); # ceiling $x ** $y; # power + +use Math::Trig; +pi; # alternate way to get pi + +use Math::Complex; +pi; # alternate way to get pi diff --git a/Task/Real-constants-and-functions/Scala/real-constants-and-functions.scala b/Task/Real-constants-and-functions/Scala/real-constants-and-functions.scala new file mode 100644 index 0000000000..c3a82da7d7 --- /dev/null +++ b/Task/Real-constants-and-functions/Scala/real-constants-and-functions.scala @@ -0,0 +1,12 @@ +object RealConstantsFunctions extends App{ + println(math.E) // e + println(math.Pi) // pi + println(math.sqrt(2.0)) // square root + println(math.log(math.E)) // log to base e + println(math.log10(10.0)) // log to base 10 + println(math.exp(1.0)) // exponential + println(math.abs(-1)) // absolute value + println(math.floor(-2.5)) // floor + println(math.ceil(-2.5)) // ceiling + println(math.pow(2.5, 3.5)) // power +} diff --git a/Task/Record-sound/Julia/record-sound.julia b/Task/Record-sound/Julia/record-sound.julia new file mode 100644 index 0000000000..fa63f83c07 --- /dev/null +++ b/Task/Record-sound/Julia/record-sound.julia @@ -0,0 +1,5 @@ +using PortAudio, LibSndFile + +stream = PortAudioStream("Microphone (USB Microphone)", 1, 0) # 44100 samples/sec +buf = read(stream, 441000) +save("recorded10sec.wav", buf) diff --git a/Task/Reduced-row-echelon-form/00DESCRIPTION b/Task/Reduced-row-echelon-form/00DESCRIPTION index 539a1f0ad1..3831fb1dab 100644 --- a/Task/Reduced-row-echelon-form/00DESCRIPTION +++ b/Task/Reduced-row-echelon-form/00DESCRIPTION @@ -1,4 +1,7 @@ {{omit from|GUISS}} + + +;Task: Show how to compute the '''reduced row echelon form''' (a.k.a. '''row canonical form''') of a matrix. @@ -37,10 +40,15 @@ Built-in functions or this pseudocode (from Wikipedia) may be used: '''end function''' For testing purposes, the RREF of this matrix: -
1   2   -1   -4
-2   3   -1   -11
--2   0   -3   22
+
+ 1    2   -1   -4
+ 2    3   -1   -11
+-2    0   -3    22
+
is: -
1   0   0   -8
-0   1   0   1
-0   0   1   -2
+
+ 1    0    0   -8
+ 0    1    0    1
+ 0    0    1   -2
+
+

diff --git a/Task/Reduced-row-echelon-form/Aime/reduced-row-echelon-form.aime b/Task/Reduced-row-echelon-form/Aime/reduced-row-echelon-form.aime index 4d64f0dddb..a47d0142cb 100644 --- a/Task/Reduced-row-echelon-form/Aime/reduced-row-echelon-form.aime +++ b/Task/Reduced-row-echelon-form/Aime/reduced-row-echelon-form.aime @@ -28,7 +28,7 @@ rref(list l, integer rows, integer columns) u = l[i]; - l_spin(l, i, r); + l.spin(i, r); e = u[lead]; if (e) { for (j, f in u) { @@ -40,7 +40,7 @@ rref(list l, integer rows, integer columns) if (i != r) { e = v[lead]; for (j, f in v) { - v[j] = f - l_q_integer(u, j) * e; + v[j] = f - u[j] * e; } } } @@ -52,14 +52,12 @@ rref(list l, integer rows, integer columns) } void -display_2(list l, integer rows, integer columns) +display_2(list l) { - integer i; list u; - i = 0; - for (i, u in l) { - l_ucall(u, o_winteger, -1, 4); + for (, u in l) { + u.ucall(o_winteger, -1, 4); o_byte('\n'); } } @@ -69,11 +67,11 @@ main(void) { list l; - l = l_effect(l_effect(1, 2, -1, -4), - l_effect(2, 3, -1, -11), - l_effect(-2, 0, -3, 22)); + l = list(list(1, 2, -1, -4), + list(2, 3, -1, -11), + list(-2, 0, -3, 22)); rref(l, 3, 4); - display_2(l, 3, 4); + display_2(l); return 0; } diff --git a/Task/Reduced-row-echelon-form/J/reduced-row-echelon-form-1.j b/Task/Reduced-row-echelon-form/J/reduced-row-echelon-form-1.j index 0ec1f9ddb9..0c07554f87 100644 --- a/Task/Reduced-row-echelon-form/J/reduced-row-echelon-form-1.j +++ b/Task/Reduced-row-echelon-form/J/reduced-row-echelon-form-1.j @@ -1,10 +1,36 @@ - ]mymatrix=: _4]\ 1 2 _1 _4 2 3 _1 _11 _2 0 _3 22 - 1 2 _1 _4 - 2 3 _1 _11 -_2 0 _3 22 +NB.*pivot v Pivot at row, column +NB. form: (row,col) pivot M +pivot=: dyad define + 'r c'=. x + col=. c{"1 y + y - (col - r = i.#y) */ (r{y) % r{col +) - require 'math/misc/linear' - gauss_jordan mymatrix -1 0 0 _8 -0 1 0 1 -0 0 1 _2 +NB.*gauss_jordan v Gauss-Jordan elimination (full pivoting) +NB. y is: matrix +NB. x is: optional minimum tolerance, default 1e_15. +NB. If a column below the current pivot has numbers of magnitude all +NB. less then x, it is treated as all zeros. +gauss_jordan=: verb define + 1e_15 gauss_jordan y +: + mtx=. y + 'r c'=. $mtx + rows=. i.r + i=. j=. 0 + max=. i.>./ + while. (i:i + end. + j=. >:j + end. + mtx +) diff --git a/Task/Reduced-row-echelon-form/J/reduced-row-echelon-form-2.j b/Task/Reduced-row-echelon-form/J/reduced-row-echelon-form-2.j index a8745495f1..322c84bca1 100644 --- a/Task/Reduced-row-echelon-form/J/reduced-row-echelon-form-2.j +++ b/Task/Reduced-row-echelon-form/J/reduced-row-echelon-form-2.j @@ -1,16 +1,10 @@ - gauss_jordan 2 0 _1 0 0,1 0 0 _1 0,3 0 0 _2 _1,0 1 0 0 _2,:0 1 _1 0 0 -1 0 0 0 _1 -0 1 0 0 _2 -0 0 1 0 _2 -0 0 0 1 _1 -0 0 0 0 0 - gauss_jordan 1 2 3 4 3 1,2 4 6 2 6 2,3 6 18 9 9 _6,4 8 12 10 12 4,:5 10 24 11 15 _4 -1 2 0 0 3 0 -0 0 1 0 0 0 -0 0 0 1 0 0 -0 0 0 0 0 1 -0 0 0 0 0 0 - gauss_jordan 0 1,1 2,:0 5 -1 0 -0 1 -0 0 + require 'math/misc/linear' + ]A=: 1 2 _1 _4 , 2 3 _1 _11 ,: _2 0 _3 22 + 1 2 _1 _4 + 2 3 _1 _11 +_2 0 _3 22 + + gauss_jordan A +1 0 0 _8 +0 1 0 1 +0 0 1 _2 diff --git a/Task/Reduced-row-echelon-form/J/reduced-row-echelon-form-3.j b/Task/Reduced-row-echelon-form/J/reduced-row-echelon-form-3.j index 08118d8381..a8745495f1 100644 --- a/Task/Reduced-row-echelon-form/J/reduced-row-echelon-form-3.j +++ b/Task/Reduced-row-echelon-form/J/reduced-row-echelon-form-3.j @@ -1,37 +1,16 @@ -mat=:".;._2]0 :0 - 1 0 0 0 0 0 1 0 0 0 0 _1 0 0 0 0 0 0 - 1 0 0 0 0 0 0 1 0 0 0 0 _1 0 0 0 0 0 - 1 0 0 0 0 0 0 0 1 0 0 0 0 _1 0 0 0 0 - 0 1 0 0 0 0 1 0 0 0 0 0 0 0 _1 0 0 0 - 0 1 0 0 0 0 0 0 1 0 0 _1 0 0 0 0 0 0 - 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 _1 0 - 0 0 1 0 0 0 1 0 0 0 0 0 _1 0 0 0 0 0 - 0 0 1 0 0 0 0 0 0 1 0 0 0 0 _1 0 0 0 - 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 _1 0 0 - 0 0 0 1 0 0 0 0 0 1 0 0 _1 0 0 0 0 0 - 0 0 0 0 1 0 0 1 0 0 0 0 0 _1 0 0 0 0 - 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 _1 0 - 0 0 0 0 1 0 0 0 0 0 1 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 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 1 - 0 0 0 0 0 1 0 0 0 0 1 0 0 0 _1 0 0 0 -) - gauss_jordan mat -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.435897 -0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.307692 -0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.512821 -0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0.717949 -0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0.487179 -0 0 0 0 0 1 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.205128 -0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0.282051 -0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0.333333 -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 1 0 0 0 0 0 0 0.512821 -0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0.641026 -0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0.717949 -0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0.769231 -0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0.512821 -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 1 0.820513 + gauss_jordan 2 0 _1 0 0,1 0 0 _1 0,3 0 0 _2 _1,0 1 0 0 _2,:0 1 _1 0 0 +1 0 0 0 _1 +0 1 0 0 _2 +0 0 1 0 _2 +0 0 0 1 _1 +0 0 0 0 0 + gauss_jordan 1 2 3 4 3 1,2 4 6 2 6 2,3 6 18 9 9 _6,4 8 12 10 12 4,:5 10 24 11 15 _4 +1 2 0 0 3 0 +0 0 1 0 0 0 +0 0 0 1 0 0 +0 0 0 0 0 1 +0 0 0 0 0 0 + gauss_jordan 0 1,1 2,:0 5 +1 0 +0 1 +0 0 diff --git a/Task/Reduced-row-echelon-form/J/reduced-row-echelon-form-4.j b/Task/Reduced-row-echelon-form/J/reduced-row-echelon-form-4.j new file mode 100644 index 0000000000..8c29a39f04 --- /dev/null +++ b/Task/Reduced-row-echelon-form/J/reduced-row-echelon-form-4.j @@ -0,0 +1,37 @@ +mat=: 0 ". ];._2 noun define + 1 0 0 0 0 0 1 0 0 0 0 _1 0 0 0 0 0 0 + 1 0 0 0 0 0 0 1 0 0 0 0 _1 0 0 0 0 0 + 1 0 0 0 0 0 0 0 1 0 0 0 0 _1 0 0 0 0 + 0 1 0 0 0 0 1 0 0 0 0 0 0 0 _1 0 0 0 + 0 1 0 0 0 0 0 0 1 0 0 _1 0 0 0 0 0 0 + 0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0 _1 0 + 0 0 1 0 0 0 1 0 0 0 0 0 _1 0 0 0 0 0 + 0 0 1 0 0 0 0 0 0 1 0 0 0 0 _1 0 0 0 + 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 _1 0 0 + 0 0 0 1 0 0 0 0 0 1 0 0 _1 0 0 0 0 0 + 0 0 0 0 1 0 0 1 0 0 0 0 0 _1 0 0 0 0 + 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 _1 0 + 0 0 0 0 1 0 0 0 0 0 1 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 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 1 + 0 0 0 0 0 1 0 0 0 0 1 0 0 0 _1 0 0 0 +) + gauss_jordan mat +1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.435897 +0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.307692 +0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.512821 +0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0.717949 +0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0.487179 +0 0 0 0 0 1 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.205128 +0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0.282051 +0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0.333333 +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 1 0 0 0 0 0 0 0.512821 +0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0.641026 +0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0.717949 +0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0.769231 +0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0.512821 +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 1 0.820513 diff --git a/Task/Reduced-row-echelon-form/Kotlin/reduced-row-echelon-form.kotlin b/Task/Reduced-row-echelon-form/Kotlin/reduced-row-echelon-form.kotlin new file mode 100644 index 0000000000..f5d39b72cb --- /dev/null +++ b/Task/Reduced-row-echelon-form/Kotlin/reduced-row-echelon-form.kotlin @@ -0,0 +1,80 @@ +// version 1.1.51 + +typealias Matrix = Array + +/* changes the matrix to RREF 'in place' */ +fun Matrix.toReducedRowEchelonForm() { + var lead = 0 + val rowCount = this.size + val colCount = this[0].size + for (r in 0 until rowCount) { + if (colCount <= lead) return + var i = r + + while (this[i][lead] == 0.0) { + i++ + if (rowCount == i) { + i = r + lead++ + if (colCount == lead) return + } + } + + val temp = this[i] + this[i] = this[r] + this[r] = temp + + if (this[r][lead] != 0.0) { + val div = this[r][lead] + for (j in 0 until colCount) this[r][j] /= div + } + + for (k in 0 until rowCount) { + if (k != r) { + val mult = this[k][lead] + for (j in 0 until colCount) this[k][j] -= this[r][j] * mult + } + } + + lead++ + } +} + +fun Matrix.printf(title: String) { + println(title) + val rowCount = this.size + val colCount = this[0].size + + for (r in 0 until rowCount) { + for (c in 0 until colCount) { + if (this[r][c] == -0.0) this[r][c] = 0.0 // get rid of negative zeros + print("${"% 6.2f".format(this[r][c])} ") + } + println() + } + + println() +} + +fun main(args: Array) { + val matrices = listOf( + arrayOf( + doubleArrayOf( 1.0, 2.0, -1.0, -4.0), + doubleArrayOf( 2.0, 3.0, -1.0, -11.0), + doubleArrayOf(-2.0, 0.0, -3.0, 22.0) + ), + arrayOf( + doubleArrayOf(1.0, 2.0, 3.0, 4.0, 3.0, 1.0), + doubleArrayOf(2.0, 4.0, 6.0, 2.0, 6.0, 2.0), + doubleArrayOf(3.0, 6.0, 18.0, 9.0, 9.0, -6.0), + doubleArrayOf(4.0, 8.0, 12.0, 10.0, 12.0, 4.0), + doubleArrayOf(5.0, 10.0, 24.0, 11.0, 15.0, -4.0) + ) + ) + + for (m in matrices) { + m.printf("Original matrix:") + m.toReducedRowEchelonForm() + m.printf("Reduced row echelon form:") + } +} diff --git a/Task/Reduced-row-echelon-form/Perl-6/reduced-row-echelon-form-1.pl6 b/Task/Reduced-row-echelon-form/Perl-6/reduced-row-echelon-form-1.pl6 index 5c2f5663ef..49251fc238 100644 --- a/Task/Reduced-row-echelon-form/Perl-6/reduced-row-echelon-form-1.pl6 +++ b/Task/Reduced-row-echelon-form/Perl-6/reduced-row-echelon-form-1.pl6 @@ -1,25 +1,21 @@ sub rref (@m) { - @m or return; + return unless @m; my ($lead, $rows, $cols) = 0, +@m, +@m[0]; for ^$rows -> $r { - return @m if $lead >= $cols; + $lead < $cols or return @m; my $i = $r; - - until @m[$i][$lead] { + until @m[$i;$lead] { ++$i == $rows or next; $i = $r; ++$lead == $cols and return @m; } - - @m[$i, $r] = @m[$r, $i]; - - my $lv = @m[$r][$lead]; + @m[$i, $r] = @m[$r, $i] if $r != $i; + my $lv = @m[$r;$lead]; @m[$r] »/=» $lv; - for ^$rows -> $n { next if $n == $r; - @m[$n] »-=» @m[$r] »*» @m[$n][$lead]; + @m[$n] »-=» @m[$r] »*» (@m[$n;$lead] // 0); } ++$lead; } diff --git a/Task/Reduced-row-echelon-form/REXX/reduced-row-echelon-form.rexx b/Task/Reduced-row-echelon-form/REXX/reduced-row-echelon-form.rexx index 35d4b53719..576fd4720f 100644 --- a/Task/Reduced-row-echelon-form/REXX/reduced-row-echelon-form.rexx +++ b/Task/Reduced-row-echelon-form/REXX/reduced-row-echelon-form.rexx @@ -3,44 +3,45 @@ cols=0; w=0; @.=0 /*max cols in a row; max width; mat.=; mat.1= ' 1 2 -1 -4 ' mat.2= ' 2 3 -1 -11 ' mat.3= ' -2 0 -3 22 ' - do r=1 until mat.r==''; _=mat.r /*build @.row.col from (matrix) mat.X*/ - do c=1 until _=''; parse var _ @.r.c _ - w=max(w, length(@.r.c) +1) /*find the maximum width of an element.*/ - end /*c*/ - cols=max(cols,c) /*remember max number of cols.*/ + do r=1 until mat.r==''; _=mat.r /*build @.row.col from (matrix) mat.X*/ + do c=1 until _=''; parse var _ @.r.c _ + w=max(w, length(@.r.c) + 1) /*find the maximum width of an element.*/ + end /*c*/ + cols=max(cols, c) /*save the maximum number of columns. */ end /*r*/ -rows=r-1 /*adjust the row count (from DO loop).*/ +rows=r - 1 /*adjust the row count (from DO loop).*/ call showMat 'original matrix' /*display the original matrix to screen*/ !=1 /*set the working column pointer to 1.*/ - /* ┌─────────────────────────────────────────◄── Reduced Row Echelon Form on matrix.*/ + /* ┌──────────────────────◄────────────────◄──── Reduced Row Echelon Form on matrix.*/ do r=1 for rows while cols>! /*begin to perform the heavy lifting. */ - j=r - do while @.j.!==0; j=j+1 - if j==rows then do; j=r; !=!+1; if cols==! then leave r; end + j=r /*use a subsitute index for the DO loop*/ + do while @.j.!==0; j=j + 1 + if j==rows then do; j=r; !=! + 1; if cols==! then leave r; end end /*while*/ /* [↓] swap rows J,R (but not if same)*/ - do _=1 for cols while j\==r; parse value @.r._ @.j._ with @.j._ @._._; end /*_*/ + do _=1 for cols while j\==r; parse value @.r._ @.j._ with @.j._ @._._ + end /*_*/ ?=@.r.! - do d=1 for cols while ?\=1; @.r.d=@.r.d/?; end /*d*/ - /* [↑] divide row J by @.r.p ──unless≡1*/ - do k=1 for rows; ?=@.k.! /*subtract (row K) @.r.s from row K.*/ - if k==r | ?=0 then iterate /*skip if row K is the same as row R.*/ - do s=1 for cols; @.k.s=@.k.s - ?*@.r.s; end /*s*/ - end /*k*/ /* [↑] for the rest of numbers in row.*/ - !=!+1 /*bump the column pointer. */ + do d=1 for cols while ?\=1; @.r.d= @.r.d / ? + end /*d*/ /* [↑] divide row J by @.r.p ──unless≡1*/ + do k=1 for rows; ?= @.k.! /*subtract (row K) @.r.s from row K.*/ + if k==r | ?=0 then iterate /*skip if row K is the same as row R.*/ + do s=1 for cols; @.k.s= @.k.s - ? * @.r.s + end /*s*/ + end /*k*/ /* [↑] for the rest of numbers in row.*/ + !=! + 1 /*bump the column pointer. */ end /*r*/ call showMat 'matrix RREF' /*display the reduced row echelon form.*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -showMat: parse arg title; say; say center(title, 3+(cols+1)*w, '─'); say +showMat: parse arg title; say; say center(title, 3 + (cols+1) * w, '─'); say do r=1 for rows; _= do c=1 for cols if @.r.c=='' then do; say "***error*** matrix element isn't defined:" - say 'row' row", column" c'.'; exit 13 + say 'row' r", column" c'.'; exit 13 end - _=_ right(@.r.c,w) + _=_ right(@.r.c, w) end /*c*/ - say _ /*display a row of the matrix to screen*/ - end /*r*/ - return + say _ /*display a matrix row to the terminal.*/ + end /*r*/; return diff --git a/Task/Reduced-row-echelon-form/Ring/reduced-row-echelon-form.ring b/Task/Reduced-row-echelon-form/Ring/reduced-row-echelon-form.ring new file mode 100644 index 0000000000..281a6642ae --- /dev/null +++ b/Task/Reduced-row-echelon-form/Ring/reduced-row-echelon-form.ring @@ -0,0 +1,60 @@ +# Project : Reduced row echelon form +# Date : 2017/12/27 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +matrix = [[1, 2, -1, -4], + [2, 3, -1, -11], + [ -2, 0, -3, 22]] +ref(matrix) +for row = 1 to 3 + for col = 1 to 4 + if matrix[row][col] = -0 + see "0 " + else + see "" + matrix[row][col] + " " + ok + next + see nl +next + +func ref(m) +nrows = 3 +ncols = 4 +lead = 1 +for r = 1 to nrows + if lead >= ncols + exit + ok + i = r + while m[i][lead] = 0 + i = i + 1 + if i = nrows + i = r + lead = lead + 1 + if lead = ncols + exit 2 + ok + ok + end + for j = 1 to ncols + temp = m[i][j] + m[i][j] = m[r][j] + m[r][j] = temp + next + n = m[r][lead] + if n != 0 + for j = 1 to ncols + m[r][j] = m[r][j] / n + next + ok + for i = 1 to nrows + if i != r + n = m[i][lead] + for j = 1 to ncols + m[i][j] = m[i][j] - m[r][j] * n + next + ok + next + lead = lead + 1 +next diff --git a/Task/Reduced-row-echelon-form/Sidef/reduced-row-echelon-form.sidef b/Task/Reduced-row-echelon-form/Sidef/reduced-row-echelon-form.sidef index 2ad4fc7041..53e6455b95 100644 --- a/Task/Reduced-row-echelon-form/Sidef/reduced-row-echelon-form.sidef +++ b/Task/Reduced-row-echelon-form/Sidef/reduced-row-echelon-form.sidef @@ -1,28 +1,27 @@ -func rref (Array m) { - m.is_empty && return; - var (lead, rows, cols) = (0, m.len, m[0].len); +func rref (M) { + var (j, rows, cols) = (0, M.len, M[0].len) - rows.range.each { |r| - lead >= cols && return m; - var i = r; + for r in (^rows) { + j < cols || return M - while (!m[i][lead]) { - ++i == rows || next; - i = r; - ++lead == cols && return m; + var i = r + while (!M[i][j]) { + ++i == rows || next + i = r + ++j == cols && return M } - m[i, r] = m[r, i]; - var lv = m[r][lead]; - m[r] = (m[r] »/» lv); + M[i, r] = M[r, i] if (r != i) + M[r] = (M[r] »/» M[r][j]) - rows.range.each { |n| - n == r && next; - m[n] = (m[n] »-« (m[r] «*« m[n][lead])) + for n in (^rows) { + next if (n == r) + M[n] = (M[n] »-« (M[r] »*» M[n][j])) } - ++lead; + ++j } - return m + + return M } func say_it (message, array) { diff --git a/Task/Regular-expressions/00DESCRIPTION b/Task/Regular-expressions/00DESCRIPTION index b41d5259ae..86c2bd4d80 100644 --- a/Task/Regular-expressions/00DESCRIPTION +++ b/Task/Regular-expressions/00DESCRIPTION @@ -3,6 +3,8 @@ {{omit from|GUISS}} {{omit from|PARI/GP}} -The goal of this task is -* to match a string against a regular expression -* to substitute part of a string using a regular expression + +;Task: +:*   match a string against a regular expression +:*   substitute part of a string using a regular expression +

diff --git a/Task/Regular-expressions/Factor/regular-expressions.factor b/Task/Regular-expressions/Factor/regular-expressions.factor new file mode 100644 index 0000000000..5a51929d24 --- /dev/null +++ b/Task/Regular-expressions/Factor/regular-expressions.factor @@ -0,0 +1,8 @@ +USING: io kernel prettyprint regexp ; +IN: rosetta-code.regexp + +"1000000" R/ 10+/ matches? . ! Does the entire string match the regexp? +"1001" R/ 10+/ matches? . +"1001" R/ 10+/ re-contains? . ! Does the string contain the regexp anywhere? + +"blueberry pie" R/ \p{alpha}+berry/ "pumpkin" re-replace print diff --git a/Task/Regular-expressions/Maple/regular-expressions.maple b/Task/Regular-expressions/Maple/regular-expressions.maple new file mode 100644 index 0000000000..cca184b3c6 --- /dev/null +++ b/Task/Regular-expressions/Maple/regular-expressions.maple @@ -0,0 +1,5 @@ +#Examples from Maple Help +StringTools:-RegMatch("^ab+bc$", "abbbbc"); +StringTools:-RegMatch("^ab+bc$", "abbbbcx"); +StringTools:-RegSub("a([bc]*)(c*d)", "abcd", "&-\\1-\\2"); +StringTools:-RegSub("(.*)c(anad[ai])(.*)", "Maple is canadian", "\\1C\\2\\3"); diff --git a/Task/Regular-expressions/Ring/regular-expressions.ring b/Task/Regular-expressions/Ring/regular-expressions.ring new file mode 100644 index 0000000000..88fb3cafd9 --- /dev/null +++ b/Task/Regular-expressions/Ring/regular-expressions.ring @@ -0,0 +1,12 @@ +# Project : Regular expressions +# Date : 2018/01/23 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : + +text = "I am a text" +if right(text,4) = "text" + see "'" + text +"' ends with 'text'" + nl +ok +i = substr(text,"am") +text = left(text,i - 1) + "was" + substr(text,i + 2) +see "replace 'am' with 'was' = " + text + nl diff --git a/Task/Remove-duplicate-elements/Aime/remove-duplicate-elements-1.aime b/Task/Remove-duplicate-elements/Aime/remove-duplicate-elements-1.aime new file mode 100644 index 0000000000..b3a9bdc326 --- /dev/null +++ b/Task/Remove-duplicate-elements/Aime/remove-duplicate-elements-1.aime @@ -0,0 +1,5 @@ +index x; + +list(1, 2, 3, 1, 2, 3, 4, 1).ucall(i_add, 1, x, 0); +x.i_vcall(o_, 1, " "); +o_newline(); diff --git a/Task/Remove-duplicate-elements/Aime/remove-duplicate-elements-2.aime b/Task/Remove-duplicate-elements/Aime/remove-duplicate-elements-2.aime new file mode 100644 index 0000000000..080b9f2e70 --- /dev/null +++ b/Task/Remove-duplicate-elements/Aime/remove-duplicate-elements-2.aime @@ -0,0 +1,12 @@ +integer a; +index x; +list l; + +l = list(8, 2, 1, 8, 2, 1, 4, 8); + +for (, a in l) { + if ((x[a] += 1) == 1) { + o_(" ", a); + } +} +o_newline(); diff --git a/Task/Remove-duplicate-elements/Elena/remove-duplicate-elements.elena b/Task/Remove-duplicate-elements/Elena/remove-duplicate-elements.elena new file mode 100644 index 0000000000..757436d75a --- /dev/null +++ b/Task/Remove-duplicate-elements/Elena/remove-duplicate-elements.elena @@ -0,0 +1,13 @@ +import extensions. +import system'collections. +import system'routines. + +program = +[ + var nums := (1,1,2,3,4,4). + dictionary unique := Dictionary new. + + nums forEach(:n)[ unique[n] := n ]. + + console printLine(unique). +]. diff --git a/Task/Remove-duplicate-elements/Fortran/remove-duplicate-elements.f b/Task/Remove-duplicate-elements/Fortran/remove-duplicate-elements-1.f similarity index 100% rename from Task/Remove-duplicate-elements/Fortran/remove-duplicate-elements.f rename to Task/Remove-duplicate-elements/Fortran/remove-duplicate-elements-1.f diff --git a/Task/Remove-duplicate-elements/Fortran/remove-duplicate-elements-2.f b/Task/Remove-duplicate-elements/Fortran/remove-duplicate-elements-2.f new file mode 100644 index 0000000000..9311d0922f --- /dev/null +++ b/Task/Remove-duplicate-elements/Fortran/remove-duplicate-elements-2.f @@ -0,0 +1,21 @@ +program remove_dups + implicit none + integer :: example(12) ! The input + integer :: res(size(example)) ! The output + integer :: k ! The number of unique elements + integer :: i + + example = [1, 2, 3, 2, 2, 4, 5, 5, 4, 6, 6, 5] + k = 1 + res(1) = example(1) + do i=2,size(example) + ! if the number already exist in res check next + if (any( res == example(i) )) cycle + ! No match found so add it to the output + k = k + 1 + res(k) = example(i) + end do + + write(*,advance='no',fmt='(a,i0,a)') 'Unique list has ',k,' elements: ' + write(*,*) res(1:k) +end program remove_dups diff --git a/Task/Remove-duplicate-elements/GW-BASIC/remove-duplicate-elements.gw-basic b/Task/Remove-duplicate-elements/GW-BASIC/remove-duplicate-elements.gw-basic new file mode 100644 index 0000000000..2df0fee4cf --- /dev/null +++ b/Task/Remove-duplicate-elements/GW-BASIC/remove-duplicate-elements.gw-basic @@ -0,0 +1,27 @@ +10 ' Remove Duplicates +20 OPTION BASE 1 +30 LET MAXI% = 7 +40 DIM D(7), R(7): ' data, result +50 ' Set the data. +60 FOR I% = 1 TO 7 +70 READ D(I%) +80 NEXT I% +90 ' Remove duplicates. +100 LET R(1) = D(1) +110 LET LRI% = 1: ' last index of result +120 LET P% = 1: ' position +130 WHILE P% < MAXI% +140 LET P% = P% + 1 +150 LET ISNEW = 1: ' is a new number? +160 LET RI% = 1: ' current index of result +170 WHILE (RI% <= LRI%) AND ISNEW +180 IF D(P%) = R(RI%) THEN LET ISNEW = 0 +190 LET RI% = RI% + 1 +200 WEND +210 IF ISNEW THEN LET LRI% = LRI% + 1: LET R(LRI%) = D(P%) +220 WEND +230 FOR RI% = 1 TO LRI% +240 PRINT R(RI%) +250 NEXT RI% +260 END +1000 DATA 1, 2, 2, 3, 4, 5, 5 diff --git a/Task/Remove-duplicate-elements/Gambas/remove-duplicate-elements.gambas b/Task/Remove-duplicate-elements/Gambas/remove-duplicate-elements.gambas new file mode 100644 index 0000000000..15d9cff4d9 --- /dev/null +++ b/Task/Remove-duplicate-elements/Gambas/remove-duplicate-elements.gambas @@ -0,0 +1,14 @@ +Public Sub Main() +Dim sString As String[] = Split("Now is the time for all the good men to come to the aid of the good party 1 2 1 3 3 3 2 1 1 2 3 4 33 2 5 4 333 5", " ") +Dim sFix As New String[] +Dim sTemp As String + +For Each sTemp In sString + sTemp &= " " + If InStr(sFix.Join(" ") & " ", sTemp) Then Continue + sFix.Add(Trim(sTemp)) +Next + +Print sFix.Join(" ") + +End diff --git a/Task/Remove-duplicate-elements/Julia/remove-duplicate-elements.julia b/Task/Remove-duplicate-elements/Julia/remove-duplicate-elements.julia index c176d57578..056b1fcac7 100644 --- a/Task/Remove-duplicate-elements/Julia/remove-duplicate-elements.julia +++ b/Task/Remove-duplicate-elements/Julia/remove-duplicate-elements.julia @@ -1,2 +1,2 @@ -a = [1,2,3,4,1,2,3,4] -unique(a) +a = [1, 2, 3, 4, 1, 2, 3, 4] +@show unique(a) Set(a) diff --git a/Task/Remove-duplicate-elements/Modula-2/remove-duplicate-elements.mod2 b/Task/Remove-duplicate-elements/Modula-2/remove-duplicate-elements.mod2 new file mode 100644 index 0000000000..3fdc6595aa --- /dev/null +++ b/Task/Remove-duplicate-elements/Modula-2/remove-duplicate-elements.mod2 @@ -0,0 +1,49 @@ +MODULE RemoveDuplicates; + +FROM STextIO IMPORT + WriteLn; +FROM SWholeIO IMPORT + WriteInt; + +TYPE + TArrayRange = [1 .. 7]; + TArray = ARRAY TArrayRange OF INTEGER; + +VAR + DataArray, ResultArray: TArray; + ResultIndex, LastResultIndex, Position: CARDINAL; + IsNewNumber: BOOLEAN; + +BEGIN + (* Set the data. *); + DataArray[1] := 1; + DataArray[2] := 2; + DataArray[3] := 2; + DataArray[4] := 3; + DataArray[5] := 4; + DataArray[6] := 5; + DataArray[7] := 5; + + ResultArray[1] := DataArray[1]; + LastResultIndex := 1; + Position := 1; + WHILE Position < HIGH(DataArray) DO + INC(Position); + IsNewNumber := TRUE; + ResultIndex := 1; + WHILE (ResultIndex <= LastResultIndex) AND IsNewNumber DO + IF DataArray[Position] = ResultArray[ResultIndex] THEN + IsNewNumber := FALSE; + END; + INC(ResultIndex); + END; + IF IsNewNumber THEN + INC(LastResultIndex); + ResultArray[LastResultIndex] := DataArray[Position]; + END + END; + FOR ResultIndex := 1 TO LastResultIndex DO + WriteInt(ResultArray[ResultIndex], 1); + WriteLn; + END; +END RemoveDuplicates. diff --git a/Task/Remove-duplicate-elements/Red/remove-duplicate-elements.red b/Task/Remove-duplicate-elements/Red/remove-duplicate-elements.red new file mode 100644 index 0000000000..d337da80c2 --- /dev/null +++ b/Task/Remove-duplicate-elements/Red/remove-duplicate-elements.red @@ -0,0 +1,3 @@ +>> items: [1 "a" "c" 1 3 4 5 "c" 3 4 5] +>> unique items +== [1 "a" "c" 3 4 5] diff --git a/Task/Remove-duplicate-elements/Rust/remove-duplicate-elements.rust b/Task/Remove-duplicate-elements/Rust/remove-duplicate-elements.rust index 0ae55d2601..9c0138450e 100644 --- a/Task/Remove-duplicate-elements/Rust/remove-duplicate-elements.rust +++ b/Task/Remove-duplicate-elements/Rust/remove-duplicate-elements.rust @@ -1,16 +1,19 @@ -use std::vec::Vec; use std::collections::HashSet; use std::hash::Hash; -use std::cmp::Eq; -fn main(){ - let mut sample_elements = vec![0u8,0,1,1,2,3,2]; - println!("Before removal of duplicates : {:?}", sample_elements); - remove_duplicate_elements(&mut sample_elements); - println!("After removal of duplicates : {:?}", sample_elements); -} - -fn remove_duplicate_elements(elements: &mut Vec){ - let set : HashSet<_> = elements.drain(..).collect(); +fn remove_duplicate_elements_hashing(elements: &mut Vec) { + let set: HashSet<_> = elements.drain(..).collect(); elements.extend(set.into_iter()); } + +fn remove_duplicate_elements_sorting(elements: &mut Vec) { + elements.sort_unstable(); // order does not matter + elements.dedup(); +} + +fn main() { + let mut sample_elements = vec![0, 0, 1, 1, 2, 3, 2]; + println!("Before removal of duplicates : {:?}", sample_elements); + remove_duplicate_elements_sorting(&mut sample_elements); + println!("After removal of duplicates : {:?}", sample_elements); +} diff --git a/Task/Remove-duplicate-elements/VBA/remove-duplicate-elements.vba b/Task/Remove-duplicate-elements/VBA/remove-duplicate-elements.vba new file mode 100644 index 0000000000..c89ba1497f --- /dev/null +++ b/Task/Remove-duplicate-elements/VBA/remove-duplicate-elements.vba @@ -0,0 +1,29 @@ +Option Explicit + +Sub Main() +Dim myArr() As Variant, i As Long + + myArr = Remove_Duplicate(Array(1.23456789101112E+16, True, False, True, "Alpha", 1, 235, 4, 1.25, 1.25, "Beta", 1.23456789101112E+16, "Delta", "Alpha", "Charlie", 1, 2, "Foxtrot", "Foxtrot", "Alpha", 235)) +'return : + For i = LBound(myArr) To UBound(myArr) + Debug.Print myArr(i) + Next +End Sub + +Private Function Remove_Duplicate(Arr As Variant) As Variant() +Dim myColl As New Collection, Temp() As Variant, i As Long, cpt As Long + + ReDim Temp(UBound(Arr)) + For i = LBound(Arr) To UBound(Arr) + On Error Resume Next + myColl.Add CStr(Arr(i)), CStr(Arr(i)) + If Err.Number > 0 Then + On Error GoTo 0 + Else + Temp(cpt) = Arr(i) + cpt = cpt + 1 + End If + Next i + ReDim Preserve Temp(cpt - 1) + Remove_Duplicate = Temp +End Function diff --git a/Task/Remove-lines-from-a-file/VBA/remove-lines-from-a-file-1.vba b/Task/Remove-lines-from-a-file/VBA/remove-lines-from-a-file-1.vba new file mode 100644 index 0000000000..7eea82d27b --- /dev/null +++ b/Task/Remove-lines-from-a-file/VBA/remove-lines-from-a-file-1.vba @@ -0,0 +1,34 @@ +Option Explicit + +Sub Main() + 'See Output #1 + RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 11, 5 + 'See Output #2 + RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 8, 5 + 'See Output #3 + RemoveLines "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 3, 5 +End Sub + +Private Sub RemoveLines(StrFile As String, StartLine As Long, NumberOfLines As Long) +Dim Nb As Integer, s As String, count As Long, out As String + Nb = FreeFile + Open StrFile For Input As #Nb + While Not EOF(Nb) + count = count + 1 + Line Input #Nb, s + If count < StartLine Or count >= StartLine + NumberOfLines Then + out = out & s & vbCrLf + End If + Wend + Close #Nb + If StartLine >= count Then + MsgBox "The file contains only " & count & " lines" + ElseIf StartLine + NumberOfLines > count Then + MsgBox "You only can remove " & count - StartLine & " lines" + Else + Nb = FreeFile + Open StrFile For Output As #Nb + Print #Nb, out + Close #Nb + End If +End Sub diff --git a/Task/Remove-lines-from-a-file/VBA/remove-lines-from-a-file-2.vba b/Task/Remove-lines-from-a-file/VBA/remove-lines-from-a-file-2.vba new file mode 100644 index 0000000000..2e1e17c10e --- /dev/null +++ b/Task/Remove-lines-from-a-file/VBA/remove-lines-from-a-file-2.vba @@ -0,0 +1,36 @@ +Option Explicit + +Sub Main() + 'See Output First call + OtherWay "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 11, 5 + 'See Output Second call + OtherWay "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 8, 5 + 'See Output Third call + OtherWay "C:\Users\" & Environ("username") & "\Desktop\foobar.txt", 3, 5 +End Sub + +Private Sub OtherWay(StrFile As String, StartLine As Long, NumberOfLines As Long) +Dim Nb As Integer, s As String, arr, i As Long, out() As String, j As Long + Nb = FreeFile + Open StrFile For Input As #Nb + s = Input(LOF(1), #Nb) + Close #Nb + arr = Split(s, Chr(13)) + If StartLine >= UBound(arr) + 1 Then + MsgBox "First call : " & vbCrLf & " The file contains only " & UBound(arr) + 1 & " lines" + ElseIf StartLine + NumberOfLines > UBound(arr) + 1 Then + MsgBox "Second call : " & vbCrLf & " You only can remove " & UBound(arr) + 1 - StartLine & " lines" + Else + For i = LBound(arr) To UBound(arr) + If i < StartLine - 1 Or i >= StartLine + NumberOfLines - 1 Then + ReDim Preserve out(j) + out(j) = arr(i) + j = j + 1 + End If + Next i + Nb = FreeFile + Open StrFile For Output As #Nb + Print #Nb, Join(out, Chr(13)) + Close #Nb + End If +End Sub diff --git a/Task/Remove-lines-from-a-file/VBScript/remove-lines-from-a-file.vb b/Task/Remove-lines-from-a-file/VBScript/remove-lines-from-a-file.vb index 634e1673c0..14fa016828 100644 --- a/Task/Remove-lines-from-a-file/VBScript/remove-lines-from-a-file.vb +++ b/Task/Remove-lines-from-a-file/VBScript/remove-lines-from-a-file.vb @@ -17,8 +17,8 @@ Sub remove_lines(filepath,start,number) Do Until discard_count = number InFile.SkipLine discard_count = discard_count + 1 - line_count = line_count + 1 Loop + line_count = line_count + 1 End If Loop InFile.Close diff --git a/Task/Rename-a-file/BaCon/rename-a-file.bacon b/Task/Rename-a-file/BaCon/rename-a-file.bacon new file mode 100644 index 0000000000..a7ebf91369 --- /dev/null +++ b/Task/Rename-a-file/BaCon/rename-a-file.bacon @@ -0,0 +1,4 @@ +RENAME "input.txt" TO "output.txt" +RENAME "/input.txt" TO "/output.txt" +RENAME "docs" TO "mydocs" +RENAME "/docs" TO "/mydocs" diff --git a/Task/Rename-a-file/JavaScript/rename-a-file.js b/Task/Rename-a-file/JavaScript/rename-a-file.js index 0eb3b89acf..451bc18212 100644 --- a/Task/Rename-a-file/JavaScript/rename-a-file.js +++ b/Task/Rename-a-file/JavaScript/rename-a-file.js @@ -1,5 +1,5 @@ -var fso = new ActiveXObject("Scripting.FileSystemObject"); -fso.MoveFile('input.txt', 'output.txt'); -fso.MoveFile('c:/input.txt', 'c:/output.txt'); -fso.MoveFolder('docs', 'mydocs'); -fso.MoveFolder('c:/docs', 'c:/mydocs'); +var fso = new ActiveXObject("Scripting.FileSystemObject") +fso.MoveFile("input.txt", "output.txt") +fso.MoveFile("c:/input.txt", "c:/output.txt") +fso.MoveFolder("docs", "mydocs") +fso.MoveFolder("c:/docs", "c:/mydocs") diff --git a/Task/Rename-a-file/OCaml/rename-a-file.ocaml b/Task/Rename-a-file/OCaml/rename-a-file.ocaml index 12a31dbe55..482ee50d57 100644 --- a/Task/Rename-a-file/OCaml/rename-a-file.ocaml +++ b/Task/Rename-a-file/OCaml/rename-a-file.ocaml @@ -1,4 +1,5 @@ -Sys.rename "input.txt" "output.txt";; -Sys.rename "docs" "mydocs";; -Sys.rename "/input.txt" "/output.txt";; -Sys.rename "/docs" "/mydocs";; +let () = + Sys.rename "input.txt" "output.txt"; + Sys.rename "docs" "mydocs"; + Sys.rename "/input.txt" "/output.txt"; + Sys.rename "/docs" "/mydocs"; diff --git a/Task/Rename-a-file/Octave/rename-a-file.octave b/Task/Rename-a-file/Octave/rename-a-file.octave index d64fba013b..302abaaaa2 100644 --- a/Task/Rename-a-file/Octave/rename-a-file.octave +++ b/Task/Rename-a-file/Octave/rename-a-file.octave @@ -1,3 +1,3 @@ - rename('docs','mydocs'); +rename('docs','mydocs'); rename('input.txt','/output.txt'); rename('/docs','/mydocs'); diff --git a/Task/Rep-string/BaCon/rep-string.bacon b/Task/Rep-string/BaCon/rep-string.bacon new file mode 100644 index 0000000000..e002b25bdf --- /dev/null +++ b/Task/Rep-string/BaCon/rep-string.bacon @@ -0,0 +1,17 @@ +all$ = "1001110011 1110111011 0010010010 1010101010 1111111111 0100101101 0100100 101 11 00 1" + +FOR word$ IN all$ + FOR x = LEN(word$)/2 DOWNTO 1 + + ex$ = EXPLODE$(word$, x) + + FOR st$ IN UNIQ$(ex$) + IF NOT(REGEX(HEAD$(ex$, 1), "^" & st$)) THEN CONTINUE 2 + NEXT + + PRINT "Repeating string: ", word$, " -> ", HEAD$(ex$, 1) + CONTINUE 2 + NEXT + + PRINT "Not a repeating string: ", word$ +NEXT diff --git a/Task/Rep-string/Julia/rep-string.julia b/Task/Rep-string/Julia/rep-string.julia index c49688dde6..8bde4ed33d 100644 --- a/Task/Rep-string/Julia/rep-string.julia +++ b/Task/Rep-string/Julia/rep-string.julia @@ -1,34 +1,23 @@ -function list_reps{T<:String}(r::T) +function repstring(r::AbstractString) n = length(r) - replst = T[] - for m in 1:n>>1 - s = r[1:chr2ind(r,m)] - (s^(div(n,m)+1))[1:chr2ind(r,n)] == r || continue + replst = String[] + for m in 1:n÷2 + s = r[1:chr2ind(r, m)] + if (s ^ cld(n, m))[1:chr2ind(r, n)] != r continue end push!(replst, s) end return replst end -tests = {"1001110011", - "1110111011", - "0010010010", - "1010101010", - "1111111111", - "0100101101", - "0100100", - "101", - "11", - "00", - "1", - "\u2200\u2203\u2200\u2203\u2200\u2203\u2200\u2203"} +tests = ["1001110011", "1110111011", "0010010010", "1010101010", "1111111111", + "0100101101", "0100100", "101", "11", "00", "1", + "\u2200\u2203\u2200\u2203\u2200\u2203\u2200\u2203"] for r in tests - replst = list_reps(r) - rlen = length(replst) - print(@sprintf(" %s ", r)) - if rlen == 0 - println("is not a rep-string.") + replst = repstring(r) + if isempty(replst) + println("$r is not a rep-string.") else - println("is a rep-string of ", join(replst, ", "), ".") + println("$r is a rep-string of ", join(replst, ", "), ".") end end diff --git a/Task/Rep-string/Ring/rep-string.ring b/Task/Rep-string/Ring/rep-string.ring new file mode 100644 index 0000000000..4d5e6850e7 --- /dev/null +++ b/Task/Rep-string/Ring/rep-string.ring @@ -0,0 +1,34 @@ +# Project : Rep-string +# Date : 2017/10/14 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + + +test = ["1001110011", + "1110111011", + "0010010010", + "1010101010", + "1111111111", + "0100101101", + "0100100", + "101", + "11", + "00", + "1"] + +for n = 1 to len(test) + strend = "" + for m=1 to len(test[n]) + strbegin = substr(test[n], 1, m) + strcut = right(test[n], len(test[n]) - m) + nr = substr(strcut, strbegin) + if nr=1 and len(test[n]) > 1 + strend = strbegin + ok + next + if strend = "" + see "" + test[n] + " -> (none)" + nl + else + see "" + test[n] + " -> " + strend + nl + ok +next diff --git a/Task/Repeat-a-string/BaCon/repeat-a-string-1.bacon b/Task/Repeat-a-string/BaCon/repeat-a-string-1.bacon new file mode 100644 index 0000000000..0a7496ea08 --- /dev/null +++ b/Task/Repeat-a-string/BaCon/repeat-a-string-1.bacon @@ -0,0 +1,4 @@ +DOTIMES 5 + s$ = s$ & "ha" +DONE +PRINT s$ diff --git a/Task/Repeat-a-string/BaCon/repeat-a-string-2.bacon b/Task/Repeat-a-string/BaCon/repeat-a-string-2.bacon new file mode 100644 index 0000000000..da134f4d70 --- /dev/null +++ b/Task/Repeat-a-string/BaCon/repeat-a-string-2.bacon @@ -0,0 +1 @@ +PRINT FILL$(5, ASC("x")) diff --git a/Task/Repeat-a-string/Julia/repeat-a-string.julia b/Task/Repeat-a-string/Julia/repeat-a-string.julia index d25ec786b0..67ffae1556 100644 --- a/Task/Repeat-a-string/Julia/repeat-a-string.julia +++ b/Task/Repeat-a-string/Julia/repeat-a-string.julia @@ -1,4 +1,4 @@ -"ha"^5 -'*'^5 -#the (^) operator is really just call to the `repeat` function -repeat("ha",5) +@show "ha" ^ 5 + +# The ^ operator is really just call to the `repeat` function +@show repeat("ha", 5) diff --git a/Task/Repeat-a-string/Perl-6/repeat-a-string.pl6 b/Task/Repeat-a-string/Perl-6/repeat-a-string.pl6 index a9ae20555f..49f4436a9e 100644 --- a/Task/Repeat-a-string/Perl-6/repeat-a-string.pl6 +++ b/Task/Repeat-a-string/Perl-6/repeat-a-string.pl6 @@ -1 +1 @@ -"ha" x 5 +print "ha" x 5 diff --git a/Task/Repeat-a-string/Red/repeat-a-string.red b/Task/Repeat-a-string/Red/repeat-a-string.red new file mode 100644 index 0000000000..357ddeb90d --- /dev/null +++ b/Task/Repeat-a-string/Red/repeat-a-string.red @@ -0,0 +1,5 @@ +>> str: "Add duplicates to string" +>> insert/dup str "ha" 3 +== "hahahaAdd duplicates to string" +>> insert/dup tail str "ha" 3 +== "hahahaAdd duplicates to stringhahaha" diff --git a/Task/Resistor-mesh/Java/resistor-mesh.java b/Task/Resistor-mesh/Java/resistor-mesh.java new file mode 100644 index 0000000000..e75f7cf7d8 --- /dev/null +++ b/Task/Resistor-mesh/Java/resistor-mesh.java @@ -0,0 +1,107 @@ +import java.util.ArrayList; +import java.util.List; + +public class ResistorMesh { + private static final int S = 10; + + private static class Node { + double v; + int fixed; + + Node(double v, int fixed) { + this.v = v; + this.fixed = fixed; + } + } + + private static void setBoundary(List> m) { + m.get(1).get(1).v = 1.0; + m.get(1).get(1).fixed = 1; + + m.get(6).get(7).v = -1.0; + m.get(6).get(7).fixed = -1; + } + + private static double calcDiff(List> m, List> d, int w, int h) { + double total = 0.0; + for (int i = 0; i < h; ++i) { + for (int j = 0; j < w; ++j) { + double v = 0.0; + int n = 0; + if (i > 0) { + v += m.get(i - 1).get(j).v; + n++; + } + if (j > 0) { + v += m.get(i).get(j - 1).v; + n++; + } + if (i + 1 < h) { + v += m.get(i + 1).get(j).v; + n++; + } + if (j + 1 < w) { + v += m.get(i).get(j + 1).v; + n++; + } + v = m.get(i).get(j).v - v / n; + d.get(i).get(j).v = v; + if (m.get(i).get(j).fixed == 0) { + total += v * v; + } + } + } + return total; + } + + private static double iter(List> m, int w, int h) { + List> d = new ArrayList<>(h); + for (int i = 0; i < h; ++i) { + List t = new ArrayList<>(w); + for (int j = 0; j < w; ++j) { + t.add(new Node(0.0, 0)); + } + d.add(t); + } + + double[] cur = new double[3]; + double diff = 1e10; + + while (diff > 1e-24) { + setBoundary(m); + diff = calcDiff(m, d, w, h); + for (int i = 0; i < h; ++i) { + for (int j = 0; j < w; ++j) { + m.get(i).get(j).v -= d.get(i).get(j).v; + } + } + } + + for (int i = 0; i < h; ++i) { + for (int j = 0; j < w; ++j) { + int k = 0; + if (i != 0) k++; + if (j != 0) k++; + if (i < h - 1) k++; + if (j < w - 1) k++; + cur[m.get(i).get(j).fixed + 1] += d.get(i).get(j).v * k; + } + } + + return (cur[2] - cur[0]) / 2.0; + } + + public static void main(String[] args) { + List> mesh = new ArrayList<>(S); + for (int i = 0; i < S; ++i) { + List t = new ArrayList<>(S); + for (int j = 0; j < S; ++j) { + t.add(new Node(0.0, 0)); + } + mesh.add(t); + } + + double r = 2.0 / iter(mesh, S, S); + System.out.printf("R = %.15f", r); + } +} diff --git a/Task/Resistor-mesh/Modula-2/resistor-mesh.mod2 b/Task/Resistor-mesh/Modula-2/resistor-mesh.mod2 new file mode 100644 index 0000000000..b1a160a892 --- /dev/null +++ b/Task/Resistor-mesh/Modula-2/resistor-mesh.mod2 @@ -0,0 +1,111 @@ +MODULE ResistorMesh; +FROM RConversions IMPORT RealToStringFixed; +FROM Terminal IMPORT WriteString,WriteLn,ReadChar; + +CONST S = 10; + +TYPE Node = RECORD + v : LONGREAL; + fixed : INTEGER; +END; + +PROCEDURE SetBoundary(VAR m : ARRAY OF ARRAY OF Node); +BEGIN + m[1][1].v := 1.0; + m[1][1].fixed := 1; + + m[6][7].v := -1.0; + m[6][7].fixed := -1; +END SetBoundary; + +PROCEDURE CalcDiff(VAR m,d : ARRAY OF ARRAY OF Node) : LONGREAL; +VAR + total,v : LONGREAL; + i,j,n : INTEGER; +BEGIN + total := 0.0; + FOR i:=0 TO S DO + FOR j:=0 TO S DO + v := 0.0; + n := 0; + IF i>0 THEN + v := v + m[i-1][j].v; + INC(n); + END; + IF j>0 THEN + v := v + m[i][j-1].v; + INC(n); + END; + IF i+11.0E-24 DO + SetBoundary(m); + diff := CalcDiff(m,d); + FOR i:=0 TO S DO + FOR j:=0 TO S DO + m[i][j].v := m[i][j].v - d[i][j].v; + END; + END; + END; + + FOR i:=0 TO S DO + FOR j:=0 TO S DO + k:=0; + IF i#0 THEN INC(k) END; + IF j#0 THEN INC(k) END; + IF i) { + println("Class C does not have a method called $id") + if (args.size > 0) println("which takes arguments: ${args.asList()}") + } +} fun main(args: Array) { val c: dynamic = C() // 'dynamic' turns off compile time checks - try { - c.foo() // the compiler now allows this call even though foo() is undefined - } - catch (t: Throwable) { - if (t.message == "undefined is not a function") { - println("Class C does not have a method called foo") - } - else { - println(t.message) - } - } + c.foo() // the compiler now allows this call even though foo() is undefined } diff --git a/Task/Return-multiple-values/Objeck/return-multiple-values.objeck b/Task/Return-multiple-values/Objeck/return-multiple-values.objeck new file mode 100644 index 0000000000..f12ae369fb --- /dev/null +++ b/Task/Return-multiple-values/Objeck/return-multiple-values.objeck @@ -0,0 +1,11 @@ +class Program { + function : Main(args : String[]) ~ Nil { + a := IntHolder->New(3); b := IntHolder->New(7); + Addon(a,b); + a->Get()->PrintLine(); b->Get()->PrintLine(); + } + + function : Addon(a : IntHolder, b : IntHolder) ~ Nil { + a->Set(a->Get() + 2); b->Set(b->Get() + 13); + } +} diff --git a/Task/Return-multiple-values/VBA/return-multiple-values-1.vba b/Task/Return-multiple-values/VBA/return-multiple-values-1.vba new file mode 100644 index 0000000000..40423a381e --- /dev/null +++ b/Task/Return-multiple-values/VBA/return-multiple-values-1.vba @@ -0,0 +1,19 @@ +Type Contact + Name As String + firstname As String + Age As Byte +End Type + +Function SetContact(N As String, Fn As String, A As Byte) As Contact + SetContact.Name = N + SetContact.firstname = Fn + SetContact.Age = A +End Function + +'For use : +Sub Test_SetContact() +Dim Cont As Contact + + Cont = SetContact("SMITH", "John", 23) + Debug.Print Cont.Name & " " & Cont.firstname & ", " & Cont.Age & " years old." +End Sub diff --git a/Task/Return-multiple-values/VBA/return-multiple-values-2.vba b/Task/Return-multiple-values/VBA/return-multiple-values-2.vba new file mode 100644 index 0000000000..330359d061 --- /dev/null +++ b/Task/Return-multiple-values/VBA/return-multiple-values-2.vba @@ -0,0 +1,21 @@ +Function Divide(Dividend As Integer, Divisor As Integer, ByRef Result As Double) As Boolean + Divide = True + On Error Resume Next + Result = Dividend / Divisor + If Err <> 0 Then + Divide = False + On Error GoTo 0 + End If +End Function + +'For use : +Sub test_Divide() +Dim R As Double, Ddd As Integer, Dvs As Integer, B As Boolean + + Ddd = 10: Dvs = 3 + B = Divide(Ddd, Dvs, R) + Debug.Print "Divide return : " & B & " Result = " & R + Ddd = 10: Dvs = 0 + B = Divide(Ddd, Dvs, R) + Debug.Print "Divide return : " & B & " Result = " & R +End Sub diff --git a/Task/Return-multiple-values/VBA/return-multiple-values-3.vba b/Task/Return-multiple-values/VBA/return-multiple-values-3.vba new file mode 100644 index 0000000000..ca91225ee4 --- /dev/null +++ b/Task/Return-multiple-values/VBA/return-multiple-values-3.vba @@ -0,0 +1,34 @@ +Function Multiple_Divide(Dividend As Integer, Divisor As Integer, ParamArray numbers() As Variant) As Long +Dim i As Integer + + On Error GoTo ErrorHandler + numbers(LBound(numbers)) = Dividend / Divisor + For i = LBound(numbers) + 1 To UBound(numbers) + numbers(i) = numbers(i - 1) / Divisor + Next i + Multiple_Divide = 1: Exit Function +ErrorHandler: + Multiple_Divide = 0 +End Function + +'For use : +Sub test_Multiple_Divide() +Dim Arr(3) As Variant, Ddd As Integer, Dvs As Integer, L As Long, i As Integer + + Ddd = 10: Dvs = 3 + L = Multiple_Divide(Ddd, Dvs, Arr(0), Arr(1), Arr(2), Arr(3)) + Debug.Print "The function return : " & L + Debug.Print "The values in return are : " + For i = LBound(Arr) To UBound(Arr) + Debug.Print Arr(i) + Next i + Erase Arr + Debug.Print "--------------------------------------" + Ddd = 10: Dvs = 0 + L = Multiple_Divide(Ddd, Dvs, Arr(0), Arr(1), Arr(2), Arr(3)) + Debug.Print "The function return : " & L + Debug.Print "The values in return are : " + For i = LBound(Arr) To UBound(Arr) + Debug.Print IIf(Arr(i) = "", "vbNullString", "Null") + Next i +End Sub diff --git a/Task/Return-multiple-values/VBA/return-multiple-values-4.vba b/Task/Return-multiple-values/VBA/return-multiple-values-4.vba new file mode 100644 index 0000000000..11f52fc651 --- /dev/null +++ b/Task/Return-multiple-values/VBA/return-multiple-values-4.vba @@ -0,0 +1,18 @@ +Function List() As String() +Dim i&, Temp(9) As String + + For i = 0 To 9 + Temp(i) = "Liste " & i + 1 + Next + List = Temp +End Function + +'For use : +Sub test_List() +Dim myArr() As String, i As Integer +'Note : you don't need to Dim your array ! + myArr = List() + For i = LBound(myArr) To UBound(myArr) + Debug.Print myArr(i) + Next +End Sub diff --git a/Task/Reverse-a-string/Aime/reverse-a-string.aime b/Task/Reverse-a-string/Aime/reverse-a-string.aime index da2c95421f..4595abfe8e 100644 --- a/Task/Reverse-a-string/Aime/reverse-a-string.aime +++ b/Task/Reverse-a-string/Aime/reverse-a-string.aime @@ -1 +1 @@ -o_(b_reverse(b_draft("Hello, World!")), "\n"); +o_(b_reverse("Hello, World!"), "\n"); diff --git a/Task/Reverse-a-string/Fortran/reverse-a-string-3.f b/Task/Reverse-a-string/Fortran/reverse-a-string-3.f new file mode 100644 index 0000000000..a9c174df49 --- /dev/null +++ b/Task/Reverse-a-string/Fortran/reverse-a-string-3.f @@ -0,0 +1,13 @@ + program reverse_string + implicit none + character (80) :: cadena + integer :: k, n + ! + cadena = "abcdefgh" + n = len_trim (cadena) + ! + write (*,*) cadena + forall (k=1:n) cadena (k:k) = cadena (n-k+1:n-k+1) + write (*,*) cadena + ! +end program reverse_string diff --git a/Task/Reverse-a-string/Modula-2/reverse-a-string.mod2 b/Task/Reverse-a-string/Modula-2/reverse-a-string.mod2 new file mode 100644 index 0000000000..993d51607d --- /dev/null +++ b/Task/Reverse-a-string/Modula-2/reverse-a-string.mod2 @@ -0,0 +1,40 @@ +MODULE ReverseStr; +FROM FormatString IMPORT FormatString; +FROM Terminal IMPORT Write,WriteString,WriteLn,ReadChar; + +PROCEDURE WriteInt(n : INTEGER); +VAR buf : ARRAY[0..15] OF CHAR; +BEGIN + FormatString("%i", buf, n); + WriteString(buf) +END WriteInt; + +PROCEDURE ReverseStr(in : ARRAY OF CHAR; VAR out : ARRAY OF CHAR); +VAR ip,op : INTEGER; +BEGIN + ip := 0; + op := 0; + WHILE in[ip] # 0C DO + INC(ip) + END; + DEC(ip); + WHILE ip>=0 DO + out[op] := in[ip]; + INC(op); + DEC(ip) + END +END ReverseStr; + +TYPE A = ARRAY[0..63] OF CHAR; +VAR is,os : A; +BEGIN + is := "Hello World"; + ReverseStr(is, os); + + WriteString(is); + WriteLn; + WriteString(os); + WriteLn; + + ReadChar +END ReverseStr. diff --git a/Task/Reverse-a-string/Nim/reverse-a-string.nim b/Task/Reverse-a-string/Nim/reverse-a-string-1.nim similarity index 100% rename from Task/Reverse-a-string/Nim/reverse-a-string.nim rename to Task/Reverse-a-string/Nim/reverse-a-string-1.nim diff --git a/Task/Reverse-a-string/Nim/reverse-a-string-2.nim b/Task/Reverse-a-string/Nim/reverse-a-string-2.nim new file mode 100644 index 0000000000..be7923b8b1 --- /dev/null +++ b/Task/Reverse-a-string/Nim/reverse-a-string-2.nim @@ -0,0 +1,4 @@ +import unicode + +doAssert "foobar".reversed == "raboof" +doAssert "先秦兩漢".reversed == "漢兩秦先" diff --git a/Task/Reverse-a-string/Red/reverse-a-string.red b/Task/Reverse-a-string/Red/reverse-a-string.red new file mode 100644 index 0000000000..4c85b8c75e --- /dev/null +++ b/Task/Reverse-a-string/Red/reverse-a-string.red @@ -0,0 +1,2 @@ +>> reverse "asdf" +== "fdsa" diff --git a/Task/Reverse-words-in-a-string/Aime/reverse-words-in-a-string.aime b/Task/Reverse-words-in-a-string/Aime/reverse-words-in-a-string.aime index 5ed7842e08..c15ac66c50 100644 --- a/Task/Reverse-words-in-a-string/Aime/reverse-words-in-a-string.aime +++ b/Task/Reverse-words-in-a-string/Aime/reverse-words-in-a-string.aime @@ -1,32 +1,23 @@ -integer i, j, s; +integer j; list l, x; -data b; -file f; +text s, t; -l_bill(l, 0, - "---------- Ice and Fire ------------", - "", - "fire, in end will world the say Some", - "ice. in say Some", - "desire of tasted I've what From", - "fire. favor who those with hold I", - "", - "... elided paragraph last ...", - "", - "Frost Robert -----------------------"); +l = list("---------- Ice and Fire ------------", + "", + "fire, in end will world the say Some", + "ice. in say Some", + "desire of tasted I've what From", + "fire. favor who those with hold I", + "", + "... elided paragraph last ...", + "", + "Frost Robert -----------------------"); -i = -l_length(l); -while (i) { - b_cast(b, l[i]); - f_b_affix(f, b); - f_list(f, x, 0); - j = l_length(x); - s = 0; - while (j) { - o_space(s); - s = 1; - o_text(x[j -= 1]); +for (, t in l) { + file().b_affix(t).list(x, 0); + for (j, s in x.reverse) { + o_space(sign(j)); + o_text(s); } o_newline(); - i += 1; } diff --git a/Task/Reverse-words-in-a-string/Factor/reverse-words-in-a-string.factor b/Task/Reverse-words-in-a-string/Factor/reverse-words-in-a-string.factor new file mode 100644 index 0000000000..48fa1afd96 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Factor/reverse-words-in-a-string.factor @@ -0,0 +1,15 @@ +USING: io sequences splitting ; +IN: rosetta-code.reverse-words + +"---------- Ice and Fire ------------ + +fire, in end will world the say Some +ice. in say Some +desire of tasted I've what From +fire. favor who those with hold I + +... elided paragraph last ... + +Frost Robert -----------------------" + +"\n" split [ " " split reverse " " join ] map [ print ] each diff --git a/Task/Reverse-words-in-a-string/Lua/reverse-words-in-a-string-1.lua b/Task/Reverse-words-in-a-string/Lua/reverse-words-in-a-string-1.lua new file mode 100644 index 0000000000..05d70f8df4 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Lua/reverse-words-in-a-string-1.lua @@ -0,0 +1,9 @@ +local lines = {} +for line in (s .. "\n"):gmatch("(.-)\n") do + local this = {} + for word in line:gmatch("%S+") do + table.insert(this, 1, word) + end + lines[#lines + 1] = table.concat(this, " ") +end +print(table.concat(lines, "\n")) diff --git a/Task/Reverse-words-in-a-string/Lua/reverse-words-in-a-string.lua b/Task/Reverse-words-in-a-string/Lua/reverse-words-in-a-string-2.lua similarity index 100% rename from Task/Reverse-words-in-a-string/Lua/reverse-words-in-a-string.lua rename to Task/Reverse-words-in-a-string/Lua/reverse-words-in-a-string-2.lua diff --git a/Task/Reverse-words-in-a-string/Modula-2/reverse-words-in-a-string.mod2 b/Task/Reverse-words-in-a-string/Modula-2/reverse-words-in-a-string.mod2 new file mode 100644 index 0000000000..9a0b102dd5 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Modula-2/reverse-words-in-a-string.mod2 @@ -0,0 +1,58 @@ +MODULE ReverseWords; + +FROM STextIO IMPORT + WriteString, WriteLn; +FROM Strings IMPORT + Assign, Concat, Append; + +CONST + NL = CHR(10); + Sp = ' '; + Txt = "---------- Ice and Fire -----------" + NL + + NL + + "fire, in end will world the say Some" + NL + + "ice. in say Some" + NL + + "desire of tasted I've what From" + NL + + "fire. favor who those with hold I" + NL + + NL + + "... elided paragraph last ..." + NL + + NL + + "Frost Robert -----------------------" + NL; + +TYPE + String400 = ARRAY [0 .. 399] OF CHAR; + +PROCEDURE AddWord(Source: ARRAY OF CHAR; VAR INOUT Destination: ARRAY OF CHAR); +VAR + R: String400; +BEGIN + Concat(Source, Sp, R); + Append(Destination, R); + Assign(R, Destination); +END AddWord; + +VAR + I: CARDINAL; + SingleWord, CurrentLine: String400; + C: CHAR; + +BEGIN + SingleWord := ""; + CurrentLine := ""; + FOR I := 0 TO HIGH(Txt) DO + C := Txt[I]; + CASE C OF + Sp: + AddWord(SingleWord, CurrentLine); + SingleWord := ""; | + NL: + AddWord(SingleWord, CurrentLine); + WriteString(CurrentLine); + WriteLn; + SingleWord := ""; + CurrentLine := ""; | + ELSE + Append(C, SingleWord); + END; + END; +END ReverseWords. diff --git a/Task/Reverse-words-in-a-string/Nial/reverse-words-in-a-string.nial b/Task/Reverse-words-in-a-string/Nial/reverse-words-in-a-string.nial new file mode 100644 index 0000000000..7bf9af0a61 --- /dev/null +++ b/Task/Reverse-words-in-a-string/Nial/reverse-words-in-a-string.nial @@ -0,0 +1,18 @@ +# Define a function to convert a list of strings to a single string. +join is rest link (' ' eachboth link) + +iterate (write join reverse (' ' string_split)) \ + \ + \ + '------------ Eldorado ----------' \ + '' \ + '... here omitted lines ...' \ + '' \ + 'Mountains the "Over' \ + 'Moon, the Of' \ + 'Shadow, the of Valley the Down' \ + 'ride," boldly Ride,' \ + 'replied,--- shade The' \ + 'Eldorado!" for seek you "If' \ + '' \ + 'Poe Edgar -----------------------' diff --git a/Task/Reverse-words-in-a-string/R/reverse-words-in-a-string-1.r b/Task/Reverse-words-in-a-string/R/reverse-words-in-a-string-1.r new file mode 100644 index 0000000000..a3d23e9189 --- /dev/null +++ b/Task/Reverse-words-in-a-string/R/reverse-words-in-a-string-1.r @@ -0,0 +1,18 @@ +whack <- function(s) { + paste( rev( unlist(strsplit(s, " "))), collapse=' ' ) } + +poem <- unlist( strsplit( +'------------ Eldorado ---------- + +... here omitted lines ... + +Mountains the "Over +Moon, the Of +Shadow, the of Valley the Down +ride," boldly Ride, +replied,--- shade The +Eldorado!" for seek you "If + +Poe Edgar -----------------------', "\n")) + +for (line in poem) cat( whack(line), "\n" ) diff --git a/Task/Reverse-words-in-a-string/R/reverse-words-in-a-string-2.r b/Task/Reverse-words-in-a-string/R/reverse-words-in-a-string-2.r new file mode 100644 index 0000000000..306073c69f --- /dev/null +++ b/Task/Reverse-words-in-a-string/R/reverse-words-in-a-string-2.r @@ -0,0 +1,3 @@ +> `{` <- function(s) rev(unlist(strsplit(s, " "))) +> {"one two three four five"} +[1] "five" "four" "three" "two" "one" diff --git a/Task/Reverse-words-in-a-string/Red/reverse-words-in-a-string.red b/Task/Reverse-words-in-a-string/Red/reverse-words-in-a-string.red new file mode 100644 index 0000000000..d78ffa549b --- /dev/null +++ b/Task/Reverse-words-in-a-string/Red/reverse-words-in-a-string.red @@ -0,0 +1,15 @@ +Red [] +foreach line +split +{---------- Ice and Fire ------------ + +fire, in end will world the say Some +ice. in say Some +desire of tasted I've what From +fire. favor who those with hold I + +... elided paragraph last ... + +Frost Robert -----------------------} newline [ + print reverse split line " " +] diff --git a/Task/Reverse-words-in-a-string/VBA/reverse-words-in-a-string.vba b/Task/Reverse-words-in-a-string/VBA/reverse-words-in-a-string.vba new file mode 100644 index 0000000000..9190a7e759 --- /dev/null +++ b/Task/Reverse-words-in-a-string/VBA/reverse-words-in-a-string.vba @@ -0,0 +1,38 @@ +Option Explicit + +Sub Main() +Dim Lines(9) As String, i& + 'Input + Lines(0) = "------------- Ice And Fire -------------" + Lines(1) = "" + Lines(2) = "fire, in end will world the say Some" + Lines(3) = "ice. in say Some" + Lines(4) = "desire of tasted I've what From" + Lines(5) = "fire. favor who those with hold I" + Lines(6) = "" + Lines(7) = "... elided paragraph last ..." + Lines(8) = "" + Lines(9) = "Frost Robert -----------------------" + 'Output + For i = 0 To 9 + Debug.Print ReverseLine(Lines(i), " ") + Next +End Sub + +Private Function ReverseLine(Line As String, Optional Separat As String) As String +Dim T, R, i&, j&, deb&, fin& + If Len(Line) = 0 Then + ReverseLine = vbNullString + Else + If Separat = "" Then Separat = " " + T = Split(Line, Separat) + ReDim R(UBound(T)): j = LBound(T) + deb = UBound(T): fin = deb / 2 + For i = deb To fin Step -1 + R(j) = T(i) + R(i) = T(j) + j = j + 1 + Next i + ReverseLine = Join(R, Separat) + End If +End Function diff --git a/Task/Rock-paper-scissors/ALGOL-68/rock-paper-scissors.alg b/Task/Rock-paper-scissors/ALGOL-68/rock-paper-scissors.alg index 5b607e0ee1..decd042a2d 100644 --- a/Task/Rock-paper-scissors/ALGOL-68/rock-paper-scissors.alg +++ b/Task/Rock-paper-scissors/ALGOL-68/rock-paper-scissors.alg @@ -1,153 +1,89 @@ -main: ( - -# rock/paper/scissors game # - -# counts of the number of times the player has chosen each move # -# we initialise each to 1 so that the total isn't zero when we are # -# choosing the computer's first move (as in the Ada version) # -INT r count := 1; -INT p count := 1; -INT s count := 1; - -# counts of how many games the player and computer have won # -INT player count := 0; -INT computer count := 0; - -print( ( "rock/paper/scissors", newline, newline ) ); - -WHILE - - CHAR player move; - - # get the players move - r => rock # - # p => paper # - # s => scissors # - # q => quit # - +BEGIN + # rock/paper/scissors game # + # counts of the number of times the player has chosen each move # + # we initialise each to 1 so that the total isn't zero when we are # + # choosing the computer's first move (as in the Ada version) # + INT r count := 1; + INT p count := 1; + INT s count := 1; + # counts of how many games the player and computer have won # + INT player count := 0; + INT computer count := 0; + print( ( "rock/paper/scissors", newline, newline ) ); WHILE - print( ( "Please enter your move (r/p/s) or q to quit: " ) ); - readf( ( $ a $, player move ) ); - read( ( newline ) ); - - ( player move /= "r" - AND player move /= "p" - AND player move /= "s" - AND player move /= "q" - ) + CHAR player move; + # get the players move - r => rock, p => paper, s => scissors # + # q => quit # + WHILE + print( ( "Please enter your move (r/p/s) or q to quit: " ) ); + read( ( player move, newline ) ); + ( player move /= "r" + AND player move /= "p" + AND player move /= "s" + AND player move /= "q" + ) + DO + print( ( "Unrecognised move", newline ) ) + OD; + # continue playing until the player chooses quit # + player move /= "q" DO - print( ( "Unrecognised move", newline ) ) - OD; - - # continue playing until the player chooses quit # - player move /= "q" - -DO - - # decide the computer's move based on the player's history # - - CHAR computer move; - - INT move count = r count + p count + s count; - - # predict player will play rock if the random number # - # is in the range 0 .. rock / total # - # predict player will play paper if the random number # - # is in the range rock / total .. ( rock + paper ) / total # - # predict player will play scissors otherwise # - - REAL r limit = r count / move count; - REAL p limit = r limit + ( p count / move count ); - - REAL random move = next random; - - IF random move < r limit - THEN - # we predict the player will choose rock - we choose paper # - computer move := "p" - - ELIF random move < p limit - THEN - # we predict the player will choose paper - we choose scissors # - computer move := "s" - - ELSE - # we predict the player will choose scissors - we choose rock # - computer move := "r" - - FI; - - print( ( "You chose: " + player move, newline ) ); - print( ( "I chose: " + computer move, newline ) ); - - IF player move = computer move - THEN - # both players chose the same - draw # - print( ( "We draw", newline ) ) - - ELSE - # players chose different moves - there is a winner # - - BOOL player wins; - - IF player move = "r" - THEN - # player chose rock - rock blunts scissors # - # but is wrapped by paper # - player wins := ( computer move = "s" ) - - ELIF player move = "p" - THEN - # player chose paper - paper wraps rock # - # but is cut by scissors # - player wins := ( computer move = "r" ) - + # decide the computer's move based on the player's history # + CHAR computer move; + INT move count = r count + p count + s count; + # predict player will play rock if the random number # + # is in the range 0 .. rock / total # + # predict player will play paper if the random number # + # is in the range rock / total .. ( rock + paper ) / total # + # predict player will play scissors otherwise # + REAL r limit = r count / move count; + REAL p limit = r limit + ( p count / move count ); + REAL random move = next random; + IF random move < r limit THEN + # we predict the player will choose rock - we choose paper # + computer move := "p" + ELIF random move < p limit THEN + # we predict the player will choose paper - we choose scissors # + computer move := "s" ELSE - # player chose scissors - scissors cut paper # - # but are blunted by rock # - player wins := ( computer move = "p" ) - + # we predict the player will choose scissors - we choose rock # + computer move := "r" FI; - - IF player wins - THEN - player count +:= 1; - print( ( "You win", newline ) ) - + print( ( "You chose: " + player move, newline ) ); + print( ( "I chose: " + computer move, newline ) ); + IF player move = computer move THEN + # both players chose the same - draw # + print( ( "We draw", newline ) ) ELSE - computer count +:= 1; - print( ( "I win", newline ) ) - FI; - - print( ( ( "You won: " - + whole( player count , 0 ) - + ", I won: " - + whole( computer count, 0 ) + # players chose different moves - there is a winner # + IF ( player move = "r" AND computer move = "s" ) + OR ( player move = "p" AND computer move = "r" ) + OR ( player move = "s" AND computer move = "p" ) + THEN + player count +:= 1; + print( ( "You win", newline ) ) + ELSE + computer count +:= 1; + print( ( "I win", newline ) ) + FI; + print( ( "You won: " + , whole( player count , 0 ) + , ", I won: " + , whole( computer count, 0 ) + , newline + ) ) - , newline - ) - ) - - - FI; - - IF player move = "r" - THEN - # player chose rock # - r count +:= 1 - - ELIF player move = "p" - THEN - # player chose paper # - p count +:= 1 - - ELSE - # player chose scissors # - s count +:= 1 - - FI - -OD; - -print( ( "Thanks for a most enjoyable game", newline ) ) - -) + FI; + IF player move = "r" THEN + # player chose rock # + r count +:= 1 + ELIF player move = "p" THEN + # player chose paper # + p count +:= 1 + ELSE + # player chose scissors # + s count +:= 1 + FI + OD; + print( ( "Thanks for a most enjoyable game", newline ) ) +END diff --git a/Task/Rock-paper-scissors/Aime/rock-paper-scissors.aime b/Task/Rock-paper-scissors/Aime/rock-paper-scissors.aime index b0bbd9bfe1..00e2e5ebd1 100644 --- a/Task/Rock-paper-scissors/Aime/rock-paper-scissors.aime +++ b/Task/Rock-paper-scissors/Aime/rock-paper-scissors.aime @@ -1,21 +1,19 @@ text computer_play(record plays, record beats) { - integer a, total; + integer a, c, total; text s; - total = r_q_integer(plays, "rock") + r_q_integer(plays, "paper") - + r_q_integer(plays, "scissors"); + total = plays["rock"] + plays["paper"] + plays["scissors"]; a = drand(total - 1); - r_first(plays, s); - do { - if (a < r_q_integer(plays, s)) { + for (s, c in plays) { + if (a < c) { break; } - a -= plays[s]; - } while (rsk_greater(plays, s, s)); + a -= c; + } - return r_q_text(beats, s); + beats[s]; } integer @@ -26,26 +24,25 @@ main(void) file f; text s; - computer = 0; - human = 0; + computer = human = 0; - f_affix(f, "/dev/stdin"); + f.stdin; - r_put(beats, "rock", "paper"); - r_put(beats, "paper", "scissors"); - r_put(beats, "scissors", "rock"); + beats["rock"] = "paper"; + beats["paper"] = "scissors"; + beats["scissors"] = "rock"; - r_put(plays, "rock", 1); - r_put(plays, "paper", 1); - r_put(plays, "scissors", 1); + plays["rock"] = 1; + plays["paper"] = 1; + plays["scissors"] = 1; while (1) { o_text("Your choice [rock/paper/scissors]:\n"); - if (f_line(f, s) == -1) { + if (f.line(s) == -1) { break; } - if (!r_key(plays, s)) { + if (!plays.key(s)) { o_text("Invalid choice, try again\n"); } else { text c; @@ -54,9 +51,9 @@ main(void) o_form("Human: ~, Computer: ~\n", s, c); - if (!compare(s, c)) { + if (s == c) { o_text("Draw\n"); - } elif (!compare(c, beats[s])) { + } elif (c == beats[s]) { computer += 1; o_text("Computer wins\n"); } else { @@ -64,7 +61,7 @@ main(void) o_text("Human wins\n"); } - r_up(plays, s); + plays.up(s); o_form("Score: Human: ~, Computer: ~\n", human, computer); } diff --git a/Task/Rock-paper-scissors/C/rock-paper-scissors-1.c b/Task/Rock-paper-scissors/C/rock-paper-scissors-1.c index 13cc3716b7..1091aecc5e 100644 --- a/Task/Rock-paper-scissors/C/rock-paper-scissors-1.c +++ b/Task/Rock-paper-scissors/C/rock-paper-scissors-1.c @@ -1,22 +1,15 @@ #include #include +#define LEN 3 -int rand_i(int n) +/* pick a random index from 0 to n-1, according to probablities listed + in p[] which is assumed to have a sum of 1. The values in the probablity + list matters up to the point where the sum goes over 1 */ +int rand_idx(double *p, int n) { - int rand_max = RAND_MAX - (RAND_MAX % n); - int ret; - while ((ret = rand()) >= rand_max); - return ret/(rand_max / n); -} - -int weighed_rand(int *tbl, int len) -{ - int i, sum, r; - for (i = 0, sum = 0; i < len; sum += tbl[i++]); - if (!sum) return rand_i(len); - - r = rand_i(sum) + 1; - for (i = 0; i < len && (r -= tbl[i]) > 0; i++); + double s = rand() / (RAND_MAX + 1.0); + int i; + for (i = 0; i < n - 1 && (s -= p[i]) >= 0; i++); return i; } @@ -27,9 +20,10 @@ int main() const char *names[] = { "Rock", "Paper", "Scissors" }; char str[2]; const char *winner[] = { "We tied.", "Meself winned.", "You win." }; + double p[LEN] = { 1./3, 1./3, 1./3 }; while (1) { - my_action = (weighed_rand(user_rec, 3) + 1) % 3; + my_action = rand_idx(p,LEN); printf("\nYour choice [1-3]:\n" " 1. Rock\n 2. Paper\n 3. Scissors\n> "); @@ -37,7 +31,10 @@ int main() /* scanf is a terrible way to do input. should use stty and keystrokes */ if (!scanf("%d", &user_action)) { scanf("%1s", str); - if (*str == 'q') return 0; + if (*str == 'q') { + printf("Your choices [rock : %d , paper : %d , scissors %d] ",user_rec[0],user_rec[1], user_rec[2]); + return 0; + } continue; } user_action --; diff --git a/Task/Rock-paper-scissors/Kotlin/rock-paper-scissors.kotlin b/Task/Rock-paper-scissors/Kotlin/rock-paper-scissors.kotlin new file mode 100644 index 0000000000..a258ab1566 --- /dev/null +++ b/Task/Rock-paper-scissors/Kotlin/rock-paper-scissors.kotlin @@ -0,0 +1,79 @@ +// version 1.2.10 + +import java.util.Random + +const val choices = "rpsq" +val rand = Random() + +var pWins = 0 // player wins +var cWins = 0 // computer wins +var draws = 0 // neither wins +var games = 0 // games played +val pFreqs = arrayOf(0, 0, 0) // player frequencies for each choice (rps) + +fun printScore() = println("Wins: You $pWins, Computer $cWins, Neither $draws\n") + +fun getComputerChoice(): Char { + // make a completely random choice until 3 games have been played + if (games < 3) return choices[rand.nextInt(3)] + val num = rand.nextInt(games) + return when { + num < pFreqs[0] -> 'p' + num < pFreqs[0] + pFreqs[1] -> 's' + else -> 'r' + } +} + +fun main(args: Array) { + println("Enter: (r)ock, (p)aper, (s)cissors or (q)uit\n") + while (true) { + printScore() + var pChoice: Char + while (true) { + print("Your choice r/p/s/q : ") + val input = readLine()!!.toLowerCase() + if (input.length == 1) { + pChoice = input[0] + if (pChoice in choices) break + } + println("Invalid choice, try again") + } + if (pChoice == 'q') { + println("OK, quitting") + return + } + val cChoice = getComputerChoice() + println("Computer's choice : $cChoice") + if (pChoice == 'r' && cChoice == 's') { + println("Rock breaks scissors - You win!") + pWins++ + } + else if (pChoice == 'p' && cChoice == 'r') { + println("Paper covers rock - You win!") + pWins++ + } + else if (pChoice == 's' && cChoice == 'p') { + println("Scissors cut paper - You win!") + pWins++ + } + else if (pChoice == 's' && cChoice == 'r') { + println("Rock breaks scissors - Computer wins!") + cWins++ + } + else if (pChoice == 'r' && cChoice == 'p') { + println("Paper covers rock - Computer wins!") + cWins++ + } + else if (pChoice == 'p' && cChoice == 's') { + println("Scissors cut paper - Computer wins!") + cWins++ + } + else { + println("It's a draw!") + draws++ + } + pFreqs[choices.indexOf(pChoice)]++ + games++ + println() + } +} diff --git a/Task/Rock-paper-scissors/Lua/rock-paper-scissors.lua b/Task/Rock-paper-scissors/Lua/rock-paper-scissors.lua index dbe39be61e..2761b84043 100644 --- a/Task/Rock-paper-scissors/Lua/rock-paper-scissors.lua +++ b/Task/Rock-paper-scissors/Lua/rock-paper-scissors.lua @@ -1,66 +1,60 @@ -math.randomseed(os.time()) -- Randomness needed for cpuMove function -math.random() - function cpuMove() - local totalChance = playerRecord.R + playerRecord.P + playerRecord.S - if totalChance == 0 then -- First game, unweighted random - local choice = math.random(1, 3) - if choice == 1 then return "R" end - if choice == 2 then return "P" end - if choice == 3 then return "S" end - end - local choice = math.random(1, totalChance) -- Weighted random bit - if choice <= playerRecord.R then return "P" end - if choice <= playerRecord.R + playerRecord.P then return "S" end - return "R" + local totalChance = record.R + record.P + record.S + if totalChance == 0 then -- First game, unweighted random + local choice = math.random(1, 3) + if choice == 1 then return "R" end + if choice == 2 then return "P" end + if choice == 3 then return "S" end + end + local choice = math.random(1, totalChance) -- Weighted random bit + if choice <= record.R then return "P" end + if choice <= record.R + record.P then return "S" end + return "R" end function playerMove() -- Get user input for choice of 'weapon' - local choice - repeat - os.execute("cls") -- Windows specific command, change per OS - print("\nRock, Paper, Scissors") - print("=====================\n") - print("Scores -\tPlayer:", score.player) - print("\t\tCPU:", score.cpu .. "\n\t\tDraws:", score.draws) - io.write("\nChoose [R]ock [P]aper or [S]cissors: ") - choice = string.upper(string.sub(io.read(), 1, 1)) - until choice == "R" or choice == "P" or choice == "S" - return choice + local choice + repeat + os.execute("cls") -- Windows specific command, change per OS + print("\nRock, Paper, Scissors") + print("=====================\n") + print("Scores -\tPlayer:", score.player) + print("\t\tCPU:", score.cpu .. "\n\t\tDraws:", score.draws) + io.write("\nChoose [R]ock [P]aper or [S]cissors: ") + choice = io.read():upper():sub(1, 1) + until choice == "R" or choice == "P" or choice == "S" + return choice end -function checkWinner (c, p) -- Decide who won, increment scores - io.write("I chose ") - if c == "R" then print("rock...") end - if c == "P" then print("paper...") end - if c == "S" then print("scissors...") end - if c == p then - print("\nDraw!") - score.draws = score.draws + 1 - elseif (c == "R" and p == "P") or - (c == "P" and p == "S") or - (c == "S" and p == "R") then - print("\nYou win!") - score.player = score.player + 1 - else - print("\nYou lose!") - score.cpu = score.cpu + 1 - end +-- Decide who won, increment scores +function checkWinner (c, p) + io.write("I chose ") + if c == "R" then print("rock...") end + if c == "P" then print("paper...") end + if c == "S" then print("scissors...") end + if c == p then + print("\nDraw!") + score.draws = score.draws + 1 + elseif (c == "R" and p == "P") or + (c == "P" and p == "S") or + (c == "S" and p == "R") then + print("\nYou win!") + score.player = score.player + 1 + else + print("\nYou lose!") + score.cpu = score.cpu + 1 + end end -function updateRecord (move) -- Keep track of player move history - if move == "R" then playerRecord.R = playerRecord.R + 1 end - if move == "P" then playerRecord.P = playerRecord.P + 1 end - if move == "S" then playerRecord.S = playerRecord.S + 1 end -end - -score = {player = 0, cpu = 0, draws = 0} -- Start of main procedure -playerRecord = {R = 0, P = 0, S = 0} +-- Main procedure +math.randomseed(os.time()) +score = {player = 0, cpu = 0, draws = 0} +record = {R = 0, P = 0, S = 0} local playerChoice, cpuChoice repeat - cpuChoice = cpuMove() - playerChoice = playerMove() - updateRecord(playerChoice) - checkWinner(cpuChoice, playerChoice) - io.write("\nPress ENTER to continue or enter 'Q' to quit . . . ") -until string.upper(string.sub(io.read(), 1, 1)) == "Q" + cpuChoice = cpuMove() + playerChoice = playerMove() + record[playerChoice] = record[playerChoice] + 1 + checkWinner(cpuChoice, playerChoice) + io.write("\nPress ENTER to continue or enter 'Q' to quit . . . ") +until io.read():upper():sub(1, 1) == "Q" diff --git a/Task/Rock-paper-scissors/PHP/rock-paper-scissors.php b/Task/Rock-paper-scissors/PHP/rock-paper-scissors.php new file mode 100644 index 0000000000..e69c2f88c7 --- /dev/null +++ b/Task/Rock-paper-scissors/PHP/rock-paper-scissors.php @@ -0,0 +1,28 @@ +" . "Choose: ROCK - PAPER - SCISSORS" . ""; +echo "

"; +echo ""; + +$player = strtoupper( $_GET["moves"] ); +$wins = [ + 'ROCK' => 'SCISSORS', + 'PAPER' => 'ROCK', + 'SCISSORS' => 'PAPER' + ]; +$a_i = array_rand($wins); +echo "
"; +echo "Player chooses " . "" . $player . ""; +echo "
"; +echo "
" . "A.I chooses " . "" . $a_i . ""; + +$results = ""; +if ($player == $a_i){ +$results = "Draw"; +} else if($wins[$a_i] == $player ){ + $results = "A.I wins"; +} else { + $results = "Player wins"; +} + +echo "
" . $results; +?> diff --git a/Task/Rock-paper-scissors/Perl-6/rock-paper-scissors-1.pl6 b/Task/Rock-paper-scissors/Perl-6/rock-paper-scissors-1.pl6 index b7168f6dc7..21e95a1ac8 100644 --- a/Task/Rock-paper-scissors/Perl-6/rock-paper-scissors-1.pl6 +++ b/Task/Rock-paper-scissors/Perl-6/rock-paper-scissors-1.pl6 @@ -19,7 +19,7 @@ my %vs = ( my %choices = %vs.map({; $_.substr(0,2).lc => $_ }); my $keys = %choices.keys.join('|'); -my $prompt = %vs.map({$_.subst(/(\w\w)/,->$/{"[$0]"})}).join(' ')~"? "; +my $prompt = %vs.map({$_.subst(/(\w\w)/, -> $/ {"[$0]"})}).join(' ')~"? "; my %weight = %choices.keys »=>» 1; my @stats = 0,0,0; diff --git a/Task/Rock-paper-scissors/REXX/rock-paper-scissors-1.rexx b/Task/Rock-paper-scissors/REXX/rock-paper-scissors-1.rexx index 64e88b8962..bfdf8bc7bb 100644 --- a/Task/Rock-paper-scissors/REXX/rock-paper-scissors-1.rexx +++ b/Task/Rock-paper-scissors/REXX/rock-paper-scissors-1.rexx @@ -1,19 +1,19 @@ /*REXX program plays rock─paper─scissors with a human; tracks what human tends to use. */ -!= '────────'; err=! '***error***'; @.=0 /*some constants for this program. */ -prompt=! 'Please enter one of: Rock Paper Scissors (or Quit)' +!= '────────'; err=! '***error***'; @.=0 /*some constants for this program. */ +prompt= ! 'Please enter one of: Rock Paper Scissors (or Quit)' $.p='paper' ; $.s='scissors'; $.r='rock' /*list of the choices in this program. */ t.p=$.r ; t.s=$.p ; t.r=$.s /*thingys that beats stuff. */ w.p=$.s ; w.s=$.r ; w.r=$.p /*stuff " " thingys. */ b.p='covers'; b.s='cuts' ; b.r='breaks' /*verbs: how the choice wins. */ - do forever; say; say prompt; say /*prompt the CBLF; then get a response.*/ - c=word($.p $.s $.r, random(1, 3)) /*choose the computer's first pick. */ + do forever; say; say prompt; say /*prompt the CBLF; then get a response.*/ + c=word($.p $.s $.r, random(1, 3) ) /*choose the computer's first pick. */ m=max(@.r, @.p, @.s); c=w.r /*prepare to examine the choice history*/ if @.p==m then c=w.p /*emulate JC's: The Amazing Karnac. */ if @.s==m then c=w.s /* " " " " " */ - c1=left(c,1) /*C1 is used for faster comparing. */ - parse pull u; a=strip(u) /*get the CBLF's choice/pick (answer). */ - upper a c1 ; a1=left(a,1) /*uppercase choices, get 1st character.*/ + c1=left(c, 1) /*C1 is used for faster comparing. */ + parse pull u; a=strip(u) /*get the CBLF's choice/pick (answer). */ + upper a c1 ; a1=left(a, 1) /*uppercase choices, get 1st character.*/ ok=0 /*indicate answer isn't OK (so far). */ select /*process/verify the CBLF's choice. */ when words(u)==0 then say err 'nothing entered' @@ -27,9 +27,8 @@ b.p='covers'; b.s='cuts' ; b.r='breaks' /*verbs: how the choice wins. if \ok then iterate /*answer ¬OK? Then get another choice.*/ @.a1=@.a1+1 /*keep a history of the CBLF's choices.*/ - say ! 'computer chose: ' c - if a1==c1 then do; say ! 'draw.'; iterate; end - if $.a1==t.c1 then say ! 'the computer wins. ' ! $.c1 b.c1 $.a1 - else say ! 'you win! ' ! $.a1 b.a1 $.c1 - end /*forever*/ - /*stick a fork in it, we're all done. */ + say ! 'computer chose: ' c + if a1== c1 then do; say ! 'draw.'; iterate; end + if $.a1==t.c1 then say ! 'the computer wins. ' ! $.c1 b.c1 $.a1 + else say ! 'you win! ' ! $.a1 b.a1 $.c1 + end /*forever*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Rock-paper-scissors/REXX/rock-paper-scissors-2.rexx b/Task/Rock-paper-scissors/REXX/rock-paper-scissors-2.rexx index a84852bc3b..e8de84197c 100644 --- a/Task/Rock-paper-scissors/REXX/rock-paper-scissors-2.rexx +++ b/Task/Rock-paper-scissors/REXX/rock-paper-scissors-2.rexx @@ -7,17 +7,17 @@ w.p= $.L $.s ; w.s= $.v $.r ; w.r= $.v $.p ; w.L= $.r $ b.p='covers disproves'; b.s="cuts decapitates"; b.r='breaks crushes'; b.L="eats poisons"; b.v='vaporizes smashes' /*how the choice wins.*/ whom.1=! 'the computer wins. ' !; whom.2=! "you win! " !; win=words(t.p) - do forever; say; say prompt; say /*prompt CBLF; then get a response. */ - c=word($.p $.s $.r $.L $.v,random(1,5)) /*the computer's first choice/pick. */ + do forever; say; say prompt; say /*prompt CBLF; then get a response. */ + c=word($.p $.s $.r $.L $.v, random(1, 5) ) /*the computer's first choice/pick. */ m=max(@.r,@.p,@.s,@.L,@.v) /*used in examining CBLF's history. */ - if @.p==m then c=word(w.p,random(1,2)) /*emulate JC's The Amazing Karnac. */ - if @.s==m then c=word(w.s,random(1,2)) /* " " " " " */ - if @.r==m then c=word(w.r,random(1,2)) /* " " " " " */ - if @.L==m then c=word(w.L,random(1,2)) /* " " " " " */ - if @.v==m then c=word(w.v,random(1,2)) /* " " " " " */ - c1=left(c,1) /*C1 is used for faster comparing. */ - parse pull u; a=strip(u) /*obtain the CBLF's choice/pick. */ - upper a c1 ; a1=left(a,1) /*uppercase the choices, get 1st char. */ + if @.p==m then c=word(w.p, random(1, 2) ) /*emulate JC's The Amazing Karnac. */ + if @.s==m then c=word(w.s, random(1, 2) ) /* " " " " " */ + if @.r==m then c=word(w.r, random(1, 2) ) /* " " " " " */ + if @.L==m then c=word(w.L, random(1, 2) ) /* " " " " " */ + if @.v==m then c=word(w.v, random(1, 2) ) /* " " " " " */ + c1=left(c, 1) /*C1 is used for faster comparing. */ + parse pull u; a=strip(u) /*obtain the CBLF's choice/pick. */ + upper a c1 ; a1=left(a, 1) /*uppercase the choices, get 1st char. */ ok=0 /*indicate answer isn't OK (so far). */ select /* [↓] process the CBLF's choice/pick.*/ when words(u)==0 then say err 'nothing entered.' @@ -26,23 +26,22 @@ whom.1=! 'the computer wins. ' !; whom.2=! "you win! " !; win=words(t.p) when abbrev('LIZARD', a) |, abbrev('ROCK', a) |, abbrev('PAPER', a) |, - abbrev('Vulcan', a) |, - abbrev('SPOCK', a,2) | , + abbrev('VULCAN', a) |, + abbrev('SPOCK', a,2) |, abbrev('SCISSORS',a,2) then ok=1 /*it's a valid choice for the human. */ otherwise say err 'you entered a bad choice: ' u end /*select*/ if \ok then iterate /*answer ¬OK? Then get another choice.*/ - @.a1=@.a1+1 /*keep a history of the CBLF's choices.*/ + @.a1= @.a1 + 1 /*keep a history of the CBLF's choices.*/ say ! 'computer chose: ' c if a1==c1 then say ! 'draw.' /*Oh rats! The contest ended up a draw*/ else do who=1 for 2 /*either the computer or the CBLF won. */ if who==2 then parse value a1 c1 with c1 a1 do j=1 for win /*see who won. */ - if $.a1\==word(t.c1,j) then iterate /*not this 'un. */ - say whom.who $.c1 word(b.c1,j) $.a1 /*notify winner.*/ + if $.a1 \== word(t.c1, j) then iterate /*not this 'un. */ + say whom.who $.c1 word(b.c1, j) $.a1 /*notify winner.*/ leave /*leave J loop.*/ end /*j*/ end /*who*/ - end /*forever*/ - /*stick a fork in it, we're all done. */ + end /*forever*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Rock-paper-scissors/Ring/rock-paper-scissors.ring b/Task/Rock-paper-scissors/Ring/rock-paper-scissors.ring new file mode 100644 index 0000000000..fadfe35cdf --- /dev/null +++ b/Task/Rock-paper-scissors/Ring/rock-paper-scissors.ring @@ -0,0 +1,40 @@ +# Project : Rock-paper-scissors +# Date : 2018/03/25 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : + +see " +welcome to the game of rock-paper-scissors. +each player guesses one of these three, and reveals it at the same time. +rock blunts scissors, which cut paper, which wraps stone. +if both players choose the same, it is a draw! +when you've had enough, choose q. +" +g = ["rock","paper","scissors"] +total=0 draw=0 +pwin=0 cwin=0 +see "what is your move (press r, p, or s)?" +while true + c=random(2)+1 + give q + gs = floor((substr("rpsq",lower(q)))) + if gs>3 or gs<1 + summarise() + exit + ok + total = total + 1 + see"you chose " + g[gs] + " and i chose " + g[c] + nl + temp = gs-c + if temp = 0 + see ". it's a draw" + draw = draw + 1 + ok + if temp = 1 or temp = -2 + see ". you win!" + pwin = pwin + 1 + ok + if temp = (-1) or temp = 2 + see ". i win!" + cwin = cwin + 1 + ok +end diff --git a/Task/Rock-paper-scissors/Rust/rock-paper-scissors.rust b/Task/Rock-paper-scissors/Rust/rock-paper-scissors.rust new file mode 100644 index 0000000000..635bde28b3 --- /dev/null +++ b/Task/Rock-paper-scissors/Rust/rock-paper-scissors.rust @@ -0,0 +1,83 @@ +extern crate rand; +#[macro_use] +extern crate rand_derive; + +use std::io; +use rand::Rng; +use Choice::*; + +#[derive(PartialEq, Clone, Copy, Rand, Debug)] +enum Choice { + Rock, + Paper, + Scissors, +} + +fn beats(c1: Choice, c2: Choice) -> bool { + (c1 == Rock && c2 == Scissors) || (c1 == Scissors && c2 == Paper) || (c1 == Paper && c2 == Rock) +} + +fn ai_move(rng: &mut R, v: [usize; 3]) -> Choice { + // weighted random choice, a dynamic version of `rand::distributions::WeightedChoice` + let rand = rng.gen_range(0, v[0] + v[1] + v[2]); + if rand < v[0] { + Paper + } else if rand < v[0] + v[1] { + Scissors + } else { + Rock + } +} + +fn main() { + let mut rng = rand::thread_rng(); + + println!("Rock, paper, scissors!"); + let mut ai_choice: Choice = rng.gen(); + let mut ucf = [0, 0, 0]; // user choice frequency + let mut score = [0, 0]; + + loop { + println!("Please input your move: 'r', 'p' or 's'. Type 'q' to quit"); + + let mut input = String::new(); + io::stdin() + .read_line(&mut input) + .expect("failed to read line"); + let u_choice = match input.to_lowercase().trim() { + s if s.starts_with('r') => { + ucf[0] += 1; + Rock + } + s if s.starts_with('p') => { + ucf[1] += 1; + Paper + } + s if s.starts_with('s') => { + ucf[2] += 1; + Scissors + } + s if s.starts_with('q') => break, + _ => { + println!("Please enter a correct choice!"); + continue; + } + }; + println!("You chose {:?}, I chose {:?}.", u_choice, ai_choice); + if beats(u_choice, ai_choice) { + score[0] += 1; + println!("You win!"); + } else if u_choice == ai_choice { + println!("It's a tie!"); + } else { + score[1] += 1; + println!("I win!"); + } + println!("-Score: You {}, Me {}", score[0], score[1]); + + // only after the 1st iteration the AI knows the stats and can make + // its weighted random move + ai_choice = ai_move(&mut rng, ucf); + } + println!("Thank you for the game!"); +} diff --git a/Task/Roman-numerals-Decode/Elena/roman-numerals-decode.elena b/Task/Roman-numerals-Decode/Elena/roman-numerals-decode.elena new file mode 100644 index 0000000000..d07ad7f0ee --- /dev/null +++ b/Task/Roman-numerals-Decode/Elena/roman-numerals-decode.elena @@ -0,0 +1,43 @@ +import extensions. +import system'collections. +import system'routines. + +static RomanDictionary = Dictionary new; + setAt("I", 1); + setAt("V", 5); + setAt("X", 10); + setAt("L", 50); + setAt("C", 100); + setAt("D", 500); + setAt("M", 1000). +literal extension $op +{ + toRomanInt + [ + var minus := 0. + var s := self upperCase. + var total := 0. + + 0 till(s length) do(:i) + [ + var thisNumeral := RomanDictionary[s[i]] - minus. + if ((i >= s length - 1) || $(thisNumeral + minus >= RomanDictionary[s[i + 1]])) + [ + total += thisNumeral. + minus := 0. + ]; + [ + minus := thisNumeral + ] + ]. + + ^ total + ] +} + +program = +[ + console printLine("MCMXC: ", "MCMXC" toRomanInt). + console printLine("MMVIII: ", "MMVIII" toRomanInt). + console printLine("MDCLXVI:", "MDCLXVI" toRomanInt). +]. diff --git a/Task/Roman-numerals-Decode/Elixir/roman-numerals-decode.elixir b/Task/Roman-numerals-Decode/Elixir/roman-numerals-decode.elixir index 7a94956e49..082593c1ae 100644 --- a/Task/Roman-numerals-Decode/Elixir/roman-numerals-decode.elixir +++ b/Task/Roman-numerals-Decode/Elixir/roman-numerals-decode.elixir @@ -4,7 +4,6 @@ defmodule Roman_numeral do def decode([h1, h2 | rest]) do case {to_value(h1), to_value(h2)} do {v1, v2} when v1 < v2 -> v2 - v1 + decode(rest) - {v1, v1} -> v1 + v1 + decode(rest) {v1, _} -> v1 + decode([h2 | rest]) end end @@ -18,6 +17,6 @@ defmodule Roman_numeral do defp to_value(?I), do: 1 end -Enum.each(['MCMXC', 'MMVIII', 'MDCLXVI'], fn clist -> +Enum.each(['MCMXC', 'MMVIII', 'MDCLXVI', 'IIIID'], fn clist -> IO.puts "#{clist}\t: #{Roman_numeral.decode(clist)}" end) diff --git a/Task/Roman-numerals-Decode/Forth/roman-numerals-decode-2.fth b/Task/Roman-numerals-Decode/Forth/roman-numerals-decode-2.fth index 2276cf894f..4e606eb07a 100644 --- a/Task/Roman-numerals-Decode/Forth/roman-numerals-decode-2.fth +++ b/Task/Roman-numerals-Decode/Forth/roman-numerals-decode-2.fth @@ -1,44 +1,48 @@ - Alternative Forth methodology +\ decode roman numerals using Forth methodology \ create words to describe and solve the problem +\ ANS/ISO Forth + HEX -: toUpper ( char -- char ) 05F and ; +: TOUPPER ( char -- char ) 05F AND ; DECIMAL \ status holders -variable oldndx -variable curndx -variable negcnt +VARIABLE OLDNDX +VARIABLE CURNDX +VARIABLE NEGFLAG -\ word to compile a quote delimtited string into memory -: ," ( -- ) [char] " word C@ 1+ allot ; +: NUMERALS ( -- addr len) S" IVXLCDM" ; ( 1st char is a blank) +CREATE VALUES ( -- addr) 0 , 1 , 5 , 10 , 50 , 100 , 500 , 1000 , -\ look-up tables place into memory -create numerals ," IVXLCDM" -create values 0 , 1 , 5 , 10 , 50 , 100 , 500 , 1000 , +: [] ( n addr -- addr[n]) SWAP CELLS + ; \ array address calc. \ define words to describe/solve the problem -: init ( -- ) curndx off oldndx off negcnt off ; -: toindex ( char -- indx) toUpper numerals count rot SCAN dup 0= abort" invalid numeral" ; -: tovalue ( ndx -- n ) cells values + @ ; -: remember ( ndx -- ndx ) curndx @ oldndx ! dup curndx ! ; -: memory@ ( -- n1 n2 ) curndx @ oldndx @ ; -: numval ( char -- n ) toindex remember tovalue ; -: ?illegal ( ndx -- ) memory@ = negcnt @ and abort" illegal format" ; +: INIT ( -- ) CURNDX OFF OLDNDX OFF NEGFLAG OFF ; -\ logic -: negate? ( n -- +/- n ) - memory@ < - if negcnt on - negate - else - ?illegal - negcnt off - then ; +: >INDEX ( char -- ndx) TOUPPER >R NUMERALS TUCK R> SCAN NIP - + DUP 7 > ABORT" Invalid Roman numeral" ; + +: REMEMBER ( ndx -- ndx ) CURNDX @ OLDNDX ! DUP CURNDX ! ; + +: ]VALUE@ ( ndx -- n ) REMEMBER VALUES [] @ ; + +: >VALUE ( char -- n ) >INDEX ]VALUE@ ; + +: ?ILLEGAL ( ndx -- ) CURNDX @ OLDNDX @ = NEGFLAG @ AND ABORT" Illegal format" ; + +\ LOGIC +: ?NEGATE ( n -- +n | -n) + CURNDX @ OLDNDX @ < + IF NEGFLAG ON + NEGATE + ELSE + ?ILLEGAL + NEGFLAG OFF + THEN ; \ solution -: decode ( c-addr -- n ) - init +: >ARABIC ( addr len -- n ) + INIT 0 \ accumulator on the stack - swap - count 1- bounds swap - do i c@ numval negate? + -1 +loop ;. + -ROT 1- BOUNDS SWAP + DO I C@ >VALUE ?NEGATE + -1 +LOOP ; diff --git a/Task/Roman-numerals-Decode/Julia/roman-numerals-decode-1.julia b/Task/Roman-numerals-Decode/Julia/roman-numerals-decode-1.julia index 80f987f460..c976299b7f 100644 --- a/Task/Roman-numerals-Decode/Julia/roman-numerals-decode-1.julia +++ b/Task/Roman-numerals-Decode/Julia/roman-numerals-decode-1.julia @@ -1,21 +1,19 @@ -function parseroman(r::ASCIIString) - const RD = ["I" => 1, "V" => 5, "X" => 10, "L" => 50, - "C" => 100, "D" => 500, "M" => 1000] - maxval = 0 - accum = 0 - for d in reverse(split(uppercase(r), "")) - if !(d in keys(RD)) +function parseroman(rnum::AbstractString) + romandigits = Dict('I' => 1, 'V' => 5, 'X' => 10, 'L' => 50, + 'C' => 100, 'D' => 500, 'M' => 1000) + mval = accm = 0 + for d in reverse(uppercase(rnum)) + val = try + romandigits[d] + catch throw(DomainError()) end - val = RD[d] - if val > maxval - maxval = val - end - if val < maxval - accum -= val + if val > mval maxval = val end + if val < mval + accm -= val else - accum += val + accm += val end end - return accum + return accm end diff --git a/Task/Roman-numerals-Decode/Julia/roman-numerals-decode-2.julia b/Task/Roman-numerals-Decode/Julia/roman-numerals-decode-2.julia index 6576e9bc3d..057761f2fb 100644 --- a/Task/Roman-numerals-Decode/Julia/roman-numerals-decode-2.julia +++ b/Task/Roman-numerals-Decode/Julia/roman-numerals-decode-2.julia @@ -1,14 +1,6 @@ -testcases = ASCIIString["I", "III", "IX", "IVI", "IIM", - "CMMDXL", "icv", "cDxLiV", "MCMLD", "ccccccd", - "iiiiiv", "MMXV", "MCMLXXXIV", "ivxmm", "SPQR"] - -println("Test parseroman, roman => arabic:") -for r in testcases - print(r, " => ") - i = try - parseroman(r) - catch - "Invalid" - end - println(i) +test = ["I", "III", "IX", "IVI", "IIM", + "CMMDXL", "icv", "cDxLiV", "MCMLD", "ccccccd", + "iiiiiv", "MMXV", "MCMLXXXIV", "ivxmm", "SPQR"] +for rnum in test + @printf("%15s → %s\n", rnum, try parseroman(rnum) catch "not valid" end) end diff --git a/Task/Roman-numerals-Decode/UNIX-Shell/roman-numerals-decode.sh b/Task/Roman-numerals-Decode/UNIX-Shell/roman-numerals-decode.sh new file mode 100644 index 0000000000..7ad9d70121 --- /dev/null +++ b/Task/Roman-numerals-Decode/UNIX-Shell/roman-numerals-decode.sh @@ -0,0 +1,35 @@ +#!/bin/bash + +roman_to_dec() { + local rnum=$1 + local n=0 + local prev=0 + + for ((i=${#rnum}-1;i>=0;i--)) + do + case "${rnum:$i:1}" in + M) a=1000 ;; + D) a=500 ;; + C) a=100 ;; + L) a=50 ;; + X) a=10 ;; + V) a=5 ;; + I) a=1 ;; + esac + + if [[ $a -lt $prev ]] + then + let n-=a + else + let n+=a + fi + + prev=$a + done + + echo "$rnum = $n" +} + +roman_to_dec MCMXC +roman_to_dec MMVIII +roman_to_dec MDCLXVI diff --git a/Task/Roman-numerals-Decode/VBA/roman-numerals-decode.vba b/Task/Roman-numerals-Decode/VBA/roman-numerals-decode.vba new file mode 100644 index 0000000000..55caeaf542 --- /dev/null +++ b/Task/Roman-numerals-Decode/VBA/roman-numerals-decode.vba @@ -0,0 +1,34 @@ +Option Explicit + +Sub Main_Romans_Decode() +Dim Arr(), i& + + Arr = Array("III", "XXX", "CCC", "MMM", "VII", "LXVI", "CL", "MCC", "IV", "IX", "XC", "ICM", "DCCCXCIX", "CMI", "CIM", "MDCLXVI", "MCMXC", "MMXVII") + For i = 0 To UBound(Arr) + Debug.Print Arr(i) & " >>> " & lngConvert(CStr(Arr(i))) + Next +End Sub + +Function Convert(Letter As String) As Long +Dim Romans(), DecInt(), Pos As Integer + + Romans = Array("M", "D", "C", "L", "X", "V", "I") + DecInt = Array(1000, 500, 100, 50, 10, 5, 1) + Pos = -1 + On Error Resume Next + Pos = Application.Match(Letter, Romans, 0) - 1 + On Error GoTo 0 + If Pos <> -1 Then Convert = DecInt(Pos) +End Function + +Function lngConvert(strRom As String) 'recursive function +Dim i As Long, iVal As Integer + + If Len(strRom) = 1 Then + lngConvert = Convert(strRom) + Else + iVal = Convert(Mid(strRom, 1, 1)) + If iVal < Convert(Mid(strRom, 2, 1)) Then iVal = iVal * (-1) + lngConvert = iVal + lngConvert(Mid(strRom, 2, Len(strRom) - 1)) + End If +End Function diff --git a/Task/Roman-numerals-Encode/Clojure/roman-numerals-encode-5.clj b/Task/Roman-numerals-Encode/Clojure/roman-numerals-encode-5.clj new file mode 100644 index 0000000000..a573757b62 --- /dev/null +++ b/Task/Roman-numerals-Encode/Clojure/roman-numerals-encode-5.clj @@ -0,0 +1,20 @@ +(def roman-map + (sorted-map-by > + 1 "I", 4 "IV", 5 "V", 9 "IX", + 10 "X", 40 "XL", 50 "L", 90 "XC", + 100 "C", 400 "CD", 500 "D", 900 "CM" + 1000 "M")) + +(defn a2r + ([r] + (reduce str (a2r r (keys roman-map)))) + ([r n] + (when-not (empty? n) + (let [e (first n) + v (- r e) + roman (roman-map e)] + (cond + (< v 0) (a2r r (rest n)) + (= v 0) (cons roman []) + (>= v e) (cons roman (a2r v n)) + (< v e) (cons roman (a2r v (rest n)))))))) diff --git a/Task/Roman-numerals-Encode/Clojure/roman-numerals-encode-6.clj b/Task/Roman-numerals-Encode/Clojure/roman-numerals-encode-6.clj new file mode 100644 index 0000000000..a27d77242b --- /dev/null +++ b/Task/Roman-numerals-Encode/Clojure/roman-numerals-encode-6.clj @@ -0,0 +1,5 @@ +(a2r 1666) +"MDCLXVI" + +(map a2r [1000 1 389 45]) +("M" "I" "CCCLXXXIX" "XLV") diff --git a/Task/Roman-numerals-Encode/Elena/roman-numerals-encode.elena b/Task/Roman-numerals-Encode/Elena/roman-numerals-encode.elena new file mode 100644 index 0000000000..1de89a5dc9 --- /dev/null +++ b/Task/Roman-numerals-Encode/Elena/roman-numerals-encode.elena @@ -0,0 +1,31 @@ +import extensions. +import system'collections. +import system'routines. + +static RomanDictionary = Dictionary new; + setAt(1000, "M"); + setAt(900, "CM"); + setAt(500, "D"); + setAt(400, "CD"); + setAt(100, "C"); + setAt(90, "XC"); + setAt(50, "L"); + setAt(40, "XL"); + setAt(10, "X"); + setAt(9, "IX"); + setAt(5, "V"); + setAt(4, "IV"); + setAt(1, "I"). + +extension $op +{ + toRoman + = RomanDictionary accumulate(String new("I",self)) with(:m:kv)(m replace(String new("I",kv key), kv value)). +} + +program = +[ + console printLine("1990 : ", 1990 toRoman). + console printLine("2008 : ", 2008 toRoman). + console printLine("1666 : ", 1666 toRoman). +]. diff --git a/Task/Roman-numerals-Encode/Julia/roman-numerals-encode.julia b/Task/Roman-numerals-Encode/Julia/roman-numerals-encode.julia index d60290ff8f..1bb9adb307 100644 --- a/Task/Roman-numerals-Encode/Julia/roman-numerals-encode.julia +++ b/Task/Roman-numerals-Encode/Julia/roman-numerals-encode.julia @@ -1,35 +1,32 @@ function romanencode(n::Integer) - const DR = [["I", "X", "C", "M"] ["V", "L", "D", "MMM"]] + if n < 1 || n > 4999 throw(DomainError()) end + + DR = [["I", "X", "C", "M"] ["V", "L", "D", "MMM"]] rnum = "" - if n > 4999 || n < 1 - throw(DomainError()) - end for (omag, d) in enumerate(digits(n)) if d == 0 omr = "" - elseif d < 4 - omr = DR[omag, 1]^d + elseif d < 4 + omr = DR[omag, 1] ^ d elseif d == 4 - omr = DR[omag, 1]*DR[omag, 2] + omr = DR[omag, 1] * DR[omag, 2] elseif d == 5 omr = DR[omag, 2] - elseif d < 9 - omr = DR[omag, 2]*(DR[omag, 1]^(d - 5)) + elseif d < 9 + omr = DR[omag, 2] * DR[omag, 1] ^ (d - 5) else - omr = DR[omag, 1]*DR[(omag +1), 1] + omr = DR[omag, 1] * DR[omag + 1, 1] end - rnum = omr*rnum + rnum = omr * rnum end return rnum end -testcases = Int64[1990, 2008, 1668] -for i in 1:12 - push!(testcases, rand(1:4999)) -end +testcases = [1990, 2008, 1668] +append!(testcases, rand(1:4999, 12)) testcases = unique(testcases) println("Test romanencode, arabic => roman:") -for i in testcases - println(i, " => ", romanencode(i)) +for n in testcases + @printf("%-4i => %s\n", n, romanencode(n)) end diff --git a/Task/Roman-numerals-Encode/Kotlin/roman-numerals-encode.kotlin b/Task/Roman-numerals-Encode/Kotlin/roman-numerals-encode-1.kotlin similarity index 100% rename from Task/Roman-numerals-Encode/Kotlin/roman-numerals-encode.kotlin rename to Task/Roman-numerals-Encode/Kotlin/roman-numerals-encode-1.kotlin diff --git a/Task/Roman-numerals-Encode/Kotlin/roman-numerals-encode-2.kotlin b/Task/Roman-numerals-Encode/Kotlin/roman-numerals-encode-2.kotlin new file mode 100644 index 0000000000..738fa765dc --- /dev/null +++ b/Task/Roman-numerals-Encode/Kotlin/roman-numerals-encode-2.kotlin @@ -0,0 +1,19 @@ +fun Int.toRomanNumeral(): String { + fun digit(k: Int, unit: String, five: String, ten: String): String { + return when (k) { + in 1..3 -> unit.repeat(k) + 4 -> unit + five + in 5..8 -> five + unit.repeat(k - 5) + 9 -> unit + ten + else -> throw IllegalArgumentException("$k not in range 1..9") + } + } + return when (this) { + 0 -> "" + in 1..9 -> digit(this, "I", "V", "X") + in 10..99 -> digit(this / 10, "X", "L", "C") + (this % 10).toRomanNumeral() + in 100..999 -> digit(this / 100, "C", "D", "M") + (this % 100).toRomanNumeral() + in 1000..3999 -> "M" + (this - 1000).toRomanNumeral() + else -> throw IllegalArgumentException("${this} not in range 0..3999") + } +} diff --git a/Task/Roman-numerals-Encode/Modula-2/roman-numerals-encode.mod2 b/Task/Roman-numerals-Encode/Modula-2/roman-numerals-encode.mod2 new file mode 100644 index 0000000000..5cf83521f1 --- /dev/null +++ b/Task/Roman-numerals-Encode/Modula-2/roman-numerals-encode.mod2 @@ -0,0 +1,46 @@ +MODULE RomanNumeralsEncode; + +FROM Strings IMPORT + Append; +FROM STextIO IMPORT + WriteString, WriteLn; + +CONST + MaxChars = 15; + (* 3888 or MMMDCCCLXXXVIII (15 chars) is the longest string properly encoded + with these symbols. *) + +TYPE + TRomanNumeral = ARRAY [0 .. MaxChars - 1] OF CHAR; + +PROCEDURE ToRoman(AValue: CARDINAL; VAR OUT Destination: ARRAY OF CHAR); +TYPE + TRomanSymbols = ARRAY [0 .. 1] OF CHAR; + TWeights = ARRAY [0 .. 12] OF CARDINAL; + TSymbols = ARRAY [0 .. 12] OF TRomanSymbols; +CONST + Weights = TWeights {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; + Symbols = TSymbols {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", + "V", "IV", "I"}; +VAR + I: CARDINAL; +BEGIN + Destination := ""; + I := 0; + WHILE (I <= HIGH(Weights)) AND (AValue > 0) DO + WHILE AValue >= Weights[I] DO + Append(Symbols[I], Destination); + AValue := AValue - Weights[I] + END; + INC(I); + END; +END ToRoman; + +VAR + Numeral: TRomanNumeral; + +BEGIN + ToRoman(1990, Numeral); WriteString(Numeral); WriteLn; (* MCMXC *) + ToRoman(2018, Numeral); WriteString(Numeral); WriteLn; (* MMXVIII *) + ToRoman(3888, Numeral); WriteString(Numeral); WriteLn; (* MMMDCCCLXXXVIII *) +END RomanNumeralsEncode. diff --git a/Task/Roman-numerals-Encode/Perl-6/roman-numerals-encode.pl6 b/Task/Roman-numerals-Encode/Perl-6/roman-numerals-encode.pl6 new file mode 100644 index 0000000000..72983c3bfd --- /dev/null +++ b/Task/Roman-numerals-Encode/Perl-6/roman-numerals-encode.pl6 @@ -0,0 +1,22 @@ +my %symbols = + 1 => "I", 5 => "V", 10 => "X", 50 => "L", 100 => "C", + 500 => "D", 1_000 => "M"; + +my @subtractors = + 1_000, 100, 500, 100, 100, 10, 50, 10, 10, 1, 5, 1, 1, 0; + +multi sub roman (0) { '' } +multi sub roman (Int $n) { + for @subtractors -> $cut, $minus { + $n >= $cut + and return %symbols{$cut} ~ roman($n - $cut); + $n >= $cut - $minus + and return %symbols{$minus} ~ roman($n + $minus); + } +} + +# Sample usage + +for 1 .. 2_010 -> $x { + say roman($x); +} diff --git a/Task/Roman-numerals-Encode/Python/roman-numerals-encode-5.py b/Task/Roman-numerals-Encode/Python/roman-numerals-encode-5.py new file mode 100644 index 0000000000..643839e260 --- /dev/null +++ b/Task/Roman-numerals-Encode/Python/roman-numerals-encode-5.py @@ -0,0 +1,22 @@ +def arabic_to_roman(dclxvi): +#=========================== + '''Convert an integer from the decimal notation to the Roman notation''' + org = dclxvi; # 666 # + out = ""; + for scale, arabic_scale in enumerate(arabic): + if org == 0: break + multiples = org // arabic_scale; + org -= arabic_scale * multiples; + out += roman[scale] * multiples; + if (org >= -adjust_arabic[scale] + arabic_scale): + org -= -adjust_arabic[scale] + arabic_scale; + out += adjust_roman[scale] + roman[scale] + return out + +if __name__ == "__main__": + test = (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,25,30,40,50,60,69,70, + 80,90,99,100,200,300,400,500,600,666,700,800,900,1000,1009,1444,1666,1945,1997,1999, + 2000,2008,2500,3000,4000,4999,5000,6666,10000,50000,100000,500000,1000000); + + for val in test: + print("%8d %s" %(val, arabic_to_roman(val))) diff --git a/Task/Roman-numerals-Encode/SETL/roman-numerals-encode.setl b/Task/Roman-numerals-Encode/SETL/roman-numerals-encode.setl new file mode 100644 index 0000000000..718d1117fe --- /dev/null +++ b/Task/Roman-numerals-Encode/SETL/roman-numerals-encode.setl @@ -0,0 +1,17 @@ +examples := [2008, 1666, 1990]; + +for example in examples loop + print( roman_numeral(example) ); +end loop; + +proc roman_numeral( n ); + R := [[1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'], [100, 'C'], [90, 'XC'], [50, 'L'], [40, 'XL'], [10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I']]; + roman := ''; + for numeral in R loop + while n >= numeral(1) loop + n := n - numeral(1); + roman := roman + numeral(2); + end loop; + end loop; + return roman; +end; diff --git a/Task/Roots-of-a-quadratic-function/Julia/roots-of-a-quadratic-function.julia b/Task/Roots-of-a-quadratic-function/Julia/roots-of-a-quadratic-function.julia index be411a0539..0487706414 100644 --- a/Task/Roots-of-a-quadratic-function/Julia/roots-of-a-quadratic-function.julia +++ b/Task/Roots-of-a-quadratic-function/Julia/roots-of-a-quadratic-function.julia @@ -1,27 +1,23 @@ -function quad_roots{S<:Real,T<:Real,U<:Real}(x::S, y::T, z::U) - (a, b, c) = promote(float(x), y, z) - 2eps(a) < abs(a) || return [-c/b] - disc = b^2 - 4a*c - 2eps(b^2) < abs(disc) || return [-sqrt(c/a)] - if disc < 0 - disc += 0.0im - end - d = sqrt(disc) - if b < 0 - d += -b - return [d/2a, 2c/d] +function quadroots(x::Real, y::Real, z::Real) + a, b, c = promote(float(x), y, z) + if a ≈ 0.0 return [-c / b] end + Δ = b ^ 2 - 4a * c + if Δ ≈ 0.0 return [-sqrt(c / a)] end + if Δ < 0.0 Δ = complex(Δ) end + d = sqrt(Δ) + if b < 0.0 + d -= b + return [d / 2a, 2c / d] else - d = -b - d - return [2c/d, d/2a] + d = -d - b + return [2c / d, d / 2a] end end -a = {1, 1, 1.0, 10} -b = {10, 2, -10.0^9, 1} -c = {1, 1, 1, 1} +a = [1, 1, 1.0, 10] +b = [10, 2, -10.0 ^ 9, 1] +c = [1, 1, 1, 1] -for i in 1:length(a) - pstr = @sprintf "%fx^2 + %fx + %f" a[i] b[i] c[i] - println("The roots of ", pstr, " are: ") - println(" ", join(quad_roots(a[i], b[i], c[i]), " and "), "\n") +for (x, y, z) in zip(a, b, c) + @printf "The roots of %.2fx² + %.2fx + %.2f\n\tx₀ = (%s)\n" x y z join(round.(quadroots(x, y, z), 2), ", ") end diff --git a/Task/Roots-of-unity/Stata/roots-of-unity.stata b/Task/Roots-of-unity/Stata/roots-of-unity.stata new file mode 100644 index 0000000000..c7ab87767e --- /dev/null +++ b/Task/Roots-of-unity/Stata/roots-of-unity.stata @@ -0,0 +1,12 @@ +n=7 +exp(2i*pi()/n*(0::n-1)) + 1 + +-----------------------------+ + 1 | 1 | + 2 | .623489802 + .781831482i | + 3 | -.222520934 + .974927912i | + 4 | -.900968868 + .433883739i | + 5 | -.900968868 - .433883739i | + 6 | -.222520934 - .974927912i | + 7 | .623489802 - .781831482i | + +-----------------------------+ diff --git a/Task/Rot-13/00DESCRIPTION b/Task/Rot-13/00DESCRIPTION index 04d60a82c5..b0c7cdaf65 100644 --- a/Task/Rot-13/00DESCRIPTION +++ b/Task/Rot-13/00DESCRIPTION @@ -10,7 +10,7 @@ The   '''rot-13'''   encoding is commonly known from the early days of Many news reader and mail user agent programs have built-in '''rot-13''' encoder/decoders or have the ability to feed a message through any external utility script for performing this (or other) actions. -The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position   (wrapping around from   '''z''''   to   '''a'''   as necessary). +The definition of the rot-13 function is to simply replace every letter of the ASCII alphabet with the letter which is "rotated" 13 characters "around" the 26 letter alphabet from its normal cardinal position   (wrapping around from   '''z'''   to   '''a'''   as necessary). Thus the letters   '''abc'''   become   '''nop'''   and so on. diff --git a/Task/Rot-13/6502-Assembly/rot-13.6502 b/Task/Rot-13/6502-Assembly/rot-13.6502 index 079f4d51cf..236093fd8b 100644 --- a/Task/Rot-13/6502-Assembly/rot-13.6502 +++ b/Task/Rot-13/6502-Assembly/rot-13.6502 @@ -1,31 +1,38 @@ -buffer = &70 ; or anywhere in zero page that's good +buffer = $fa ; or anywhere in zero page that's good +maxpage = $95 ; if non-terminated that's bad -org &1900 +org $1900 .rot13 - stx buffer - sty buffer+1 - ldy #0 -.loop lda (buffer),y - bne decode ; quit on ASCII 0 - rts -.decode cmp #&7b ; high range - bcs next - cmp #&41 ; low range - bcc next - cmp #&4f - bcc add13 - cmp #&5b - bcc sub13 - cmp #&61 - bcc next - cmp #&6f - bcc add13 - bcs sub13 ; saves a byte over a jump -.next iny - jmp loop -.add13 adc #13 ; we only get here via bcc; so clc not needed - jmp storeit -.sub13 sec - sbc #13 -.storeit sta (buffer),y - jmp next + stx buffer + sty buffer+1 + ldy #0 + beq readit +.loop cmp #$7b ; high range + bcs next ; >= { + cmp #$41 ; low range + bcc next ; < A + cmp #$4e + bcc add13 ; < N + cmp #$5b + bcc sub13set ; < [ + cmp #$61 + bcc next ; < a + cmp #$6e + bcs sub13 ; >= n +.add13 adc #13 ; we only get here via bcc; so clc not needed + bne storeit +.sub13set sec ; because we got here via bcc; so sec is needed +.sub13 sbc #13 ; we can get here via bcs; so sec not needed +.storeit sta (buffer),y +.next iny + bne readit + ldx buffer+1 + cpx maxpage + beq done + inx + stx buffer+1 +.readit lda (buffer),y ; quit on ascii 0 + bne loop +.done rts +.end +save "rot-13", rot13, end diff --git a/Task/Rot-13/Applesoft-BASIC/rot-13.applesoft b/Task/Rot-13/Applesoft-BASIC/rot-13.applesoft new file mode 100644 index 0000000000..f6694a2b1d --- /dev/null +++ b/Task/Rot-13/Applesoft-BASIC/rot-13.applesoft @@ -0,0 +1,2 @@ +100HOME:INPUT"ENTER A STRING:";S$:FORL=1TOLEN(S$):I$=MID$(S$,L,1):LC=(ASC(I$)>95)*32:C$=CHR$(ASC(I$)-LC):IFC$>="A"ANDC$<="Z"THENC$=CHR$(ASC(C$)+13):C$=CHR$(ASC(C$)-26*(C$>"Z")):I$=CHR$(ASC(C$)+LC) +110A$=A$+I$:NEXT:PRINTA$ diff --git a/Task/Rot-13/Elena/rot-13.elena b/Task/Rot-13/Elena/rot-13.elena new file mode 100644 index 0000000000..a28ea446b1 --- /dev/null +++ b/Task/Rot-13/Elena/rot-13.elena @@ -0,0 +1,30 @@ +import system'routines. +import extensions. + +singleton rotConvertor +{ + char convert(char ch) + [ + if (($97 <= ch) && (ch <= $109) || ($65 <= ch) && (ch <= $77)) + [ + ^ (ch toInt + 13) toChar + ]. + if (($110 <= ch) && (ch <= $122) || ($78 <= ch) && (ch <= $90)) + [ + ^ (ch toInt - 13) toChar + ]. + + ^ ch + ] + + literal convert(literal s) + = s selectBy(:ch)(rotConvertor convert(ch)); summarize(String new). +} + +program = +[ + if ('program'arguments length > 1) + [ + console printLine(rotConvertor convert('program'arguments[1])). + ] +]. diff --git a/Task/Rot-13/Julia/rot-13.julia b/Task/Rot-13/Julia/rot-13.julia index f4b73421ec..ff8ae296a6 100644 --- a/Task/Rot-13/Julia/rot-13.julia +++ b/Task/Rot-13/Julia/rot-13.julia @@ -1,7 +1,6 @@ function rot13(c::Char) - c in 'a':'z' ? 'a' + (c - 'a' + 13)%26 : - c in 'A':'Z' ? 'A' + (c - 'A' + 13)%26 : - c + shft = islower(c) ? 'a' : 'A' + isalpha(c) ? c = shft + (c - shft + 13) % 26 : c end -rot13(s::String) = map(rot13,s) +rot13(str::AbstractString) = map(rot13, str) diff --git a/Task/Rot-13/Perl-6/rot-13.pl6 b/Task/Rot-13/Perl-6/rot-13.pl6 index f528435343..89e22a9d5d 100644 --- a/Task/Rot-13/Perl-6/rot-13.pl6 +++ b/Task/Rot-13/Perl-6/rot-13.pl6 @@ -1 +1 @@ -.=trans: 'a..mn..z' => 'n..za..m', :ii +print slurp.trans: ['A'..'Z','a'..'z'] => ['N'..'Z','A'..'M','n'..'z','a'..'m'] diff --git a/Task/Rot-13/PowerBASIC/rot-13.powerbasic b/Task/Rot-13/PowerBASIC/rot-13.powerbasic new file mode 100644 index 0000000000..afc6e69e30 --- /dev/null +++ b/Task/Rot-13/PowerBASIC/rot-13.powerbasic @@ -0,0 +1,40 @@ +#COMPILE EXE +#COMPILER PBWIN 9.05 +#DIM ALL + +FUNCTION ROT13(BYVAL a AS STRING) AS STRING + LOCAL p AS BYTE PTR + LOCAL n AS BYTE, e AS BYTE + LOCAL res AS STRING + + res = a + p = STRPTR(res) + n = @p + DO WHILE n + SELECT CASE n + CASE 65 TO 90 + e = 90 + n += 13 + CASE 97 TO 122 + e = 122 + n += 13 + CASE ELSE + e = 255 + END SELECT + + IF n > e THEN + n -= 26 + END IF + @p = n + INCR p + n = @p + LOOP +FUNCTION = res +END FUNCTION + +'testing: + +FUNCTION PBMAIN () AS LONG +#DEBUG PRINT ROT13("abc") +#DEBUG PRINT ROT13("nop") +END FUNCTION diff --git a/Task/Rot-13/PowerShell/rot-13.psh b/Task/Rot-13/PowerShell/rot-13.psh index 316678c46a..710be4fad3 100644 --- a/Task/Rot-13/PowerShell/rot-13.psh +++ b/Task/Rot-13/PowerShell/rot-13.psh @@ -1,13 +1,3 @@ -Function ROT13($String) -{ - $Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" - $Cipher = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm" - Foreach($Char in $String.ToCharArray()) - { - If ( $Char -match "[A-Za-z]" ) - { $NewString += $Cipher.Chars($Alphabet.IndexOf($Char)) } - else - { $NewString += $Char } - } - Return $NewString -} +$e = "This is a test Guvf vf n grfg" + +[char[]](0..64+78..90+65..77+91..96+110..122+97..109+123..255)[[char[]]$e] -join "" diff --git a/Task/Rot-13/Python/rot-13-3.py b/Task/Rot-13/Python/rot-13-3.py index 8feb958ea7..711e62cdae 100644 --- a/Task/Rot-13/Python/rot-13-3.py +++ b/Task/Rot-13/Python/rot-13-3.py @@ -1,21 +1,20 @@ #!/usr/bin/env python import string + +TRANSLATION_TABLE = str.maketrans( + string.ascii_uppercase + string.ascii_lowercase, + string.ascii_uppercase[13:] + string.ascii_uppercase[:13] + + string.ascii_lowercase[13:] + string.ascii_lowercase[:13] +) + + def rot13(s): - """Implement the rot-13 encoding function: "rotate" each letter by the - letter that's 13 steps from it (wrapping from z to a) - """ - return s.translate( - string.maketrans( - string.ascii_uppercase + string.ascii_lowercase, - string.ascii_uppercase[13:] + string.ascii_uppercase[:13] + - string.ascii_lowercase[13:] + string.ascii_lowercase[:13] - ) - ) + """Return the rot-13 encoding of s.""" + return s.translate(TRANSLATION_TABLE) + + if __name__ == "__main__": - """Peform line-by-line rot-13 encoding on any files listed on our - command line or act as a standard UNIX filter (if no arguments - specified). - """ - import fileinput - for line in fileinput.input(): - print rot13(line), # (Note the trailing comma; avoid double-spacing our output)! + """rot-13 encode the input files, or stdin if no files are provided.""" + import fileinput + for line in fileinput.input(): + print(rot13(line), end="") diff --git a/Task/Rot-13/Python/rot-13-4.py b/Task/Rot-13/Python/rot-13-4.py index 2b433c8cac..cf36434c8f 100644 --- a/Task/Rot-13/Python/rot-13-4.py +++ b/Task/Rot-13/Python/rot-13-4.py @@ -1,21 +1,15 @@ #!/usr/bin/env python +from __future__ import print_function import string -def rot13(s): - """Implement the rot-13 encoding function: "rotate" each letter by the - letter that's 13 steps from it (wrapping from z to a) - """ - return s.translate( - str.maketrans( - string.ascii_uppercase + string.ascii_lowercase, - string.ascii_uppercase[13:] + string.ascii_uppercase[:13] + - string.ascii_lowercase[13:] + string.ascii_lowercase[:13] - ) - ) -if __name__ == "__main__": +lets = string.ascii_lowercase +key = {x:y for (x,y) in zip(lets[13:]+lets[:14], lets)} +key.update({x.upper():key[x].upper() for x in key.keys()}) +encode = lambda x: ''.join((key.get(c,c) for c in x)) +if __name__ == '__main__': """Peform line-by-line rot-13 encoding on any files listed on our command line or act as a standard UNIX filter (if no arguments specified). """ import fileinput for line in fileinput.input(): - print(rot13(line), end="") + print(encode(line), end="") diff --git a/Task/Rot-13/Ring/rot-13.ring b/Task/Rot-13/Ring/rot-13.ring index 726d56fab7..bb70cbd386 100644 --- a/Task/Rot-13/Ring/rot-13.ring +++ b/Task/Rot-13/Ring/rot-13.ring @@ -10,5 +10,5 @@ for a = 1 to len(s) if char > "z" char = char(ascii(char) - 26) else char = letter ok ok ans = ans + char -nex +next see ans + nl diff --git a/Task/Rot-13/Stata/rot-13.stata b/Task/Rot-13/Stata/rot-13.stata new file mode 100644 index 0000000000..59d7779ff7 --- /dev/null +++ b/Task/Rot-13/Stata/rot-13.stata @@ -0,0 +1,11 @@ +function rot13(s) { + u = ascii(s) + i = selectindex(u:>64 :& u:<91) + if (length(i)>0) u[i] = mod(u[i]:-52, 26):+65 + i = selectindex(u:>96 :& u:<123) + if (length(i)>0) u[i] = mod(u[i]:-84, 26):+97 + return(char(u)) +} + +rot13("Shall Not Perish") + Funyy Abg Crevfu diff --git a/Task/Rot-13/Visual-Basic/rot-13-1.vb b/Task/Rot-13/Visual-Basic/rot-13-1.vb new file mode 100644 index 0000000000..efde0c44ff --- /dev/null +++ b/Task/Rot-13/Visual-Basic/rot-13-1.vb @@ -0,0 +1,24 @@ +Function ROT13(ByVal a As String) As String + Dim i As Long + Dim n As Integer, e As Integer + + ROT13 = a + For i = 1 To Len(a) + n = Asc(Mid$(a, i, 1)) + Select Case n + Case 65 To 90 + e = 90 + n = n + 13 + Case 97 To 122 + e = 122 + n = n + 13 + Case Else + e = 255 + End Select + + If n > e Then + n = n - 26 + End If + Mid$(ROT13, i, 1) = Chr$(n) + Next i +End Function diff --git a/Task/Rot-13/Visual-Basic/rot-13-2.vb b/Task/Rot-13/Visual-Basic/rot-13-2.vb new file mode 100644 index 0000000000..b950531489 --- /dev/null +++ b/Task/Rot-13/Visual-Basic/rot-13-2.vb @@ -0,0 +1,4 @@ +Sub Main() + Debug.Assert ROT13("abc") = "nop" + Debug.Assert ROT13("nop") = "abc" +End Sub diff --git a/Task/Run-length-encoding/BaCon/run-length-encoding.bacon b/Task/Run-length-encoding/BaCon/run-length-encoding.bacon new file mode 100644 index 0000000000..f80ebc39ce --- /dev/null +++ b/Task/Run-length-encoding/BaCon/run-length-encoding.bacon @@ -0,0 +1,42 @@ +FUNCTION Rle_Encode$(txt$) + + LOCAL result$, c$ = LEFT$(txt$, 1) + LOCAL total = 1 + + FOR x = 2 TO LEN(txt$) + IF c$ = MID$(txt$, x, 1) THEN + INCR total + ELSE + result$ = result$ & STR$(total) & c$ + c$ = MID$(txt$, x, 1) + total = 1 + END IF + NEXT + + RETURN result$ & STR$(total) & c$ + +END FUNCTION + +FUNCTION Rle_Decode$(txt$) + + LOCAL nr$, result$ + + FOR x = 1 TO LEN(txt$) + IF REGEX(MID$(txt$, x, 1), "[[:digit:]]") THEN + nr$ = nr$ & MID$(txt$, x, 1) + ELSE + result$ = result$ & FILL$(VAL(nr$), ASC(MID$(txt$, x, 1))) + nr$ = "" + END IF + NEXT + + RETURN result$ + +END FUNCTION + +rle_data$ = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" + +PRINT "RLEData: ", rle_data$ +encoded$ = Rle_Encode$(rle_data$) +PRINT "Encoded: ", encoded$ +PRINT "Decoded: ", Rle_Decode$(encoded$) diff --git a/Task/Run-length-encoding/Ceylon/run-length-encoding.ceylon b/Task/Run-length-encoding/Ceylon/run-length-encoding.ceylon new file mode 100644 index 0000000000..f6640aa625 --- /dev/null +++ b/Task/Run-length-encoding/Ceylon/run-length-encoding.ceylon @@ -0,0 +1,31 @@ +shared void run() { + + "Takes a string such as aaaabbbbbbcc and returns 4a6b2c" + String compress(String string) { + if (exists firstChar = string.first) { + if (exists index = string.firstIndexWhere((char) => char != firstChar)) { + return "``index````firstChar````compress(string[index...])``"; + } + else { + return "``string.size````firstChar``"; + } + } + else { + return ""; + } + } + + "Takes a string such as 4a6b2c and returns aaaabbbbbbcc" + String decompress(String string) => + let (runs = string.split(Character.letter, false).paired) + "".join { + for ([length, char] in runs) + if (is Integer int = Integer.parse(length)) + char.repeat(int) + }; + + assert (compress("aaaabbbbbaa") == "4a5b2a"); + assert (decompress("4a6b2c") == "aaaabbbbbbcc"); + assert (compress("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW") == "12W1B12W3B24W1B14W"); + assert (decompress("24a") == "aaaaaaaaaaaaaaaaaaaaaaaa"); +} diff --git a/Task/Run-length-encoding/Elena/run-length-encoding.elena b/Task/Run-length-encoding/Elena/run-length-encoding.elena new file mode 100644 index 0000000000..4770e1f68a --- /dev/null +++ b/Task/Run-length-encoding/Elena/run-length-encoding.elena @@ -0,0 +1,63 @@ +import system'text. +import system'routines. +import extensions. + +singleton compressor +{ + literal compress(literal s) + [ + type tb := TextBuilder new. + int count := 0. + char current := s[0]. + s forEach(:ch) + [ + if (ch == current) + [ + count += 1 + ]; + [ + tb writeFormatted("{0}{1}",count,current). + count := 1. + current := ch + ] + ]. + + tb writeFormatted("{0}{1}",count,current). + + ^ tb + ] + + literal decompress(literal s) + [ + type tb := TextBuilder new. + char current := $0. + var a := String new. + s forEach(:ch) + [ + current := ch. + if (current isDigit) + [ + a append(ch) + ]; + [ + int count := a toInt. + a clear. + + tb fill(current,count). + ] + ]. + + ^ tb + ] +} + +program = +[ + var s := "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW". + + s := compressor compress(s). + console printLine(s). + + s := compressor decompress(s). + console printLine(s). +]. diff --git a/Task/Run-length-encoding/Factor/run-length-encoding.factor b/Task/Run-length-encoding/Factor/run-length-encoding.factor new file mode 100644 index 0000000000..5a441d9e1f --- /dev/null +++ b/Task/Run-length-encoding/Factor/run-length-encoding.factor @@ -0,0 +1,18 @@ +USING: io kernel literals math.parser math.ranges sequences +sequences.extras sequences.repeating splitting.extras +splitting.monotonic strings ; +IN: rosetta-code.run-length-encoding + +CONSTANT: alpha $[ CHAR: A CHAR: Z [a,b] >string ] + +: encode ( str -- str ) + [ = ] monotonic-split [ [ length number>string ] [ first ] + bi suffix ] map concat ; + +: decode ( str -- str ) + alpha split* [ odd-indices ] [ even-indices + [ string>number ] map ] bi [ repeat ] 2map concat ; + +"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" +"12W1B12W3B24W1B14W" +[ encode ] [ decode ] bi* [ print ] bi@ diff --git a/Task/Run-length-encoding/Julia/run-length-encoding.julia b/Task/Run-length-encoding/Julia/run-length-encoding.julia new file mode 100644 index 0000000000..973860c4ee --- /dev/null +++ b/Task/Run-length-encoding/Julia/run-length-encoding.julia @@ -0,0 +1,10 @@ +using IterTools + +encode(str::String) = collect((length(g), first(g)) for g in groupby(first, str)) +decode(cod::Vector) = join(repeat("$l", n) for (n, l) in cod) + +for original in ["aaaaahhhhhhmmmmmmmuiiiiiiiaaaaaa", "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"] + encoded = encode(original) + decoded = decode(encoded) + println("Original: $original\n -> encoded: $encoded\n -> decoded: $decoded") +end diff --git a/Task/Run-length-encoding/Python/run-length-encoding-1.py b/Task/Run-length-encoding/Python/run-length-encoding-1.py index 941b463083..f4c30eefb4 100644 --- a/Task/Run-length-encoding/Python/run-length-encoding-1.py +++ b/Task/Run-length-encoding/Python/run-length-encoding-1.py @@ -13,10 +13,13 @@ def encode(input_string): else: count += 1 else: - entry = (character,count) - lst.append(entry) - return lst - + try: + entry = (character,count) + lst.append(entry) + return (lst, 0) + except Exception as e: + print("Exception encountered {e}".format(e=e)) + return (e, 1) def decode(lst): q = "" @@ -25,5 +28,7 @@ def decode(lst): return q #Method call -encode("aaaaahhhhhhmmmmmmmuiiiiiiiaaaaaa") -decode([('a', 5), ('h', 6), ('m', 7), ('u', 1), ('i', 7), ('a', 6)]) +value = encode("aaaaahhhhhhmmmmmmmuiiiiiiiaaaaaa") +if value[1] == 0: + print("Encoded value is {}".format(value[0])) + decode(value[0]) diff --git a/Task/Run-length-encoding/Ring/run-length-encoding.ring b/Task/Run-length-encoding/Ring/run-length-encoding.ring new file mode 100644 index 0000000000..532fc2d7db --- /dev/null +++ b/Task/Run-length-encoding/Ring/run-length-encoding.ring @@ -0,0 +1,30 @@ +# Project : Run-length encoding +# Date : 2017/12/04 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +load "stdlib.ring" +test = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" +num = 0 +nr = 0 +decode = newlist(7,2) +for n = 1 to len(test) - 1 + if test[n] = test[n+1] + num = num + 1 + else + nr = nr + 1 + decode[nr][1] = (num + 1) + decode[nr][2] = test[n] + see "" + (num + 1) + test[n] + num = 0 + ok +next +see "" + (num + 1) + test[n] +see nl +nr = nr + 1 +decode[nr][1] = (num + 1) +decode[nr][2] = test[n] +for n = 1 to len(decode) + dec = copy(decode[n][2], decode[n][1]) + see dec +next diff --git a/Task/Run-length-encoding/VBA/run-length-encoding.vba b/Task/Run-length-encoding/VBA/run-length-encoding.vba new file mode 100644 index 0000000000..30ccb086d8 --- /dev/null +++ b/Task/Run-length-encoding/VBA/run-length-encoding.vba @@ -0,0 +1,37 @@ +Option Explicit + +Sub Main() +Dim p As String + p = length_encoding("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW") + Debug.Print p + Debug.Print length_decoding(p) +End Sub + +Private Function length_encoding(S As String) As String +Dim F As String, r As String, a As String, n As Long, c As Long, k As Long + r = Left(S, 1) + c = 1 + For n = 2 To Len(S) + If r <> Mid(S, n, 1) Then + a = a & c & r + r = Mid(S, n, 1) + c = 1 + Else + c = c + 1 + End If + Next + length_encoding = a & c & r +End Function + +Private Function length_decoding(S As String) As String +Dim F As Long, r As String, a As String + For F = 1 To Len(S) + If IsNumeric(Mid(S, F, 1)) Then + r = r & Mid(S, F, 1) + Else + a = a & String(CLng(r), Mid(S, F, 1)) + r = vbNullString + End If + Next + length_decoding = a +End Function diff --git a/Task/Runge-Kutta-method/C/runge-kutta-method.c b/Task/Runge-Kutta-method/C/runge-kutta-method.c index 0961d3a74e..88c7896171 100644 --- a/Task/Runge-Kutta-method/C/runge-kutta-method.c +++ b/Task/Runge-Kutta-method/C/runge-kutta-method.c @@ -21,7 +21,7 @@ int main(void) double *y, x, y2; double x0 = 0, x1 = 10, dx = .1; int i, n = 1 + (x1 - x0)/dx; - y = malloc(sizeof(double) * n); + y = (double *)malloc(sizeof(double) * n); for (y[0] = 1, i = 1; i < n; i++) y[i] = rk4(rate, dx, x0 + dx * (i - 1), y[i-1]); diff --git a/Task/Runge-Kutta-method/Julia/runge-kutta-method-1.julia b/Task/Runge-Kutta-method/Julia/runge-kutta-method-1.julia new file mode 100644 index 0000000000..7d8fe52c65 --- /dev/null +++ b/Task/Runge-Kutta-method/Julia/runge-kutta-method-1.julia @@ -0,0 +1,23 @@ +f(x, y) = x * sqrt(y) +theoric(t) = (t ^ 2 + 4.0) ^ 2 / 16.0 + +rk4(f) = (t, y, δt) -> # 1st (result) lambda + ((δy1) -> # 2nd lambda + ((δy2) -> # 3rd lambda + ((δy3) -> # 4th lambda + ((δy4) -> ( δy1 + 2δy2 + 2δy3 + δy4 ) / 6 # 5th and deepest lambda: calc y_{n+1} + )(δt * f(t + δt, y + δy3)) # calc δy₄ + )(δt * f(t + δt / 2, y + δy2 / 2)) # calc δy₃ + )(δt * f(t + δt / 2, y + δy1 / 2)) # calc δy₂ + )(δt * f(t, y)) # calc δy₁ + +δy = rk4(f) +t₀, δt, tmax = 0.0, 0.1, 10.0 +y₀ = 1.0 + +t, y = t₀, y₀ +while t ≤ tmax + if t ≈ round(t) @printf("y(%4.1f) = %10.6f\terror: %12.6e\n", t, y, abs(y - theoric(t))) end + y += δy(t, y, δt) + t += δt +end diff --git a/Task/Runge-Kutta-method/Julia/runge-kutta-method-2.julia b/Task/Runge-Kutta-method/Julia/runge-kutta-method-2.julia new file mode 100644 index 0000000000..77601d87c3 --- /dev/null +++ b/Task/Runge-Kutta-method/Julia/runge-kutta-method-2.julia @@ -0,0 +1,21 @@ +function rk4(f::Function, x₀::Float64, y₀::Float64, x₁::Float64, n) + vx = Vector{Float64}(n + 1) + vy = Vector{Float64}(n + 1) + vx[1] = x = x₀ + vy[1] = y = y₀ + h = (x₁ - x₀) / n + for i in 1:n + k₁ = h * f(x, y) + k₂ = h * f(x + 0.5h, y + 0.5k₁) + k₃ = h * f(x + 0.5h, y + 0.5k₂) + k₄ = h * f(x + h, y + k₃) + vx[i + 1] = x = x₀ + i * h + vy[i + 1] = y = y + (k₁ + 2k₂ + 2k₃ + k₄) / 6 + end + return vx, vy +end + +vx, vy = rk4(f, 0.0, 1.0, 10.0, 100) +for (x, y) in Iterators.take(zip(vx, vy), 10) + @printf("%4.1f %10.5f %+12.4e\n", x, y, y - theoric(x)) +end diff --git a/Task/Runge-Kutta-method/Julia/runge-kutta-method.julia b/Task/Runge-Kutta-method/Julia/runge-kutta-method.julia deleted file mode 100644 index 026d7a4efd..0000000000 --- a/Task/Runge-Kutta-method/Julia/runge-kutta-method.julia +++ /dev/null @@ -1,33 +0,0 @@ -function rk4(f) - return (t,y,dt)-> - ( (dy1 )-> - ( (dy2 )-> - ( (dy3 )-> - ( (dy4 )->( dy1 + 2*dy2 + 2*dy3 + dy4 ) / 6 - )( dt * f( t +dt , y + dy3 ) ) - )( dt * f( t +dt/2, y + dy2/2 ) ) - )( dt * f( t +dt/2, y + dy1/2 ) ) - )( dt * f( t , y ) ) -end - -theory(t) = (t^2 + 4.0)^2 / 16.0 - -tmax = 10.0 -ttol = 1.e-5 - -t0 = 0.0 -y0 = 1.0 -dt = 0.1 - -dy = rk4( (t,y) -> t*sqrt(y) ) - -t = t0 -y = y0 - -while t <= tmax - if abs(round(t) - t) < ttol - @printf( STDOUT,"y(%4.1f)\t= %12.6f \t error: %12.6e\n",t,y,abs(y-theory(t)) ) - end - y = y + dy(t,y,dt) - t = t + dt -end diff --git a/Task/Runge-Kutta-method/Nim/runge-kutta-method.nim b/Task/Runge-Kutta-method/Nim/runge-kutta-method.nim new file mode 100644 index 0000000000..ae6914f3d5 --- /dev/null +++ b/Task/Runge-Kutta-method/Nim/runge-kutta-method.nim @@ -0,0 +1,26 @@ +import math + +proc fn(t, y: float): float = + result = t * math.sqrt(y) + +proc solution(t: float): float = + result = (t^2 + 4)^2 / 16 + +proc rk(start, stop, step: float) = + let nsteps = int(round((stop - start) / step)) + 1 + let delta = (stop - start) / float(nsteps - 1) + var cur_y = 1.0 + for i in 0..(nsteps - 1): + let cur_t = start + delta * float(i) + + if abs(cur_t - math.round(cur_t)) < 1e-5: + echo "y(", cur_t, ") = ", cur_y, ", error = ", solution(cur_t) - cur_y + + let dy1 = step * fn(cur_t, cur_y) + let dy2 = step * fn(cur_t + 0.5 * step, cur_y + 0.5 * dy1) + let dy3 = step * fn(cur_t + 0.5 * step, cur_y + 0.5 * dy2) + let dy4 = step * fn(cur_t + step, cur_y + dy3) + + cur_y += (dy1 + 2.0 * (dy2 + dy3) + dy4) / 6.0 + +rk(start=0.0, stop=10.0, step=0.1) diff --git a/Task/Runge-Kutta-method/Octave/runge-kutta-method.octave b/Task/Runge-Kutta-method/Octave/runge-kutta-method.octave index f0a34fd1f8..e4af3a9b33 100644 --- a/Task/Runge-Kutta-method/Octave/runge-kutta-method.octave +++ b/Task/Runge-Kutta-method/Octave/runge-kutta-method.octave @@ -1,8 +1,29 @@ -function ydot = f(y, t) - ydot = t * sqrt( y ); +#Applying the Runge-Kutta method (This code must be implement on a different file than the main one). + +function temp = rk4(func,x,pvi,h) + K1 = h*func(x,pvi); + K2 = h*func(x+0.5*h,pvi+0.5*K1); + K3 = h*func(x+0.5*h,pvi+0.5*K2); + K4 = h*func(x+h,pvi+K3); + temp = pvi + (K1 + 2*K2 + 2*K3 + K4)/6; endfunction -t = [0:10]'; -y = lsode("f", 1, t); +#Main Program. -[ t, y, y - 1/16 * (t.**2 + 4).**2 ] +f = @(t) (1/16)*((t.^2 + 4).^2); +df = @(t,y) t*sqrt(y); + +pvi = 1.0; +h = 0.1; +Yn = pvi; + +for x = 0:h:10-h + pvi = rk4(df,x,pvi,h); + Yn = [Yn pvi]; +endfor + +fprintf('Time \t Exact Value \t ODE4 Value \t Num. Error\n'); + +for i=0:10 + fprintf('%d \t %.5f \t %.5f \t %.4g \n',i,f(i),Yn(1+i*10),f(i)-Yn(1+i*10)); +endfor diff --git a/Task/Runge-Kutta-method/REXX/runge-kutta-method.rexx b/Task/Runge-Kutta-method/REXX/runge-kutta-method.rexx index 0e696e2918..ec5f47b23b 100644 --- a/Task/Runge-Kutta-method/REXX/runge-kutta-method.rexx +++ b/Task/Runge-Kutta-method/REXX/runge-kutta-method.rexx @@ -1,32 +1,28 @@ /*REXX program uses the Runge─Kutta method to solve the equation: y'(t)=t² √[y(t)] */ -numeric digits 40; f=digits()%4 /*use 40 digits, but only show 1/4 that*/ -x0=0; x1=10; w=digits()%2; dx= .1 /*set X0 & X1; calculate W & DX */ +numeric digits 40; f=digits() % 4 /*use 40 decimal digs, but only show 10*/ +x0=0; x1=10; dx= .1 /*define variables: X0 X1 DX */ n=1 + (x1-x0) / dx -y.=1; do m=1 for n-1; mm=m-1 - y.m=RK4(dx, x0+dx*mm, y.mm) /*use 4th order Runge─Kutta.*/ - end /*m*/ +y.=1; do m=1 for n-1; p=m-1; y.m=RK4(dx, x0 + dx*p, y.p) + end /*m*/ /* [↑] use 4th order Runge─Kutta. */ +w=digits() % 2 /*W: width used for displaying numbers.*/ +say center('X', f, "═") center('Y', w+2, "═") center("relative error", w+8, '═') /*hdr*/ -say center('X', f, "═") center('Y', w+2, "═") center("relative error", w+8, '═') - - do i=0 to n-1 by 10; x=(x0+dx*i)/1; $=y.i / (x*x/4+1)**2 - 1 - say center(x,f) fmt(y.i) left('', 2 + ($>=0)) fmt($) - end /*i*/ + do i=0 to n-1 by 10; x=(x0 + dx*i) / 1; $=y.i/(x*x/4+1)**2 -1 + say center(x, f) fmt(y.i) left('', 2 + ($>=0) ) fmt($) + end /*i*/ /*└┴┴┴───◄─────── aligns positive #'s. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -fmt: z=right( format( arg(1), w, f), w); hasE=pos('E', z)\==0 /*right adjust number.*/ - if pos(.,z)\==0 & \hasE then z=left( strip( strip(z, 'T', 0), "T", .), w) - return translate(right(z, (z>=0) + w + 5*hasE), 'e', "E") /*Positive | E, adjust*/ +fmt: z=right( format( arg(1), w, f), w); hasE=pos('E', z)\==0; has.=pos(., z)\==0 + jus=has. & \hasE; if jus then z=left( strip( strip(z, 'T', 0), "T", .), w) + return translate(right(z, (z>=0) + w + 5*hasE + 2*(jus & (z<0) ) ), 'e', "E") /*──────────────────────────────────────────────────────────────────────────────────────*/ -rate: return arg(1) * sqrt( arg(2) ) /*compute the rate. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -RK4: procedure; parse arg dx,x,y; k1= dx * rate( x , y ) - k2= dx * rate( x +dx/2 , y +k1/2 ) - k3= dx * rate( x +dx/2 , y +k2/2 ) - k4= dx * rate( x +dx , y +k3 ) - return y + (k1 + k2+k2 + k3+k3 + k4) / 6 +RK4: procedure; parse arg dx,x,y; dxH=dx/2; k1= dx * (x ) * sqrt(y ) + k2= dx * (x + dxH) * sqrt(y + k1/2) + k3= dx * (x + dxH) * sqrt(y + k2/2) + k4= dx * (x + dx ) * sqrt(y + k3 ) + return y + (k1 + k2*2 + k3*2 + k4) / 6 /*──────────────────────────────────────────────────────────────────────────────────────*/ sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); m.=9; numeric form; h=d+6 - numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_ %2 - do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ - do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ - numeric digits d; return g/1 + 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 diff --git a/Task/Runge-Kutta-method/Rust/runge-kutta-method.rust b/Task/Runge-Kutta-method/Rust/runge-kutta-method.rust index 2fcf694c72..144eba05bd 100644 --- a/Task/Runge-Kutta-method/Rust/runge-kutta-method.rust +++ b/Task/Runge-Kutta-method/Rust/runge-kutta-method.rust @@ -1,10 +1,10 @@ -fn runge_kutta4( fx: &Fn(f64, f64) -> f64, x: f64, y: f64, dx: f64 ) -> f64 { - let k1 = dx * fx( x, y ); - let k2 = dx * fx( x + dx / 2.0, y + k1 / 2.0 ); - let k3 = dx * fx( x + dx / 2.0, y + k2 / 2.0 ); - let k4 = dx * fx( x + dx, y + k3 ); +fn runge_kutta4(fx: &Fn(f64, f64) -> f64, x: f64, y: f64, dx: f64) -> f64 { + let k1 = dx * fx(x, y); + let k2 = dx * fx(x + dx / 2.0, y + k1 / 2.0); + let k3 = dx * fx(x + dx / 2.0, y + k2 / 2.0); + let k4 = dx * fx(x + dx, y + k3); - y + ( k1 + 2.0 * k2 + 2.0 * k3 + k4 ) / 6.0 + y + (k1 + 2.0 * k2 + 2.0 * k3 + k4) / 6.0 } fn f(x: f64, y: f64) -> f64 { @@ -12,17 +12,17 @@ fn f(x: f64, y: f64) -> f64 { } fn actual(x: f64) -> f64 { - (1.0/16.0) * (x*x+4.0).powi(2) + (1.0 / 16.0) * (x * x + 4.0).powi(2) } fn main() { let mut y = 1.0; let mut x = 0.0; let step = 0.1; - let mut steps = 0; let max_steps = 101; let sample_every_n = 10; - while steps < max_steps { + + for steps in 0..max_steps { if steps % sample_every_n == 0 { println!("y({}):\t{:.10}\t\t {:E}", x, y, actual(x) - y) } @@ -30,7 +30,5 @@ fn main() { y = runge_kutta4(&f, x, y, step); x = ((x * 10.0) + (step * 10.0)) / 10.0; - steps += 1; - } } diff --git a/Task/Runge-Kutta-method/Stata/runge-kutta-method.stata b/Task/Runge-Kutta-method/Stata/runge-kutta-method.stata new file mode 100644 index 0000000000..3f50844a58 --- /dev/null +++ b/Task/Runge-Kutta-method/Stata/runge-kutta-method.stata @@ -0,0 +1,41 @@ +function rk4(f, t0, y0, t1, n) { + h = (t1-t0)/(n-1) + a = J(n, 2, 0) + a[1, 1] = t = t0 + a[1, 2] = y = y0 + for (i=2; i<=n; i++) { + k1 = h*(*f)(t, y) + k2 = h*(*f)(t+0.5*h, y+0.5*k1) + k3 = h*(*f)(t+0.5*h, y+0.5*k2) + k4 = h*(*f)(t+h, y+k3) + t = t+h + y = y+(k1+2*k2+2*k3+k4)/6 + a[i, 1] = t + a[i, 2] = y + } + return(a) +} + +function f(t, y) { + return(t*sqrt(y)) +} + +a = rk4(&f(), 0, 1, 10, 101) +t = a[., 1] +a = a, a[., 2]:-(t:^2:+4):^2:/16 +a[range(1,101,10), .] + + 1 2 3 + +----------------------------------------------+ + 1 | 0 1 0 | + 2 | 1 1.562499854 -1.45722e-07 | + 3 | 2 3.999999081 -9.19479e-07 | + 4 | 3 10.56249709 -2.90956e-06 | + 5 | 4 24.99999377 -6.23491e-06 | + 6 | 5 52.56248918 -.0000108197 | + 7 | 6 99.99998341 -.0000165946 | + 8 | 7 175.5624765 -.0000235177 | + 9 | 8 288.9999684 -.0000315652 | + 10 | 9 451.5624593 -.0000407232 | + 11 | 10 675.999949 -.0000509833 | + +----------------------------------------------+ diff --git a/Task/Runtime-evaluation-In-an-environment/Elena/runtime-evaluation-in-an-environment.elena b/Task/Runtime-evaluation-In-an-environment/Elena/runtime-evaluation-in-an-environment.elena new file mode 100644 index 0000000000..912156887d --- /dev/null +++ b/Task/Runtime-evaluation-In-an-environment/Elena/runtime-evaluation-in-an-environment.elena @@ -0,0 +1,9 @@ +import extensions. +import extensions'scripting. + +program = +[ + var program := escript eval("^{ eval(x)[ ^" + 'program'arguments[1] + " ] }"). + + console printLine('program'arguments[1],",",'program'arguments[2]," = ", program eval('program'arguments[2] toReal)). +]. diff --git a/Task/Runtime-evaluation-In-an-environment/Julia/runtime-evaluation-in-an-environment-1.julia b/Task/Runtime-evaluation-In-an-environment/Julia/runtime-evaluation-in-an-environment-1.julia new file mode 100644 index 0000000000..2c0e6c5939 --- /dev/null +++ b/Task/Runtime-evaluation-In-an-environment/Julia/runtime-evaluation-in-an-environment-1.julia @@ -0,0 +1,10 @@ +macro evalwithx(expr, a, b) + return quote + x = $a + tmp = $expr + x = $b + return $expr - tmp + end +end + +@evalwithx(2 ^ x, 3, 5) # raw expression (AST) diff --git a/Task/Runtime-evaluation-In-an-environment/Julia/runtime-evaluation-in-an-environment-2.julia b/Task/Runtime-evaluation-In-an-environment/Julia/runtime-evaluation-in-an-environment-2.julia new file mode 100644 index 0000000000..1e0eeeca5d --- /dev/null +++ b/Task/Runtime-evaluation-In-an-environment/Julia/runtime-evaluation-in-an-environment-2.julia @@ -0,0 +1,9 @@ +function evalwithx(expr::Expr, a, b) + a = eval(quote let x = $a; return $expr end end) + b = eval(quote let x = $b; return $expr end end) + return b - a +end +evalwithx(expr::AbstractString, a, b) = evalwithx(parse(expr), a, b) + +evalwithx(:(2 ^ x), 3, 5) +evalwithx("2 ^ x", 3, 5) diff --git a/Task/Runtime-evaluation-In-an-environment/Scala/runtime-evaluation-in-an-environment.scala b/Task/Runtime-evaluation-In-an-environment/Scala/runtime-evaluation-in-an-environment.scala new file mode 100644 index 0000000000..fefa62fdf0 --- /dev/null +++ b/Task/Runtime-evaluation-In-an-environment/Scala/runtime-evaluation-in-an-environment.scala @@ -0,0 +1,8 @@ +object Eval extends App { + + def evalWithX(expr: String, a: Double, b: Double)= + {val x = b; eval(expr)} - {val x = a; eval(expr)} + + println(evalWithX("Math.exp(x)", 0.0, 1.0)) + +} diff --git a/Task/Runtime-evaluation/Elena/runtime-evaluation.elena b/Task/Runtime-evaluation/Elena/runtime-evaluation.elena new file mode 100644 index 0000000000..37c4e5c69b --- /dev/null +++ b/Task/Runtime-evaluation/Elena/runtime-evaluation.elena @@ -0,0 +1,6 @@ +import extensions'scripting. + +program = +[ + escript eval("system'console writeLine(""Hello World"")."). +]. diff --git a/Task/Runtime-evaluation/Java/runtime-evaluation.java b/Task/Runtime-evaluation/Java/runtime-evaluation.java new file mode 100644 index 0000000000..d500087d1c --- /dev/null +++ b/Task/Runtime-evaluation/Java/runtime-evaluation.java @@ -0,0 +1,86 @@ +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.lang.reflect.InvocationTargetException; +import java.net.URI; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import javax.tools.FileObject; +import javax.tools.ForwardingJavaFileManager; +import javax.tools.JavaCompiler; +import javax.tools.JavaFileObject; +import javax.tools.SimpleJavaFileObject; +import javax.tools.StandardJavaFileManager; +import javax.tools.StandardLocation; +import javax.tools.ToolProvider; + +public class Evaluator{ + public static void main(String[] args){ + new Evaluator().eval( + "SayHello", + "public class SayHello{public void speak(){System.out.println(\"Hello world\");}}", + "speak" + ); + } + + void eval(String className, String classCode, String methodName){ + Map classCache = new HashMap<>(); + JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); + + if ( null == compiler ) + throw new RuntimeException("Could not get a compiler."); + + StandardJavaFileManager sfm = compiler.getStandardFileManager(null, null, null); + ForwardingJavaFileManager fjfm = new ForwardingJavaFileManager(sfm){ + @Override + public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling) + throws IOException{ + if (StandardLocation.CLASS_OUTPUT == location && JavaFileObject.Kind.CLASS == kind) + return new SimpleJavaFileObject(URI.create("mem:///" + className + ".class"), JavaFileObject.Kind.CLASS){ + @Override + public OutputStream openOutputStream() + throws IOException{ + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + classCache.put(className, baos); + return baos; + } + }; + else + throw new IllegalArgumentException("Unexpected output file requested: " + location + ", " + className + ", " + kind); + } + }; + List files = new LinkedList(){{ + add( + new SimpleJavaFileObject(URI.create("string:///" + className + ".java"), JavaFileObject.Kind.SOURCE){ + @Override + public CharSequence getCharContent(boolean ignoreEncodingErrors){ + return classCode; + } + } + ); + }}; + + // Now we can compile! + compiler.getTask(null, fjfm, null, null, null, files).call(); + + try{ + Class clarse = new ClassLoader(){ + @Override + public Class findClass(String name){ + if (! name.startsWith(className)) + throw new IllegalArgumentException("This class loader is for " + className + " - could not handle \"" + name + '"'); + byte[] bytes = classCache.get(name).toByteArray(); + return defineClass(name, bytes, 0, bytes.length); + } + }.loadClass(className); + + // Invoke a method on the thing we compiled + clarse.getMethod(methodName).invoke(clarse.newInstance()); + + }catch(ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException x){ + throw new RuntimeException("Run failed: " + x, x); + } + } +} diff --git a/Task/Runtime-evaluation/Julia/runtime-evaluation-1.julia b/Task/Runtime-evaluation/Julia/runtime-evaluation-1.julia new file mode 100644 index 0000000000..e2727ff2bd --- /dev/null +++ b/Task/Runtime-evaluation/Julia/runtime-evaluation-1.julia @@ -0,0 +1 @@ +include("myfile.jl") diff --git a/Task/Runtime-evaluation/Julia/runtime-evaluation-2.julia b/Task/Runtime-evaluation/Julia/runtime-evaluation-2.julia new file mode 100644 index 0000000000..56ec852455 --- /dev/null +++ b/Task/Runtime-evaluation/Julia/runtime-evaluation-2.julia @@ -0,0 +1,6 @@ +include_string(""" + x = sum([1, 2, 3]) + @show x + """) + +@show typeof(x) # Int64 diff --git a/Task/S-Expressions/Julia/s-expressions.julia b/Task/S-Expressions/Julia/s-expressions.julia new file mode 100644 index 0000000000..866f1b7dd2 --- /dev/null +++ b/Task/S-Expressions/Julia/s-expressions.julia @@ -0,0 +1,74 @@ +function rewritequotedparen(s) + segments = split(s, "\"") + for i in 1:length(segments) + if i & 1 == 0 # even i + ret = replace(segments[i], r"\(", s"_O_PAREN") + segments[i] = replace(ret, r"\)", s"_C_PAREN") + end + end + join(segments, "\"") +end + +function reconsdata(n, s) + if n > 1 + print(" ") + end + if s isa String && ismatch(r"[\$\%\!\$\#]", s) == false + print("\"$s\"") + else + print(s) + end +end + +function printAny(anyarr) + print("(") + for (i, el) in enumerate(anyarr) + if el isa Array + print("(") + for (j, el2) in enumerate(el) + if el2 isa Array + print("(") + for(k, el3) in enumerate(el2) + if el3 isa Array + print(" (") + for(n, el4) in enumerate(el3) + reconsdata(n, el4) + end + print(")") + else + reconsdata(k, el3) + end + end + print(")") + else + reconsdata(j, el2) + end + end + if i == 1 + print(")\n ") + else + print(")") + end + end + end + println(")") +end + +removewhitespace(s) = replace(replace(s, r"\n", " "), r"^\s*(\S.*\S)\s*$", s"\1") +quote3op(s) = replace(s, r"([\$\!\@\#\%]{3})", s"\"\1\"") +paren2bracket(s) = replace(replace(s, r"\(", s"["), r"\)", s"]") +data2symbol(s) = replace(s, "[data", "[:data") +unrewriteparens(s) = replace(replace(s, "_C_PAREN", ")"), "_O_PAREN", "(") +addcommas(s) = replace(replace(s, r"\]\s*\[", "],["), r" (?![a-z])", ",") + +inputstring = """ +((data "quoted data" 123 4.5) + (data (!@# (4.5) "(more" "data)"))) + """ + +println("The input string is:\n", inputstring) +processed = (inputstring |> removewhitespace |> rewritequotedparen |> quote3op + |> paren2bracket |> data2symbol |> unrewriteparens |> addcommas) +nat = eval(parse("""$processed""")) +println("The processed native structure is:\n", nat) +println("The reconstructed string is:\n"), printAny(nat) diff --git a/Task/S-Expressions/Kotlin/s-expressions.kotlin b/Task/S-Expressions/Kotlin/s-expressions.kotlin new file mode 100644 index 0000000000..495a1b24c0 --- /dev/null +++ b/Task/S-Expressions/Kotlin/s-expressions.kotlin @@ -0,0 +1,98 @@ +// version 1.2.31 + +const val INDENT = 2 + +fun String.parseSExpr(): List? { + val r = Regex("""\s*("[^"]*"|\(|\)|"|[^\s()"]+)""") + val t = r.findAll(this).map { it.value }.toMutableList() + if (t.size == 0) return null + var o = false + var c = 0 + for (i in t.size - 1 downTo 0) { + val ti = t[i].trim() + val nd = ti.toDoubleOrNull() + if (ti == "\"") return null + if (ti == "(") { + t[i] = "[" + c++ + } + else if (ti == ")") { + t[i] = "]" + c-- + } + else if (nd != null) { + val ni = ti.toIntOrNull() + if (ni != null) t[i] = ni.toString() + else t[i] = nd.toString() + } + else if (ti.startsWith("\"")) { // escape embedded double quotes + var temp = ti.drop(1).dropLast(1) + t[i] = "\"" + temp.replace("\"", "\\\"") + "\"" + } + if (i > 0 && t[i] != "]" && t[i - 1].trim() != "(") t.add(i, ", ") + if (c == 0) { + if (!o) o = true else return null + } + } + return if (c != 0) null else t +} + +fun MutableList.toSExpr(): String { + for (i in 0 until this.size) { + this[i] = when (this[i]) { + "[" -> "(" + "]" -> ")" + ", " -> " " + else -> { + if (this[i].startsWith("\"")) { // unescape embedded quotes + var temp = this[i].drop(1).dropLast(1) + "\"" + temp.replace("\\\"", "\"") + "\"" + } + else this[i] + } + } + } + return this.joinToString("") +} + +fun List.prettyPrint() { + var level = 0 + loop@for (t in this) { + var n: Int + when(t) { + ", ", " " -> continue@loop + "[", "(" -> { + n = level * INDENT + 1 + level++ + } + "]", ")" -> { + level-- + n = level * INDENT + 1 + } + else -> { + n = level * INDENT + t.length + } + } + println("%${n}s".format(t)) + } +} + +fun main(args: Array) { + val str = """((data "quoted data" 123 4.5)""" + "\n" + + """ (data (!@# (4.5) "(more" "data)")))""" + val tokens = str.parseSExpr() + if (tokens == null) + println("Invalid s-expr!") + else { + println("Native data structure:") + println(tokens.joinToString("")) + println("\nNative data structure (pretty print):") + tokens.prettyPrint() + + val tokens2 = tokens.toMutableList() + println("\nRecovered S-Expression:") + println(tokens2.toSExpr()) + println("\nRecovered S-Expression (pretty print):") + tokens2.prettyPrint() + } +} diff --git a/Task/SEDOLs/C++/sedols.cpp b/Task/SEDOLs/C++/sedols.cpp index 3c2cf949a9..09f435a1a7 100644 --- a/Task/SEDOLs/C++/sedols.cpp +++ b/Task/SEDOLs/C++/sedols.cpp @@ -1,52 +1,43 @@ #include -#include #include #include -#include -#include -#include +#include -using namespace std; -const int weights[] = {1,3,1,7,3,9}; -const string valid_chars = "BCDFGHJKLMNPQRSTVWXYZ0123456789"; - -int char_value(char c){ return isalpha(c) ? c -'A' + 10 : c - '0'; } - -int sedol_checksum(string const& sedol) +template +auto sedol_checksum(std::string const& sedol, result_sink_t result_sink) { - //Check contents if(sedol.size() != 6) - throw length_error("length of sedol string != 6"); - if(sedol.find_first_not_of(valid_chars) != std::string::npos) - throw invalid_argument("sedol string contains disallowed characters"); + return result_sink(0, "length of sedol string != 6"); - vector char_values; - transform(sedol.begin(), sedol.end(), back_inserter(char_values), char_value); - const int weighted_sum = inner_product(char_values.begin(), char_values.end(), weights, 0); - return (10 - (weighted_sum % 10)) % 10; + const char * valid_chars = "BCDFGHJKLMNPQRSTVWXYZ0123456789"; + if(sedol.find_first_not_of(valid_chars) != std::string::npos) + return result_sink(0, "sedol string contains disallowed characters"); + + const int weights[] = {1,3,1,7,3,9}; + auto weighted_sum = std::inner_product(sedol.begin(), sedol.end(), weights, 0 + , [](int acc, int prod){ return acc + prod; } + , [](char c, int weight){ return (std::isalpha(c) ? c -'A' + 10 : c - '0') * weight; } + ); + return result_sink((10 - (weighted_sum % 10)) % 10, nullptr); } int main() { + using namespace std; string inputs[] = { - "710889", - "B0YBKJ", - "406566", - "B0YBLH", - "228276", - "B0YBKL", - "557910", - "B0YBKR", - "585284", - "B0YBKT", - "B00030" + "710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", + "557910", "B0YBKR", "585284", "B0YBKT", "B00030" }; - const size_t n_inputs = sizeof(inputs) / sizeof(*inputs); - - for(size_t i = 0; i != n_inputs; ++i) + for(auto const & sedol : inputs) { - cout << inputs[i] << sedol_checksum(inputs[i]) << "\n"; + sedol_checksum(sedol, [&](auto sum, char const * errorMessage) + { + if(errorMessage) + cout << "error for sedol: " << sedol << " message: " << errorMessage << "\n"; + else + cout << sedol << sum << "\n"; + }); } return 0; } diff --git a/Task/SEDOLs/Gambas/sedols.gambas b/Task/SEDOLs/Gambas/sedols.gambas new file mode 100644 index 0000000000..a931633f77 --- /dev/null +++ b/Task/SEDOLs/Gambas/sedols.gambas @@ -0,0 +1,29 @@ +Public Sub Main() +Dim byWeight As Byte[] = [1, 3, 1, 7, 3, 9, 1] +Dim byCount, byCompute As Byte +Dim siTotal As Short +Dim sWork As New String[] +Dim sToProcess As String[] = ["710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", + "557910", "B0YBKR", "585284", "B0YBKT", "B00030"] + +For byCompute = 0 To sToProcess.Max + For byCount = 1 To 6 + If IsLetter(Mid(sToProcess[byCompute], byCount, 1)) Then + sWork.Add(Str(Asc(Mid(sToProcess[byCompute], byCount, 1)) - 55) * byWeight[byCount - 1]) + Else + sWork.Add(Val(Mid(sToProcess[byCompute], byCount, 1)) * byWeight[byCount - 1]) + End If + Next + + For byCount = 0 To 5 + siTotal += Val(sWork[byCount]) + Next + + siTotal = (10 - (siTotal Mod 10)) Mod 10 + + Print sToProcess[byCompute] & " = " & sToProcess[byCompute] & siTotal + sWork.Clear() + siTotal = 0 +Next + +End diff --git a/Task/SEDOLs/Julia/sedols.julia b/Task/SEDOLs/Julia/sedols.julia new file mode 100644 index 0000000000..57ebe59d57 --- /dev/null +++ b/Task/SEDOLs/Julia/sedols.julia @@ -0,0 +1,21 @@ +using Base.Test + +function appendchecksum(chars::AbstractString) + if !all(isalnum, chars) throw(ArgumentError("invalid SEDOL number '$chars'")) end + weights = [1, 3, 1, 7, 3, 9, 1] + + s = 0 + for (w, c) in zip(weights, chars) + s += w * parse(Int, c, 36) + end + return string(chars, (10 - s % 10) % 10) +end + +tests = ["710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL", "557910", "B0YBKR", "585284", "B0YBKT", "B00030"] +csums = ["7108899", "B0YBKJ7", "4065663", "B0YBLH2", "2282765", "B0YBKL9", "5579107", "B0YBKR5", "5852842", "B0YBKT7", "B000300"] + +@testset "Checksums" begin + for (t, c) in zip(tests, csums) + @test appendchecksum(t) == c + end +end diff --git a/Task/SHA-1/Astro/sha-1.astro b/Task/SHA-1/Astro/sha-1.astro index 2cc9f5fc34..ec35138ad1 100644 --- a/Task/SHA-1/Astro/sha-1.astro +++ b/Task/SHA-1/Astro/sha-1.astro @@ -1,2 +1,3 @@ -import crypto -let hash = sha1 bytes('Ars longa, vita brevis', encoding:'ascii') +import crypto { sha1 } +let hash = sha1.hexdigest('Ars longa, vita brevis') +print hash diff --git a/Task/SHA-1/J/sha-1-2.j b/Task/SHA-1/J/sha-1-2.j index 1e843a5d7d..d4a2c90e04 100644 --- a/Task/SHA-1/J/sha-1-2.j +++ b/Task/SHA-1/J/sha-1-2.j @@ -1,36 +1,3 @@ -pad=: ,1,(0#~512 | [: - 65 + #),(64#2)#:# - -f=:4 :0 - 'B C D'=: _32 ]\ y - if. x < 20 do. - (B*C)+.D>B - elseif. x < 40 do. - B~:C~:D - elseif. x < 60 do. - (B*C)+.(B*D)+.C*D - elseif. x < 80 do. - B~:C~:D - end. -) - -K=: ((32#2) #: 16b5a827999 16b6ed9eba1 16b8f1bbcdc 16bca62c1d6) {~ <.@%&20 - -plus=:+&.((32#2)&#.) - -H=: #: 16b67452301 16befcdab89 16b98badcfe 16b10325476 16bc3d2e1f0 - -process=:4 :0 - W=. (, [: , 1 |."#. _3 _8 _14 _16 ~:/@:{ ])^:64 x ]\~ _32 - 'A B C D E'=. y=._32[\,y - for_t. i.80 do. - TEMP=. (5|.A) plus (t f B,C,D) plus E plus (W{~t) plus K t - E=. D - D=. C - C=. 30 |. B - B=. A - A=. TEMP - end. - ,y plus A,B,C,D,:E -) - -sha1=: [:> [: process&.>/ (B + elseif. x < 40 do. + B~:C~:D + elseif. x < 60 do. + (B*C)+.(B*D)+.C*D + elseif. x < 80 do. + B~:C~:D + end. +) + +K=: ((32#2) #: 16b5a827999 16b6ed9eba1 16b8f1bbcdc 16bca62c1d6) {~ <.@%&20 + +plus=:+&.((32#2)&#.) + +H=: #: 16b67452301 16befcdab89 16b98badcfe 16b10325476 16bc3d2e1f0 + +process=:4 :0 + W=. (, [: , 1 |."#. _3 _8 _14 _16 ~:/@:{ ])^:64 x ]\~ _32 + 'A B C D E'=. y=._32[\,y + for_t. i.80 do. + TEMP=. (5|.A) plus (t f B,C,D) plus E plus (W{~t) plus K t + E=. D + D=. C + C=. 30 |. B + B=. A + A=. TEMP + end. + ,y plus A,B,C,D,:E +) + +sha1=: [:> [: process&.>/ ( "a9993e364706816aba3e25717850c26c9cd0d89d", + "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" => + "84983e441c3bd26ebaae4aa1f95129e5e54670f1", + "a" ^ 1_000_000 => "34aa973cd4c4daa4f61eeb2bdbad27316534016f",) + +for (text, expect) in testdict + digest = hexdigest("sha1", text) + if length(text) > 50 text = text[1:50] * "..." end + println("# $text\n -> digest: $digest\n -> expect: $expect") end - -println("Testing SHA-1 function against FIPS 180-1") - -s = sha1sum("abc") -t = lowercase("A9993E364706816ABA3E25717850C26C9CD0D89D") -print(" \"abc\" should yield ", t) -if s == t - println(", and it does.") -else - println(", but it yields ", s) -end - -s = sha1sum("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") -t = lowercase("84983E441C3BD26EBAAE4AA1F95129E5E54670F1") -print(" \"abcdbc...\" should yield ", t) -if s == t - println(", and it does.") -else - println(", but it yields ", s) -end - -s = sha1sum("a"^10^6) -t = lowercase("34AA973CD4C4DAA4F61EEB2BDBAD27316534016F") -print(" a million \"a\"s should yield ", t) -if s == t - println(", and it does.") -else - println(", but it yields ", s) -end - -println("\nAlso") -s = "Rosetta Code" -h = sha1sum(s) -println(" ", s, " => ", h) diff --git a/Task/SHA-1/Lingo/sha-1.lingo b/Task/SHA-1/Lingo/sha-1.lingo new file mode 100644 index 0000000000..51430188fe --- /dev/null +++ b/Task/SHA-1/Lingo/sha-1.lingo @@ -0,0 +1,2 @@ +crypto = xtra("Crypto").new() +put crypto.cx_sha1_string("Rosetta Code") diff --git a/Task/SHA-1/Ring/sha-1.ring b/Task/SHA-1/Ring/sha-1.ring new file mode 100644 index 0000000000..ee4798b6fd --- /dev/null +++ b/Task/SHA-1/Ring/sha-1.ring @@ -0,0 +1,10 @@ +# Project : SHA-1 +# Date : 2018/05/18 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : + +load "stdlib.ring" +str = "Rosetta Code" +see "String: " + str + nl +see "SHA-1: " +see sha1(str) + nl diff --git a/Task/SHA-256/J/sha-256-3.j b/Task/SHA-256/J/sha-256-3.j new file mode 100644 index 0000000000..5ce9565eda --- /dev/null +++ b/Task/SHA-256/J/sha-256-3.j @@ -0,0 +1 @@ +sha256=: 3&(128!:6) diff --git a/Task/SHA-256/J/sha-256-4.j b/Task/SHA-256/J/sha-256-4.j new file mode 100644 index 0000000000..43be63bb8e --- /dev/null +++ b/Task/SHA-256/J/sha-256-4.j @@ -0,0 +1,2 @@ + sha256 'Rosetta code' +764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf diff --git a/Task/SHA-256/Julia/sha-256.julia b/Task/SHA-256/Julia/sha-256.julia index 6469cb01b8..05346dc08f 100644 --- a/Task/SHA-256/Julia/sha-256.julia +++ b/Task/SHA-256/Julia/sha-256.julia @@ -1,13 +1,10 @@ -clear = "Rosetta code" -standard = "764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf" +msg = "Rosetta code" +using Nettle +digest = hexdigest("sha256", msg) + +# native using SHA +digest1 = join(num2hex.(sha256(msg))) -crypt = join(map(hex, sha256("Rosetta code"))) - -println("Testing Julia's SHA-256:") -if crypt == standard - println(" OK, \"", clear, "\" => ", crypt) -else - println("The hash does not match the standard value.") -end +@assert digest == digest1 diff --git a/Task/SHA-256/Ring/sha-256.ring b/Task/SHA-256/Ring/sha-256.ring new file mode 100644 index 0000000000..08ab2d661a --- /dev/null +++ b/Task/SHA-256/Ring/sha-256.ring @@ -0,0 +1,10 @@ +# Project: SHA-256 +# Date : 2018/06/09 +# Author: Gal Zsolt [~ CalmoSoft ~] +# Email : + +load "stdlib.ring" +str = "Rosetta code" +see "String: " + str + nl +see "SHA-256: " +see sha256(str) + nl diff --git a/Task/SHA-256/Rust/sha-256.rust b/Task/SHA-256/Rust/sha-256.rust index b19da64b3a..ed51a4faf3 100644 --- a/Task/SHA-256/Rust/sha-256.rust +++ b/Task/SHA-256/Rust/sha-256.rust @@ -1,10 +1,12 @@ -extern crate crypto; +extern crate ring; -use crypto::sha2::Sha256; -use crypto::digest::Digest; +use ring::digest::{digest, SHA256}; fn main() { - let mut digest = Sha256::new(); - digest.input_str("Rosetta code"); - assert!(digest.result_str() == "764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf".into()); + println!("{}", sha_256("Rosetta code")); +} + +fn sha_256(input: &str) -> String { + let result = digest(&SHA256, input.as_bytes()); + result.as_ref().iter().map(|b| format!("{:x}", b)).collect() } diff --git a/Task/SOAP/C/soap-1.c b/Task/SOAP/C/soap-1.c new file mode 100644 index 0000000000..9b162e04c5 --- /dev/null +++ b/Task/SOAP/C/soap-1.c @@ -0,0 +1,56 @@ +/*Abhishek Ghosh, 26th October 2017*/ + +#include +#include +#include + +size_t write_data(void *ptr, size_t size, size_t nmeb, void *stream){ + return fwrite(ptr,size,nmeb,stream); +} + +size_t read_data(void *ptr, size_t size, size_t nmeb, void *stream){ + return fread(ptr,size,nmeb,stream); +} + +void callSOAP(char* URL, char * inFile, char * outFile) { + + FILE * rfp = fopen(inFile, "r"); + if(!rfp) + perror("Read File Open:"); + + FILE * wfp = fopen(outFile, "w+"); + if(!wfp) + perror("Write File Open:"); + + struct curl_slist *header = NULL; + header = curl_slist_append (header, "Content-Type:text/xml"); + header = curl_slist_append (header, "SOAPAction: rsc"); + header = curl_slist_append (header, "Transfer-Encoding: chunked"); + header = curl_slist_append (header, "Expect:"); + CURL *curl; + + curl = curl_easy_init(); + if(curl) { + curl_easy_setopt(curl, CURLOPT_URL, URL); + curl_easy_setopt(curl, CURLOPT_POST, 1L); + curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_data); + curl_easy_setopt(curl, CURLOPT_READDATA, rfp); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, wfp); + curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header); + curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)-1); + curl_easy_setopt(curl, CURLOPT_VERBOSE,1L); + curl_easy_perform(curl); + + curl_easy_cleanup(curl); + } +} + +int main(int argC,char* argV[]) +{ + if(argC!=4) + printf("Usage : %s ",argV[0]); + else + callSOAP(argV[1],argV[2],argV[3]); + return 0; +} diff --git a/Task/SOAP/C/soap-2.c b/Task/SOAP/C/soap-2.c new file mode 100644 index 0000000000..91ad2a3f63 --- /dev/null +++ b/Task/SOAP/C/soap-2.c @@ -0,0 +1,10 @@ + + + + + + + diff --git a/Task/SOAP/C/soap-3.c b/Task/SOAP/C/soap-3.c new file mode 100644 index 0000000000..faeb76d62a --- /dev/null +++ b/Task/SOAP/C/soap-3.c @@ -0,0 +1,10 @@ + + + + + + + diff --git a/Task/SOAP/Clojure/soap.clj b/Task/SOAP/Clojure/soap.clj new file mode 100644 index 0000000000..c2a4e5a076 --- /dev/null +++ b/Task/SOAP/Clojure/soap.clj @@ -0,0 +1,5 @@ +(require '[clj-soap.core :as soap]) + +(let [client (soap/client-fn "http://example.com/soap/wsdl")] + (client :soapFunc) + (client :anotherSoapFunc)) diff --git a/Task/SOAP/Kotlin/soap.kotlin b/Task/SOAP/Kotlin/soap.kotlin new file mode 100644 index 0000000000..5b20357083 --- /dev/null +++ b/Task/SOAP/Kotlin/soap.kotlin @@ -0,0 +1,59 @@ +// Kotlin Native v0.6 + +import kotlinx.cinterop.* +import platform.posix.* +import libcurl.* + +fun writeData(ptr: COpaquePointer?, size: size_t, nmeb: size_t, stream: COpaquePointer?) + = fwrite(ptr, size, nmeb, stream?.reinterpret()) + +fun readData(ptr: COpaquePointer?, size: size_t, nmeb: size_t, stream: COpaquePointer?) + = fread(ptr, size, nmeb, stream?.reinterpret()) + +fun callSOAP(url: String, inFile: String, outFile: String) { + val rfp = fopen(inFile, "r") + if (rfp == null) { + perror("Read File Open: ") + exit(1) + } + val wfp = fopen(outFile, "w+") + if (wfp == null) { + perror("Write File Open: ") + fclose(rfp) + exit(1) + } + + var header: CPointer? = null + header = curl_slist_append (header, "Content-Type:text/xml") + header = curl_slist_append (header, "SOAPAction: rsc") + header = curl_slist_append (header, "Transfer-Encoding: chunked") + header = curl_slist_append (header, "Expect:") + + val curl = curl_easy_init() + if (curl != null) { + curl_easy_setopt(curl, CURLOPT_URL, url) + curl_easy_setopt(curl, CURLOPT_POST, 1L) + curl_easy_setopt(curl, CURLOPT_READFUNCTION, staticCFunction(::readData)) + curl_easy_setopt(curl, CURLOPT_READDATA, rfp) + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, staticCFunction(::writeData)) + curl_easy_setopt(curl, CURLOPT_WRITEDATA, wfp) + curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header) + curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, -1L) + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L) + curl_easy_perform(curl) + curl_easy_cleanup(curl) + } + + curl_slist_free_all(header) + fclose(rfp) + fclose(wfp) +} + +fun main(args: Array) { + if (args.size != 3) { + println("You need to pass exactly 3 command line arguments, namely :-") + println(" ") + return + } + callSOAP(args[0], args[1], args[2]) +} diff --git a/Task/SQL-based-authentication/Julia/sql-based-authentication.julia b/Task/SQL-based-authentication/Julia/sql-based-authentication.julia new file mode 100644 index 0000000000..d66bae4d82 --- /dev/null +++ b/Task/SQL-based-authentication/Julia/sql-based-authentication.julia @@ -0,0 +1,48 @@ +using MySQL +using Nettle # for md5 + +function connect_db(uri, user, pw, dbname) + mydb = mysql_connect(uri, user, pw, dbname) + + const command = """CREATE TABLE IF NOT EXISTS users ( + userid INT PRIMARY KEY AUTO_INCREMENT, + username VARCHAR(32) UNIQUE KEY NOT NULL, + pass_salt tinyblob NOT NULL, + -- a string of 16 random bytes + pass_md5 tinyblob NOT NULL + -- binary MD5 hash of pass_salt concatenated with the password + );""" + mysql_execute(mydb, command) + mydb +end + +function create_user(dbh, user, pw) + mysql_stmt_prepare(dbh, "INSERT IGNORE INTO users (username, pass_salt, pass_md5) values (?, ?, ?);") + salt = join([Char(c) for c in rand(UInt8, 16)], "") + passmd5 = digest("md5", salt * user) + mysql_execute(dbh, [MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR, MYSQL_TYPE_VARCHAR], [user, salt, passmd5]) +end + +function addusers(dbh, userdict) + for user in keys(userdict) + create_user(dbh, user, userdict[user]) + end +end + +""" + authenticate_user +Note this returns true if password provided authenticates as correct, false otherwise +""" +function authenticate_user(dbh, username, pw) + mysql_stmt_prepare(dbh, "SELECT pass_salt, pass_md5 FROM users WHERE username = ?;") + pass_salt, pass_md5 = mysql_execute(dbh, [MYSQL_TYPE_VARCHAR], [username], opformat=MYSQL_TUPLES)[1] + pass_md5 == digest("md5", pass_salt * username) +end + +const users = Dict("Joan" => "joanspw", "John" => "johnspw", "Mary" => "marpw", "Mark" => "markpw") +const mydb = connect_db("192.168.1.1", "julia", "julia", "mydb") + +addusers(mydb, users) +println("""John authenticates correctly: $(authenticate_user(mydb, "John", "johnspw")==false)""") +println("""Mary does not authenticate with password of 123: $(authenticate_user(mydb, "Mary", "123")==false)""") +mysql_disconnect(mydb) diff --git a/Task/SQL-based-authentication/Kotlin/sql-based-authentication.kotlin b/Task/SQL-based-authentication/Kotlin/sql-based-authentication.kotlin new file mode 100644 index 0000000000..beca6ea880 --- /dev/null +++ b/Task/SQL-based-authentication/Kotlin/sql-based-authentication.kotlin @@ -0,0 +1,101 @@ +// Version 1.2.41 + +import java.sql.Connection +import java.sql.DriverManager +import java.sql.ResultSet +import java.security.MessageDigest +import java.security.SecureRandom +import java.math.BigInteger + +class UserManager { + private lateinit var dbConnection: Connection + + private fun md5(message: String): String { + val hexString = StringBuilder() + val bytes = message.toByteArray() + val md = MessageDigest.getInstance("MD5") + val dig = md.digest(bytes) + for (i in 0 until dig.size) { + val hex = (0xff and dig[i].toInt()).toString(16) + if (hex.length == 1) hexString.append('0') + hexString.append(hex) + } + return hexString.toString() + } + + fun connectDB(host: String, port: Int, db: String, user: String, pwd: String) { + Class.forName("com.mysql.jdbc.Driver") + dbConnection = DriverManager.getConnection( + "jdbc:mysql://$host:$port/$db", user, pwd + ) + } + + fun createUser(user: String, pwd: String): Boolean { + val random = SecureRandom() + val salt = BigInteger(130, random).toString(16) + val insert = "INSERT INTO users " + + "(username, pass_salt, pass_md5) " + + "VALUES (?, ?, ?)" + try { + val pstmt = dbConnection.prepareStatement(insert) + with (pstmt) { + setString(1, user) + setString(2, salt) + setString(3, md5(salt + pwd)) + val rowCount = executeUpdate() + close() + if (rowCount == 0) return false + } + return true + } + catch (ex: Exception) { + return false + } + } + + fun authenticateUser(user: String, pwd: String): Boolean { + val select = "SELECT pass_salt, pass_md5 FROM users WHERE username = ?" + lateinit var res: ResultSet + try { + val pstmt = dbConnection.prepareStatement(select) + with (pstmt) { + setString(1, user) + res = executeQuery() + res.next() // assuming that username is unique + val passSalt = res.getString(1) + val passMD5 = res.getString(2) + close() + return passMD5 == md5(passSalt + pwd) + } + } + catch (ex: Exception) { + return false + } + finally { + if (!res.isClosed) res.close() + } + } + + fun closeConnection() { + if (!dbConnection.isClosed) dbConnection.close() + } +} + +fun main(args: Array) { + val um = UserManager() + with (um) { + try { + connectDB("localhost", 3306, "test", "root", "admin") + if (createUser("johndoe", "test")) println("User created") + if (authenticateUser("johndoe", "test")) { + println("User authenticated") + } + } + catch(ex: Exception) { + ex.printStackTrace() + } + finally { + closeConnection() + } + } +} diff --git a/Task/Safe-addition/D/safe-addition.d b/Task/Safe-addition/D/safe-addition.d new file mode 100644 index 0000000000..ee98b57eb0 --- /dev/null +++ b/Task/Safe-addition/D/safe-addition.d @@ -0,0 +1,16 @@ +import std.traits; +auto safeAdd(T)(T a, T b) +if (isFloatingPoint!T) { + import std.math; // nexDown, nextUp + import std.typecons; // tuple + return tuple!("d", "u")(nextDown(a+b), nextUp(a+b)); +} + +import std.stdio; +void main() { + auto a = 1.2; + auto b = 0.03; + + auto r = safeAdd(a, b); + writefln("(%s + %s) is in the range %0.16f .. %0.16f", a, b, r.d, r.u); +} diff --git a/Task/Safe-addition/Java/safe-addition.java b/Task/Safe-addition/Java/safe-addition.java new file mode 100644 index 0000000000..4925ccb6e7 --- /dev/null +++ b/Task/Safe-addition/Java/safe-addition.java @@ -0,0 +1,20 @@ +public class SafeAddition { + private static double stepDown(double d) { + return Math.nextAfter(d, Double.NEGATIVE_INFINITY); + } + + private static double stepUp(double d) { + return Math.nextUp(d); + } + + private static double[] safeAdd(double a, double b) { + return new double[]{stepDown(a + b), stepUp(a + b)}; + } + + public static void main(String[] args) { + double a = 1.2; + double b = 0.03; + double[] result = safeAdd(a, b); + System.out.printf("(%.2f + %.2f) is in the range %.16f..%.16f", a, b, result[0], result[1]); + } +} diff --git a/Task/Safe-addition/Julia/safe-addition.julia b/Task/Safe-addition/Julia/safe-addition.julia new file mode 100644 index 0000000000..272821f956 --- /dev/null +++ b/Task/Safe-addition/Julia/safe-addition.julia @@ -0,0 +1,19 @@ +julia> using IntervalArithmetic + +julia> n = 2.0 +2.0 + +julia> @interval 2n/3 + 1 +[2.33333, 2.33334] + +julia> showall(ans) +Interval(2.333333333333333, 2.3333333333333335) + +julia> a = @interval(0.1, 0.3) +[0.0999999, 0.300001] + +julia> b = @interval(0.3, 0.6) +[0.299999, 0.600001] + +julia> a + b +[0.399999, 0.900001] diff --git a/Task/Safe-addition/Scala/safe-addition.scala b/Task/Safe-addition/Scala/safe-addition.scala new file mode 100644 index 0000000000..21ee314459 --- /dev/null +++ b/Task/Safe-addition/Scala/safe-addition.scala @@ -0,0 +1,13 @@ +object SafeAddition extends App { + val (a, b) = (1.2, 0.03) + val result = safeAdd(a, b) + + private def safeAdd(a: Double, b: Double) = Seq(stepDown(a + b), stepUp(a + b)) + + private def stepDown(d: Double) = Math.nextAfter(d, Double.NegativeInfinity) + + private def stepUp(d: Double) = Math.nextUp(d) + + println(f"($a%.2f + $b%.2f) is in the range ${result.head}%.16f .. ${result.last}%.16f") + +} diff --git a/Task/Same-Fringe/Julia/same-fringe.julia b/Task/Same-Fringe/Julia/same-fringe.julia new file mode 100644 index 0000000000..336bef2412 --- /dev/null +++ b/Task/Same-Fringe/Julia/same-fringe.julia @@ -0,0 +1,50 @@ +using Lazy + +""" + Input a tree for display as a fringed structure. +""" +function fringe(tree) + fringey(node::Pair) = [fringey(i) for i in node] + fringey(leaf::Int) = leaf + fringey(tree) +end + + +""" + equalsfringe() uses a reduction to a lazy 1D list via + getleaflist() for its "equality" of fringes +""" +getleaflist(tree::Int) = [tree] +getleaflist(tree::Pair) = vcat(getleaflist(seq(tree[1])), getleaflist(seq(tree[2]))) +getleaflist(tree::Lazy.LazyList) = vcat(getleaflist(tree[1]), getleaflist(tree[2])) +getleaflist(tree::Void) = [] +equalsfringe(t1, t2) = (getleaflist(t1) == getleaflist(t2)) + + +a = 1 => 2 => 3 => 4 => 5 => 6 => 7 => 8 +b = 1 => (( 2 => 3 ) => (4 => (5 => ((6 => 7) => 8)))) +c = (((1 => 2) => 3) => 4) => 5 => 6 => 7 => 8 + +x = 1 => 2 => 3 => 4 => 5 => 6 => 7 => 8 => 9 +y = 0 => 2 => 3 => 4 => 5 => 6 => 7 => 8 +z = 1 => 2 => (4 => 3) => 5 => 6 => 7 => 8 + +prettyprint(s) = println(replace("$s", r"\{Any,1\}|Any|Array\{T,1\}\swhere\sT|Array|", "")) +prettyprint(fringe(a)) +prettyprint(fringe(b)) +prettyprint(fringe(c)) +prettyprint(fringe(x)) +prettyprint(fringe(y)) +prettyprint(fringe(z)) + +prettyprint(getleaflist(a)) +prettyprint(getleaflist(b)) +prettyprint(getleaflist(c)) + +println(equalsfringe(a, a)) +println(equalsfringe(a, b)) +println(equalsfringe(a, c)) +println(equalsfringe(b, c)) +println(equalsfringe(a, x) == false) +println(equalsfringe(a, y) == false) +println(equalsfringe(a, z) == false) diff --git a/Task/Same-Fringe/Perl-6/same-fringe.pl6 b/Task/Same-Fringe/Perl-6/same-fringe.pl6 new file mode 100644 index 0000000000..3e1ad4fdef --- /dev/null +++ b/Task/Same-Fringe/Perl-6/same-fringe.pl6 @@ -0,0 +1,26 @@ +sub fringe ($tree) { + multi sub fringey (Pair $node) { fringey $_ for $node.kv; } + multi sub fringey ( Any $leaf) { take $leaf; } + + gather fringey $tree; +} + +sub samefringe ($a, $b) { fringe($a) eqv fringe($b) } + +# Testing: + +my $a = 1 => 2 => 3 => 4 => 5 => 6 => 7 => 8; +my $b = 1 => (( 2 => 3 ) => (4 => (5 => ((6 => 7) => 8)))); +my $c = (((1 => 2) => 3) => 4) => 5 => 6 => 7 => 8; + +my $x = 1 => 2 => 3 => 4 => 5 => 6 => 7 => 8 => 9; +my $y = 0 => 2 => 3 => 4 => 5 => 6 => 7 => 8; +my $z = 1 => 2 => (4 => 3) => 5 => 6 => 7 => 8; + +say so samefringe $a, $a; +say so samefringe $a, $b; +say so samefringe $a, $c; + +say not samefringe $a, $x; +say not samefringe $a, $y; +say not samefringe $a, $z; diff --git a/Task/Same-Fringe/REXX/same-fringe-3.rexx b/Task/Same-Fringe/REXX/same-fringe-3.rexx index 87b643f505..952290ddfe 100644 --- a/Task/Same-Fringe/REXX/same-fringe-3.rexx +++ b/Task/Same-Fringe/REXX/same-fringe-3.rexx @@ -1,81 +1,73 @@ -/*REXX program examines the leaves of two binary trees (as shown below).*/ -_=left('',28); say _ " A A " - say _ " / \ ◄════1st tree / \ " - say _ " / \ / \ " - say _ " / \ / \ " - say _ " B C B C " - say _ " / \ / 2nd tree════► / \ / " - say _ " D E F D E F " - say _ " / / \ / / \ " - say _ "G H I G δ I " +/*REXX pgm examines the leaves of 2 binary trees (as shown below), and finds inequities.*/ +_=left('', 28); say _ " A A " + say _ " / \ ◄════1st tree / \ " + say _ " / \ / \ " + say _ " / \ / \ " + say _ " B C B C " + say _ " / \ / 2nd tree════► / \ / " + say _ " D E F D E F " + say _ " / / \ / / \ " + say _ "G H I G δ I " say -#=0; done.=0; node.=0 /*initialize # leaves,DONE.,NODE.*/ -call make_tree 1 /*define tree number 1 (1st tree)*/ -call make_tree 2 /* " " " 2 (2nd " )*/ -z1=root.1; L1=node.1.z1; done.1.z1=1 /*L1 is a leaf on tree number 1. */ -z2=z1; L2=node.2.z2; done.2.z2=1 /*L2 " " " " " " 2. */ +#=0; done.=0; @.=0 /*initialize: #, leaves, DONE., nodes*/ +call make_tree 1 /*define tree number 1 (the 1st tree).*/ +call make_tree 2 /* " " " 2 (the 2nd " ).*/ +z1=root.1; L1=@.1.z1; done.1.z1=1 /*L1: is a leaf on tree number 1. */ +z2=z1; L2=@.2.z2; done.2.z2=1 /*L2: " " " " " " 2. */ - do # % 2 /*loop for the number of leaves. */ + do # % 2 /*loop for the number of (tree) leaves.*/ if L1==L2 then do if L1==0 then call sayX 'The trees are equal.' - say ' The ' L1 " leaf is identical in both trees." - do until \done.1.z1 - z1=go_next(z1,1); L1=node.1.z1 - end + say ' The ' L1 " leaf is identical in both trees." + do until \done.1.z1; z1=go_next(z1, 1); L1=@.1.z1; end done.1.z1=1 - do until \done.2.z2 - z2=go_next(z2,2); L2=node.2.z2 - end + do until \done.2.z2; z2=go_next(z2, 2); L2=@.2.z2; end done.2.z2=1 end else select - when L1==0 then call sayX L2 'exceeds leaves in 1st tree' - when L2==0 then call sayX L1 'exceeds leaves in 2nd tree' - otherwise call sayX 'A difference is: ' L1 '¬=' L2 + when L1==0 then call sayX L2 'exceeds leaves in 1st tree' + when L2==0 then call sayX L1 'exceeds leaves in 2nd tree' + otherwise call sayX 'A difference is: ' L1 '¬=' L2 end /*select*/ end /*# % 2*/ exit -/*──────────────────────────────────GO_NEXT subroutine──────────────────*/ -go_next: procedure expose node.; arg q,t /*find next node.*/ -next=. -if node.t.q._Lson\==0 &, /*is there a left branch in tree?*/ - node.t.q._Lson.vis==0 then do /*has this node been visited yet?*/ - next=node.t.q._Lson /*──► next node. */ - node.t.q._Lson.vis=1 /*leftside done. */ - end -if next==. &, - node.t.q._Rson\==0 &, /*is there a right tree branch ? */ - node.t.q._Rson.vis==0 then do /*has this node been VISited yet?*/ - next=node.t.q._Rson /*──► next node. */ - node.t.q._Rson.vis=1 /*rightside done.*/ - end -if next==. then next=node.t.q._dad /*process the father node. */ -return next /*the next node (or 0, if done).*/ -/*──────────────────────────────────MAKE_NODE subroutine────────────────*/ -make_node: parse arg name,t; # = #+1 /*make a new node/branch on tree.*/ -q = node.t.0 + 1 ; node.t.q = name ; node.t.q._dad = 0 -node.t.q._Lson = 0 ; node.t.q._Rson = 0 ; node.t.0 = q -return q /*number of the node just created*/ -/*──────────────────────────────────MAKE_TREE subroutine────────────────*/ -make_tree: procedure expose node. root. #; parse arg tree /*build trees*/ -if tree==1 then hhh='H' /* [↓] must be a wood duck*/ - else hhh='δ' /*the odd duck in the whole tree.*/ - a=make_node('A', tree); root.tree=a - b=make_node('B', tree); call son 'L', b,a,tree - c=make_node('C', tree); call son 'R', c,a,tree - d=make_node('D', tree); call son 'L', d,b,tree - e=make_node('E', tree); call son 'R', e,b,tree - f=make_node('F', tree); call son 'L', f,c,tree - g=make_node('G', tree); call son 'L', g,d,tree -/*quacks like a duck?*/ h=make_node(hhh, tree); call son 'L', h,f,tree - i=make_node('I', tree); call son 'R', i,f,tree -return -/*──────────────────────────────────SAYX subroutine─────────────────────*/ -sayX: say; say arg(1); say; exit /*tell msg and exit.*/ -/*──────────────────────────────────SON subroutine──────────────────────*/ -son: procedure expose node.; parse arg ?,son,dad,t; LR = '_'?"SON" -node.t.son._dad=dad; q=node.t.dad.LR /*define which son [↑] */ -if q\==0 then do; node.t.q._dad=son; node.t.son.LR=q; end -node.t.dad.LR=son -if ?=='R' & node.t.dad.LR>0 then node.t.le._brother=node.t.dad.LR -return +/*──────────────────────────────────────────────────────────────────────────────────────*/ +go_next: procedure expose @.; arg q,t; next=. /*find next node in the tree. */ + if @.t.q._Lson\==0 &, /*there a left branch in tree?*/ + @.t.q._Lson.vis==0 then do /*has this node been visited? */ + next= @.t.q._Lson /*point to the ──► next node.*/ + @.t.q._Lson.vis= 1 /*the leftside is completed. */ + end + if next==. &, + @.t.q._Rson\==0 &, /*there a right tree branch ? */ + @.t.q._Rson.vis==0 then do /*has this node been visited? */ + next= @.t.q._Rson /*──► next node. */ + @.t.q._Rson.vis= 1 /*the rightside is completed. */ + end + if next==. then next= @.t.q._dad /*process the father node. */ + return next /*next node (or 0, if done).*/ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +make_node: parse arg name,t; #=# +1; q= @.t.0 +1 /*make new node/branch on tree*/ + @.t.q= name; @.t.q._Lson= 0; @.t.0= q + @.t.q._dad=0; @.t.q._Rson= 0; return q /*number of node just created.*/ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +make_tree: procedure expose @. root. #; parse arg tree /*construct a couple of trees.*/ + if tree==1 then hhh='H' /* [↓] must be a wood duck*/ + else hhh='δ' /*the odd duck in the tree. */ + a=make_node('A', tree); root.tree=a + b=make_node('B', tree); call son 'L', b, a, tree + c=make_node('C', tree); call son 'R', c, a, tree + d=make_node('D', tree); call son 'L', d, b, tree + e=make_node('E', tree); call son 'R', e, b, tree + f=make_node('F', tree); call son 'L', f, c, tree + g=make_node('G', tree); call son 'L', g, d, tree + /*quacks like a duck?*/ h=make_node(hhh, tree); call son 'L', h, f, tree + i=make_node('I', tree); call son 'R', i, f, tree + return +/*──────────────────────────────────────────────────────────────────────────────────────*/ +sayX: say; say arg(1); say; exit /*display a message and exit. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +son: procedure expose @.; parse arg ?,son,dad,t; LR= '_'?"SON" + @.t.son._dad= dad; q= @.t.dad.LR /* [↓] define which son. */ + if q\==0 then do; @.t.q._dad= son; @.t.son.LR= q; end + @.t.dad.LR= son; return diff --git a/Task/Scope-Function-names-and-labels/00DESCRIPTION b/Task/Scope-Function-names-and-labels/00DESCRIPTION index c07ccaecb5..2f1b3f047c 100644 --- a/Task/Scope-Function-names-and-labels/00DESCRIPTION +++ b/Task/Scope-Function-names-and-labels/00DESCRIPTION @@ -1,4 +1,5 @@ -;Task: +;Task:fruby + Explain or demonstrate the levels of visibility of function names and labels within the language. diff --git a/Task/Scope-Function-names-and-labels/Ring/scope-function-names-and-labels.ring b/Task/Scope-Function-names-and-labels/Ring/scope-function-names-and-labels.ring new file mode 100644 index 0000000000..b3ca13ac4a --- /dev/null +++ b/Task/Scope-Function-names-and-labels/Ring/scope-function-names-and-labels.ring @@ -0,0 +1,11 @@ +# Project : Scope/Function names and labels +# Date : 2018/02/22 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +see "What is your name?" + nl +give name +welcome(name) + +func welcome(name) + see "hello " + name + nl diff --git a/Task/Scope-Function-names-and-labels/Scala/scope-function-names-and-labels.scala b/Task/Scope-Function-names-and-labels/Scala/scope-function-names-and-labels.scala new file mode 100644 index 0000000000..c5d6a27d1d --- /dev/null +++ b/Task/Scope-Function-names-and-labels/Scala/scope-function-names-and-labels.scala @@ -0,0 +1,55 @@ +object ScopeFunction extends App { + val c = new C() + val d = new D() + val n = 1 + + def a() = println("calling a") + + trait E { + def m() = println("calling m") + } + + a() // OK as a is internal + B.f() // OK as f is public + + class C { + // class level function visible everywhere, by default + def g() = println("calling g") + + // class level function only visible within C and its subclasses + protected def i() { + println("calling i") + println("calling h") // OK as h within same class + // nested function in scope until end of i + def j() = println("calling j") + + j() + } + + // class level function only visible within C + private def h() = println("calling h") + } + + c.g() // OK as g is public but can't call h or i via c + + class D extends C with E { + // class level function visible anywhere within the same module + def k() { + println("calling k") + i() // OK as C.i is protected + m() // OK as E.m is public and has a body + } + } + + d.k() // OK as k is public + + object B { + // object level function visible everywhere, by default + def f() = println("calling f") + } + + val l = (i:Int, j: Int) => println(i,j) + + println("Good-bye!") // will be executed + +} diff --git a/Task/Scope-modifiers/C-sharp/scope-modifiers-1.cs b/Task/Scope-modifiers/C-sharp/scope-modifiers-1.cs index 957eb45462..4462272a64 100644 --- a/Task/Scope-modifiers/C-sharp/scope-modifiers-1.cs +++ b/Task/Scope-modifiers/C-sharp/scope-modifiers-1.cs @@ -3,11 +3,16 @@ protected //visible to current class and to derived classes. internal //visible to anything inside the same assembly (.dll/.exe). protected internal //visible to anything inside the same assembly and also to derived classes outside the assembly. private //visible only to the current class. +//C# 7.2 adds: +private protected //visible to current class and to derived classes inside the same assembly. -//Modifier | Class | Assembly | Subclass | World -//-------------------------------------------------------- -//public | Y | Y | Y | Y -//protected internal | Y | Y | Y | N -//protected | Y | N | Y | N -//internal | Y | Y | N | N -//private | Y | N | N | N +// | | subclass | other class || subclass | other class +//Modifier | class | in same assembly | in same assembly || outside assembly | outside assembly +//------------------------------------------------------------------------------------------------------- +//public | Yes | Yes | Yes || Yes | Yes +//protected internal | Yes | Yes | Yes || Yes | No +//protected | Yes | Yes | No || Yes | No +//internal | Yes | Yes | Yes || No | No +//private | Yes | No | No || No | No +// C# 7.2: +//private protected | Yes | Yes | No || No | No diff --git a/Task/Search-a-list/Aime/search-a-list.aime b/Task/Search-a-list/Aime/search-a-list.aime index bd76cdb763..9d1907a8a7 100644 --- a/Task/Search-a-list/Aime/search-a-list.aime +++ b/Task/Search-a-list/Aime/search-a-list.aime @@ -5,13 +5,13 @@ search(list l, text s) i = 0; while (i < ~l) { - if (!compare(l[i], s)) { + if (l[i] == s) { break; } i += 1; } - o_(s, " is ", i == ~l ? "not in the haystack" : cat("at ", itoa(i)), "\n"); + o_(s, " is ", i == ~l ? "not in the haystack" : "at " + itoa(i), "\n"); } integer diff --git a/Task/Search-a-list/Julia/search-a-list.julia b/Task/Search-a-list/Julia/search-a-list.julia index 10a96ba8a0..da29fe501e 100644 --- a/Task/Search-a-list/Julia/search-a-list.julia +++ b/Task/Search-a-list/Julia/search-a-list.julia @@ -1,13 +1,4 @@ -julia> findfirst(x -> x=="yes", {"no","?","yes","maybe","yes"}) -3 -julia> indexin({"yes"},{"no","?","yes","maybe","yes"}) -1-element Array{Int64,1}: - 5 -julia> findin({"no","?","yes","maybe","yes"},{"yes"}) -2-element Array{Int64,1}: - 3 - 5 -julia> find(x -> x=="yes", {"no","?","yes","maybe","yes"}) -2-element Array{Int64,1}: - 3 - 5 +@show findfirst(["no", "?", "yes", "maybe", "yes"], "yes") +@show indexin(["yes"], ["no", "?", "yes", "maybe", "yes"]) +@show findin(["no", "?", "yes", "maybe", "yes"], ["yes"]) +@show find(["no", "?", "yes", "maybe", "yes"] .== "yes") diff --git a/Task/Search-a-list/Maple/search-a-list.maple b/Task/Search-a-list/Maple/search-a-list.maple new file mode 100644 index 0000000000..f87167d749 --- /dev/null +++ b/Task/Search-a-list/Maple/search-a-list.maple @@ -0,0 +1,10 @@ +haystack := ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"]: +occurences := ListTools:-SearchAll(needle,haystack): +try + #first occurence + printf("The first occurence is at index %d\n", occurences[1]); + #last occurence, note that StringTools:-SearchAll()retuns a list of all occurences positions + printf("The last occurence is at index %d\n", occurences[-1]); +catch : + print("Erros: Needle not found in the haystack"): +end try: diff --git a/Task/Secure-temporary-file/Perl-6/secure-temporary-file.pl6 b/Task/Secure-temporary-file/Perl-6/secure-temporary-file.pl6 new file mode 100644 index 0000000000..f00519eb4d --- /dev/null +++ b/Task/Secure-temporary-file/Perl-6/secure-temporary-file.pl6 @@ -0,0 +1,20 @@ +use File::Temp; + +# Generate a temp file in a temp dir +my ($filename0,$filehandle0) = tempfile; + +# specify a template for the filename +# * are replaced with random characters +my ($filename1,$filehandle1) = tempfile("******"); + +# Automatically unlink files at DESTROY (this is the default) +my ($filename2,$filehandle2) = tempfile("******", :unlink); + +# Specify the directory where the tempfile will be created +my ($filename3,$filehandle3) = tempfile(:tempdir("/path/to/my/dir")); + +# don't unlink this one +my ($filename4,$filehandle4) = tempfile(:tempdir('.'), :!unlink); + +# specify a prefix, a suffix, or both for the filename +my ($filename5,$filehandle5) = tempfile(:prefix('foo'), :suffix(".txt")); diff --git a/Task/Secure-temporary-file/PicoLisp/secure-temporary-file.l b/Task/Secure-temporary-file/PicoLisp/secure-temporary-file.l index 4cbf857b4b..4e338c18c3 100644 --- a/Task/Secure-temporary-file/PicoLisp/secure-temporary-file.l +++ b/Task/Secure-temporary-file/PicoLisp/secure-temporary-file.l @@ -6,6 +6,7 @@ : (let F (tmp "foo") (ctl F # Get exclusive lock - (let N (in F (read)) # Atomic increment - (out F (println (inc N))) ) ) ) + (in F + (let N (read) # Atomic increment + (out F (println (inc N))) ) ) ) ) -> 124 diff --git a/Task/Self-describing-numbers/Factor/self-describing-numbers.factor b/Task/Self-describing-numbers/Factor/self-describing-numbers.factor new file mode 100644 index 0000000000..4de8e3d1d0 --- /dev/null +++ b/Task/Self-describing-numbers/Factor/self-describing-numbers.factor @@ -0,0 +1,11 @@ +USING: kernel math.parser prettyprint sequences ; +IN: rosetta-code.self-describing-numbers + +: digits ( n -- seq ) number>string string>digits ; + +: digit-count ( seq n -- m ) [ = ] curry count ; + +: self-describing-number? ( n -- ? ) + digits dup [ digit-count = ] with map-index [ t = ] all? ; + +100,000,000 [ self-describing-number? ] filter . diff --git a/Task/Self-describing-numbers/Haskell/self-describing-numbers-1.hs b/Task/Self-describing-numbers/Haskell/self-describing-numbers-1.hs index 73d620be7b..cfca6c4be4 100644 --- a/Task/Self-describing-numbers/Haskell/self-describing-numbers-1.hs +++ b/Task/Self-describing-numbers/Haskell/self-describing-numbers-1.hs @@ -4,13 +4,14 @@ count :: Int -> [Int] -> Int count x = length . filter (x ==) isSelfDescribing :: Integer -> Bool -isSelfDescribing n = - nu == f where - nu = map digitToInt (show n) - f = map (\a -> count a nu) [0 .. ((length nu)-1)] +isSelfDescribing n = nu == f + where + nu = digitToInt <$> show n + f = (`count` nu) <$> [0 .. length nu - 1] +main :: IO () main = do - let tests = [1210, 2020, 21200, 3211000, - 42101000, 521001000, 6210001000] - print $ map isSelfDescribing tests - print $ filter isSelfDescribing [0 .. 4000000] + print $ + isSelfDescribing <$> + [1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000] + print $ filter isSelfDescribing [0 .. 4000000] diff --git a/Task/Self-describing-numbers/Haskell/self-describing-numbers-2.hs b/Task/Self-describing-numbers/Haskell/self-describing-numbers-2.hs index a63a7d1a74..df3e66a5e8 100644 --- a/Task/Self-describing-numbers/Haskell/self-describing-numbers-2.hs +++ b/Task/Self-describing-numbers/Haskell/self-describing-numbers-2.hs @@ -7,15 +7,16 @@ count x = length . filter (x ==) -- all the combinations of n digits of base n -- a base-n number are represented as a list of ints, one per digit allBaseNNumsOfLength :: Int -> [[Int]] -allBaseNNumsOfLength n = replicateM n [0..n-1] +allBaseNNumsOfLength = replicateM <*> (enumFromTo 0 . subtract 1) isSelfDescribing :: [Int] -> Bool -isSelfDescribing num = - all (\(i,x) -> x == count i num) $ zip [0..] num +isSelfDescribing num = all (\(i, x) -> x == count i num) $ zip [0 ..] num -- translate it back into an integer in base-10 decimalize :: [Int] -> Int decimalize = read . map intToDigit -main = forM_ [1..7] $ - print . map decimalize . filter isSelfDescribing . allBaseNNumsOfLength +main :: IO () +main = + (print . concat) $ + map decimalize . filter isSelfDescribing . allBaseNNumsOfLength <$> [1 .. 8] diff --git a/Task/Self-describing-numbers/Julia/self-describing-numbers.julia b/Task/Self-describing-numbers/Julia/self-describing-numbers.julia index d7a61eb430..07fe71f55f 100644 --- a/Task/Self-describing-numbers/Julia/self-describing-numbers.julia +++ b/Task/Self-describing-numbers/Julia/self-describing-numbers.julia @@ -1,9 +1,14 @@ -function selfie(x) - y = reverse(digits(x)) - len = length(y) - sum(y) != len && return false - for i = 1:len - y[i] != sum(y .== i-1) && return false +function selfie(x::Integer) + ds = reverse(digits(x)) + if sum(ds) != length(ds) return false end + for (i, d) in enumerate(ds) + if d != sum(ds .== i - 1) return false end end return true end + +@show selfie(2020) +@show selfie(2021) + +selfies(x) = for i in 1:x selfie(i) && println(i) end +@time selfies(4000000) diff --git a/Task/Self-describing-numbers/Modula-2/self-describing-numbers.mod2 b/Task/Self-describing-numbers/Modula-2/self-describing-numbers.mod2 new file mode 100644 index 0000000000..1487213af2 --- /dev/null +++ b/Task/Self-describing-numbers/Modula-2/self-describing-numbers.mod2 @@ -0,0 +1,51 @@ +MODULE SelfDescribingNumber; + +FROM WholeStr IMPORT + CardToStr; +FROM STextIO IMPORT + WriteString, WriteLn; +FROM SWholeIO IMPORT + WriteCard; + +PROCEDURE Check(Number: CARDINAL): BOOLEAN; +VAR + I, D: CARDINAL; + A: ARRAY [0 .. 9] OF CHAR; + Count, W: ARRAY [0 .. 9] OF CARDINAL; + Result: BOOLEAN; +BEGIN + CardToStr(Number, A); + FOR I := 0 TO 9 DO + Count[I] := 0; + W[I] := 0; + END; + FOR I := 0 TO LENGTH(A) - 1 DO + D := ORD(A[I]) - ORD("0"); + INC(Count[D]); + W[I] := D; + END; + Result := TRUE; + I := 0; + WHILE Result AND (I <= 9) DO + Result := (Count[I] = W[I]); + INC(I); + END; + RETURN Result; +END Check; + +VAR + X: CARDINAL; + +BEGIN + WriteString("Autodescriptive numbers from 1 to 100000000:"); + WriteLn; + FOR X := 1 TO 100000000 DO + IF Check(X) THEN + WriteString(" "); + WriteCard(X, 1); + WriteLn; + END; + END; + WriteString("Job done."); + WriteLn; +END SelfDescribingNumber. diff --git a/Task/Self-describing-numbers/Red/self-describing-numbers.red b/Task/Self-describing-numbers/Red/self-describing-numbers.red new file mode 100644 index 0000000000..f76ea9238a --- /dev/null +++ b/Task/Self-describing-numbers/Red/self-describing-numbers.red @@ -0,0 +1,30 @@ +Red [] + +;;------------------------------------- +count-dig: func ["count occurence of digit in number" +;;------------------------------------- + s [string!] "number as string" + sdig [char!] "search number as char" +][ +cnt: #"0" ;; counter as char for performance optimization + +while [s: find/tail s sdig][cnt: cnt + 1] +return cnt +] + +;;------------------------------------- +isSDN?: func ["test if number is self describing number" + s [string!] "number to test as string " + ][ +;;------------------------------------- + +ind: #"0" ;; use digit as char for performance optimization + +foreach ele s [ + if ele <> count-dig s ind [return false] + ind: ind + 1 +] +return true +] + +repeat i 4000000 [ if isSDN? to-string i [print i] ] diff --git a/Task/Self-describing-numbers/Ring/self-describing-numbers.ring b/Task/Self-describing-numbers/Ring/self-describing-numbers.ring new file mode 100644 index 0000000000..b33cdf9ef4 --- /dev/null +++ b/Task/Self-describing-numbers/Ring/self-describing-numbers.ring @@ -0,0 +1,27 @@ +# Project : Self-describing numbers +# Date : 2017/11/18 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +for num = 1 to 45000000 + res = 0 + for n=1 to len(string(num)) + temp = string(num) + pos = number(temp[n]) + cnt = count(temp,string(n-1)) + if cnt = pos + res = res + 1 + ok + next + if res = len(string(num)) + see num + nl + ok +next + +func count(cString,dString) + sum = 0 + while substr(cString,dString) > 0 + sum = sum + 1 + cString = substr(cString,substr(cString,dString)+len(string(sum))) + end + return sum diff --git a/Task/Self-describing-numbers/Rust/self-describing-numbers.rust b/Task/Self-describing-numbers/Rust/self-describing-numbers.rust new file mode 100644 index 0000000000..386a7a3b85 --- /dev/null +++ b/Task/Self-describing-numbers/Rust/self-describing-numbers.rust @@ -0,0 +1,22 @@ +fn is_self_desc(xx: u64) -> bool +{ + let s: String = xx.to_string(); + let mut count_vec = vec![0; 10]; + for c in s.chars() { + count_vec[c.to_digit(10).unwrap() as usize] += 1; + } + for (i, c) in s.chars().enumerate() { + if count_vec[i] != c.to_digit(10).unwrap() as usize { + return false; + } + } + return true; +} + +fn main() { + for i in 1..100000000 { + if is_self_desc(i) { + println!("{}", i) + } + } +} diff --git a/Task/Self-describing-numbers/Scala/self-describing-numbers.scala b/Task/Self-describing-numbers/Scala/self-describing-numbers.scala new file mode 100644 index 0000000000..77cc7e3590 --- /dev/null +++ b/Task/Self-describing-numbers/Scala/self-describing-numbers.scala @@ -0,0 +1,14 @@ +object SelfDescribingNumbers extends App { + def isSelfDescribing(a: Int): Boolean = { + val s = Integer.toString(a) + + (0 until s.length).forall(i => s.count(_.toString.toInt == i) == s(i).toString.toInt) + } + + println("Curious numbers n = x0 x1 x2...x9 such that xi is the number of digits equal to i in n.") + + for (i <- 0 to 42101000 by 10 + if isSelfDescribing(i)) println(i) + + println("Successfully completed without errors.") +} diff --git a/Task/Self-referential-sequence/Aime/self-referential-sequence.aime b/Task/Self-referential-sequence/Aime/self-referential-sequence.aime index 482ba7d272..8b30ee4f9a 100644 --- a/Task/Self-referential-sequence/Aime/self-referential-sequence.aime +++ b/Task/Self-referential-sequence/Aime/self-referential-sequence.aime @@ -1,34 +1,20 @@ text -next(text s, integer show) +next(text s) { - integer l; - record v; + integer c, e, l; + index v; data d; - text u; - l = length(s); + l = ~s; while (l) { - integer e; - - l -= 1; - e = 0; - u = insert("", 0, s[l]); - r_j_integer(e, v, u); - r_f_integer(v, u, e + 1); + v[-s[l -= 1]] += 1; } - if (r_last(v, u)) { - do { - b_plan(d, v[u], u); - } while (rsk_less(v, u, u)); + for (c, e in v) { + b_form(d, "%d%c", e, -c); } - if (show) { - o_text(b_string(d)); - o_newline(); - } - - return b_string(d); + return d; } integer @@ -40,17 +26,12 @@ depth(text s, integer i, record r) r_j_integer(d, r, s); if (d <= 0) { i += 1; - if (d) { - d += i; - } else { - d = -i; - } - r_f_integer(r, s, d); - i = depth(next(s, 0), i, r); + d += d ? i : -i; + r[s] = d; + i = depth(next(s), i, r); d = r[s]; if (d <= 0) { - d = i + 1; - r_r_integer(r, s, d); + r[s] = d = i + 1; } } @@ -78,19 +59,15 @@ main(void) } } - o_text(cat3("longest length is ", itoa(d), "\n")); - while (l_length(l)) { + o_("longest length is ", d, "\n"); + while (l_o_integer(i, l, 0)) { text s; - o_newline(); - r_clear(r); - lf_e_integer(i, l); - o_integer(i); - o_newline(); + o_("\n", i, "\n"); e = d - 1; s = itoa(i); while (e) { - s = next(s, 1); + o_(s = next(s), "\n"); e -= 1; } } diff --git a/Task/Self-referential-sequence/Perl-6/self-referential-sequence.pl6 b/Task/Self-referential-sequence/Perl-6/self-referential-sequence.pl6 index 18b3fb2760..cbe218d6ad 100644 --- a/Task/Self-referential-sequence/Perl-6/self-referential-sequence.pl6 +++ b/Task/Self-referential-sequence/Perl-6/self-referential-sequence.pl6 @@ -7,30 +7,29 @@ for 1 .. 1000000 -> $m { my $j = join '', $m.comb.sort; next if %seen{$j}:exists; # already tested a permutation %seen{$j} = ''; - my @seq := converging($m); + my @seq = converging($m); my %elems; my $count; for @seq[] -> $value { last if ++%elems{$value} == 2; $count++; }; if $longest == $count { @list.push($m); - say "\b" x 20, "$count, $m"; # monitor progress } elsif $longest < $count { $longest = $count; @list = $m; - say "\b" x 20, "$count, $m"; # monitor progress + print "\b" x 20, "$count, $m"; # monitor progress } }; for @list -> $m { - say "Seed Value(s): ", my $seeds = ~permutations($m).unique.grep( { .substr(0,1) != 0 } ); - my @seq := converging($m); + say "\nSeed Value(s): ", my $seeds = ~permutations($m).unique.grep( { .substr(0,1) != 0 } ); + my @seq = converging($m); my %elems; my $count; for @seq[] -> $value { last if ++%elems{$value} == 2; $count++; }; say "\nIterations: ", $count; say "\nSequence: (Only one shown per permutation group.)"; - .say for @seq[^$count], "\n"; + .say for |@seq[^$count], "\n"; } sub converging ($seed) { return $seed, -> $l { join '', map { $_.value.elems~$_.key }, $l.comb.classify({$^b}).sort: {-$^c.key} } ... * } diff --git a/Task/Semiprime/Factor/semiprime-1.factor b/Task/Semiprime/Factor/semiprime-1.factor new file mode 100644 index 0000000000..5c578aa02f --- /dev/null +++ b/Task/Semiprime/Factor/semiprime-1.factor @@ -0,0 +1,4 @@ +USING: kernel math.combinatorics math.primes.factors sequences ; +: semiprime? ( n -- ? ) + [ factors 2 [ product ] map ] + [ [ = ] curry ] bi any? ; diff --git a/Task/Semiprime/Factor/semiprime-2.factor b/Task/Semiprime/Factor/semiprime-2.factor new file mode 100644 index 0000000000..e753793579 --- /dev/null +++ b/Task/Semiprime/Factor/semiprime-2.factor @@ -0,0 +1 @@ +100 iota [ semiprime? ] filter [ pprint bl ] each nl diff --git a/Task/Semiprime/Julia/semiprime.julia b/Task/Semiprime/Julia/semiprime.julia index 0635e626ad..e5eb2b6bc6 100644 --- a/Task/Semiprime/Julia/semiprime.julia +++ b/Task/Semiprime/Julia/semiprime.julia @@ -1 +1,3 @@ -semiprime(n) = sum(values(factor(n))) == 2 +using Primes +issemiprime(n::Integer) = sum(values(factor(n))) == 2 +@show filter(issemiprime, 1:100) diff --git a/Task/Semiprime/Lingo/semiprime-1.lingo b/Task/Semiprime/Lingo/semiprime-1.lingo new file mode 100644 index 0000000000..0859446066 --- /dev/null +++ b/Task/Semiprime/Lingo/semiprime-1.lingo @@ -0,0 +1,13 @@ +on isSemiPrime (n) + div = 2 + cnt = 0 + repeat while cnt < 3 and n <> 1 + if n mod div = 0 then + n = n / div + cnt = cnt + 1 + else + div = div + 1 + end if + end repeat + return cnt=2 +end diff --git a/Task/Semiprime/Lingo/semiprime-2.lingo b/Task/Semiprime/Lingo/semiprime-2.lingo new file mode 100644 index 0000000000..67532a5c08 --- /dev/null +++ b/Task/Semiprime/Lingo/semiprime-2.lingo @@ -0,0 +1,5 @@ +res = [] +repeat with i = 1 to 100 + if isSemiPrime(i) then res.add(i) +end repeat +put res diff --git a/Task/Semiprime/Perl-6/semiprime-1.pl6 b/Task/Semiprime/Perl-6/semiprime-1.pl6 index e28515ca60..ffdec6cd41 100644 --- a/Task/Semiprime/Perl-6/semiprime-1.pl6 +++ b/Task/Semiprime/Perl-6/semiprime-1.pl6 @@ -1,12 +1,11 @@ sub is-semiprime (Int $n --> Bool) { not $n.is-prime and .is-prime given - $n div first $n %% *, - grep &is-prime, 2 .. *; + $n div first $n %% *, flat grep &is-prime, 2 .. *; } use Test; -my @primes = grep &is-prime, 2 .. 100; +my @primes = flat grep &is-prime, 2 .. 100; for ^5 { nok is-semiprime([*] my @f1 = @primes.roll(1)), ~@f1; ok is-semiprime([*] my @f2 = @primes.roll(2)), ~@f2; diff --git a/Task/Semiprime/Perl-6/semiprime-2.pl6 b/Task/Semiprime/Perl-6/semiprime-2.pl6 index aa63ecc0c7..c539669f1a 100644 --- a/Task/Semiprime/Perl-6/semiprime-2.pl6 +++ b/Task/Semiprime/Perl-6/semiprime-2.pl6 @@ -25,7 +25,7 @@ sub find-factor ( Int $n, $constant = 1 ) { INIT my $start = now; # Infinite list of semiprimes -constant @semiprimes = 4, 6, 9, -> $p { ($p + 1 ... &is-semiprime).tail } ... *; +constant @semiprimes = lazy gather for 4 .. * { .take if .&is-semiprime }; # Show the semiprimes < 100 say 'Semiprimes less than 100:'; @@ -33,6 +33,6 @@ say @semiprimes[^ @semiprimes.first: * > 100, :k ], "\n"; # Check individual integers, or in this case, a range my $s = 2⁹⁷ - 1; -say "Is $_ semiprime?: ", is-semiprime( $_ ) for $s .. $s + 30; +say "Is $_ semiprime?: ", .&is-semiprime for $s .. $s + 30; say 'elapsed seconds: ', now - $start; diff --git a/Task/Semiprime/Ring/semiprime.ring b/Task/Semiprime/Ring/semiprime.ring index 642d8f75b2..2375c4c30c 100644 --- a/Task/Semiprime/Ring/semiprime.ring +++ b/Task/Semiprime/Ring/semiprime.ring @@ -17,7 +17,7 @@ next func isPrime n if n < 2 return false ok if n < 4 return true ok - if n % 2 = 0 return false ok + if n % 2 = 0 and n != 2 return false ok for d = 3 to sqrt(n) step 2 if n % d = 0 return false ok next diff --git a/Task/Semiprime/Ruby/semiprime.rb b/Task/Semiprime/Ruby/semiprime.rb index 37e6ef853e..70bac11687 100644 --- a/Task/Semiprime/Ruby/semiprime.rb +++ b/Task/Semiprime/Ruby/semiprime.rb @@ -3,7 +3,7 @@ require 'prime' class Integer def semi_prime? - prime_division.map( &:last ).inject( &:+ ) == 2 + prime_division.map( &:last ).sum == 2 end end diff --git a/Task/Semiprime/Rust/semiprime.rust b/Task/Semiprime/Rust/semiprime.rust new file mode 100644 index 0000000000..9d2f6899cd --- /dev/null +++ b/Task/Semiprime/Rust/semiprime.rust @@ -0,0 +1,56 @@ +extern crate primal; + +fn isqrt(n: usize) -> usize { + (n as f64).sqrt() as usize +} + +fn is_semiprime(mut n: usize) -> bool { + let root = isqrt(n) + 1; + let primes1 = primal::Sieve::new(root); + let mut count = 0; + + for i in primes1.primes_from(2).take_while(|&x| x < root) { + while n % i == 0 { + n /= i; + count += 1; + } + if n == 1 { + break; + } + } + + if n != 1 { + count += 1; + } + count == 2 +} + +#[test] +fn test1() { + assert_eq!((2..10).filter(|&n| is_semiprime(n)).count(), 3); +} + +#[test] +fn test2() { + assert_eq!((2..100).filter(|&n| is_semiprime(n)).count(), 34); +} + +#[test] +fn test3() { + assert_eq!((2..1_000).filter(|&n| is_semiprime(n)).count(), 299); +} + +#[test] +fn test4() { + assert_eq!((2..10_000).filter(|&n| is_semiprime(n)).count(), 2_625); +} + +#[test] +fn test5() { + assert_eq!((2..100_000).filter(|&n| is_semiprime(n)).count(), 23_378); +} + +#[test] +fn test6() { + assert_eq!((2..1_000_000).filter(|&n| is_semiprime(n)).count(), 210_035); +} diff --git a/Task/Semordnilap/00DESCRIPTION b/Task/Semordnilap/00DESCRIPTION index f1b6f8f781..1723636bc8 100644 --- a/Task/Semordnilap/00DESCRIPTION +++ b/Task/Semordnilap/00DESCRIPTION @@ -4,7 +4,7 @@ A [[wp:semordnilap|semordnilap]] is a word (or phrase) that spells a different w Example: ''lager'' and ''regal''

;Task -Using only words from the [http://www.puzzlers.org/pub/wordlists/unixdict.txt unixdict], report the total number of unique semordnilap pairs, and print 5 examples. (Note that lager/regal and regal/lager should be counted as one unique pair.) +Using only words from [http://www.puzzlers.org/pub/wordlists/unixdict.txt this list], report the total number of unique semordnilap pairs, and print 5 examples. (Note that lager/regal and regal/lager should be counted as one unique pair.)

;Related tasks * [[Palindrome_detection|Palindrome detection]] diff --git a/Task/Semordnilap/Aime/semordnilap.aime b/Task/Semordnilap/Aime/semordnilap.aime index 7b423342ec..367655a406 100644 --- a/Task/Semordnilap/Aime/semordnilap.aime +++ b/Task/Semordnilap/Aime/semordnilap.aime @@ -1,28 +1,21 @@ integer p; record r; file f; -text s; +text s, t; -f_affix(f, "unixdict.txt"); - -while (f_line(f, s) != -1) { - r[s] = 0; -} +f.affix("unixdict.txt"); p = 0; -for (s in r) { - text t; - - t = b_string(b_reverse(b_draft(s))); - if (s > t) { - if (r_key(r, t)) { - p += 1; - if (p <= 5) { - o_(s, " ", t, "\n"); - } +while (f.line(s) != -1) { + if (r_o_integer(z, r, t = b_reverse(s))) { + p += 1; + if (p <= 5) { + o_(s, " ", t, "\n"); } } + + r[s] = 0; } o_form("Semordnilap pairs: ~\n", p); diff --git a/Task/Semordnilap/Haskell/semordnilap.hs b/Task/Semordnilap/Haskell/semordnilap.hs index 9baeea60bd..377aa18574 100644 --- a/Task/Semordnilap/Haskell/semordnilap.hs +++ b/Task/Semordnilap/Haskell/semordnilap.hs @@ -1,10 +1,17 @@ import qualified Data.Set as S -semordnilaps = snd . foldl f (S.empty,[]) where - f (s,w) x | S.member (reverse x) s = (s, x:w) - | otherwise = (S.insert x s, w) +semordnilaps + :: (Ord a, Foldable t) + => t [a] -> [[a]] +semordnilaps = + let f x (s, w) + | S.member (reverse x) s = (s, x : w) + | otherwise = (S.insert x s, w) + in snd . foldr f (S.empty, []) -main=do s <- readFile "unixdict.txt" - let l = semordnilaps (lines s) - print $ length l - mapM_ print $ map (\x->(x, reverse x)) $ take 5 l +main :: IO () +main = do + s <- readFile "unixdict.txt" + let l = semordnilaps (lines s) + print $ length l + mapM_ (print . ((,) <*> reverse)) $ take 5 l diff --git a/Task/Semordnilap/Kotlin/semordnilap.kotlin b/Task/Semordnilap/Kotlin/semordnilap.kotlin index 1b42e279a3..d3bf24ceb2 100644 --- a/Task/Semordnilap/Kotlin/semordnilap.kotlin +++ b/Task/Semordnilap/Kotlin/semordnilap.kotlin @@ -1,7 +1,9 @@ +// version 1.2.0 + import java.io.File fun main(args: Array) { - val words = File("/usr/share/dict/words").readLines().toSet() + val words = File("unixdict.txt").readLines().toSet() val pairs = words.map { Pair(it, it.reversed()) } .filter { it.first < it.second && it.second in words } // avoid dupes+palindromes, find matches println("Found ${pairs.size} semordnilap pairs") diff --git a/Task/Semordnilap/OCaml/semordnilap.ocaml b/Task/Semordnilap/OCaml/semordnilap.ocaml index 0576a3ce7b..20ca329814 100644 --- a/Task/Semordnilap/OCaml/semordnilap.ocaml +++ b/Task/Semordnilap/OCaml/semordnilap.ocaml @@ -2,11 +2,11 @@ module StrSet = Set.Make(String) let str_rev s = let len = String.length s in - let r = String.create len in + let r = Bytes.create len in for i = 0 to len - 1 do - r.[i] <- s.[len - 1 - i] + Bytes.set r i s.[len - 1 - i] done; - (r) + Bytes.to_string r let input_line_opt ic = try Some (input_line ic) diff --git a/Task/Semordnilap/Octave/semordnilap.octave b/Task/Semordnilap/Octave/semordnilap.octave new file mode 100644 index 0000000000..31cba5b8d3 --- /dev/null +++ b/Task/Semordnilap/Octave/semordnilap.octave @@ -0,0 +1,5 @@ +a = strsplit(fileread("unixdict.txt"), "\n"); +a = intersect(a, cellfun(@fliplr, a, "UniformOutput", false)); +a = a(arrayfun(@(i) ismember(fliplr(a{i}), a(i+1:length(a))), 1:length(a))); +length(a) +arrayfun(@(i) printf("%s %s\n", a{i}, fliplr(a{i})), 1:5) diff --git a/Task/Semordnilap/Ring/semordnilap.ring b/Task/Semordnilap/Ring/semordnilap.ring index 37069484a0..4a3b465a3c 100644 --- a/Task/Semordnilap/Ring/semordnilap.ring +++ b/Task/Semordnilap/Ring/semordnilap.ring @@ -1,17 +1,27 @@ -load "stdlib.ring" -aList = file2list("C:\Ring\unixdict.txt") -for m = 1 to 10 - nr = random(len(aList)-1) + 1 - bool = semordnilap(aList[nr]) - see aList[nr] + nl - if bool = 0 see "is palindrome" + nl + nl - else see "is semordnilap" + nl + nl ok -next +# Project : Semordnilap +# Date : 2018/04/18 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : -func semordnilap aString - bString = "" - for i=len(aString) to 1 step -1 - bString = bString + aString[i] - next - see aString - if aString = bString return 0 else return 1 ok +load "stdlib.ring" +nr = 0 +num = 0 +aList = file2list("C:\Ring\CalmoSoft\unixdict.txt") +for n = 1 to len(aList) + bool = semordnilap(aList[n]) + if (bool > 0 and nr > n) + num = num + 1 + if num % 31 = 0 + see aList[n] + " " + aList[nr] + nl + ok + ok +next +see "Total number of unique pairs = " + num + nl + +func semordnilap(aString) + bString = "" + for i=len(aString) to 1 step -1 + bString = bString + aString[i] + next + nr = find(aList,bString) + return nr diff --git a/Task/Semordnilap/Stata/semordnilap.stata b/Task/Semordnilap/Stata/semordnilap.stata new file mode 100644 index 0000000000..9769a2cde5 --- /dev/null +++ b/Task/Semordnilap/Stata/semordnilap.stata @@ -0,0 +1,18 @@ +set seed 17760704 +import delimited http://www.puzzlers.org/pub/wordlists/unixdict.txt, clear +save temp, replace +replace v1=strreverse(v1) +merge 1:1 v1 using temp, nogen keep(3) +drop if v1>=strreverse(v1) +count + 158 +sample 5, count +gen v2=strreverse(v1) +list, noheader noobs + +-------------+ + | evil live | + | pat tap | + | at ta | + | nit tin | + | ku uk | + +-------------+ diff --git a/Task/Send-an-unknown-method-call/Julia/send-an-unknown-method-call.julia b/Task/Send-an-unknown-method-call/Julia/send-an-unknown-method-call.julia new file mode 100644 index 0000000000..9ba80984f0 --- /dev/null +++ b/Task/Send-an-unknown-method-call/Julia/send-an-unknown-method-call.julia @@ -0,0 +1,6 @@ +const functions = Dict{String,Function}( + "foo" => x -> 42 + x, + "bar" => x -> 42 * x) + +@show functions["foo"](3) +@show functions["bar"](3) diff --git a/Task/Send-email/C/send-email.c b/Task/Send-email/C/send-email.c new file mode 100644 index 0000000000..5fee6fbd49 --- /dev/null +++ b/Task/Send-email/C/send-email.c @@ -0,0 +1,99 @@ +/*Abhishek Ghosh, 13th June 2018*/ + +#include +#include +#include + +#define from "" +#define to "" +#define cc "" + +static const char *payload_text[] = { + "Date: Mon, 13 Jun 2018 11:30:00 +0100\r\n", + "To: " to "\r\n", + "From: " from " (Example User)\r\n", + "Cc: " cc " (Another example User)\r\n", + "Message-ID: \r\n", + "Subject: Sanding mail via C\r\n", + "\r\n", + "This mail is being sent by a C program.\r\n", + "\r\n", + "It connects to the GMail SMTP server, by far, the most popular mail program of all.\r\n", + "Which is also probably written in C.\r\n", + "To C or not to C..............\r\n", + "That is the question.\r\n", + NULL +}; + +struct upload_status { + int lines_read; +}; + +static size_t payload_source(void *ptr, size_t size, size_t nmemb, void *userp) +{ + struct upload_status *upload_ctx = (struct upload_status *)userp; + const char *data; + + if((size == 0) || (nmemb == 0) || ((size*nmemb) < 1)) { + return 0; + } + + data = payload_text[upload_ctx->lines_read]; + + if(data) { + size_t len = strlen(data); + memcpy(ptr, data, len); + upload_ctx->lines_read++; + + return len; + } + + return 0; +} + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + struct curl_slist *recipients = NULL; + struct upload_status upload_ctx; + + upload_ctx.lines_read = 0; + + curl = curl_easy_init(); + if(curl) { + + curl_easy_setopt(curl, CURLOPT_USERNAME, "user"); + curl_easy_setopt(curl, CURLOPT_PASSWORD, "secret"); + + curl_easy_setopt(curl, CURLOPT_URL, "smtp://smtp.gmail.com:465"); + + curl_easy_setopt(curl, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL); + + curl_easy_setopt(curl, CURLOPT_CAINFO, "/path/to/certificate.pem"); + + curl_easy_setopt(curl, CURLOPT_MAIL_FROM, from); + + recipients = curl_slist_append(recipients, to); + recipients = curl_slist_append(recipients, cc); + curl_easy_setopt(curl, CURLOPT_MAIL_RCPT, recipients); + + curl_easy_setopt(curl, CURLOPT_READFUNCTION, payload_source); + curl_easy_setopt(curl, CURLOPT_READDATA, &upload_ctx); + curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L); + + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); + + res = curl_easy_perform(curl); + + if(res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(res)); + + curl_slist_free_all(recipients); + + curl_easy_cleanup(curl); + } + + return (int)res; +} diff --git a/Task/Send-email/Groovy/send-email.groovy b/Task/Send-email/Groovy/send-email.groovy new file mode 100644 index 0000000000..cca0f16d34 --- /dev/null +++ b/Task/Send-email/Groovy/send-email.groovy @@ -0,0 +1,47 @@ +import javax.mail.* +import javax.mail.internet.* + +public static void simpleMail(String from, String password, String to, + String subject, String body) throws Exception { + + String host = "smtp.gmail.com"; + Properties props = System.getProperties(); + props.put("mail.smtp.starttls.enable",true); + /* mail.smtp.ssl.trust is needed in script to avoid error "Could not convert socket to TLS" */ + props.setProperty("mail.smtp.ssl.trust", host); + props.put("mail.smtp.auth", true); + props.put("mail.smtp.host", host); + props.put("mail.smtp.user", from); + props.put("mail.smtp.password", password); + props.put("mail.smtp.port", "587"); + + Session session = Session.getDefaultInstance(props, null); + MimeMessage message = new MimeMessage(session); + message.setFrom(new InternetAddress(from)); + + InternetAddress toAddress = new InternetAddress(to); + + message.addRecipient(Message.RecipientType.TO, toAddress); + + message.setSubject(subject); + message.setText(body); + + Transport transport = session.getTransport("smtp"); + + transport.connect(host, from, password); + + transport.sendMessage(message, message.getAllRecipients()); + transport.close(); +} + +/* Set email address sender */ +String s1 = "example@gmail.com"; + +/* Set password sender */ +String s2 = ""; + +/* Set email address sender */ +String s3 = "example@gmail.com" + +/*Call function */ +simpleMail(s1, s2 , s3, "TITLE", "TEXT"); diff --git a/Task/Send-email/Haskell/send-email-1.hs b/Task/Send-email/Haskell/send-email-1.hs new file mode 100644 index 0000000000..94f3da0805 --- /dev/null +++ b/Task/Send-email/Haskell/send-email-1.hs @@ -0,0 +1,24 @@ +{-# LANGUAGE OverloadedStrings #-} + +module Main (main) where + +import Network.Mail.SMTP + ( Address(..) + , htmlPart + , plainTextPart + , sendMailWithLogin' + , simpleMail + ) + +main :: IO () +main = + sendMailWithLogin' "smtp.example.com" 25 "user" "password" $ + simpleMail + (Address (Just "From Example") "from@example.com") + [Address (Just "To Example") "to@example.com"] + [] -- CC + [] -- BCC + "Subject" + [ plainTextPart "This is plain text." + , htmlPart "

Title

This is HTML.

" + ] diff --git a/Task/Send-email/Haskell/send-email-2.hs b/Task/Send-email/Haskell/send-email-2.hs new file mode 100644 index 0000000000..fb1360862f --- /dev/null +++ b/Task/Send-email/Haskell/send-email-2.hs @@ -0,0 +1,7 @@ +procedure main(args) + mail := open("mailto:"||args[1], "m", "Subject : "||args[2], + "X-Note: automatically send by Unicon") | + stop("Cannot send mail to ",args[1]) + every write(mail , !&input) + close (mail) +end diff --git a/Task/Send-email/Julia/send-email.julia b/Task/Send-email/Julia/send-email.julia new file mode 100644 index 0000000000..149616d5a1 --- /dev/null +++ b/Task/Send-email/Julia/send-email.julia @@ -0,0 +1,18 @@ +using SMTPClient + +addbrackets(s) = replace(s, r"^\s*([^\<\>]+)\s*$", s"<\1>") + +function wrapRFC5322(from, to, subject, msg) + timestr = Libc.strftime("%a, %d %b %Y %H:%M:%S %z", time()) + IOBuffer("Date: $timestr\nTo: $to\nFrom: $from\nSubject: $subject\n\n$msg") +end + +function sendemail(from, to, subject, messagebody, serverandport; + cc=[], user="", password="", isSSL=true, blocking=true) + opt = SendOptions(blocking=blocking, isSSL=isSSL, username=user, passwd=password) + send(serverandport, map(s -> addbrackets(s), vcat(to, cc)), addbrackets(from), + wrapRFC5322(addbrackets(from), addbrackets(to), subject, messagebody), opt) +end + +sendemail("to@example.com", "from@example.com", "TEST", "hello there test message text here", "smtps://smtp.gmail.com", + user="from@example.com", password="example.com") diff --git a/Task/Send-email/Ring/send-email.ring b/Task/Send-email/Ring/send-email.ring index 8b3c95685a..2581f42aa7 100644 --- a/Task/Send-email/Ring/send-email.ring +++ b/Task/Send-email/Ring/send-email.ring @@ -1,3 +1,4 @@ +load "stdlib.ring" See "Send email..." + nl sendemail("smtp://smtp.gmail.com", "calmosoft@gmail.com", diff --git a/Task/Sequence-of-non-squares/Factor/sequence-of-non-squares.factor b/Task/Sequence-of-non-squares/Factor/sequence-of-non-squares.factor new file mode 100644 index 0000000000..86de001b37 --- /dev/null +++ b/Task/Sequence-of-non-squares/Factor/sequence-of-non-squares.factor @@ -0,0 +1,12 @@ +USING: kernel math math.functions math.ranges prettyprint +sequences ; + +: non-sq ( n -- m ) dup sqrt 1/2 + floor + >integer ; + +: print-first22 ( -- ) 22 [1,b] [ non-sq ] map . ; + +: check-for-sq ( -- ) 1,000,000 [1,b) + [ non-sq sqrt dup floor = [ "Square found." throw ] when ] + each ; + +print-first22 check-for-sq diff --git a/Task/Sequence-of-non-squares/Julia/sequence-of-non-squares.julia b/Task/Sequence-of-non-squares/Julia/sequence-of-non-squares.julia index 1bb0debcc2..15b15304a9 100644 --- a/Task/Sequence-of-non-squares/Julia/sequence-of-non-squares.julia +++ b/Task/Sequence-of-non-squares/Julia/sequence-of-non-squares.julia @@ -1,4 +1,2 @@ -[n + ifloor(1/2 + sqrt(n)) for n = 1:22] - -julia> intersect([1:1000].^2, [n + ifloor(1/2 + sqrt(n)) for n = 1:1000000]) -0-element Array{Int64,1} +nonsquare(n::Real) = n + floor(typeof(n), 0.5 + sqrt(n)) +@show nonsquare.(1:1_000_000) ∩ collect(1:1000) .^ 2 diff --git a/Task/Sequence-of-non-squares/REXX/sequence-of-non-squares.rexx b/Task/Sequence-of-non-squares/REXX/sequence-of-non-squares.rexx index f5a1d9cd3f..996f927f5c 100644 --- a/Task/Sequence-of-non-squares/REXX/sequence-of-non-squares.rexx +++ b/Task/Sequence-of-non-squares/REXX/sequence-of-non-squares.rexx @@ -1,33 +1,31 @@ -/*REXX program displays some non─square numbers, and also displays a validation check.*/ +/*REXX pgm displays some non─square numbers, & also displays a validation check up to 1M*/ parse arg N M . /*obtain optional arguments from the CL*/ if N=='' | N=="," then N= 22 /*Not specified? Then use the default.*/ if M=='' | M=="," then M= 1000000 /* " " " " " " */ -say 'The first ' N " non-square numbers:" /*display a header of what's to come. */ +say 'The first ' N " non─square numbers:" /*display a header of what's to come. */ say /* [↑] default for M is one million.*/ -say center('index', 20) center('non-square numbers', 20) +say center('index', 20) center("non─square numbers", 20) say center('' , 20, "═") center('' , 20, "═") do j=1 for N - say center(j, 20) center(j +floor(1/2 +sqrt(j)), 20) /*could use (.5+ ···*/ + say center(j, 20) center(j +floor(1/2 +sqrt(j)), 20) end /*j*/ -#oops=0 - do k=1 for abs(M-1) /*have it step through a million of 'em*/ - $= k + floor( .5 + sqrt(k) ) /*use the specified formula (algorithm)*/ +#=0 + do k=1 for M /*have it step through a million of 'em*/ + $= k + floor( sqrt(k) + .5 ) /*use the specified formula (algorithm)*/ iRoot=iSqrt($) /*··· and also use the ISQRT function.*/ - if iRoot*iRoot==$ then #oops=#oops+1 /*have we found a mistook? (sic) */ + if iRoot*iRoot==$ then #=# + 1 /*have we found a mistook? (sic) */ end /*k*/ -say; if #oops==0 then #oops= 'no' /*use gooder English.*/ -say 'Using the formula: floor[ 1/2 + sqrt(n) ], ' #oops " squares found up to " M'.' +say; if #==0 then #= 'no' /*use gooder English for display below.*/ +say 'Using the formula: floor[ 1/2 + sqrt(n) ], ' # " squares found up to " M'.' /* [↑] display (possible) error count.*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -floor: procedure; parse arg x; return trunc( x - (x<0) ) +floor: parse arg floor_; return trunc( floor_ - (floor_ < 0) ) /*──────────────────────────────────────────────────────────────────────────────────────*/ -iSqrt: procedure; parse arg x; x=trunc(x); r=0; q=1; do while q<=x; q=q*4; end - do while q>1; q=q%4; _=x-r-q; r=r%2; if _>=0 then do; x=_; r=r+q; end; end - return r /*return the integer square root of X.*/ +iSqrt: procedure; parse arg x; #=1; r=0; do while # <= x; #=#*4; end + do while #>1; #=#%4; _=x-r-#; r=r%2; if _<0 then iterate; x=_; r=r+#; end; return r /*──────────────────────────────────────────────────────────────────────────────────────*/ sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); m.=9; numeric form; h=d+6 numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g *.5'e'_ %2 - do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ - do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ - return g + 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/Sequence-of-non-squares/VBA/sequence-of-non-squares.vba b/Task/Sequence-of-non-squares/VBA/sequence-of-non-squares.vba new file mode 100644 index 0000000000..ca11d62646 --- /dev/null +++ b/Task/Sequence-of-non-squares/VBA/sequence-of-non-squares.vba @@ -0,0 +1,19 @@ +Sub Main() +Dim i&, c&, j#, s$ +Const N& = 1000000 + s = "values for n in the range 1 to 22 : " + For i = 1 To 22 + s = s & ns(i) & ", " + Next + For i = 1 To N + j = Sqr(ns(i)) + If j = CInt(j) Then c = c + 1 + Next + + Debug.Print s + Debug.Print c & " squares less than " & N +End Sub + +Private Function ns(l As Long) As Long + ns = l + Int(1 / 2 + Sqr(l)) +End Function diff --git a/Task/Set-consolidation/Aime/set-consolidation.aime b/Task/Set-consolidation/Aime/set-consolidation.aime index a7d1c4e35e..bc0f1eab5d 100644 --- a/Task/Set-consolidation/Aime/set-consolidation.aime +++ b/Task/Set-consolidation/Aime/set-consolidation.aime @@ -3,18 +3,14 @@ display(list l) { integer i; record r; - text s; for (i, r in l) { text u, v; - o_text(s); - s = ", "; - o_text("{"); + o_text(i ? ", {" : "{"); for (u in r) { - o_text(v); + o_(v, u); v = ", "; - o_text(u); } o_text("}"); } @@ -25,24 +21,13 @@ display(list l) integer intersect(record r, record u) { - integer a; - text s; - - a = 0; - for (s in r) { - if (r_key(u, s)) { - a = 1; - break; - } - } - - return a; + trap_q(r_vcall, r, r_put, 1, record().copy(u), 0); } void merge(record u, record r) { - r_wcall(r, r_add, 1, 2, u); + r.wcall(r_add, 1, 2, u); } list @@ -54,28 +39,21 @@ consolidate(list l) for (i, r in l) { integer j; - j = i - ~l + 1; - while (j) { + j = i - ~l; + while (j += 1) { record u; u = l[j]; - j += 1; if (intersect(r, u)) { merge(u, r); - l_delete(l, i); + l.delete(i); i -= 1; break; } } } - return l; -} - -list -L(...) -{ - return xcall(l_assemble); + l; } record @@ -83,7 +61,7 @@ R(...) { record r; - ucall(r_p_integer, 1, r, 0); + ucall(r_put, 1, r, 0); return r; } @@ -91,11 +69,11 @@ R(...) integer main(void) { - display(consolidate(L(R("A", "B"), R("C", "D")))); - display(consolidate(L(R("A", "B"), R("B", "D")))); - display(consolidate(L(R("A", "B"), R("C", "D"), R("D", "B")))); - display(consolidate(L(R("H", "I", "K"), R("A", "B"), R("C", "D"), - R("D", "B"), R("F", "G", "K")))); + display(consolidate(list(R("A", "B"), R("C", "D")))); + display(consolidate(list(R("A", "B"), R("B", "D")))); + display(consolidate(list(R("A", "B"), R("C", "D"), R("D", "B")))); + display(consolidate(list(R("H", "I", "K"), R("A", "B"), R("C", "D"), + R("D", "B"), R("F", "G", "K")))); - return 0; + 0; } diff --git a/Task/Set-consolidation/Ring/set-consolidation.ring b/Task/Set-consolidation/Ring/set-consolidation.ring new file mode 100644 index 0000000000..4155065081 --- /dev/null +++ b/Task/Set-consolidation/Ring/set-consolidation.ring @@ -0,0 +1,41 @@ +# Project : Set consolidation +# Date : 2018/03/29 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : + +load "stdlib.ring" +test = ["AB","AB,CD","AB,CD,DB","HIK,AB,CD,DB,FGH"] +for t in test + see consolidate(t) + nl +next +func consolidate(s) + sets = split(s,",") + n = len(sets) + for i = 1 to n + p = i + ts = "" + for j = i to 1 step -1 + if ts = "" + p = j + ok + ts = "" + for k = 1 to len(sets[p]) + if j > 1 + if substring(sets[j-1],substr(sets[p],k,1),1) = 0 + ts = ts + substr(sets[p],k,1) + ok + ok + next + if len(ts) < len(sets[p]) + if j > 1 + sets[j-1] = sets[j-1] + ts + sets[p] = "-" + ts = "" + ok + else + p = i + ok + next + next + consolidate = s + " = " + substr(list2str(sets),nl,",") + return consolidate diff --git a/Task/Set-of-real-numbers/Elena/set-of-real-numbers.elena b/Task/Set-of-real-numbers/Elena/set-of-real-numbers.elena index f8709d20e0..b1e79c13d4 100644 --- a/Task/Set-of-real-numbers/Elena/set-of-real-numbers.elena +++ b/Task/Set-of-real-numbers/Elena/set-of-real-numbers.elena @@ -17,21 +17,21 @@ program = // union var set := (:x)( (x >= 0.0r) && (x <= 1.0r) ) union(:x)( (x >= 0.0r) && (x < 2.0r) ). - set eval:0.0r; assertTrue. - set eval:1.0r; assertTrue. - set eval:2.0r; assertFalse. + set(0.0r) assertTrue. + set(1.0r) assertTrue. + set(2.0r) assertFalse. // intersection var set2 := (:x)( (x >= 0.0r) && (x < 2.0r) ) intersection(:x)( (x >= 1.0r) && (x <= 2.0r) ). - set2 eval:0.0r; assertFalse. - set2 eval:1.0r; assertTrue. - set2 eval:2.0r; assertFalse. + set2(0.0r) assertFalse. + set2(1.0r) assertTrue. + set2(2.0r) assertFalse. // difference var set3 := (:x)( (x >= 0.0r) && (x < 3.0r) ) difference(:x) ( (x >= 0.0r) && (x <= 1.0r) ). - set3 eval:0.0r; assertFalse. - set3 eval:1.0r; assertFalse. - set3 eval:2.0r; assertTrue. + set3 (0.0r) assertFalse. + set3 (1.0r) assertFalse. + set3 (2.0r) assertTrue. ]. diff --git a/Task/Set-of-real-numbers/Julia/set-of-real-numbers.julia b/Task/Set-of-real-numbers/Julia/set-of-real-numbers.julia new file mode 100644 index 0000000000..ba779dc6ae --- /dev/null +++ b/Task/Set-of-real-numbers/Julia/set-of-real-numbers.julia @@ -0,0 +1,76 @@ +""" + struct ConvexRealSet +Convex real set (similar to a line segment). +Parameters: lower bound, upper bound: floating point numbers + includelower, includeupper: boolean true or false to indicate whether + the set has a closed boundary (set to true) or open (set to false). +""" +mutable struct ConvexRealSet + lower::Float64 + includelower::Bool + upper::Float64 + includeupper::Bool + function ConvexRealSet(lo, up, incllo, inclup) + this = new() + this.upper = Float64(up) + this.lower = Float64(lo) + this.includelower = incllo + this.includeupper = inclup + this + end +end + + +function ∈(s, xelem) + x = Float64(xelem) + if(x == s.lower) + if(s.includelower) + return true + else + return false + end + elseif(x == s.upper) + if(s.includeupper) + return true + else + return false + end + end + s.lower < x && x < s.upper +end + + +⋃(aset, bset, x) = (∈(aset, x) || ∈(bset, x)) + +⋂(aset, bset, x) = (∈(aset, x) && ∈(bset, x)) + +-(aset, bset, x) = (∈(aset, x) && !∈(bset, x)) + +isempty(s::ConvexRealSet) = (s.lower > s.upper) || + ((s.lower == s.upper) && !s.includeupper && !s.includelower) + + +const s1 = ConvexRealSet(0.0, 1.0, false, true) +const s2 = ConvexRealSet(0.0, 2.0, true, false) +const s3 = ConvexRealSet(1.0, 2.0, false, true) +const s4 = ConvexRealSet(0.0, 3.0, true, false) +const s5 = ConvexRealSet(0.0, 1.0, false, false) +const s6 = ConvexRealSet(0.0, 1.0, true, true) +const sempty = ConvexRealSet(0.0, -1.0, true, true) +const testlist = [0, 1, 2] + + +function testconvexrealset() + for i in testlist + println("Testing with x = $i.\nResults:") + println(" (0, 1] ∪ [0, 2): $(⋃(s1, s2, i))") + println(" [0, 2) ∩ (1, 2]: $(⋂(s2, s3, i))") + println(" [0, 3) − (0, 1): $(-(s4, s5, i))") + println(" [0, 3) − [0, 1]: $(-(s4, s6, i))\n") + end + print("The set sempty is ") + println(isempty(sempty) ? "empty." : "not empty.") +end + + +testconvexrealset() diff --git a/Task/Set-of-real-numbers/Perl-6/set-of-real-numbers.pl6 b/Task/Set-of-real-numbers/Perl-6/set-of-real-numbers.pl6 index 10792079d5..05b004a06e 100644 --- a/Task/Set-of-real-numbers/Perl-6/set-of-real-numbers.pl6 +++ b/Task/Set-of-real-numbers/Perl-6/set-of-real-numbers.pl6 @@ -1,14 +1,14 @@ class Iv { - has $.range handles ; + has $.range handles ; method empty { - $.min after $.max or $.min === $.max && ($.excludes_min || $.excludes_max) + $.min after $.max or $.min === $.max && ($.excludes-min || $.excludes-max) } multi method Bool() { not self.empty }; method length() { $.max - $.min } method gist() { - ($.excludes_min ?? '(' !! '[') ~ + ($.excludes-min ?? '(' !! '[') ~ $.min ~ ',' ~ $.max ~ - ($.excludes_max ?? ')' !! ']'); + ($.excludes-max ?? ')' !! ']'); } } @@ -22,7 +22,7 @@ class IvSet { method new(@ranges) { my @iv = canon @ranges.map: { Iv.new(:range($_)) } - self.bless(*, :intervals(@iv)); + self.bless(:intervals(@iv)); } method complement { @@ -41,9 +41,9 @@ class IvSet { } while @old { my $old = @old.shift; - my $excludes_min = !$pre.excludes_max; - my $excludes_max = !$old.excludes_min; - push @new, $(Range.new($pre.max,$old.min,:$excludes_min,:$excludes_max)); + my $excludes-min = !$pre.excludes-max; + my $excludes-max = !$old.excludes-min; + push @new, $(Range.new($pre.max,$old.min,:$excludes-min,:$excludes-max)); $pre = $old; } IvSet.new(@new); @@ -65,17 +65,17 @@ multi infix:<∩> (Iv $a, Iv $b) { if $a.min ~~ $b or $a.max ~~ $b or $b.min ~~ $a or $b.max ~~ $a { my $min = $a.range.min max $b.range.min; my $max = $a.range.max min $b.range.max; - my $excludes_min = not $min ~~ $a & $b; - my $excludes_max = not $max ~~ $a & $b; - Iv.new(:range(Range.new($min,$max,:$excludes_min, :$excludes_max))); + my $excludes-min = not $min ~~ $a & $b; + my $excludes-max = not $max ~~ $a & $b; + Iv.new(:range(Range.new($min,$max,:$excludes-min, :$excludes-max))); } } multi infix:<∪> (Iv $a, Iv $b) { my $min = $a.range.min min $b.range.min; my $max = $a.range.max max $b.range.max; - my $excludes_min = not $min ~~ $a | $b; - my $excludes_max = not $max ~~ $a | $b; - Iv.new(:range(Range.new($min,$max,:$excludes_min, :$excludes_max))); + my $excludes-min = not $min ~~ $a | $b; + my $excludes-max = not $max ~~ $a | $b; + Iv.new(:range(Range.new($min,$max,:$excludes-min, :$excludes-max))); } multi infix:<∩> (IvSet $ars, IvSet $brs) { @@ -85,9 +85,9 @@ multi infix:<∩> (IvSet $ars, IvSet $brs) { if $a.min ~~ $b or $a.max ~~ $b or $b.min ~~ $a or $b.max ~~ $a { my $min = $a.range.min max $b.range.min; my $max = $a.range.max min $b.range.max; - my $excludes_min = not $min ~~ $a & $b; - my $excludes_max = not $max ~~ $a & $b; - push @overlap, $(Range.new($min,$max,:$excludes_min, :$excludes_max)); + my $excludes-min = not $min ~~ $a & $b; + my $excludes-max = not $max ~~ $a & $b; + push @overlap, $(Range.new($min,$max,:$excludes-min, :$excludes-max)); } } } @@ -121,19 +121,18 @@ my $s3 = iv(0..^3) − iv(0^..^1); my $s4 = iv(0..^3) − iv(0..1) ; say "\t\t\t\t0\t1\t2"; -say "(0, 1] ∪ [0, 2) -> $s1.gist()\t", 0 ~~ $s1,"\t", 1 ~~ $s1,"\t", 2 ~~ $s1; +say "(0, 1] ∪ [0, 2) -> $s1.gist()\t", 0 ~~ $s1,"\t", 1 ~~ $s1,"\t", 2 ~~ $s1; say "[0, 2) ∩ (1, 2] -> $s2.gist()\t", 0 ~~ $s2,"\t", 1 ~~ $s2,"\t", 2 ~~ $s2; -say "[0, 3) − (0, 1) -> $s3.gist()\t", 0 ~~ $s3,"\t", 1 ~~ $s3,"\t", 2 ~~ $s3; -say "[0, 3) − [0, 1] -> $s4.gist()\t", 0 ~~ $s4,"\t", 1 ~~ $s4,"\t", 2 ~~ $s4; +say "[0, 3) − (0, 1) -> $s3.gist()\t", 0 ~~ $s3,"\t", 1 ~~ $s3,"\t", 2 ~~ $s3; +say "[0, 3) − [0, 1] -> $s4.gist()\t", 0 ~~ $s4,"\t", 1 ~~ $s4,"\t", 2 ~~ $s4; say ''; say "ℝ is not empty: ", !ℝ.empty; say "[0,3] − ℝ is empty: ", not iv(0..3) − ℝ; -my $A = iv(0..10) - ∩ - [∪] (0..10).map: { iv $_ - 1/6 .. $_ + 1/6 } +my $A = iv(0..10) ∩ + iv |(0..10).map({ $_ - 1/6 .. $_ + 1/6 }).cache; my $B = iv 0..sqrt(1/6), |(1..99).map({ $(sqrt($_-1/6) .. sqrt($_ + 1/6)) }), diff --git a/Task/Set/Lua/set.lua b/Task/Set/Lua/set-1.lua similarity index 100% rename from Task/Set/Lua/set.lua rename to Task/Set/Lua/set-1.lua diff --git a/Task/Set/Lua/set-2.lua b/Task/Set/Lua/set-2.lua new file mode 100644 index 0000000000..b7227f7cab --- /dev/null +++ b/Task/Set/Lua/set-2.lua @@ -0,0 +1,111 @@ +local function new(_, ...) + local r = {} + local s = setmetatable({}, { + -- API operations + __index = { + + -- single value insertion + insert = function(s, v) + if not r[v] then + table.insert(s, v) + r[v] = #s + end + return s + end, + + -- single value removal + remove = function(s, v) + local i = r[v] + if i then + r[v] = nil + local t = table.remove(s) + if t ~= v then + r[t] = i + s[i] = t + end + end + return s + end, + + -- multi-value insertion + batch_insert = function(s, ...) + for _,v in pairs {...} do + s:insert(v) + end + return s + end, + + -- multi-value removal + batch_remove = function(s, ...) + for _,v in pairs {...} do + s:remove(v) + end + return s + end, + + -- membership test + has = function(s, e) + return r[e] ~= nil + end + }, + + -- set manipulation operators + + -- union + __add = function(s1, s2) + r = set() + r:batch_insert(table.unpack(s1)) + r:batch_insert(table.unpack(s2)) + return r + end, + + -- subtraction + __sub = function(s1, s2) + r = set() + r:batch_insert(table.unpack(s1)) + r:batch_remove(table.unpack(s2)) + return r + end, + + -- intersection + __mul = function(s1, s2) + r = set() + for _,v in ipairs(s1) do + if s2:has(v) then + r:insert(v) + end + end + return r + end, + + -- equality + __eq = function(s1, s2) + if #s1 ~= #s2 then return false end + for _,v in ipairs(s1) do + if not s2:has(v) then return false end + end + return true + end, + + -- proper subset + __lt = function(s1, s2) + if s1 == s2 then return false end + for _,v in ipairs(s1) do + if not s2:has(v) then return false end + end + return true + end, + + -- subset + __lte = function(s1, s2) + return (s1 == s2) or (s1 < s2) + end, + + -- metatable type tag + __type__ = 'set' + }) + s:batch_insert(...) + return s +end + +return setmetatable({}, { __call = new }) diff --git a/Task/Set/Perl-6/set.pl6 b/Task/Set/Perl-6/set.pl6 index 5eb19a80e7..7c1f74b142 100644 --- a/Task/Set/Perl-6/set.pl6 +++ b/Task/Set/Perl-6/set.pl6 @@ -7,8 +7,8 @@ my $c = set
; ok 'c' ∈ $a, "c is an element in set A"; nok 'd' ∈ $a, "d is not an element in set A"; -is $a ∪ $b, set(), "union; a set of all elements either in set A or in set B"; -is $a ∩ $b, set(), "intersection; a set of all elements in both set A and set B"; +is-deeply $a ∪ $b, set(), "union; a set of all elements either in set A or in set B"; +is-deeply $a ∩ $b, set(), "intersection; a set of all elements in both set A and set B"; is $a (-) $b, set(), "difference; a set of all elements in set A, except those in set B"; ok $a ⊆ $c, "subset; true if every element in set A is also in set B"; diff --git a/Task/Set/Ring/set.ring b/Task/Set/Ring/set.ring new file mode 100644 index 0000000000..1a972dfb79 --- /dev/null +++ b/Task/Set/Ring/set.ring @@ -0,0 +1,116 @@ +# Project : Set +# Date : 2018/03/26 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : + +arr = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape"] +for n = 1 to 25 + add(arr,"") +next +seta = "1010101" +see "Set A: " + arrset(arr,seta) + nl +setb = "0111110" +see "Set B: " + arrset(arr,setb) + nl +elementm = "0000010" +see "Element M: " + arrset(arr,elementm) + nl + +temp = arrsetinsec(elementm,seta) +if len(temp) > 0 + see "M is an element of set A" + nl +else + see "M is not an element of set A" + nl +ok +temp = arrsetinsec(elementm,setb) +if len(temp) > 0 + see "M is an element of set B" + nl +else + see "M is not an element of set B" + nl +ok + +see "The union of A and B is: " +see arrsetunion(seta,setb) + nl +see "The intersection of A and B is: " +see arrsetinsec(seta,setb) + nl +see "The difference of A and B is: " +see arrsetnot(seta,setb) + nl + +flag = arrsetsub(seta,setb) +if flag = 1 + see "Set A is a subset of set B" + nl +else + see "Set A is not a subset of set B" + nl +ok +if seta = setb + see "Set A is equal to set B" + nl +else + see "Set A is not equal to set B" + nl +ok + +func arrset(arr,set) + o = "" + for i = 1 to 7 + if set[i] = "1" + o = o + arr[i] + ", " + ok + next + return left(o,len(o)-2) + +func arrsetunion(seta,setb) + o = "" + union = list(len(seta)) + for n = 1 to len(seta) + if seta[n] = "1" or setb[n] = "1" + union[n] = "1" + else + union[n] = "0" + ok + next + for i = 1 to len(union) + if union[i] = "1" + o = o + arr[i] + ", " + ok + next + return o + +func arrsetinsec(setc,setd) + o = "" + union = list(len(setc)) + for n = 1 to len(setc) + if setc[n] = "1" and setd[n] = "1" + union[n] = "1" + else + union[n] = "0" + ok + next + for i = 1 to len(union) + if union[i] = "1" + o = o + arr[i] + ", " + ok + next + return o + +func arrsetnot(seta,setb) + o = "" + union = list(len(seta)) + for n = 1 to len(seta) + if seta[n] = "1" and setb[n] = "0" + union[n] = "1" + else + union[n] = "0" + ok + next + for i = 1 to len(union) + if union[i] = "1" + o = o + arr[i] + ", " + ok + next + return o + +func arrsetsub(setc,setd) + flag = 1 + for n = 1 to len(setc) + if setc[n] = "1" and setd[n] = "0" + flag = 0 + ok + next + return flag diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Perl-6/seven-sided-dice-from-five-sided-dice.pl6 b/Task/Seven-sided-dice-from-five-sided-dice/Perl-6/seven-sided-dice-from-five-sided-dice.pl6 new file mode 100644 index 0000000000..bcf06761f1 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Perl-6/seven-sided-dice-from-five-sided-dice.pl6 @@ -0,0 +1,20 @@ +my $d5 = 1..5; +sub d5() { $d5.roll; } # 1d5 + +sub d7() { + my $flat = 21; + $flat = 5 * d5() - d5() until $flat < 21; + $flat % 7 + 1; +} + +# Testing +my @dist; +my $n = 1_000_000; +my $expect = $n / 7; + +loop ($_ = $n; $n; --$n) { @dist[d7()]++; } + +say "Expect\t",$expect.fmt("%.3f"); +for @dist.kv -> $i, $v { + say "$i\t$v\t" ~ (($v - $expect)/$expect*100).fmt("%+.2f%%") if $v; +} diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Ring/seven-sided-dice-from-five-sided-dice.ring b/Task/Seven-sided-dice-from-five-sided-dice/Ring/seven-sided-dice-from-five-sided-dice.ring new file mode 100644 index 0000000000..b98647dc58 --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Ring/seven-sided-dice-from-five-sided-dice.ring @@ -0,0 +1,22 @@ +# Project : Seven-sided dice from five-sided dice +# Date : 2018/02/02 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : + +for n = 1 to 20 + d = dice7() + see "" + d + " " +next +see nl + +func dice7() + x = dice5() * 5 + dice5() - 6 + if x > 20 + return dice7() + ok + dc = x % 7 + 1 + return dc + +func dice5() + rnd = random(4) + 1 + return rnd diff --git a/Task/Shell-one-liner/Go/shell-one-liner.go b/Task/Shell-one-liner/Go/shell-one-liner.go new file mode 100644 index 0000000000..1dc4bda313 --- /dev/null +++ b/Task/Shell-one-liner/Go/shell-one-liner.go @@ -0,0 +1 @@ +echo 'package main;func main(){println("hlowrld")}'>/tmp/h.go;go run /tmp/h.go diff --git a/Task/Short-circuit-evaluation/Elena/short-circuit-evaluation.elena b/Task/Short-circuit-evaluation/Elena/short-circuit-evaluation.elena index 650791ef37..790e1abbf2 100644 --- a/Task/Short-circuit-evaluation/Elena/short-circuit-evaluation.elena +++ b/Task/Short-circuit-evaluation/Elena/short-circuit-evaluation.elena @@ -11,10 +11,10 @@ program = [ (false, true) forEach(:j) [ - console printLine(i," and ",j," = ",a eval:i && $(b eval:j)). + console printLine(i," and ",j," = ",a(i) && $(b(j))). console writeLine. - console printLine(i," or ",j," = ",a eval:i || $(b eval:j)). + console printLine(i," or ",j," = ",a(i) || $(b(j))). console writeLine. ]. ]. diff --git a/Task/Short-circuit-evaluation/Factor/short-circuit-evaluation.factor b/Task/Short-circuit-evaluation/Factor/short-circuit-evaluation.factor new file mode 100644 index 0000000000..9d7f455535 --- /dev/null +++ b/Task/Short-circuit-evaluation/Factor/short-circuit-evaluation.factor @@ -0,0 +1,14 @@ +USING: combinators.short-circuit.smart io prettyprint ; +IN: rosetta-code.short-circuit + +: a ( ? -- ? ) "(a)" write ; +: b ( ? -- ? ) "(b)" write ; + +"f && f = " write { [ f a ] [ f b ] } && . +"f || f = " write { [ f a ] [ f b ] } || . +"f && t = " write { [ f a ] [ t b ] } && . +"f || t = " write { [ f a ] [ t b ] } || . +"t && f = " write { [ t a ] [ f b ] } && . +"t || f = " write { [ t a ] [ f b ] } || . +"t && t = " write { [ t a ] [ t b ] } && . +"t || t = " write { [ t a ] [ t b ] } || . diff --git a/Task/Short-circuit-evaluation/LiveCode/short-circuit-evaluation.livecode b/Task/Short-circuit-evaluation/LiveCode/short-circuit-evaluation.livecode index e73402f9d2..2263d13f8b 100644 --- a/Task/Short-circuit-evaluation/LiveCode/short-circuit-evaluation.livecode +++ b/Task/Short-circuit-evaluation/LiveCode/short-circuit-evaluation.livecode @@ -1,21 +1,22 @@ -function aa bool - global outcome - put "aa called with" && bool & cr after outcome +global outcome +function a bool + put "a called with" && bool & cr after outcome return bool -end aa +end a function b bool - global outcome put "b called with" && bool & cr after outcome return bool end b on mouseUp - global outcome + local tExp put empty into outcome repeat for each item op in "and,or" repeat for each item x in "true,false" - put merge("[[aa(x)]] [[op]] [[b(x)]]") & cr after outcome - put merge("[[aa(x)]] [[op]] [[b(not x)]]") & cr after outcome + put merge("a([[x]]) [[op]] b([[x]])") into tExp + put merge(tExp && "is [[" & tExp & "]]") & cr after outcome + put merge("a([[x]]) [[op]] b([[not x]])") into tExp + put merge(tExp && "is [[" & tExp & "]]") & cr after outcome end repeat put cr after outcome end repeat diff --git a/Task/Short-circuit-evaluation/Modula-2/short-circuit-evaluation.mod2 b/Task/Short-circuit-evaluation/Modula-2/short-circuit-evaluation.mod2 new file mode 100644 index 0000000000..31cc0e4a69 --- /dev/null +++ b/Task/Short-circuit-evaluation/Modula-2/short-circuit-evaluation.mod2 @@ -0,0 +1,42 @@ +MODULE ShortCircuit; +FROM FormatString IMPORT FormatString; +FROM Terminal IMPORT WriteString,WriteLn,ReadChar; + +PROCEDURE a(v : BOOLEAN) : BOOLEAN; +VAR buf : ARRAY[0..63] OF CHAR; +BEGIN + FormatString(" # Called function a(%b)\n", buf, v); + WriteString(buf); + RETURN v +END a; + +PROCEDURE b(v : BOOLEAN) : BOOLEAN; +VAR buf : ARRAY[0..63] OF CHAR; +BEGIN + FormatString(" # Called function b(%b)\n", buf, v); + WriteString(buf); + RETURN v +END b; + +PROCEDURE Print(x,y : BOOLEAN); +VAR buf : ARRAY[0..63] OF CHAR; +VAR temp : BOOLEAN; +BEGIN + FormatString("a(%b) AND b(%b)\n", buf, x, y); + WriteString(buf); + temp := a(x) AND b(y); + + FormatString("a(%b) OR b(%b)\n", buf, x, y); + WriteString(buf); + temp := a(x) OR b(y); + + WriteLn; +END Print; + +BEGIN + Print(FALSE,FALSE); + Print(FALSE,TRUE); + Print(TRUE,TRUE); + Print(TRUE,FALSE); + ReadChar +END ShortCircuit. diff --git a/Task/Short-circuit-evaluation/Ring/short-circuit-evaluation.ring b/Task/Short-circuit-evaluation/Ring/short-circuit-evaluation.ring new file mode 100644 index 0000000000..257a456724 --- /dev/null +++ b/Task/Short-circuit-evaluation/Ring/short-circuit-evaluation.ring @@ -0,0 +1,31 @@ +# Project : Short-circuit evaluation +# Date : 2018/01/23 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : + +for k = 1 to 2 + word = ["AND","OR"] + see "========= " + word[k] + " ==============" + nl + for i = 0 to 1 + for j = 0 to 1 + see "a(" + i + ") " + word[k] +" b(" + j + ")" + nl + res =a(i) + if word[k] = "AND" and res != 0 + res = b(j) + ok + if word[k] = "OR" and res = 0 + res = b(j) + ok + next + next +next + +func a(t) + see char(9) + "calls func a" + nl + a = t + return a + +func b(t) + see char(9) + "calls func b" + nl + b = t + return b diff --git a/Task/Short-circuit-evaluation/Rust/short-circuit-evaluation.rust b/Task/Short-circuit-evaluation/Rust/short-circuit-evaluation.rust new file mode 100644 index 0000000000..09999084de --- /dev/null +++ b/Task/Short-circuit-evaluation/Rust/short-circuit-evaluation.rust @@ -0,0 +1,19 @@ +fn a(foo: bool) -> bool { + println!("a"); + foo +} + +fn b(foo: bool) -> bool { + println!("b"); + foo +} + +fn main() { + for i in vec![true, false] { + for j in vec![true, false] { + println!("{} and {} == {}", i, j, a(i) && b(j)); + println!("{} or {} == {}", i, j, a(i) || b(j)); + println!(); + } + } +} diff --git a/Task/Short-circuit-evaluation/Stata/short-circuit-evaluation-1.stata b/Task/Short-circuit-evaluation/Stata/short-circuit-evaluation-1.stata new file mode 100644 index 0000000000..f787123e41 --- /dev/null +++ b/Task/Short-circuit-evaluation/Stata/short-circuit-evaluation-1.stata @@ -0,0 +1,24 @@ +function a(x) { + printf(" a") + return(x) +} + +function b(x) { + printf(" b") + return(x) +} + +function call(i, j) { + printf("and:") + x = a(i) + if (x) { + x = b(j) + } + printf("\nor:") + y = a(i) + if (!y) { + y = b(j) + } + printf("\n") + return((x,y)) +} diff --git a/Task/Short-circuit-evaluation/Stata/short-circuit-evaluation-2.stata b/Task/Short-circuit-evaluation/Stata/short-circuit-evaluation-2.stata new file mode 100644 index 0000000000..8ac499a058 --- /dev/null +++ b/Task/Short-circuit-evaluation/Stata/short-circuit-evaluation-2.stata @@ -0,0 +1,15 @@ +: call(0,1) +and: a +or: a b + 1 2 + +---------+ + 1 | 0 1 | + +---------+ + +: call(1,1) +and: a b +or: a + 1 2 + +---------+ + 1 | 1 1 | + +---------+ diff --git a/Task/Show-the-epoch/ABAP/show-the-epoch.abap b/Task/Show-the-epoch/ABAP/show-the-epoch-1.abap similarity index 100% rename from Task/Show-the-epoch/ABAP/show-the-epoch.abap rename to Task/Show-the-epoch/ABAP/show-the-epoch-1.abap diff --git a/Task/Show-the-epoch/ABAP/show-the-epoch-2.abap b/Task/Show-the-epoch/ABAP/show-the-epoch-2.abap new file mode 100644 index 0000000000..9540122c0c --- /dev/null +++ b/Task/Show-the-epoch/ABAP/show-the-epoch-2.abap @@ -0,0 +1 @@ +cl_demo_output=>display( |Result: { CONV datum( 0 ) }| ). diff --git a/Task/Show-the-epoch/Julia/show-the-epoch.julia b/Task/Show-the-epoch/Julia/show-the-epoch.julia index 719a4f9413..68d266d2ac 100644 --- a/Task/Show-the-epoch/Julia/show-the-epoch.julia +++ b/Task/Show-the-epoch/Julia/show-the-epoch.julia @@ -1 +1,2 @@ -println("Time zero (the epoch) is ", strftime("%c", 0), ".") +using Base.Dates +println("Time zero (the epoch) is $(unix2datetime(0)).") diff --git a/Task/Show-the-epoch/Lingo/show-the-epoch.lingo b/Task/Show-the-epoch/Lingo/show-the-epoch.lingo new file mode 100644 index 0000000000..a88e600732 --- /dev/null +++ b/Task/Show-the-epoch/Lingo/show-the-epoch.lingo @@ -0,0 +1,9 @@ +now = the systemDate +put now +-- date( 2018, 3, 21 ) + +babylonianDate = date(-1800,1,1) + +-- print approx. year difference between "babylonianDate" and now +put (now-babylonianDate)/365.2425 +-- 3818.1355 diff --git a/Task/Show-the-epoch/REXX/show-the-epoch.rexx b/Task/Show-the-epoch/REXX/show-the-epoch.rexx index 7ae795cc81..85457151d5 100644 --- a/Task/Show-the-epoch/REXX/show-the-epoch.rexx +++ b/Task/Show-the-epoch/REXX/show-the-epoch.rexx @@ -1,11 +1,11 @@ -/*REXX program shows the # of days since the epoch for the DATE function*/ +/*REXX program displays the number of days since the epoch for the DATE function (BIF). */ -say ' today is' date() /*today's is format: mm MON YYYY */ +say ' today is: ' date() /*today's is format: mm MON YYYY */ -days=date('Basedate') /*only 1st char of option is used*/ -say right(days,35) "days since the REXX base date of January 1st, year 1" +days=date('Basedate') /*only the first char of option is used*/ +say right(days, 40) " days since the REXX base date of January 1st, year 1" -say 'and today is:' date(,days,'B') /*this should be today (still). */ - - /*──────── The above statement is only valid for the newer REXXes,*/ - /*──────── older versions don't support the 2nd and 3rd arguments.*/ +say ' and today is: ' date(, days, "B") /*it should still be today (µSec later)*/ + /* ↑ ┌───◄─── This BIF (Built-In Function) is only */ + /* └─────────◄──────┘ for newer versions of REXX that */ + /* support the 2nd and 3rd arguments. */ diff --git a/Task/Show-the-epoch/Stata/show-the-epoch.stata b/Task/Show-the-epoch/Stata/show-the-epoch.stata new file mode 100644 index 0000000000..b271338f11 --- /dev/null +++ b/Task/Show-the-epoch/Stata/show-the-epoch.stata @@ -0,0 +1,4 @@ +. di %td 0 +01jan1960 +. di %tc 0 +01jan1960 00:00:00 diff --git a/Task/Sierpinski-carpet/Julia/sierpinski-carpet.julia b/Task/Sierpinski-carpet/Julia/sierpinski-carpet.julia index 6127797262..97528b6345 100644 --- a/Task/Sierpinski-carpet/Julia/sierpinski-carpet.julia +++ b/Task/Sierpinski-carpet/Julia/sierpinski-carpet.julia @@ -1,12 +1,16 @@ -pprint(matrix) = for i = 1:size(matrix,1) println(join(matrix[i,:])) end - -spaces(m,n) = [" " for i=1:m, j=1:n] - -function sierpinski(n, token = "*") - x = [token for i=1:1, j=1:1] - for i = 1:n - t = spaces(size(x)...) - x = [[x x x] ; [x t x] ; [x x x]] - end - x +function sierpinski(n::Integer, token::AbstractString="*") + x = fill(token, 1, 1) + for _ in 1:n + t = fill(" ", size(x)) + x = [x x x; x t x; x x x] + end + return x end + +function printsierpinski(m::Matrix) + for r in 1:size(m, 1) + println(join(m[r, :])) + end +end + +sierpinski(2, "#") |> printsierpinski diff --git a/Task/Sierpinski-carpet/Perl-6/sierpinski-carpet.pl6 b/Task/Sierpinski-carpet/Perl-6/sierpinski-carpet.pl6 new file mode 100644 index 0000000000..bcf12ba2c3 --- /dev/null +++ b/Task/Sierpinski-carpet/Perl-6/sierpinski-carpet.pl6 @@ -0,0 +1,27 @@ +sub carpet +{ + (['#'], -> @c { + [ + |@c.map({$_ x 3}), + |@c.map({ $_ ~ $_.trans('#'=>' ') ~ $_}), + |@c.map({$_ x 3}) + ] + } ... *).map: { .join("\n") }; +} + +say carpet[3]; + +# Same as above, structured as an array bound to a sequence, with a separate sub for clarity. +sub weave ( @c ) { + [ + |@c.map({ $_ x 3 }), + |@c.map({ $_ ~ .trans( '#' => ' ' ) ~ $_ }), + |@c.map({ $_ x 3 }) + ] +} + +my @carpet = ( ['#'], &weave ... * ).map: { .join: "\n" }; + +say @carpet[3]; + +# Output of both versions matches task example. diff --git a/Task/Sierpinski-triangle-Graphical/ATS/sierpinski-triangle-graphical.ats b/Task/Sierpinski-triangle-Graphical/ATS/sierpinski-triangle-graphical.ats new file mode 100644 index 0000000000..7ea1488102 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/ATS/sierpinski-triangle-graphical.ats @@ -0,0 +1,103 @@ +// patscc -O2 -flto -D_GNU_SOURCE -DATS_MEMALLOC_LIBC sierpinski.dats -o sierpinski -latslib -lSDL2 +#include "share/atspre_staload.hats" + +typedef point = (int, int) + +extern fun midpoint(A: point, B: point): point = "mac#" + +extern fun sierpinski_draw(n: int, A: point, B: point, C: point): void = "mac#" + +extern fun triangle_remove(A: point, B: point, C: point): void = "mac#" + +extern fun sdl_drawline(x1: int, y1: int, x2: int, y2: int): void = "ext#sdl_drawline" + +extern fun line(A: point, B: point): void + +extern fun ats_tredraw(): void = "mac#ats_tredraw" + +implement midpoint(A, B) = (xmid, ymid) where { + val xmid = (A.0 + B.0) / 2 + val ymid = (A.1 + B.1) / 2 +} + +implement triangle_remove(A, B, C) = ( + line(A, B); + line(B, C); + line(C, A); +) + +implement sierpinski_draw(n, A, B, C) = + if n > 0 then + let + val AB = midpoint(A, B) + val BC = midpoint(B, C) + val CA = midpoint(C, A) + in + triangle_remove(AB, BC, CA); + sierpinski_draw(n-1, A, AB, CA); + sierpinski_draw(n-1, B, BC, AB); + sierpinski_draw(n-1, C, CA, BC); + end + +implement line(A, B) = sdl_drawline(A.0, A.1, B.0, B.1) + +extern fun SDL_Init(): void = "ext#sdl_init" +extern fun SDL_Quit(): void = "ext#sdl_quit" +extern fun SDL_Loop(): void = "ext#sdl_loop" + +implement ats_tredraw() = sierpinski_draw(7, (320, 0), (0, 480), (640, 480)) + +implement main0() = ( + SDL_Init(); + SDL_Loop(); + SDL_Quit(); +) + +%{ +#include +#include +extern void ats_tredraw(); +SDL_Window *sdlwin; +SDL_Renderer *sdlren; +void sdl_init() { + if (SDL_Init(SDL_INIT_VIDEO)) { + exit(1); + } + if ((sdlwin = SDL_CreateWindow("sierpinski triangles", 100, 100, 640, 480, SDL_WINDOW_SHOWN)) == NULL) { + SDL_Quit(); + exit(2); + } + if ((sdlren = SDL_CreateRenderer(sdlwin, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC)) == NULL) { + SDL_DestroyWindow(sdlwin); + SDL_Quit(); + exit(3); + } +} +void sdl_clear() { + SDL_SetRenderDrawColor(sdlren, 0, 0, 0, SDL_ALPHA_OPAQUE); + SDL_RenderClear(sdlren); + SDL_SetRenderDrawColor(sdlren, 255, 255, 255, SDL_ALPHA_OPAQUE); +} +void sdl_loop() { + SDL_Event event; + while (1) { + sdl_clear(); + ats_tredraw(); + SDL_RenderPresent(sdlren); + while (SDL_PollEvent(&event)) { + if (event.type == SDL_QUIT) { + return; + } + } + } +} +void sdl_quit() { + SDL_DestroyRenderer(sdlren); + SDL_DestroyWindow(sdlwin); + SDL_Quit(); +} + +void sdl_drawline(int x1, int y1, int x2, int y2) { + SDL_RenderDrawLine(sdlren, x1, y1, x2, y2); +} +%} diff --git a/Task/Sierpinski-triangle-Graphical/Erlang/sierpinski-triangle-graphical.erl b/Task/Sierpinski-triangle-Graphical/Erlang/sierpinski-triangle-graphical.erl new file mode 100644 index 0000000000..6912d73d22 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Erlang/sierpinski-triangle-graphical.erl @@ -0,0 +1,29 @@ +-module(sierpinski). +-author("zduchac"). +-export([start/0]). + +sierpinski(DC, Order) -> + Size = 1 bsl Order, + sierpinski(DC, Order, Size, 0, 0). + +sierpinski(_, _, Size, _, Y) when Y =:= Size -> + ok; +sierpinski(DC, Order, Size, X, Y) when X =:= Size -> + sierpinski(DC, Order, Size, 0, Y + 1); +sierpinski(DC, Order, Size, X, Y) when X band Y =:= 0 -> + wxDC:drawPoint(DC, {X, Y}), + sierpinski(DC, Order, Size, X + 1, Y); +sierpinski(DC, Order, Size, X, Y) -> + sierpinski(DC, Order, Size, X + 1, Y). + +start() -> + Wx = wx:new(), + Frame = wxFrame:new(Wx, -1, "Raytracer", []), + wxFrame:connect(Frame, paint, [{callback, + fun(_Evt, _Obj) -> + DC = wxPaintDC:new(Frame), + sierpinski(DC, 8), + wxPaintDC:destroy(DC) + end + }]), + wxFrame:show(Frame). diff --git a/Task/Sierpinski-triangle-Graphical/Julia/sierpinski-triangle-graphical.julia b/Task/Sierpinski-triangle-Graphical/Julia/sierpinski-triangle-graphical.julia new file mode 100644 index 0000000000..02f7d14c5e --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Julia/sierpinski-triangle-graphical.julia @@ -0,0 +1,21 @@ +using Luxor + +function sierpinski(txy, levelsyet) + nxy = zeros(6) + if levelsyet > 0 + for i in 1:6 + pos = i < 5 ? i + 2 : i - 4 + nxy[i] = (txy[i] + txy[pos]) / 2.0 + end + sierpinski([txy[1],txy[2],nxy[1],nxy[2],nxy[5],nxy[6]], levelsyet-1) + sierpinski([nxy[1],nxy[2],txy[3],txy[4],nxy[3],nxy[4]], levelsyet-1) + sierpinski([nxy[5],nxy[6],nxy[3],nxy[4],txy[5],txy[6]], levelsyet-1) + else + poly([Point(txy[1],txy[2]),Point(txy[3],txy[4]),Point(txy[5],txy[6])], :fill ,close=true) + end +end + +Drawing(800, 800) +sierpinski([400., 100., 700., 500., 100., 500.], 7) +finish() +preview() diff --git a/Task/Sierpinski-triangle-Graphical/Python/sierpinski-triangle-graphical-1.py b/Task/Sierpinski-triangle-Graphical/Python/sierpinski-triangle-graphical-1.py index 57dda5208a..3a50c05e89 100644 --- a/Task/Sierpinski-triangle-Graphical/Python/sierpinski-triangle-graphical-1.py +++ b/Task/Sierpinski-triangle-Graphical/Python/sierpinski-triangle-graphical-1.py @@ -1,20 +1,9 @@ -#!/usr/bin/env python -########################################################################################## -# import necessary modules -# ------------------------ -from numpy import * -import turtle - -########################################################################################## -# Functions defining the drawing actions -# (used by the function DrawSierpinskiTriangle). -# ---------------------------------------------- -def Left(turn, point, fwd, angle, turt): - turt.left(angle) - return [turn, point, fwd, angle, turt] -def Right(turn, point, fwd, angle, turt): - turt.right(angle) - return [turn, point, fwd, angle, turt] -def Forward(turn, point, fwd, angle, turt): - turt.forward(fwd) - return [turn, point, fwd, angle, turt] +# likely the simplest possible version? +import turtle as t +def sier(n,length): + if (n==0): + return + for i in range(3): + sier(n-1, length/2) + t.fd(length) + t.rt(120) diff --git a/Task/Sierpinski-triangle-Graphical/Python/sierpinski-triangle-graphical-2.py b/Task/Sierpinski-triangle-Graphical/Python/sierpinski-triangle-graphical-2.py index 172ab41e55..4c456d835e 100644 --- a/Task/Sierpinski-triangle-Graphical/Python/sierpinski-triangle-graphical-2.py +++ b/Task/Sierpinski-triangle-Graphical/Python/sierpinski-triangle-graphical-2.py @@ -1,60 +1,21 @@ +#!/usr/bin/env python ########################################################################################## -# The drawing function -# -------------------- -# -# level level of Sierpinski triangle (minimum value = 1) -# ss screensize (Draws on a screen of size ss x ss. Default value = 400.) -#----------------------------------------------------------------------------------------- -def DrawSierpinskiTriangle(level, ss=400): - # typical values - turn = 0 # initial turn (0 to start horizontally) - angle=60.0 # in degrees +# a very complicated version +# import necessary modules +# ------------------------ +from numpy import * +import turtle - # Initialize the turtle - turtle.hideturtle() - turtle.screensize(ss,ss) - turtle.penup() - turtle.degrees() - - # The starting point on the canvas - fwd0 = float(ss) - point=array([-fwd0/2.0, -fwd0/2.0]) - - # Setting up the Lindenmayer system - # Assuming that the triangle will be drawn in the following way: - # 1.) Start at a point - # 2.) Draw a straight line - the horizontal line (H) - # 3.) Bend twice by 60 degrees to the left (--) - # 4.) Draw a straight line - the slanted line (X) - # 5.) Bend twice by 60 degrees to the left (--) - # 6.) Draw a straight line - another slanted line (X) - # This produces the triangle in the first level. (so the axiom to begin with is H--X--X) - # 7.) For the next level replace each horizontal line using - # X->XX - # H -> H--X++H++X--H - # The lengths will be halved. - - - decode = {'-':Left, '+':Right, 'X':Forward, 'H':Forward} - axiom = 'H--X--X' - - # Start the drawing - turtle.goto(point[0], point[1]) - turtle.pendown() - turtle.hideturtle() - turt=turtle.getpen() - startposition=turt.clone() - - # Get the triangle in the Lindenmayer system - fwd = fwd0/(2.0**level) - path = axiom - for i in range(0,level): - path=path.replace('X','XX') - path=path.replace('H','H--X++H++X--H') - - # Draw it. - for i in path: - [turn, point, fwd, angle, turt]=decode[i](turn, point, fwd, angle, turt) ########################################################################################## - -DrawSierpinskiTriangle(5) +# Functions defining the drawing actions +# (used by the function DrawSierpinskiTriangle). +# ---------------------------------------------- +def Left(turn, point, fwd, angle, turt): + turt.left(angle) + return [turn, point, fwd, angle, turt] +def Right(turn, point, fwd, angle, turt): + turt.right(angle) + return [turn, point, fwd, angle, turt] +def Forward(turn, point, fwd, angle, turt): + turt.forward(fwd) + return [turn, point, fwd, angle, turt] diff --git a/Task/Sierpinski-triangle-Graphical/Python/sierpinski-triangle-graphical-3.py b/Task/Sierpinski-triangle-Graphical/Python/sierpinski-triangle-graphical-3.py new file mode 100644 index 0000000000..172ab41e55 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Python/sierpinski-triangle-graphical-3.py @@ -0,0 +1,60 @@ +########################################################################################## +# The drawing function +# -------------------- +# +# level level of Sierpinski triangle (minimum value = 1) +# ss screensize (Draws on a screen of size ss x ss. Default value = 400.) +#----------------------------------------------------------------------------------------- +def DrawSierpinskiTriangle(level, ss=400): + # typical values + turn = 0 # initial turn (0 to start horizontally) + angle=60.0 # in degrees + + # Initialize the turtle + turtle.hideturtle() + turtle.screensize(ss,ss) + turtle.penup() + turtle.degrees() + + # The starting point on the canvas + fwd0 = float(ss) + point=array([-fwd0/2.0, -fwd0/2.0]) + + # Setting up the Lindenmayer system + # Assuming that the triangle will be drawn in the following way: + # 1.) Start at a point + # 2.) Draw a straight line - the horizontal line (H) + # 3.) Bend twice by 60 degrees to the left (--) + # 4.) Draw a straight line - the slanted line (X) + # 5.) Bend twice by 60 degrees to the left (--) + # 6.) Draw a straight line - another slanted line (X) + # This produces the triangle in the first level. (so the axiom to begin with is H--X--X) + # 7.) For the next level replace each horizontal line using + # X->XX + # H -> H--X++H++X--H + # The lengths will be halved. + + + decode = {'-':Left, '+':Right, 'X':Forward, 'H':Forward} + axiom = 'H--X--X' + + # Start the drawing + turtle.goto(point[0], point[1]) + turtle.pendown() + turtle.hideturtle() + turt=turtle.getpen() + startposition=turt.clone() + + # Get the triangle in the Lindenmayer system + fwd = fwd0/(2.0**level) + path = axiom + for i in range(0,level): + path=path.replace('X','XX') + path=path.replace('H','H--X++H++X--H') + + # Draw it. + for i in path: + [turn, point, fwd, angle, turt]=decode[i](turn, point, fwd, angle, turt) +########################################################################################## + +DrawSierpinskiTriangle(5) diff --git a/Task/Sierpinski-triangle/Julia/sierpinski-triangle.julia b/Task/Sierpinski-triangle/Julia/sierpinski-triangle.julia index d6d6152bdc..aa052aff70 100644 --- a/Task/Sierpinski-triangle/Julia/sierpinski-triangle.julia +++ b/Task/Sierpinski-triangle/Julia/sierpinski-triangle.julia @@ -1,13 +1,18 @@ -pprint(matrix) = for i = 1:size(matrix,1) println(join(matrix[i,:])) end -spaces(m,n) = [" " for i=1:m, j=1:n] - -function sierpinski(n) - x = ["*" for i=1:1, j=1:1] - for i = 1:n - h,w = size(x) - s = spaces(h,(w+1)/2) - t = spaces(h,1) - x = [[s x s] ; [x t x]] - end - x +function sierpinski(n, token::AbstractString="*") + x = fill(token, 1, 1) + for _ in 1:n + h, w = size(x) + s = fill(" ", h,(w + 1) ÷ 2) + t = fill(" ", h,1) + x = [[s x s] ; [x t x]] + end + return x end + +function printsierpinski(m::Matrix) + for r in 1:size(m, 1) + println(join(m[r, :])) + end +end + +sierpinski(4) |> printsierpinski diff --git a/Task/Sierpinski-triangle/MATLAB/sierpinski-triangle-3.m b/Task/Sierpinski-triangle/MATLAB/sierpinski-triangle-3.m new file mode 100644 index 0000000000..172380d3f1 --- /dev/null +++ b/Task/Sierpinski-triangle/MATLAB/sierpinski-triangle-3.m @@ -0,0 +1 @@ +spy(mod(abs(pascal(32,1)),2)==1) diff --git a/Task/Sieve-of-Eratosthenes/C++/sieve-of-eratosthenes-1.cpp b/Task/Sieve-of-Eratosthenes/C++/sieve-of-eratosthenes-1.cpp index 23ba066f33..68427298b0 100644 --- a/Task/Sieve-of-Eratosthenes/C++/sieve-of-eratosthenes-1.cpp +++ b/Task/Sieve-of-Eratosthenes/C++/sieve-of-eratosthenes-1.cpp @@ -1,20 +1,47 @@ -// yield all prime numbers less than limit. -template -void primesupto(int limit, UnaryFunction yield) +#include +#include +#include + +template +size_t prime_sieve(ForwardIterator start, ForwardIterator end) { - std::vector is_prime(limit, true); - - const int sqrt_limit = static_cast(std::sqrt(limit)); - for (int n = 2; n <= sqrt_limit; ++n) - if (is_prime[n]) { - yield(n); - - for (unsigned k = n*n, ulim = static_cast(limit); k < ulim; k += n) - //NOTE: "unsigned" is used to avoid an overflow in `k+=n` for `limit` near INT_MAX - is_prime[k] = false; + if (start == end) return 0; + // clear the container with 0 + std::fill(start, end, 0); + // mark composites with 1 + for (ForwardIterator prime_it = start + 1; prime_it != end; ++prime_it) + { + if (*prime_it == 1) continue; + // determine the prime number represented by this iterator location + size_t stride = (prime_it - start) + 1; + // mark all multiples of this prime number up to max + ForwardIterator mark_it = prime_it; + while ((end - mark_it) > stride) + { + std::advance(mark_it, stride); + *mark_it = 1; + } } - - for (int n = sqrt_limit + 1; n < limit; ++n) - if (is_prime[n]) - yield(n); + // copy marked primes into container + ForwardIterator out_it = start; + for (ForwardIterator it = start + 1; it != end; ++it) + { + if (*it == 0) + { + *out_it = (it - start) + 1; + ++out_it; + } + } + return out_it - start; +} + +int main(int argc, const char* argv[]) +{ + std::vector primes(100); + size_t count = prime_sieve(primes.begin(), primes.end()); + // display the primes + for (size_t i = 0; i < count; ++i) + std::cout << primes[i] << " "; + std::cout << std::endl; + return 1; } diff --git a/Task/Sieve-of-Eratosthenes/C++/sieve-of-eratosthenes-2.cpp b/Task/Sieve-of-Eratosthenes/C++/sieve-of-eratosthenes-2.cpp index 9c213d01c0..23ba066f33 100644 --- a/Task/Sieve-of-Eratosthenes/C++/sieve-of-eratosthenes-2.cpp +++ b/Task/Sieve-of-Eratosthenes/C++/sieve-of-eratosthenes-2.cpp @@ -1,42 +1,20 @@ -/** - $ g++ -I/path/to/boost sieve.cpp -o sieve && sieve 10000000 - */ -#include // uintmax_t -#include -#include -#include -#include -#include - -#include - - -int main(int argc, char *argv[]) +// yield all prime numbers less than limit. +template +void primesupto(int limit, UnaryFunction yield) { - using namespace std; - using namespace boost::lambda; + std::vector is_prime(limit, true); - int limit = 10000; - if (argc == 2) { - stringstream ss(argv[--argc]); - ss >> limit; + const int sqrt_limit = static_cast(std::sqrt(limit)); + for (int n = 2; n <= sqrt_limit; ++n) + if (is_prime[n]) { + yield(n); - if (limit < 1 or ss.fail()) { - cerr << "USAGE:\n sieve LIMIT\n\nwhere LIMIT in the range [1, " - << numeric_limits::max() << ")" << endl; - return 2; + for (unsigned k = n*n, ulim = static_cast(limit); k < ulim; k += n) + //NOTE: "unsigned" is used to avoid an overflow in `k+=n` for `limit` near INT_MAX + is_prime[k] = false; } - } - // print primes less then 100 - primesupto(100, cout << _1 << " "); - cout << endl; - - // find number of primes less then limit and their sum - int count = 0; - uintmax_t sum = 0; - primesupto(limit, (var(sum) += _1, var(count) += 1)); - - cout << "limit sum pi(n)\n" - << limit << " " << sum << " " << count << endl; + for (int n = sqrt_limit + 1; n < limit; ++n) + if (is_prime[n]) + yield(n); } diff --git a/Task/Sieve-of-Eratosthenes/C++/sieve-of-eratosthenes-3.cpp b/Task/Sieve-of-Eratosthenes/C++/sieve-of-eratosthenes-3.cpp new file mode 100644 index 0000000000..38fb138acd --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/C++/sieve-of-eratosthenes-3.cpp @@ -0,0 +1,41 @@ +/** + $ g++ -I/path/to/boost sieve.cpp -o sieve && sieve 10000000 + */ +#include // uintmax_t +#include +#include +#include +#include +#include + +#include + +int main(int argc, char *argv[]) +{ + using namespace std; + using namespace boost::lambda; + + int limit = 10000; + if (argc == 2) { + stringstream ss(argv[--argc]); + ss >> limit; + + if (limit < 1 or ss.fail()) { + cerr << "USAGE:\n sieve LIMIT\n\nwhere LIMIT in the range [1, " + << numeric_limits::max() << ")" << endl; + return 2; + } + } + + // print primes less then 100 + primesupto(100, cout << _1 << " "); + cout << endl; + + // find number of primes less then limit and their sum + int count = 0; + uintmax_t sum = 0; + primesupto(limit, (var(sum) += _1, var(count) += 1)); + + cout << "limit sum pi(n)\n" + << limit << " " << sum << " " << count << endl; +} diff --git a/Task/Sieve-of-Eratosthenes/C/sieve-of-eratosthenes-2.c b/Task/Sieve-of-Eratosthenes/C/sieve-of-eratosthenes-2.c index 4fb0a8523d..5dff65007d 100644 --- a/Task/Sieve-of-Eratosthenes/C/sieve-of-eratosthenes-2.c +++ b/Task/Sieve-of-Eratosthenes/C/sieve-of-eratosthenes-2.c @@ -5,7 +5,7 @@ void sieve(int *, int); int main(int argc, char *argv) { int *array, n=10; - array =(int *)malloc(sizeof(int)); + array =(int *)malloc((n + 1) * sizeof(int)); sieve(array,n); return 0; } diff --git a/Task/Sieve-of-Eratosthenes/Common-Lisp/sieve-of-eratosthenes-2.lisp b/Task/Sieve-of-Eratosthenes/Common-Lisp/sieve-of-eratosthenes-2.lisp index bb21ec1457..84aa2c1168 100644 --- a/Task/Sieve-of-Eratosthenes/Common-Lisp/sieve-of-eratosthenes-2.lisp +++ b/Task/Sieve-of-Eratosthenes/Common-Lisp/sieve-of-eratosthenes-2.lisp @@ -1,10 +1,14 @@ -(defun sieve-odds (maximum) "sieve for odd numbers" - (cons 2 - (let ((maxi (ash (1- maximum) -1)) (stop (ash (isqrt maximum) -1))) - (let ((sieve (make-array (1+ maxi) :element-type 'bit :initial-element 0))) - (loop for i from 1 to maxi - when (zerop (sbit sieve i)) - collect (1+ (ash i 1)) - and when (<= i stop) do - (loop for j from (ash (* i (1+ i)) 1) to maxi by (1+ (ash i 1)) - do (setf (sbit sieve j) 1))))))) +(defun sieve-odds (maximum) + "Prime numbers sieve for odd numbers. + Returns a list with all the primes that are less than or equal to maximum." + (loop :with maxi = (ash (1- maximum) -1) + :with stop = (ash (isqrt maximum) -1) + :with sieve = (make-array (1+ maxi) :element-type 'bit :initial-element 0) + :for i :from 1 :to maxi + :for odd-number = (1+ (ash i 1)) + :when (zerop (sbit sieve i)) + :collect odd-number :into values + :when (<= i stop) + :do (loop :for j :from (* i (1+ i) 2) :to maxi :by odd-number + :do (setf (sbit sieve j) 1)) + :finally (return (cons 2 values)))) diff --git a/Task/Sieve-of-Eratosthenes/Go/sieve-of-eratosthenes-6.go b/Task/Sieve-of-Eratosthenes/Go/sieve-of-eratosthenes-6.go new file mode 100644 index 0000000000..ac4b859a70 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Go/sieve-of-eratosthenes-6.go @@ -0,0 +1,58 @@ +package main + +import "fmt" + +func main() { + primes := make(chan int) + go PrimeSieve(primes) + + p := <-primes + for p < 100 { + fmt.Printf("%d ", p) + p = <-primes + } + + fmt.Println() +} + +func PrimeSieve(out chan int) { + out <- 2 + out <- 3 + + primes := make(chan int) + go PrimeSieve(primes) + + var p int + p = <-primes + p = <-primes + + sieve := make(map[int]int) + q := p * p + n := p + + for { + n += 2 + step, isComposite := sieve[n] + if isComposite { + delete(sieve, n) + m := n + step + for sieve[m] != 0 { + m += step + } + sieve[m] = step + + } else if n < q { + out <- n + + } else { + step = p + p + m := n + step + for sieve[m] != 0 { + m += step + } + sieve[m] = step + p = <-primes + q = p * p + } + } +} diff --git a/Task/Sieve-of-Eratosthenes/Limbo/sieve-of-eratosthenes.limbo b/Task/Sieve-of-Eratosthenes/Limbo/sieve-of-eratosthenes.limbo new file mode 100644 index 0000000000..3d14e43828 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Limbo/sieve-of-eratosthenes.limbo @@ -0,0 +1,40 @@ +implement Sieve; + +include "sys.m"; + sys: Sys; + print: import sys; +include "draw.m"; + draw: Draw; + +Sieve : module +{ + init : fn(ctxt : ref Draw->Context, args : list of string); +}; + +init (ctxt: ref Draw->Context, args: list of string) +{ + sys = load Sys Sys->PATH; + + limit := 201; + sieve : array of int; + sieve = array [201] of {* => 1}; + (sieve[0], sieve[1]) = (0, 0); + + for (n := 2; n < limit; n++) { + if (sieve[n]) { + for (i := n*n; i < limit; i += n) { + sieve[i] = 0; + } + } + } + + for (n = 1; n < limit; n++) { + if (sieve[n]) { + print ("%4d", n); + } else { + print(" ."); + }; + if ((n%20) == 0) + print("\n\n"); + } +} diff --git a/Task/Sieve-of-Eratosthenes/Lingo/sieve-of-eratosthenes-1.lingo b/Task/Sieve-of-Eratosthenes/Lingo/sieve-of-eratosthenes-1.lingo new file mode 100644 index 0000000000..aa83615534 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Lingo/sieve-of-eratosthenes-1.lingo @@ -0,0 +1,41 @@ +-- parent script "sieve" +property _sieve + +---------------------------------------- +-- @constructor +---------------------------------------- +on new (me) + me._sieve = [] + return me +end + +---------------------------------------- +-- Returns list of primes <= n +---------------------------------------- +on getPrimes (me, limit) + if me._sieve.count cull its composites - for i in countup((n *% n), limit+1, n): # start at ``n`` squared - is_cmpsts[i] = true +iterator primesUpto(limit: int): int = + let sqrtLimit = int(sqrt(float64(limit))) + var composites = newSeq[bool](limit + 1) + composites[0] = true + composites[1] = true + for n in 2 .. sqrtLimit: # cull to square root of limit + if not composites[n]: # if prime -> cull its composites + for i in countup(n *% n, limit + 1, n): # start at ``n`` squared + composites[i] = true for n in 2 .. limit: # separate iteration over results - if not is_cmpsts[n]: + if not composites[n]: yield n echo("Primes are:") -for x in iprimes_upto(100): +for x in primesUpto(100): write(stdout, x, " ") echo "" var count = 0 -for p in iprimes_upto(1000000): +for p in primesUpto(1000000): count += 1 -writeLine stdout, "There are ", count, " primes up to 1000000." +echo "There are ", count, " primes up to 1000000." diff --git a/Task/Sieve-of-Eratosthenes/SAS/sieve-of-eratosthenes.sas b/Task/Sieve-of-Eratosthenes/SAS/sieve-of-eratosthenes.sas new file mode 100644 index 0000000000..6b38f0bcc1 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/SAS/sieve-of-eratosthenes.sas @@ -0,0 +1,17 @@ +proc iml; +start sieve(n); + a = J(n,1); + a[1] = 0; + do i = 1 to n; + if a[i] then do; + if i*i>n then return(a); + a[i*(i:int(n/i))] = 0; + end; + end; +finish; + +a = loc(sieve(1000))`; +create primes from a; +append from a; +close primes; +quit; diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-8.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-8.ss index 2f8f49543a..9355360f1c 100644 --- a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-8.ss +++ b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-8.ss @@ -1,5 +1,5 @@ (define (sieve s) (let ((p (head s))) (s-cons p - (sieve (s-diff (tail s) (from-By (+ p p) p)))))) + (sieve (s-diff s (from-By p p)))))) (define primes (sieve (from-By 2 1))) diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-9.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-9.ss index 3b1a770acc..a18d56feff 100644 --- a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-9.ss +++ b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-9.ss @@ -1,7 +1,8 @@ (define (primes-To m) (define (sieve s) - (let ((p (head s))) - (cond ((> (* p p) m) s) - (else (s-cons p - (sieve (s-diff (tail s) (from-By (* p p) p)))))))) + (let ((p (head s))) + (cond ((> (* p p) m) s) + (else (s-cons p + (sieve (s-diff (tail s) + (from-By (* p p) p)))))))) (sieve (from-By 2 1))) diff --git a/Task/Sieve-of-Eratosthenes/Stata/sieve-of-eratosthenes-1.stata b/Task/Sieve-of-Eratosthenes/Stata/sieve-of-eratosthenes-1.stata index f82e0bc338..6a1f8d09ee 100644 --- a/Task/Sieve-of-Eratosthenes/Stata/sieve-of-eratosthenes-1.stata +++ b/Task/Sieve-of-Eratosthenes/Stata/sieve-of-eratosthenes-1.stata @@ -1,22 +1,20 @@ -program sieve +prog def sieve + args n clear - quietly set obs `1' + qui set obs `n' gen long p=_n gen byte a=_n>1 - local i=2 - while 1 { + forv i=2/`n' { if a[`i'] { - local j=`i'*`i' - if `j'>`1' { + loc j=`i'*`i' + if `j'>`n' { continue, break } - while `j'<=`1' { - quietly replace a=0 in `j' - local j=`j'+`i' + forv k=`j'(`i')`n' { + qui replace a=0 in `k' } } - local ++i } - quietly keep if a + qui keep if a drop a end diff --git a/Task/Simple-database/Kotlin/simple-database.kotlin b/Task/Simple-database/Kotlin/simple-database.kotlin new file mode 100644 index 0000000000..2eb57ec0ec --- /dev/null +++ b/Task/Simple-database/Kotlin/simple-database.kotlin @@ -0,0 +1,110 @@ +// version 1.2.31 + +import java.text.SimpleDateFormat +import java.util.Date +import java.io.File +import java.io.IOException + +val file = File("simdb.csv") + +class Item( + val name: String, + val date: String, + val category: String +) : Comparable { + + override fun compareTo(other: Item) = date.compareTo(other.date) + + override fun toString() = "$name, $date, $category" +} + +fun addItem(input: Array) { + if (input.size < 2) { + printUsage() + return + } + val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") + val date = sdf.format(Date()) + val cat = if (input.size == 3) input[2] else "none" + store(Item(input[1], date, cat)) +} + +fun printLatest(a: Array) { + val db = load() + if (db.isEmpty()) { + println("No entries in database.") + return + } + // no need to sort db as items are added chronologically + if (a.size == 2) { + var found = false + for (item in db.reversed()) { + if (item.category == a[1]) { + println(item) + found = true + break + } + } + if (!found) println("There are no items for category '${a[1]}'") + } + else println(db[db.lastIndex]) +} + +fun printAll() { + val db = load() + if (db.isEmpty()) { + println("No entries in database.") + return + } + // no need to sort db as items are added chronologically + for (item in db) println(item) +} + +fun load(): MutableList { + val db = mutableListOf() + try { + file.forEachLine { line -> + val item = line.split(", ") + db.add(Item(item[0], item[1], item[2])) + } + } + catch (e: IOException) { + println(e) + System.exit(1) + } + return db +} + +fun store(item: Item) { + try { + file.appendText("$item\n") + } + catch (e: IOException) { + println(e) + } +} + +fun printUsage() { + println(""" + |Usage: + | simdb cmd [categoryName] + | add add item, followed by optional category + | latest print last added item(s), followed by optional category + | all print all + | For instance: add "some item name" "some category name" + """.trimMargin()) +} + +fun main(args: Array) { + if (args.size !in 1..3) { + printUsage() + return + } + file.createNewFile() // create file if it doesn't already exist + when (args[0].toLowerCase()) { + "add" -> addItem(args) + "latest" -> printLatest(args) + "all" -> printAll() + else -> printUsage() + } +} diff --git a/Task/Simple-database/Perl-6/simple-database-1.pl6 b/Task/Simple-database/Perl-6/simple-database-1.pl6 new file mode 100644 index 0000000000..64c5bcf4b5 --- /dev/null +++ b/Task/Simple-database/Perl-6/simple-database-1.pl6 @@ -0,0 +1,104 @@ +#!/usr/bin/env perl6 +use JSON::Fast ; +sub MAIN( :$server='0.0.0.0', :$port=3333, :$dbfile='db' ) { + my %db; + my %index; + my $dbdata = slurp "$dbfile.json" ; + my $indexdata = slurp "{$dbfile}_index.json" ; + %db = from-json($dbdata) if $dbdata ; + %index = from-json($indexdata) if $indexdata ; + react { + whenever IO::Socket::Async.listen( $server , $port ) -> $conn { + whenever $conn.Supply.lines -> $line { + my %response = 'status' => '' ; + my $msg = from-json $line ; + say $msg.perl ; + given $msg { + when 'set' { + %db{ $msg } = $msg ; + %response = 'ok' ; + %index = $msg ; + for %index.keys -> $key { + if $msg{$key} { + %index{ $key }{ $msg{$key} } = $msg ; + %index{ $key }{ $msg{$key} }{ $msg } = 1 ; + } + } + spurt "$dbfile.json", to-json(%db); + spurt "{$dbfile}_index.json", to-json(%index); + } + when 'get' { + %response = $msg ; + %response = %db{ $msg } ; + %response = 'ok' ; + } + when 'dump' { + %response{'data'} = %db ; + %response = 'ok' ; + } + when 'dumpindex' { + %response{'data'} = %index ; + %response = 'ok' ; + } + when 'delete' { + %db{ $msg }:delete; + %response = 'ok' ; + spurt "$dbfile.json", to-json(%db); + reindex(); + } + when 'addindex' { + %response = 'ok' ; + %index{ $msg} =1 ; + reindex(); + } + when 'reportlast' { + %response{'data'} = %db{%index} ; + %response = 'ok' ; + } + when 'reportlastindex' { + %response = $msg ; + for %index{$msg}.keys -> $value { + #%response{'data'}.push: %db{ %index{ $msg }{ $value } } ; + %response{'data'}{$value} = %db{ %index{ $msg }{ $value } } ; + } + %response = 'ok' ; + } + when 'reportindex' { + %response = 'ok' ; + for %index{$msg}.keys.sort -> $value { + for %index{ $msg }{ $value }.keys.sort -> $topic { + %response.push: %db{ $topic } ; + #%response{$value} = %db{ $topic } ; + } + } + } + when 'commit' { + spurt "$dbfile.json", to-json(%db); + spurt "{$dbfile}_index.json", to-json(%index); + %response = 'ok' ; + } + default { + %response = 'error'; + %response = 'no function or not supported'; + } + } + $conn.print( to-json(%response, :!pretty) ~ "\n" ) ; + LAST { $conn.close ; } + QUIT { default { $conn.close ; say "oh no, $_";}} + CATCH { default { say .^name, ': ', .Str , " handled in $?LINE";}} + } + } + } + sub reindex { + %index:delete; + for %db.keys -> $topic { + my $msg = %db{$topic} ; + for %index.keys -> $key { + if $msg{$key} { + %index{ $key }{ $msg{$key} }{ $topic } = 1 ; + } + } + } + spurt "{$dbfile}_index.json", to-json(%index) ; + } +} diff --git a/Task/Simple-database/Perl-6/simple-database-2.pl6 b/Task/Simple-database/Perl-6/simple-database-2.pl6 new file mode 100644 index 0000000000..368139ad22 --- /dev/null +++ b/Task/Simple-database/Perl-6/simple-database-2.pl6 @@ -0,0 +1,50 @@ +#!/usr/bin/env perl6 +use JSON::Fast ; +multi MAIN('set', $topic, $message='', :$server='localhost', :$port='3333', :$json='') { + my %msg = function => 'set' , topic=> $topic , message=> $message ; + %msg{"message"} = from-json( $json ) if $json ; + sendmsg( %msg , $server, $port) ; +} +multi MAIN('add', $topic, $json, :$server='localhost', :$port='3333' ) { + my %msg = function => 'set' , topic=> $topic; + %msg{"message"} = from-json( $json ) if $json ; + sendmsg( %msg , $server, $port) ; +} +multi MAIN('get', $topic, :$server='localhost', :$port='3333') { + my %msg = function => 'get' , topic=> $topic ; + sendmsg( %msg , $server, $port) ; +} +multi MAIN('delete', $topic, :$server='localhost', :$port='3333') { + my %msg = function => 'delete' , topic=> $topic ; + sendmsg( %msg , $server, $port) ; +} +multi MAIN('dump', :$server='localhost', :$port='3333') { + my %msg = function => 'dump' ; + sendmsg( %msg , $server, $port) ; +} +multi MAIN('addindex', $key, :$server='localhost', :$port='3333') { + my %msg = function => 'addindex', key => $key ; + sendmsg( %msg , $server, $port) ; +} +multi MAIN('reportindex', $key, :$server='localhost', :$port='3333') { + my %msg = function => 'reportindex', key => $key ; + sendmsg( %msg , $server, $port) ; +} +multi MAIN('reportlastindex', $key, :$server='localhost', :$port='3333') { + my %msg = function => 'reportlastindex', key => $key ; + sendmsg( %msg , $server, $port) ; +} +multi MAIN('reportlast', :$server='localhost', :$port='3333') { + my %msg = function => 'reportlast' ; + sendmsg( %msg , $server, $port) ; +} +sub sendmsg( %msg , $server, $port){ + my $conn = await IO::Socket::Async.connect( $server , $port ); + $conn.print: to-json( %msg,:!pretty)~"\n"; + react { + whenever $conn.Supply -> $data { + print $data; + $conn.close; + } + } +} diff --git a/Task/Simple-database/Perl/simple-database.pl b/Task/Simple-database/Perl/simple-database.pl new file mode 100644 index 0000000000..e2d7761cb0 --- /dev/null +++ b/Task/Simple-database/Perl/simple-database.pl @@ -0,0 +1,118 @@ +#!/usr/bin/perl +use warnings; +use strict; +use feature qw{ say }; + +use JSON::PP; +use Time::Piece; + +use constant { + NAME => 0, + CATEGORY => 1, + DATE => 2, + DB => 'simple-db', +}; + +my $operation = shift // ""; + +my %dispatch = ( + n => \&add_new, + l => \&print_latest, + L => \&print_latest_for_categories, + a => \&print_all, +); + +if ($dispatch{$operation}) { + $dispatch{$operation}->(@ARGV); +} else { + die "Invalid option. Use one of n, l, L, a.\n" +} + +sub add_new { + my ($name, $category, $date) = @_; + my $db = eval { load() } || {}; + if (defined $date) { + eval { 'Time::Piece'->strptime($date, '%Y-%m-%d'); 1 } + or die "Invalid date format: YYYY-MM-DD.\n"; + + } else { + $date //= localtime->ymd; + } + + my @ids = keys %{ $db->{by_id} }; + my $max_id = max(num => @ids) || 0; + $db->{by_id}{ ++$max_id } = [ $name, $category, $date ]; + save($db); +} + +sub print_latest { + build_indexes( my $db = load(), 0, 1 ); + _print_latest($db); +} + +sub _print_latest { + my ($db, $category) = @_; + my @dates = keys %{ $db->{by_date} }; + @dates = grep { + grep $db->{by_id}{$_}[CATEGORY] eq $category, + @{ $db->{by_date}{$_} }; + } @dates if defined $category; + + my $last_date = max(str => @dates); + say for map $db->{by_id}{$_}[NAME], + grep ! defined $category + || $db->{by_id}{$_}[CATEGORY] eq $category, + @{ $db->{by_date}{$last_date} }; +} + +sub max { + my $type = shift; + my $max = $_[0]; + { num => sub { $_ > $max }, + str => sub { $_ gt $max}, + }->{$type}->() and $max = $_ + for @_[ 1 .. $#_ ]; + return $max +} + +sub print_latest_for_categories { + build_indexes( my $db = load(), 1, 1 ); + + for my $category (sort keys %{ $db->{by_category} }){ + say "* $category"; + _print_latest($db, $category); + } +} + +sub print_all { + build_indexes( my $db = load(), 0, 1 ); + + for my $date (sort keys %{ $db->{by_date} }) { + for my $id (@{ $db->{by_date}{$date} }) { + say $db->{by_id}{$id}[NAME]; + } + } +} + +sub load { + open my $in, '<', DB or die "Can't open database: $!\n"; + local $/; + return { by_id => decode_json(<$in>) }; +} + +sub save { + my ($db) = @_; + open my $out, '>', DB or die "Can't save database: $!\n"; + print {$out} encode_json($db->{by_id}); + close $out; +} + +sub build_indexes { + my ($db, $by_category, $by_date) = @_; + for my $id (keys %{ $db->{by_id} }) { + push @{ $db->{by_category}{ $db->{by_id}{$id}[CATEGORY] } }, $id + if $by_category; + push @{ $db->{by_date}{ $db->{by_id}{$id}[DATE] } }, $id + if $by_date; + } +} diff --git a/Task/Simple-windowed-application/Factor/simple-windowed-application.factor b/Task/Simple-windowed-application/Factor/simple-windowed-application.factor new file mode 100644 index 0000000000..d63a415bfa --- /dev/null +++ b/Task/Simple-windowed-application/Factor/simple-windowed-application.factor @@ -0,0 +1,27 @@ +USING: accessors arrays kernel math math.parser namespaces +sequences ui ui.gadgets ui.gadgets.borders ui.gadgets.buttons +ui.gadgets.grids ui.gadgets.labels ui.gadgets.worlds ; +IN: rosetta-code.simple-windowed-application + +SYMBOL: n + +CONSTANT: on-btn-press [ + parents second n get number>string
 1991-03-30	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1
 1991-03-31	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	20.000	1	20.000	1	20.000	1	35.000	1	50.000	1	60.000	1	40.000	1	30.000	1	30.000	1	30.000	1	25.000	1	20.000	1	20.000	1	20.000	1	20.000	1	20.000	1	35.000	1
diff --git a/Task/Text-processing-1/Aime/text-processing-1.aime b/Task/Text-processing-1/Aime/text-processing-1.aime
index 2165338a8c..b8519da952 100644
--- a/Task/Text-processing-1/Aime/text-processing-1.aime
+++ b/Task/Text-processing-1/Aime/text-processing-1.aime
@@ -4,45 +4,32 @@ list l;
 real s;
 text bad_day, worst_day;
 
-f_affix(f, "/dev/stdin");
+f.stdin;
 
-max_bads = 0;
-count = 0;
-bads = 0;
-s = 0;
+max_bads = count = bads = s = 0;
 
-while (f_list(f, l, 0) ^ -1) {
-    integer e, i;
+while (f.list(l, 0) ^ -1) {
+    integer i;
 
     i = 2;
     while (i < 49) {
-	e = atoi(l_q_text(l, i));
-	if (0 < e) {
-	    count += 1;
-	    s += atof(l_q_text(l, i - 1));
-	    if (max_bads < bads) {
-		max_bads = bads;
-		worst_day = bad_day;
-	    }
-	    bads = 0;
-	} else {
-	    if (!bads) {
-		bad_day = l_q_text(l, 0);
-	    }
-	    bads += 1;
-	}
-	i += 2;
+        if (0 < atoi(l[i])) {
+            count += 1;
+            s += atof(l[i - 1]);
+            if (max_bads < bads) {
+                max_bads = bads;
+                worst_day = bad_day;
+            }
+            bads = 0;
+        } else {
+            if (!bads) {
+                bad_day = l[0];
+            }
+            bads += 1;
+        }
+        i += 2;
     }
 }
 
-o_text("Averaged ");
-o_real(3, s / count);
-o_text(" over ");
-o_integer(count);
-o_text(" readings.\n");
-
-o_text("Longest bad run ");
-o_integer(max_bads);
-o_text(", started ");
-o_text(worst_day);
-o_text(".\n");
+o_form("Averaged /d3/ over ~ readings.\n", s / count, count);
+o_("Longest bad run ", max_bads, ", started ", worst_day, ".\n");
diff --git a/Task/Text-processing-1/Julia/text-processing-1.julia b/Task/Text-processing-1/Julia/text-processing-1.julia
new file mode 100644
index 0000000000..2adb7b9e50
--- /dev/null
+++ b/Task/Text-processing-1/Julia/text-processing-1.julia
@@ -0,0 +1,54 @@
+using DataFrames
+
+function mungdata(filename)
+    lines = readlines(filename)
+    numlines = length(lines)
+    dates = Array{DateTime, 1}(numlines)
+    means = zeros(Float64, numlines)
+    numvalid = zeros(Int, numlines)
+    invalidlength = zeros(Int, numlines)
+    invalidpos = zeros(Int, numlines)
+    datamatrix = Array{Float64,2}(numlines, 24)
+    datamatrix .= NaN
+    totalsum = 0.0
+    totalgood = 0
+    for (linenum,line) in enumerate(lines)
+        data = split(line)
+        validcount = badlength = 0
+        validsum = 0.0
+        for i in 2:2:length(data)-1
+            if parse(Int, data[i+1]) >= 0
+                validsum += (datamatrix[linenum, Int(i/2)] = parse(Float64, data[i]))
+                validcount += 1
+                badlength = 0
+            else
+                badlength += 1
+                if badlength > invalidlength[linenum]
+                    invalidlength[linenum] = badlength
+                    invalidpos[linenum] = Int(i/2) - invalidlength[linenum] + 1
+                end
+            end
+        end
+        dates[linenum] = DateTime(data[1], "y-m-d")
+        means[linenum] = validsum / validcount
+        numvalid[linenum] = validcount
+        totalsum += validsum
+        totalgood += validcount
+    end
+    dt = DataFrame(Date = dates, Mean = means, ValidValues = numvalid,
+                   MaximumGap = invalidlength, GapPosition = invalidpos)
+    for i in 1:size(datamatrix)[2]
+        dt[Symbol("$(i-1):00")] = datamatrix[:,i]
+    end
+    dt, totalsum/totalgood
+end
+
+datafilename = "data.txt" # this is taken from the example listed on the task, since the actual text file is not available
+df, dmean = mungdata(datafilename)
+println(df)
+println("The overall mean is $dmean")
+maxbadline = indmax(df[:MaximumGap])
+maxbadval = df[:MaximumGap][maxbadline]
+maxbadtime = df[:GapPosition][maxbadline] - 1
+maxbaddate = replace("$(df[:Date][maxbadline])", r"T.+$", "")
+println("The largest run of bad values is $(maxbadval), on $(maxbaddate) beginning at $(maxbadtime):00 hours.")
diff --git a/Task/Text-processing-1/Kotlin/text-processing-1.kotlin b/Task/Text-processing-1/Kotlin/text-processing-1.kotlin
new file mode 100644
index 0000000000..bdd3bf65d2
--- /dev/null
+++ b/Task/Text-processing-1/Kotlin/text-processing-1.kotlin
@@ -0,0 +1,51 @@
+// version 1.2.31
+
+import java.io.File
+
+fun main(args: Array) {
+    val rx = Regex("""\s+""")
+    val file = File("readings.txt")
+    val fmt = "Line:  %s  Reject: %2d  Accept: %2d  Line_tot: %7.3f  Line_avg: %7.3f"
+    var grandTotal = 0.0
+    var readings = 0
+    var date = ""
+    var run = 0
+    var maxRun = -1
+    var finishLine = ""
+    file.forEachLine { line ->
+        val fields = line.split(rx)
+        date = fields[0]
+        if (fields.size == 49) {
+            var accept = 0
+            var total = 0.0
+            for (i in 1 until fields.size step 2) {
+                if (fields[i + 1].toInt() >= 1) {
+                    accept++
+                    total += fields[i].toDouble()
+                    if (run > maxRun) {
+                        maxRun = run
+                        finishLine = date
+                    }
+                    run = 0
+                }
+                else run++
+            }
+            grandTotal += total
+            readings += accept
+            println(fmt.format(date, 24 - accept, accept, total, total / accept))
+        }
+        else println("Line:  $date does not have 49 fields and has been ignored")
+    }
+
+    if (run > maxRun) {
+        maxRun = run
+        finishLine = date
+    }
+    val average = grandTotal / readings
+    println("\nFile     = ${file.name}")
+    println("Total    = ${"%7.3f".format(grandTotal)}")
+    println("Readings = $readings")
+    println("Average  = ${"%-7.3f".format(average)}")
+    println("\nMaximum run of $maxRun consecutive false readings")
+    println("ends at line starting with date: $finishLine")
+}
diff --git a/Task/Text-processing-1/Phix/text-processing-1.phix b/Task/Text-processing-1/Phix/text-processing-1.phix
new file mode 100644
index 0000000000..15a1d56e40
--- /dev/null
+++ b/Task/Text-processing-1/Phix/text-processing-1.phix
@@ -0,0 +1,78 @@
+constant lines = split(data,'\n')
+
+include builtins\timedate.e
+
+integer count = 0,
+        max_count = 0,
+        ntot = 0
+atom readtot = 0
+timedate run_start, max_start
+
+procedure end_bad_run()
+    if count then
+        if count>max_count then
+            max_count = count
+            max_start = run_start
+        end if
+        count = 0
+    end if
+end procedure
+
+for i=1 to length(lines) do
+    sequence oneline = split(lines[i],no_empty:=true), r
+    if length(oneline)!=49 then
+        ?"bad line (length!=49)"
+    else
+        r = parse_date_string(oneline[1],{"YYYY-MM-DD"})
+        if not timedate(r) then
+            ?{"bad date",oneline[1]}
+        else
+            timedate td = r
+            integer rejects=0, accepts=0
+            atom readsum = 0
+            for j=2 to 48 by 2 do
+                r = scanf(oneline[j],"%f")
+                if length(r)!=1 then
+                    ?{"error scanning",oneline[j]}
+                    rejects += 1
+                else
+                    atom reading = r[1][1]
+                    r = scanf(oneline[j+1],"%d")
+                    if length(r)!=1 then
+                        ?{"error scanning",oneline[j+1]}
+                        rejects += 1
+                    else
+                        integer flag = r[1][1]
+                        if flag<=0 then
+                            if count=0 then
+                                run_start = td
+                            end if
+                            count += 1
+                            rejects += 1
+                        else
+                            end_bad_run()
+                            accepts += 1
+                            readsum += reading
+                        end if
+                    end if
+                end if
+            end for
+            if rejects=0 then
+                readtot += readsum
+                ntot += 1
+            end if
+--          readtot += readsum
+--          ntot += accepts
+            printf(1,"Date: %s, Rejects: %2d, Accepts: %2d, Line total: %7.3f, Average %6.3f\n",
+                   {format_timedate(td,"DD/MM/YYYY"),rejects, accepts, readsum, readsum/accepts})
+        end if
+    end if
+end for
+
+printf(1,"Average: %.3f (of %d entirely valid days)\n",{readtot/(24*ntot),ntot})
+--printf(1,"Average: %.3f\n",{readtot/ntot})
+end_bad_run()
+if max_count then
+    printf(1,"Maximum run of %d consecutive false readings starting: %s\n",
+            {max_count,format_timedate(max_start,"DD/MM/YYYY")})
+end if
diff --git a/Task/Text-processing-2/00DESCRIPTION b/Task/Text-processing-2/00DESCRIPTION
index e27ccc4042..5e72ec5968 100644
--- a/Task/Text-processing-2/00DESCRIPTION
+++ b/Task/Text-processing-2/00DESCRIPTION
@@ -4,7 +4,9 @@ The fields (from the left) are:
   DATESTAMP [ VALUEn FLAGn ] * 24
 i.e. a datestamp followed by twenty-four repetitions of a floating-point instrument value and that instrument's associated integer flag. Flag values are >= 1 if the instrument is working and < 1 if there is some problem with it, in which case that instrument's value should be ignored.
 
-A sample from the full data file [http://rosettacode.org/resources/readings.zip readings.txt], which is also used in the [[Data Munging]] task, follows:
+A sample from the full data file [http://rosettacode.org/resources/readings.zip readings.txt], which is also used in the [[Text processing/1]] task, follows:
+
+Data is no longer available at that link. Zipped mirror available [https://github.com/thundergnat/rc/blob/master/resouces/readings.zip here]
 
 1991-03-30	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1
 1991-03-31	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	10.000	1	20.000	1	20.000	1	20.000	1	35.000	1	50.000	1	60.000	1	40.000	1	30.000	1	30.000	1	30.000	1	25.000	1	20.000	1	20.000	1	20.000	1	20.000	1	20.000	1	35.000	1
diff --git a/Task/Text-processing-2/Aime/text-processing-2.aime b/Task/Text-processing-2/Aime/text-processing-2.aime
index 3dbf51e326..8995995aae 100644
--- a/Task/Text-processing-2/Aime/text-processing-2.aime
+++ b/Task/Text-processing-2/Aime/text-processing-2.aime
@@ -4,21 +4,21 @@ check_format(list l)
     integer i;
     text s;
 
-    if (l_length(l) != 49) {
+    if (~l != 49) {
         error("wrong number of fields");
     }
 
-    s = lf_q_text(l);
-    if (length(s) != 10 || s[4] != '-' || s[7] != '-') {
+    s = l[0];
+    if (~s != 10 || s[4] != '-' || s[7] != '-') {
         error("bad date format");
     }
-    atoi(delete(delete(s, 7), 4));
+    l[0] = atoi(delete(delete(s, 7), 4));
 
     i = 1;
     while (i < 49) {
-        l_r_real(l, i, atof(l_q_text(l, i)));
+        l[i] = atof(l[i]);
         i += 1;
-        l_r_integer(l, i, atoi(l_q_text(l, i)));
+        l[i] = atoi(l[i]);
         i += 1;
     }
 }
@@ -26,39 +26,36 @@ check_format(list l)
 integer
 main(void)
 {
-    integer goods;
+    integer goods, i, v;
     file f;
     list l;
-    record r;
+    index x;
 
     goods = 0;
 
-    f_affix(f, "readings.txt");
+    f.affix("readings.txt");
 
-    while (f_list(f, l, 0) != -1) {
+    while (f.list(l, 0) != -1) {
         if (!trap(check_format, l)) {
-            if (r_key(r, l_head(l))) {
-                v_form("duplicate ~ line\n", l_head(l));
-            } else {
-                integer i;
+            if (x.key(v = lf_pick(l))) {
+                v_form("duplicate ~ line\n", v);
+            }
 
-                r_put(r, l_head(l), 0);
-                i = 2;
-                while (i < 49) {
-                    if (l_q_integer(l, i) != 1) {
-                        break;
-                    }
-                    i += 2;
-                }
-                if (49 < i) {
-                    goods += 1;
+            x[v] = 0;
+            i = 1;
+            while (i < 48) {
+                if (l[i] < 1) {
+                    break;
                 }
+                i += 2;
+            }
+            if (48 < i) {
+                goods += 1;
             }
         }
     }
 
-    o_integer(goods);
-    o_text(" good unique lines\n");
+    o_(goods, " good lines\n");
 
     return 0;
 }
diff --git a/Task/Text-processing-2/Julia/text-processing-2.julia b/Task/Text-processing-2/Julia/text-processing-2.julia
new file mode 100644
index 0000000000..95c9be17c6
--- /dev/null
+++ b/Task/Text-processing-2/Julia/text-processing-2.julia
@@ -0,0 +1,5 @@
+dupdate = df[nonunique(df[:,[:Date]]),:][:Date]
+println("The following rows have duplicate DATESTAMP:")
+println(df[df[:Date] .== dupdate,:])
+println("All values good in these rows:")
+println(df[df[:ValidValues] .== 24,:])
diff --git a/Task/Text-processing-2/Kotlin/text-processing-2.kotlin b/Task/Text-processing-2/Kotlin/text-processing-2.kotlin
new file mode 100644
index 0000000000..8a8df6cc62
--- /dev/null
+++ b/Task/Text-processing-2/Kotlin/text-processing-2.kotlin
@@ -0,0 +1,42 @@
+// version 1.2.31
+
+import java.io.File
+
+fun main(args: Array) {
+    val rx = Regex("""\s+""")
+    val file = File("readings.txt")
+    var count = 0
+    var invalid = 0
+    var allGood = 0
+    var map = mutableMapOf()
+    file.forEachLine { line ->
+        count++
+        val fields = line.split(rx)
+        val date = fields[0]
+        if (fields.size == 49) {
+            if (map.containsKey(date))
+                map[date] = map[date]!! + 1
+            else
+                map.put(date, 1)
+            var good = 0
+            for (i in 2 until fields.size step 2) {
+                if (fields[i].toInt() >= 1) {
+                    good++
+                }
+            }
+            if (good == 24) allGood++
+        }
+        else invalid++
+    }
+
+    println("File = ${file.name}")
+    println("\nDuplicated dates:")
+    for ((k,v) in map) {
+        if (v > 1) println("  $k ($v times)")
+    }
+    println("\nTotal number of records   : $count")
+    var percent = invalid.toDouble() / count * 100.0
+    println("Number of invalid records : $invalid (${"%5.2f".format(percent)}%)")
+    percent = allGood.toDouble() / count * 100.0
+    println("Number which are all good : $allGood (${"%5.2f".format(percent)}%)")
+}
diff --git a/Task/Text-processing-2/Perl-6/text-processing-2.pl6 b/Task/Text-processing-2/Perl-6/text-processing-2.pl6
new file mode 100644
index 0000000000..3f2051159b
--- /dev/null
+++ b/Task/Text-processing-2/Perl-6/text-processing-2.pl6
@@ -0,0 +1,19 @@
+my $good-records;
+my $line;
+my %dates;
+
+for lines() {
+    $line++;
+    / ^
+    (\d ** 4 '-' \d\d '-' \d\d)
+    [ \h+ \d+'.'\d+ \h+ ('-'?\d+) ] ** 24
+    $ /
+        or note "Bad format at line $line" and next;
+    %dates.push: $0 => $line;
+    $good-records++ if $1.all >= 1;
+}
+
+say "$good-records good records out of $line total";
+
+say 'Repeated timestamps (with line numbers):';
+.say for sort %dates.pairs.grep: *.value.elems > 1;
diff --git a/Task/Text-processing-Max-licenses-in-use/00DESCRIPTION b/Task/Text-processing-Max-licenses-in-use/00DESCRIPTION
index 0555c02ab1..8b2ee43fc6 100644
--- a/Task/Text-processing-Max-licenses-in-use/00DESCRIPTION
+++ b/Task/Text-processing-Max-licenses-in-use/00DESCRIPTION
@@ -10,4 +10,6 @@ An example of  checkout and  checkin events are:
 
 ;Task:
 Save the 10,000 line log file from   [http://rosettacode.org/resources/mlijobs.txt  here]   into a local file, then write a program to scan the file extracting both the maximum licenses that were out at any time, and the time(s) at which this occurs.
+
+Mirror of log file available as a zip [https://github.com/thundergnat/rc/blob/master/resouces/mlijobs.zip here] (offsite mirror).
 

diff --git a/Task/Text-processing-Max-licenses-in-use/Julia/text-processing-max-licenses-in-use.julia b/Task/Text-processing-Max-licenses-in-use/Julia/text-processing-max-licenses-in-use.julia new file mode 100644 index 0000000000..c21fa96c1d --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Julia/text-processing-max-licenses-in-use.julia @@ -0,0 +1,18 @@ +function maximumsimultlicenses(io::IO) + out, maxout, maxtimes = 0, -1, String[] + for job in readlines(io) + out += ifelse(occursin("OUT", job), 1, -1) + if out > maxout + maxout = out + empty!(maxtimes) + end + if out == maxout + push!(maxtimes, split(job)[4]) + end + end + return maxout, maxtimes +end + +let (maxout, maxtimes) = open(maximumsimultlicenses, "data/mlijobs.txt") + println("Maximum simultaneous license use is $maxout at the following times: \n - ", join(maxtimes, "\n - ")) +end diff --git a/Task/Text-processing-Max-licenses-in-use/Kotlin/text-processing-max-licenses-in-use.kotlin b/Task/Text-processing-Max-licenses-in-use/Kotlin/text-processing-max-licenses-in-use.kotlin new file mode 100644 index 0000000000..5b9b0ffc0b --- /dev/null +++ b/Task/Text-processing-Max-licenses-in-use/Kotlin/text-processing-max-licenses-in-use.kotlin @@ -0,0 +1,30 @@ +// version 1.1.51 + +import java.io.File + +fun main(args: Array) { + val filePath = "mlijobs.txt" + var licenses = 0 + var maxLicenses = 0 + val dates = mutableListOf() + val f = File(filePath) + + f.forEachLine { line -> + if (line.startsWith("License OUT")) { + licenses++ + if (licenses > maxLicenses) { + maxLicenses = licenses + dates.clear() + dates.add(line.substring(14, 33)) + } + else if(licenses == maxLicenses) { + dates.add(line.substring(14, 33)) + } + } + else if (line.startsWith("License IN")) { + licenses-- + } + } + println("Maximum simultaneous license use is $maxLicenses at the following time(s):") + println(dates.map { " $it" }.joinToString("\n")) +} diff --git a/Task/Textonyms/Clojure/textonyms.clj b/Task/Textonyms/Clojure/textonyms.clj new file mode 100644 index 0000000000..9811efc266 --- /dev/null +++ b/Task/Textonyms/Clojure/textonyms.clj @@ -0,0 +1,24 @@ +(def table + {\a 2 \b 2 \c 2 \A 2 \B 2 \C 2 + \d 3 \e 3 \f 3 \D 3 \E 3 \F 3 + \g 4 \h 4 \i 4 \G 4 \H 4 \I 4 + \j 5 \k 5 \l 5 \J 5 \K 5 \L 5 + \m 6 \n 6 \o 6 \M 6 \N 6 \O 6 + \p 7 \q 7 \r 7 \s 7 \P 7 \Q 7 \R 7 \S 7 + \t 8 \u 8 \v 8 \T 8 \U 8 \V 8 + \w 9 \x 9 \y 9 \z 9 \W 9 \X 9 \Y 9 \Z 9}) + +(def words-url "http://www.puzzlers.org/pub/wordlists/unixdict.txt") + +(def words (-> words-url slurp clojure.string/split-lines)) + +(def digits (partial map table)) + +(let [textable (filter #(every? table %) words) ;; words with letters only + mapping (group-by digits textable) ;; map of digits to words + textonyms (filter #(< 1 (count (val %))) mapping)] ;; textonyms only + (print + (str "There are " (count textable) " words in " \' words-url \' + " which can be represented by the digit key mapping. They require " + (count mapping) " digit combinations to represent them. " + (count textonyms) " digit combinations represent Textonyms."))) diff --git a/Task/Textonyms/REXX/textonyms.rexx b/Task/Textonyms/REXX/textonyms.rexx index 7e2ca77ca8..6218cac1af 100644 --- a/Task/Textonyms/REXX/textonyms.rexx +++ b/Task/Textonyms/REXX/textonyms.rexx @@ -1,36 +1,38 @@ /*REXX program counts and displays the number of textonyms that are in a dictionary file*/ parse arg iFID . /*obtain optional fileID from the C.L. */ -if iFID=='' then iFID='UNIXDICT.TXT' /*Not specified? Then use the default.*/ +if iFID=='' | iFID=="," then iFID='UNIXDICT.TXT' /*Not specified? Then use the default.*/ @.=0 /*the placeholder of digit combinations*/ !.=; $.= /*sparse array of textonyms; words. */ alphabet= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' /*the supported alphabet to be used. */ digitKey= 22233344455566677778889999 /*translated alphabet to digit keys. */ -digKey=0; wordCount=0 /*number digit combinations; wordCount.*/ -ills=0; dups=0; longest=0; mostus=0 /*illegals; duplicated words; longest..*/ -first=0; last=0; long=0; most=0 /*first, last, longest, most counts. */ -call linein iFID, 1, 0 /*point to the first char in dictionary*/ +digKey=0; wordCount=0 /*number digit combinations; wordCount.*/ +ills=0; dups=0; longest=0; mostus=0 /*illegals; duplicated words; longest..*/ +first=.; last=.; long=0; most=0 /*first, last, longest, most counts. */ #=0 /*number of textonyms in file (so far).*/ +call linein iFID, 1, 0 /*point to the first char in dictionary*/ /* ◄■■■■■ optional.*/ - do j=1 while lines(iFID)\==0 /*keep reading the file until exhausted*/ - x=linein(iFID); y=x; upper x /*get a word; save a copy; uppercase it*/ - if \datatype(x,'U') then do; ills=ills+1; iterate; end /*is it illegal? */ - if $.x\=='' then do; dups=dups+1; iterate; end /*is it duplicate?*/ - else $.x=. /*indicate that it's a righteous word. */ - wordCount=wordCount+1 /*bump the word count (for the file). */ + do while lines(iFID)\==0 /*keep reading the file until exhausted*/ + x=linein(iFID); y=x; upper x /*get a word; save a copy; uppercase it*/ + if \datatype(x,'U') then do; ills=ills + 1; iterate; end /*Not legal? Skip.*/ + if $.x==. then do; dups=dups + 1; iterate; end /*Duplicate? Skip.*/ + $.x=. /*indicate that it's a righteous word. */ + wordCount=wordCount + 1 /*bump the word count (for the file). */ z=translate(x, digitKey, alphabet) /*build a translated digit key word. */ - @.z=@.z+1 /*flag that the digit key word exists. */ - !.z=!.z y; _=words(!.z) /*build list of equivalent digit key(s)*/ - if _>most then do; mostus=z; most=_; end /*remember the "mostus" digit keys. */ - if @.z==2 then do; #=#+1 /*bump the count of the textonyms. */ - if first==0 then first=z /*the first textonym found. */ + @.z=@.z + 1 /*flag that the digit key word exists. */ + !.z=!.z y; _=words(!.z) /*build list of equivalent digit key(s)*/ + + if _>most then do; mostus=z; most=_; end /*remember the "mostus" digit keys. */ + + if @.z==2 then do; #=# + 1 /*bump the count of the textonyms. */ + if first==. then first=z /*the first textonym found. */ last=z /* " last " " */ _=length(!.z) /*the length (# chars) of the digit key*/ if _>longest then long=z /*is this the longest textonym ? */ longest=max(_, longest) /*now, use this length as a target/goal*/ end /* [↑] discretionary (extra credit). */ - if @.z\==1 then iterate /*Does it already exist? Then Skip it.*/ - digKey=digKey+1 /*bump the count of digit key words. */ - end /*j*/ + + if @.z==1 then digKey=digKey + 1 /*bump the count of digit key words. */ + end /*while*/ @whichCan...= 'which can be represented by digit key mapping.' @Ta = 'There are ' say 'The dictionary file being used is: ' iFID @@ -38,12 +40,12 @@ say @Ta wordCount ' words in the file' @whichCan... if ills\==0 then say @Ta ills ' word's(ills) "contained illegal characters." if dups\==0 then say @Ta dups " duplicate word"s(dups) 'in the dictionary detected.' say 'The textonyms require ' digKey " combination"s(digKey) 'to represent them.' -say @Ta # ' digit combination's(#) " that can represent Textonyms." +say @Ta # ' digit combination's(#) " that can represent Textonyms." say -if first\==0 then say ' first digit key=' !.first -if last\==0 then say ' last digit key=' !.last +if first\==. then say ' first digit key=' !.first +if last\==. then say ' last digit key=' !.last if long\==0 then say ' longest digit key=' !.long -if most\==0 then say ' numerous digit key=' !.mostus ' ('most "words)" +if most\==0 then say ' numerous digit key=' !.mostus ' ('most "words)" exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ s: if arg(1)==1 then return ''; return "s" /*a simple pluralizer.*/ diff --git a/Task/The-ISAAC-Cipher/Julia/the-isaac-cipher.julia b/Task/The-ISAAC-Cipher/Julia/the-isaac-cipher.julia new file mode 100644 index 0000000000..f526794fb1 --- /dev/null +++ b/Task/The-ISAAC-Cipher/Julia/the-isaac-cipher.julia @@ -0,0 +1,180 @@ +""" +Julia translation of code from the following: +------------------------------------------------------------------------------ +readable.c: My random number generator, ISAAC. +(c) Bob Jenkins, March 1996, Public Domain +You may use this code in any way you wish, and it is free. No warrantee. +------------------------------------------------------------------------------ +""" +# maximum length of message here is set to 4096 +const MAXMSG = 4096 + +# cipher modes for encryption versus decryption modes +@enum CipherMode mEncipher mDecipher mNone + +# external results +mutable struct IState + randrsl::Array{UInt32, 1} + randcnt::UInt32 + mm::Array{UInt32, 1} + aa::UInt32 + bb::UInt32 + cc::UInt32 + function IState() + this = new() + this.randrsl = zeros(UInt32, 256) + this.randcnt = UInt32(0) + this.mm = zeros(UInt32, 256) + this.aa = this.bb = this.cc = UInt32(0) + this + end +end + +""" + isaac +Randomize the pool +""" +function isaac(istate) + istate.cc += 1 # cc gets incremented once per 256 results + istate.bb += istate.cc # then combined with bb + + for (j, c) in enumerate(istate.mm) # Julia NB: indexing ahead so use i for c indexing + i = j - 1 + xmod4 = i % 4 + if(xmod4 == 0) + istate.aa ⊻= istate.aa << 13 + elseif(xmod4 == 1) + istate.aa ⊻= istate.aa >> 6 + elseif(xmod4 == 2) + istate.aa ⊻= istate.aa << 2 + else + istate.aa ⊻= istate.aa >> 16 + end + istate.aa += istate.mm[(i + 128) % 256 + 1] + y = istate.mm[(c >> 2) % 256 + 1] + istate.aa + istate.bb + istate.mm[j] = y + istate.bb = istate.mm[(y >> 10) % 256 + 1] + c + istate.randrsl[j] = istate.bb + end + # not in original readable.c + istate.randcnt = 0 +end + + +""" + mix +Mix the bytes in a reversible way. +""" +function mix(arr) # Julia NB: use E for e in c code here + (a,b,c,d,E,f,g,h) = arr + a⊻=b<<11; d+=a; b+=c; + b⊻=c>>2; E+=b; c+=d; + c⊻=d<<8; f+=c; d+=E; + d⊻=E>>16; g+=d; E+=f; + E⊻=f<<10; h+=E; f+=g; + f⊻=g>>4; a+=f; g+=h; + g⊻=h<<8; b+=g; h+=a; + h⊻=a>>9; c+=h; a+=b; + (a,b,c,d,E,f,g,h) +end + + +""" + randinit +Make a random UInt32 array. +If flag is true, use the contents of randrsl[] to initialize mm[]. +""" +function randinit(istate, flag::Bool) + istate.aa = istate.bb = istate.cc = 0 + mixer = Array{UInt32,1}(8) + fill!(mixer, 0x9e3779b9) # the golden ratio + for i in 1:4 # scramble it + mixer = mix(mixer) + end + for i in 0:8:255 # fill in mm[] with messy stuff + if(flag) # use all the information in the seed + mixer = [mixer[j] + istate.randrsl[i+j] for j in 1:8] + end + mixer = mix(mixer) + istate.mm[i+1:i+8] .= mixer + end + if(flag) # do a second pass to seed all of mm + for i in 0:8:255 + mixer = [mixer[j] + istate.mm[i+j] for j in 1:8] + mixer = mix(mixer) + istate.mm[i+1:i+8] .= mixer + end + end + isaac(istate) # fill in the first set of results + istate.randcnt = 0 +end + + +""" + Get a random 32-bit value 0..MAXINT +""" +function irandom(istate) + retval::UInt32 = istate.randrsl[istate.randcnt+1] + istate.randcnt += 1 + if(istate.randcnt > 255) + isaac(istate) + istate.randcnt = 0 + end + retval +end + + +""" + Get a random character in printable ASCII range +""" +iranda(istate) = UInt8(irandom(istate) % 95 + 32) + + +""" + Do XOR cipher on random stream. + Output: UInt8 array +""" +vernam(istate, msg) = [UInt8(iranda(istate) ⊻ c) for c in msg] + + +""" + Seed ISAAC with a string +""" +function iseed(istate, seed, flag) + fill!(istate.mm, 0) + fill!(istate.randrsl, 0) + len = min(length(seed), length(istate.randrsl)) + istate.randrsl[1:len] .= seed[1:len] + randinit(istate, flag) # initialize ISAAC with seed +end + + +tohexstring(arr::Array{UInt8,1}) = join([hex(i, 2) for i in arr]) + + +function test(istate, msg, key) + # Vernam ciphertext & plaintext + vctx = zeros(UInt8, MAXMSG) + vptx = zeros(UInt8, MAXMSG) + # Encrypt: Vernam XOR + iseed(istate, Vector{UInt8}(key), true) + vctx = vernam(istate, Vector{UInt8}(msg)) + # Decrypt: Vernam XOR + iseed(istate, Vector{UInt8}(key), true) + vptx = vernam(istate, vctx) + # Program output + println("Message: $msg") + println("Key : $key") + println("XOR : $(tohexstring(vctx))") + # Output Vernam decrypted plaintext + println("XOR dcr: $(join(map(c -> Char(c), vptx)))") + 0 +end + + +""" +Test the above. +""" +const msg = "a Top Secret secret" +const key = "this is my secret key" +test(IState(), msg, key) diff --git a/Task/The-ISAAC-Cipher/Modula-2/the-isaac-cipher.mod2 b/Task/The-ISAAC-Cipher/Modula-2/the-isaac-cipher.mod2 new file mode 100644 index 0000000000..932bef3948 --- /dev/null +++ b/Task/The-ISAAC-Cipher/Modula-2/the-isaac-cipher.mod2 @@ -0,0 +1,250 @@ +MODULE RosettaIsaac; + +FROM Strings IMPORT + Length, Assign, Append; +FROM STextIO IMPORT + WriteString, WriteLn; +FROM Conversions IMPORT + CardBaseToStr; + +CONST + MaxStrLength = 256; + +TYPE + TMode = (iEncrypt, iDecrypt); + TString = ARRAY [0 .. MaxStrLength - 1] OF CHAR; + TCardIndexedFrom0To7 = ARRAY [0 .. 7] OF CARDINAL; + +VAR +(* TASK globals *) + Msg: TString = 'a Top Secret secret'; + Key: TString = 'this is my secret key'; + XCTxt: TString = ''; (* XOR ciphertext *) + MCTxt: TString = ''; (* MOD ciphertext *) + XPTxt: TString = ''; (* XOR decryption (plaintext) *) + MPTxt: TString = ''; (* MOD decryption (plaintext) *) + Mode: TMode = iEncrypt; + HexTxt: TString; + +(* ISAAC globals *) +(* external results *) + RandRsl: ARRAY [0 .. 256] OF CARDINAL; + RandCnt: CARDINAL; + +(* internal state *) + MM: ARRAY [0 .. 256] OF CARDINAL; + AA: CARDINAL = 0; + BB: CARDINAL = 0; + CC: CARDINAL = 0; + +PROCEDURE Isaac; +VAR + I, X, Y: CARDINAL; +BEGIN + CC := CC + 1; (* CC just gets incremented once per 256 results *) + BB := BB + CC; (* then combined with BB *) + FOR I := 0 TO 255 DO + X := MM[I]; + CASE (I MOD 4) OF + 0: AA := AA BXOR (AA SHL 13); | + 1: AA := AA BXOR (AA SHR 6); | + 2: AA := AA BXOR (AA SHL 2); | + 3: AA := AA BXOR (AA SHR 16); + ELSE + END; + AA := MM[(I + 128) MOD 256] + AA; + Y := MM[(X SHR 2) MOD 256] + AA + BB; + MM[I] := Y; + BB := MM[(Y SHR 10) MOD 256] + X; + RandRsl[I] := BB; + END; (* FOR *) + RandCnt := 0; (* Prepare to use the first set of results. *) +END Isaac; + +PROCEDURE Mix(VAR A: TCardIndexedFrom0To7); +BEGIN + A[0] := A[0] BXOR A[1] SHL 11; A[3] := A[3] + A[0]; A[1] := A[1] + A[2]; + A[1] := A[1] BXOR A[2] SHR 2; A[4] := A[4] + A[1]; A[2] := A[2] + A[3]; + A[2] := A[2] BXOR A[3] SHL 8; A[5] := A[5] + A[2]; A[3] := A[3] + A[4]; + A[3] := A[3] BXOR A[4] SHR 16; A[6] := A[6] + A[3]; A[4] := A[4] + A[5]; + A[4] := A[4] BXOR A[5] SHL 10; A[7] := A[7] + A[4]; A[5] := A[5] + A[6]; + A[5] := A[5] BXOR A[6] SHR 4; A[0] := A[0] + A[5]; A[6] := A[6] + A[7]; + A[6] := A[6] BXOR A[7] SHL 8; A[1] := A[1] + A[6]; A[7] := A[7] + A[0]; + A[7] := A[7] BXOR A[0] SHR 9; A[2] := A[2] + A[7]; A[0] := A[0] + A[1]; +END Mix; + +PROCEDURE RandInit(Flag: BOOLEAN); +VAR + I, J: CARDINAL; + A: TCardIndexedFrom0To7; +BEGIN + AA := 0; BB := 0; CC := 0; + A[0] := 2654435769; (* $9e3779b9: the golden ratio *) + FOR J := 1 TO 7 DO + A[J] := A[0]; + END; + + FOR I := 0 TO 3 DO (* Scramble it *) + Mix(A); + END; + FOR I := 0 TO 255 BY 8 DO (* Fill in MM[] with messy stuff. *) + IF Flag THEN (* Use all the information in the seed. *) + FOR J := 0 TO 7 DO + A[J] := A[J] + RandRsl[I + J]; + END; + END; + Mix(A); + FOR J := 0 TO 7 DO + MM[I + J] := A[J]; + END; + END; (* FOR I*) + + IF Flag THEN + (* Do a second pass to make all of the Seed affect all of MM *) + FOR I := 0 TO 255 BY 8 DO + FOR J := 0 TO 7 DO + A[J] := A[J] + MM[I + J]; + END; + Mix(A); + FOR J := 0 TO 7 DO + MM[I + J] := A[J]; + END; + END; (* FOR I *) + END; + Isaac(); (* Fill in the first set of results *) + RandCnt := 0; (* Prepare to use the first set of results *) +END RandInit; + +(* Seed ISAAC with a given string. + The string can be any size. The first 256 values will be used. *) +PROCEDURE SeedIsaac(Seed: ARRAY OF CHAR; Flag: BOOLEAN); +VAR + I, M: CARDINAL; +BEGIN + FOR I := 0 TO 255 DO + MM[I] := 0; + END; + M := Length(Seed); + FOR I := 0 TO 255 DO + (* In case seed has less than 256 elements *) + IF I > M THEN + RandRsl[I] := 0 + ELSE + (* Modula-2 strings are 0-based (at least, in this case). *) + RandRsl[I] := ORD(Seed[I]); + END; + END; + (* Initialize ISAAC with seed. *) + RandInit(Flag); +END SeedIsaac; + +(* Get a random 32-bit value 0..MAXINT *) +PROCEDURE GetRandom32Bit(): CARDINAL; +VAR + Result: CARDINAL; +BEGIN + Result := RandRsl[RandCnt]; + INC(RandCnt); + IF RandCnt > 255 THEN + Isaac(); + RandCnt := 0; + END; + RETURN Result; +END GetRandom32Bit; + +(* Get a random character in printable ASCII range. *) +PROCEDURE GetRandomChar(): SHORTCARD; +BEGIN + RETURN GetRandom32Bit() MOD 95 + 32; +END GetRandomChar; + +(* Convert an ASCII string to a hexadecimal string. *) +PROCEDURE ASCII2Hex(Source: ARRAY OF CHAR; VAR OUT Destination: ARRAY OF CHAR); +VAR + I: CARDINAL; + NumbHex: ARRAY [0 .. 1] OF CHAR; +BEGIN + Assign('', Destination); + FOR I := 0 TO Length(Source) - 1 DO + CardBaseToStr(ORD(Source[I]), 16, NumbHex); + IF Length(NumbHex) <= 1 THEN + Append('0', Destination); + END; + Append(NumbHex, Destination); + END; +END ASCII2Hex; + +(* XOR encrypt on random stream. *) +PROCEDURE Vernam(Msg: ARRAY OF CHAR; VAR OUT Destination: ARRAY OF CHAR); +VAR + I: CARDINAL; + OrdMsgI: SHORTCARD; +BEGIN + Assign('', Destination); + FOR I := 0 TO Length(Msg) - 1 DO + OrdMsgI := ORD(Msg[I]); + Append(CHR(GetRandomChar() BXOR OrdMsgI), Destination); + END; +END Vernam; + +(* Get position of the letter in chosen alphabet *) +PROCEDURE LetterNum(Letter, Start: CHAR): SHORTCARD; +BEGIN + RETURN ORD(Letter) - ORD(Start); +END LetterNum; + +(* Caesar-shift a character places: Generalized Vigenere *) +PROCEDURE Caesar(M: TMode; Ch: CHAR; Shift, Modulo: INTEGER; Start: CHAR): CHAR; +VAR + N, IntOrdStart: INTEGER; +BEGIN + IF M = iDecrypt THEN + Shift := -Shift; + END; + N := LetterNum(Ch, Start); + N := N + Shift; + N := N MOD Modulo; + IF N < 0 THEN + N := N + Modulo; + END; + IntOrdStart := ORD(Start); + RETURN CHR(IntOrdStart + N); +END Caesar; + +(* Vigenere mod 95 encryption & decryption. *) +PROCEDURE Vigenere(Msg: ARRAY OF CHAR; M: TMode; VAR OUT Destination: ARRAY OF CHAR); +VAR + I: CARDINAL; +BEGIN + Assign('', Destination); + FOR I := 0 TO Length(Msg) - 1 DO + Append(Caesar(M, Msg[I], GetRandomChar(), 95, ' '), Destination); + END; +END Vigenere; + +BEGIN + (* (1) Seed ISAAC with the key *) + SeedIsaac(Key, TRUE); + (* (2) Encryption *) + Mode := iEncrypt; + (* (a) XOR (Vernam) *) + Vernam(Msg, XCTxt); + (* (b) MOD (Vigenere) *) + Vigenere(Msg, Mode, MCTxt); + (* (3) Decryption *) + Mode := iDecrypt; + SeedIsaac(Key, TRUE); + (* (a) XOR (Vernam) *) + Vernam(XCTxt, XPTxt); + (* (b) MOD (Vigenere) *) + Vigenere(MCTxt, Mode, MPTxt); + (* program output *) + WriteString('Message: '); WriteString(Msg); WriteLn; + WriteString('Key : '); WriteString(Key); WriteLn; + ASCII2Hex(XCTxt, HexTxt); + WriteString('XOR : '); WriteString(HexTxt); WriteLn; + ASCII2Hex(MCTxt, HexTxt); + WriteString('MOD : '); WriteString(HexTxt); WriteLn; + WriteString('XOR dcr: '); WriteString(XPTxt); WriteLn; + WriteString('MOD dcr: '); WriteString(MPTxt); WriteLn; +END RosettaIsaac. diff --git a/Task/The-Twelve-Days-of-Christmas/00DESCRIPTION b/Task/The-Twelve-Days-of-Christmas/00DESCRIPTION index 514011826b..3d430e649b 100644 --- a/Task/The-Twelve-Days-of-Christmas/00DESCRIPTION +++ b/Task/The-Twelve-Days-of-Christmas/00DESCRIPTION @@ -1,6 +1,12 @@ +;Task: Write a program that outputs the lyrics of the Christmas carol ''The Twelve Days of Christmas''. The lyrics can be found [http://www.lyricsmode.com/lyrics/c/christmas_carols/the_twelve_days_of_christmas.html here]. + (You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.) -;Cf: -* [[Comma quibbling]] + +;Related tasks: +*   [[99 Bottles of Beer]] +*   [[Old_lady_swallowed_a_fly]] +*   [[Comma quibbling]] +

diff --git a/Task/The-Twelve-Days-of-Christmas/Elena/the-twelve-days-of-christmas.elena b/Task/The-Twelve-Days-of-Christmas/Elena/the-twelve-days-of-christmas.elena new file mode 100644 index 0000000000..01bb331249 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Elena/the-twelve-days-of-christmas.elena @@ -0,0 +1,42 @@ +import extensions. + +program = +[ + var days := ( + "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", + "tenth", "eleventh", "twelfth" + ). + + var gifts := ( + "And a partridge in a pear tree", + "Two turtle doves", + "Three french hens", + "Four calling birds", + "Five golden rings", + "Six geese a-laying", + "Seven swans a-swimming", + "Eight maids a-milking", + "Nine ladies dancing", + "Ten lords a-leaping", + "Eleven pipers piping", + "Twelve drummers drumming" + ). + + 0 till:12 do(:i) + [ + console printLine("On the ", days[i], " day of Christmas, my true love gave to me"). + + if (i == 0) + [ + console printLine("A partridge in a pear tree"). + ]; + [ + i to:0 do(:j) + [ + console printLine(gifts[j]) + ]. + ]. + + console printLine. + ]. +]. diff --git a/Task/The-Twelve-Days-of-Christmas/Factor/the-twelve-days-of-christmas.factor b/Task/The-Twelve-Days-of-Christmas/Factor/the-twelve-days-of-christmas.factor new file mode 100644 index 0000000000..3187a33665 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Factor/the-twelve-days-of-christmas.factor @@ -0,0 +1,34 @@ +USING: formatting io kernel math math.ranges qw sequences ; +IN: rosetta-code.twelve-days-of-christmas + +CONSTANT: opener + "On the %s day of Christmas, my true love sent to me:\n" + +CONSTANT: ordinals qw{ + first second third fourth fifth sixth seventh eighth ninth + tenth eleventh twelfth +} + +CONSTANT: gifts { + "A partridge in a pear tree." + "Two turtle doves, and" + "Three french hens," + "Four calling birds," + "Five golden rings," + "Six geese a-laying," + "Seven swans a-swimming," + "Eight maids a-milking," + "Nine ladies dancing," + "Ten lords a-leaping," + "Eleven pipers piping," + "Twelve drummers drumming," +} + +: descend ( n -- ) 0 [a,b] [ gifts nth print ] each nl ; + +: verse ( n -- ) + 1 - [ ordinals nth opener printf ] [ descend ] bi ; + +: twelve-days-of-christmas ( -- ) 12 [1,b] [ verse ] each ; + +MAIN: twelve-days-of-christmas diff --git a/Task/The-Twelve-Days-of-Christmas/PureBasic/the-twelve-days-of-christmas.purebasic b/Task/The-Twelve-Days-of-Christmas/PureBasic/the-twelve-days-of-christmas.purebasic new file mode 100644 index 0000000000..950568d2b1 --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/PureBasic/the-twelve-days-of-christmas.purebasic @@ -0,0 +1,16 @@ +#TXT$ = "On the * day of Christmas, my true love sent to me:" +days$ = ~"first\nsecond\nthird\nfourth\nfifth\nsixth\nseventh\neighth\nninth\ntenth\neleventh\ntwelfth\n" +gifts$= ~"Twelve drummers drumming,\nEleven pipers piping,\nTen lords a-leaping,\nNine ladies dancing,\n"+ + ~"Eight maids a-milking,\nSeven swans a-swimming,\nSix geese a-laying,\nFive golden rings,\n"+ + ~"Four calling birds,\nThree french hens,\nTwo turtle doves,\nA partridge in a pear tree.\n" +Define I.i, J.i + +If OpenConsole("The twelve days of Christmas") + For I = 1 To 12 + PrintN(ReplaceString(#TXT$,"*",StringField(days$,I,~"\n"))) + For J = 13-I To 12 + PrintN(" -> "+StringField(gifts$,J,~"\n")) + Next J + Next I + Input() +EndIf diff --git a/Task/The-Twelve-Days-of-Christmas/REXX/the-twelve-days-of-christmas.rexx b/Task/The-Twelve-Days-of-Christmas/REXX/the-twelve-days-of-christmas.rexx index e3877c948f..5b84b8d554 100644 --- a/Task/The-Twelve-Days-of-Christmas/REXX/the-twelve-days-of-christmas.rexx +++ b/Task/The-Twelve-Days-of-Christmas/REXX/the-twelve-days-of-christmas.rexx @@ -1,17 +1,19 @@ -/*REXX program displays the verses of the song: "The 12 days of Christmas". */ -@='first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth' -pad=left('',20) /*used for indenting the shown verses.*/ +/*REXX program displays the verses of the song: "The 12 days of Christmas". */ +ordD= 'first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth' +pad=left('', 20) /*used for indenting the shown verses. */ - g.1= 'A partridge in a pear-tree.'; g.7 = 'Seven swans a-swimming,' - g.2= 'Two Turtle Doves, and' ; g.8 = 'Eight maids a-milking,' - g.3= 'Three French Hens,' ; g.9 = 'Nine ladies dancing,' - g.4= 'Four Calling Birds,' ; g.10= 'Ten lords a-leaping,' - g.5= 'Five Golden Rings,' ; g.11= 'Eleven pipers piping,' - g.6= 'Six geese a-laying,' ; g.12= 'Twelve drummers drumming,' + @.1= 'A partridge in a pear-tree.'; @.7 = "Seven swans a-swimming," + @.2= 'Two Turtle Doves, and' ; @.8 = "Eight maids a-milking," + @.3= 'Three French Hens,' ; @.9 = "Nine ladies dancing," + @.4= 'Four Calling Birds,' ; @.10= "Ten lords a-leaping," + @.5= 'Five Golden Rings,' ; @.11= "Eleven pipers piping," + @.6= 'Six geese a-laying,' ; @.12= "Twelve drummers drumming," do day=1 for 12 - say pad 'On the' word(@,day) 'day of Christmas' /*display line 1 prologue*/ - say pad 'My True Love gave to me:' /* " " 2 " */ - do j=day to 1 by -1; say pad g.j; end /* " the daily gifts*/ - say /*add a blank line between the verses. */ - end /*day*/ /*stick a fork in it, we're all done. */ + say pad 'On the' word(ordD, day) "day of Christmas" /*display line 1 prologue.*/ + say pad 'My True Love gave to me:' /* " " 2 " */ + + do j=day by -1 to 1; say pad @.j /* " the daily gifts.*/ + end /*j*/ + say /*add a blank line between the verses. */ + end /*day*/ /*stick a fork in it, we're all done. */ diff --git a/Task/The-Twelve-Days-of-Christmas/Ring/the-twelve-days-of-christmas.ring b/Task/The-Twelve-Days-of-Christmas/Ring/the-twelve-days-of-christmas.ring new file mode 100644 index 0000000000..40c056b2bf --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/Ring/the-twelve-days-of-christmas.ring @@ -0,0 +1,20 @@ +# Project : The Twelve Days of Christmas +# Date : 2017/11/14 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +gifts = "A partridge in a pear tree,Two turtle doves,Three french hens,Four calling birds,Five golden rings,Six geese a-laying,Seven swans a-swimming,Eight maids a-milking,Nine ladies dancing,Ten lords a-leaping,Eleven pipers piping,Twelve drummers drumming" +days = "first second third fourth fifth sixth seventh eighth ninth tenth eleventh twelfth" +lstgifts = str2list(substr(gifts,",", nl)) +lstdays = str2list(substr(days, " ", nl)) +for i = 1 to 12 + see "On the "+ lstdays[i]+ " day of Christmas" + nl + see "My true love gave to me:" + nl + for j = i to 1 step -1 + if i > 1 and j = 1 + see "and " + nl + ok + see "" + lstgifts[j] + nl + next + see nl +next diff --git a/Task/The-Twelve-Days-of-Christmas/VBA/the-twelve-days-of-christmas.vba b/Task/The-Twelve-Days-of-Christmas/VBA/the-twelve-days-of-christmas.vba new file mode 100644 index 0000000000..1f82eb0b2d --- /dev/null +++ b/Task/The-Twelve-Days-of-Christmas/VBA/the-twelve-days-of-christmas.vba @@ -0,0 +1,16 @@ +Sub Main() +Dim i As Integer, c As Integer, j As Integer, strReturn() As String +Dim s, n + s = Split(SING_, "$") + n = Split(NUMBERS_, " ") + ReDim strReturn(UBound(s)) + For i = LBound(s) To UBound(s) + strReturn(i) = Replace(BASE_, "(X)", n(i)) + For j = c To 0 Step -1 + strReturn(i) = strReturn(i) & s(j) & vbCrLf + Next + c = c + 1 + Next i + strReturn(UBound(strReturn)) = Replace(strReturn(UBound(strReturn)), "and" & vbCrLf & "A", vbCrLf & "And a") + Debug.Print Join(strReturn, vbCrLf) +End Sub diff --git a/Task/Thieles-interpolation-formula/Perl-6/thieles-interpolation-formula.pl6 b/Task/Thieles-interpolation-formula/Perl-6/thieles-interpolation-formula.pl6 index 0c21746564..16bfe3be7b 100644 --- a/Task/Thieles-interpolation-formula/Perl-6/thieles-interpolation-formula.pl6 +++ b/Task/Thieles-interpolation-formula/Perl-6/thieles-interpolation-formula.pl6 @@ -1,5 +1,3 @@ -use v6; - # reciprocal difference: multi sub ρ(&f, @x where * < 1) { 0 } # Identity multi sub ρ(&f, @x where * == 1) { &f(@x[0]) } @@ -15,11 +13,11 @@ multi sub thiele($x, %f, $ord where { $ord == +%f }) { 1 } # Identity multi sub thiele($x, %f, $ord) { my &f = {%f{$^a}}; # f(x) as a table lookup - # Caveat: depends on the fact that Rakudo maintains key order within hashes - my $a = ρ(&f, %f.keys[^($ord +1)]); - my $b = ρ(&f, %f.keys[^($ord -1)]); + # must sort hash keys to maintain order between invocations + my $a = ρ(&f, %f.keys.sort[^($ord +1)]); + my $b = ρ(&f, %f.keys.sort[^($ord -1)]); - my $num = $x - %f.keys[$ord]; + my $num = $x - %f.keys.sort[$ord]; my $cont = thiele($x, %f, $ord +1); # Thiele always takes this form: diff --git a/Task/Tic-tac-toe/00DESCRIPTION b/Task/Tic-tac-toe/00DESCRIPTION index 601a46bb0d..6606956cd8 100644 --- a/Task/Tic-tac-toe/00DESCRIPTION +++ b/Task/Tic-tac-toe/00DESCRIPTION @@ -1,9 +1,12 @@ [[File:Tic_tac_toe.jpg|500px||right]] ;Task: -Play a game of [[wp:Tic-tac-toe|tic-tac-toe]]. Ensure that legal moves are played and that a winning position is notified. +Play a game of [[wp:Tic-tac-toe|tic-tac-toe]]. + +Ensure that legal moves are played and that a winning position is notified. ;See also -* [http://mathworld.wolfram.com/Tic-Tac-Toe.html Mathworld™, Tic-Tac-Toe game]. +*   [http://mathworld.wolfram.com/Tic-Tac-Toe.html MathWorld™, Tic-Tac-Toe game]. +*   [https://en.wikipedia.org/wiki/Tic-tac-toe Wikipedia tic-tac-toe].

diff --git a/Task/Tic-tac-toe/Fortran/tic-tac-toe.f b/Task/Tic-tac-toe/Fortran/tic-tac-toe.f new file mode 100644 index 0000000000..8655f38b7c --- /dev/null +++ b/Task/Tic-tac-toe/Fortran/tic-tac-toe.f @@ -0,0 +1,99 @@ +! This is a fortran95 implementation of the game of tic-tac-toe. +! - Objective was to use less than 100 lines. +! - No attention has been devoted to efficiency. +! - Indentation by findent: https://sourceforge.net/projects/findent/ +! - This is free software, use as you like at own risk. +! - Compile: gfortran -o tictactoe tictactoe.f90 +! - Run: ./tictactoe +! Comments to: wvermin at gmail dot com +module tic + implicit none + integer :: b(9) +contains + logical function iswin(p) + integer,intent(in) :: p + iswin = & + all(b([1,2,3])==p).or.all(b([4,5,6])==p).or.all(b([7,8,9])==p).or.& + all(b([1,4,7])==p).or.all(b([2,5,8])==p).or.all(b([3,6,9])==p).or.& + all(b([1,5,9])==p).or.all(b([3,5,7])==p) + end function iswin + subroutine printb(mes) + character(len=*) :: mes + integer :: i,j + character :: s(0:2) = ['.','X','O'] + print "(3a3,' ',3i3)",(s(b(3*i+1:3*i+3)),(j,j=3*i+1,3*i+3),i=0,2) + if(mes /= ' ') print "(/,a)",mes + end subroutine printb + integer recursive function minmax(player,bestm) result(bestv) + integer :: player,bestm,move,v,bm,win=1000,inf=100000 + real :: x + if (all(b .ne. 0)) then + bestv = 0 + else + bestv = -inf + do move=1,9 + if (b(move) == 0) then + b(move) = player + if (iswin(player)) then + v = win + else + call random_number(x) + v = -minmax(3-player,bm) - int(10*x) + endif + if (v > bestv) then + bestv = v + bestm = move + endif + b(move) = 0 + if (v == win) exit + endif + enddo + endif + end function minmax +end module tic +program tictactoe + ! computer: player=1, user: player=2 + use tic + implicit none + integer :: move,ios,v,bestmove,ply,player=2,k,values(8) + integer,allocatable :: seed(:) + call date_and_time(values=values) + call random_seed(size=k) + allocate(seed(k)) + seed = values(8)+1000*values(7)+60*1000*values(6)+60*60*1000*values(5) + call random_seed(put=seed) + mainloop: do + b = 0 + call printb('You have O, I have X. You enter 0: game ends.') + plyloop: do ply=0,4 + if (player == 2 .or. ply >0 ) then ! user move + write(*,"(/,a)",advance='no'),'Your move? (0..9) ' + getloop: do + readloop: do + read (*,*,iostat=ios),move + if (ios == 0 .and. move >= 0 .and. move <= 9) exit readloop + write(*,"(a)",advance='no'),'huh? Try again (0..9): ' + enddo readloop + if ( move == 0) exit mainloop + if (b(move) == 0) exit getloop + write(*,"(a)",advance='no'),'Already occupied, again (0..9): ' + enddo getloop + b(move) = 2 + if(iswin(2)) then ! this should not happen + call printb('***** You win *****') + exit plyloop + endif + endif + v = minmax(1,bestmove) ! computer move + b(bestmove) = 1 + if(iswin(1)) then + call printb('***** I win *****') + exit plyloop + endif + write(*,"(/,a,i3)"), 'My move: ',bestmove + call printb(' ') + enddo plyloop + if(ply == 5) write(*,"('***** Draw *****',/)") + player = 3-player + enddo mainloop +end program diff --git a/Task/Tic-tac-toe/Kotlin/tic-tac-toe.kotlin b/Task/Tic-tac-toe/Kotlin/tic-tac-toe.kotlin new file mode 100644 index 0000000000..dcacd1c3c9 --- /dev/null +++ b/Task/Tic-tac-toe/Kotlin/tic-tac-toe.kotlin @@ -0,0 +1,107 @@ +// version 1.1.51 + +import java.util.Random + +val r = Random() +val b = Array(3) { IntArray(3) } // board -> 0: blank; -1: computer; 1: human + +var bestI = 0 +var bestJ = 0 + +fun checkWinner(): Int { + for (i in 0..2) { + if (b[i][0] != 0 && b[i][1] == b[i][0] && b[i][2] == b[i][0]) return b[i][0] + if (b[0][i] != 0 && b[1][i] == b[0][i] && b[2][i] == b[0][i]) return b[0][i] + } + if (b[1][1] == 0) return 0 + if (b[1][1] == b[0][0] && b[2][2] == b[0][0]) return b[0][0] + if (b[1][1] == b[2][0] && b[0][2] == b[1][1]) return b[1][1] + return 0 +} + +fun showBoard() { + val t = "X O" + for (i in 0..2) { + for (j in 0..2) print("${t[b[i][j] + 1]} ") + println() + } + println("-----") +} + +fun testMove(value: Int, depth: Int): Int { + var best = -1 + var changed = 0 + var score = checkWinner() + if (score != 0) return if (score == value) 1 else -1 + for (i in 0..2) { + for (j in 0..2) { + if (b[i][j] != 0) continue + b[i][j] = value + changed = value + score = -testMove(-value, depth + 1) + b[i][j] = 0 + if (score <= best) continue + if (depth == 0) { + bestI = i + bestJ = j + } + best = score + } + } + return if (changed != 0) best else 0 +} + +fun game(user: Boolean): String { + var u = user + for (i in 0..2) b[i].fill(0) + print("Board postions are numbered so:\n1 2 3\n4 5 6\n7 8 9\n") + print("You have O, I have X.\n\n") + + for (k in 0..8) { + while (u) { + var move: Int? + do { + print("Your move: ") + move = readLine()!!.toIntOrNull() + } + while (move != null && move !in 1..9) + move = move!! - 1 + val i = move / 3 + val j = move % 3 + if (b[i][j] != 0) continue + b[i][j] = 1 + break + } + if (!u) { + if (k == 0) { // randomize if computer opens, less boring + bestI = r.nextInt(Int.MAX_VALUE) % 3 + bestJ = r.nextInt(Int.MAX_VALUE) % 3 + } + else testMove(-1, 0) + b[bestI][bestJ] = -1 + val myMove = bestI * 3 + bestJ + 1 + println("My move: $myMove") + } + showBoard() + val win = checkWinner() + if (win != 0) return (if (win == 1) "You win" else "I win") + ".\n\n" + u = !u + } + return "A draw.\n\n" +} + +fun main(args: Array) { + var user = false + while (true) { + user = !user + print(game(user)) + var yn: String + do { + print("Play again y/n: ") + yn = readLine()!!.toLowerCase() + } + while (yn != "y" && yn != "n") + if (yn != "y") return + println() + } +} diff --git a/Task/Tic-tac-toe/Lingo/tic-tac-toe.lingo b/Task/Tic-tac-toe/Lingo/tic-tac-toe.lingo new file mode 100644 index 0000000000..7ae95fe656 --- /dev/null +++ b/Task/Tic-tac-toe/Lingo/tic-tac-toe.lingo @@ -0,0 +1,237 @@ +global $ -- object representing simple framework +global gBoard -- current board image +global gBoardTemplate -- empty board image +global gHumanChip -- cross image +global gComputerChip -- circle image +global gM -- 3x3 matrix storing game state: 0=free cell, 1=human cell, -1=computer cell +global gStep -- index of current move (1..9) +global gGameOverFlag -- TRUE if current game is over + +---------------------------------------- +-- Entry point +---------------------------------------- +on startMovie + + -- libs + $.import("sprite") + + -- window properties + _movie.stage.title = "Tic-Tac-Toe" + _movie.stage.rect = rect(0, 0, 224, 310) + _movie.centerStage = TRUE + + -- load images from filesystem + m = new(#bitmap) + m.importFileInto($.@("resources/cross.bmp"), [#trimWhiteSpace:FALSE]) + gHumanChip = m.image + + m = new(#bitmap) + m.importFileInto($.@("resources/circle.bmp"), [#trimWhiteSpace:FALSE]) + gComputerChip = m.image + + -- create GUI + m = new(#bitmap) + m.importFileInto($.@("resources/board.bmp")) + m.regpoint = point(0, 0) + s = $.sprite.make(m, [#loc:point(20, 20)], TRUE) + s.addListener(#mouseDown, _movie, #humanMove) + + gBoard = m.image + gBoardTemplate = gBoard.duplicate() + + m = $.sprite.newMember(#button, [#text:"New Game (Human starts)", #fontstyle:"bold", #rect:rect(0, 0, 180, 0)]) + s = $.sprite.make(m, [#loc:point(20, 220)], TRUE) + s.addListener(#mouseDown, _movie, #newGame, 1) + + m = $.sprite.newMember(#button, [#text:"New Game (Computer starts)", #fontstyle:"bold", #rect:rect(0, 0, 180, 0)]) + s = $.sprite.make(m, [#loc:point(20, 250)], TRUE) + s.addListener(#mouseDown, _movie, #newGame, -1) + + m = $.sprite.newMember(#field, [#name:"feedback", #editable:FALSE, #fontstyle:"bold", #alignment:"center",\ + #border:0, #color:rgb(255, 0, 0), #rect:rect(0, 0, 180, 0)]) + s = $.sprite.make(m, [#loc:point(20, 280)], TRUE) + + newGame(1) + + -- show the application window + _movie.updateStage() + _movie.stage.visible = TRUE +end + +---------------------------------------- +-- Starts a new game +---------------------------------------- +on newGame (whoStarts) + -- reset board + gBoard.copyPixels(gBoardTemplate, gBoardTemplate.rect, gBoardTemplate.rect) + -- clear feedback + member("feedback").text = "" + -- reset states + gM = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] + gStep = 0 + gGameOverFlag = FALSE + if whoStarts=-1 then computerMove() +end + +---------------------------------------- +-- Handles a human move (mouse click) +---------------------------------------- +on humanMove () + if gGameOverFlag then return + -- find cell for mouse position + p = _mouse.clickLoc - sprite(1).loc + if p.locH mod 60<4 or p.locV mod 60<4 then return + p = p / 60 + x = p[1] + 1 + y = p[2] + 1 + if gM[x][y] then return -- ignore illegal moves + gM[x][y] = 1 + -- update cell image + p = p * 60 + gBoard.copyPixels(gHumanChip, gHumanChip.rect.offset(4+p[1], 4+p[2]), gHumanChip.rect) + -- proceed (unless game over) + gStep = gStep + 1 + if not checkHumanMove(x, y) then computerMove() +end + +---------------------------------------- +-- Checks if human has won or game ended with draw +---------------------------------------- +on checkHumanMove (x, y) + if sum([gM[x][1], gM[x][2], gM[x][3]])=3 then return gameOver(1, [[x, 1], [x, 2], [x, 3]]) + if sum([gM[1][y], gM[2][y], gM[3][y]])=3 then return gameOver(1, [[1, y], [2, y], [3, y]]) + if x=y and sum([gM[1][1], gM[2][2], gM[3][3]])=3 then return gameOver(1, [[1, 1], [2, 2], [3, 3]]) + if x+y=4 and sum([gM[1][3], gM[2][2], gM[3][1]])=3 then return gameOver(1, [[1, 3], [2, 2], [3, 1]]) + if gStep=9 then return gameOver(0) + return FALSE +end + +---------------------------------------- +-- Checks if selecting specified empty cell makes computer or human win +---------------------------------------- +on checkCellWins (x, y, who) + wins = who*2 + if sum([gM[1][y], gM[2][y], gM[3][y]]) = wins then return [[1, y], [2, y], [3, y]] + if sum([gM[x][1], gM[x][2], gM[x][3]]) = wins then return [[x, 1], [x, 2], [x, 3]] + if x=y and sum([gM[1][1], gM[2][2], gM[3][3]]) = wins then return [[1, 1], [2, 2], [3, 3]] + if x+y=4 and sum([gM[1][3], gM[2][2], gM[3][1]]) = wins then return [[1, 3], [2, 2], [3, 1]] + return FALSE +end + +---------------------------------------- +-- Handles game over +---------------------------------------- +on gameOver (winner, cells) + gGameOverFlag = TRUE + if winner = 0 then + member("feedback").text = "It's a draw!" + else + -- hilite winning line with yellow + img = image(56, 56, 32) + img.fill(img.rect, rgb(255, 255, 0)) + repeat with c in cells + x = (c[1]-1)*60 + 4 + y = (c[2]-1)*60 + 4 + gBoard.copyPixels(img, img.rect.offset(x, y), img.rect, [#ink:#darkest]) + end repeat + member("feedback").text = ["Human", "Computer"][1+(winner=-1)] & " has won!" + end if + return TRUE +end + +---------------------------------------- +-- Calculates next computer move +---------------------------------------- +on computerMove () + gStep = gStep + 1 + + -- move 1: select center + if gStep=1 then return doComputerMove(2, 2) + + -- move 2 (human started) + if gStep=2 then + if gM[2][2]=1 then + -- if center, select arbitrary corner + return doComputerMove(1, 1) + else + -- otherwise select center + return doComputerMove(2, 2) + end if + end if + + -- move 3 (computer started) + if gStep=3 then + -- if corner, select diagonally opposite corner + if gM[1][1]=1 then return doComputerMove(3, 3) + if gM[3][3]=1 then return doComputerMove(1, 1) + if gM[1][3]=1 then return doComputerMove(3, 1) + return doComputerMove(1, 1) -- top left corner as default + end if + + -- get free cells + free = [] + repeat with x = 1 to 3 + repeat with y = 1 to 3 + if gM[x][y]=0 then free.add([x, y]) + end repeat + end repeat + + -- check if computer can win now + repeat with c in free + res = checkCellWins(c[1], c[2], -1) + if res<>FALSE then + doComputerMove(c[1], c[2]) + return gameOver(-1, res) + end if + end repeat + + -- check if human could win with next move (if yes, prevent it) + repeat with c in free + res = checkCellWins(c[1], c[2], 1) + if res<>FALSE then return doComputerMove(c[1], c[2], TRUE) + end repeat + + -- move 4 (human started): prevent "double mills" + if gStep=4 then + if gM[2][2]=1 and (gM[1][1]=1 or gM[3][3]=1) then return doComputerMove(3, 1) + if gM[2][2]=1 and (gM[1][3]=1 or gM[3][1]=1) then return doComputerMove(1, 1) + if gM[2][3]+gM[3][2]=2 then return doComputerMove(3, 3) + if gM[1][2]+gM[2][3]=2 then return doComputerMove(1, 3) + if gM[1][2]+gM[2][1]=2 then return doComputerMove(1, 1) + if gM[2][1]+gM[3][2]=2 then return doComputerMove(3, 1) + if (gM[1][3]+gM[3][1]=2) or (gM[1][1]+gM[3][3]=2) then return doComputerMove(2, 1) + end if + + -- move 5 (computer started): try to create a "double mill" + if gStep=5 then + repeat with x = 1 to 3 + col = [gM[x][1], gM[x][2], gM[x][3]] + if not (sum(col)=-1 and max(col)=0) then next repeat + repeat with y = 1 to 3 + row = [gM[1][y], gM[2][y], gM[3][y]] + if not (sum(row)=-1 and max(row)=0 and gM[x][y]=0) then next repeat + return doComputerMove(x, y) + end repeat + end repeat + end if + + -- otherwise use first free cell + c = free[1] + doComputerMove(c[1], c[2]) +end + +---------------------------------------- +-- Updates state matrix and cell image +---------------------------------------- +on doComputerMove (x, y, checkDraw) + gM[x][y] = -1 + gBoard.copyPixels(gComputerChip, gComputerChip.rect.offset(4+(x-1)*60, 4+(y-1)*60), gComputerChip.rect) + if checkDraw and gStep=9 then gameOver(0) +end + +---------------------------------------- +-- +---------------------------------------- +on sum (aLine) + return aLine[1]+aLine[2]+aLine[3] +end diff --git a/Task/Tic-tac-toe/Perl-6/tic-tac-toe.pl6 b/Task/Tic-tac-toe/Perl-6/tic-tac-toe.pl6 index b38a268743..46e2eefa67 100644 --- a/Task/Tic-tac-toe/Perl-6/tic-tac-toe.pl6 +++ b/Task/Tic-tac-toe/Perl-6/tic-tac-toe.pl6 @@ -1,12 +1,10 @@ -use v6; - my @board = 1..9; my @winning-positions = [0..2], [3..5], [6..8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [6,4,2]; sub get-winner() { for @winning-positions { - return (@board[$_][0], $_) if [eq] @board[$_]; + return (@board[|$_][0], $_) if [eq] @board[|$_]; } } @@ -22,12 +20,13 @@ sub ai-move() { } sub print-board() { - say @board.map({ "$^a | $^b | $^c" }).join("\n--+---+--\n"), "\n"; + print "\e[2J"; + say @board.map({ "$^a | $^b | $^c" }).join("\n--+---+--\n"), "\n"; } sub human-move() { - my $pos = prompt "Choose one of { (free-indexes >>+>> 1).join(",") }: "; - if $pos eq any(free-indexes >>+>> 1) { + my $pos = prompt "Choose one of { (free-indexes() »+» 1).join(",") }: "; + if $pos eq any(free-indexes() »+» 1) { @board[$pos - 1] = 'x'; } else { say "Sorry, you want to put your 'x' where?"; @@ -35,14 +34,14 @@ sub human-move() { } } -for (&ai-move, &human-move) xx * { +for flat (&ai-move, &human-move) xx * { print-board; - .(); - last if get-winner() or not free-indexes; + last if get-winner() or not free-indexes; + .(); } if get-winner() -> ($player, $across) { - say "$player wins across [", ($across >>+>> 1).join(", "), "]."; + say "$player wins across [", ($across »+» 1).join(", "), "]."; } else { say "How boring, a draw!"; } diff --git a/Task/Tic-tac-toe/REXX/tic-tac-toe.rexx b/Task/Tic-tac-toe/REXX/tic-tac-toe.rexx index 0ba522c693..92f83902fc 100644 --- a/Task/Tic-tac-toe/REXX/tic-tac-toe.rexx +++ b/Task/Tic-tac-toe/REXX/tic-tac-toe.rexx @@ -1,111 +1,143 @@ /*REXX program plays (with a human) the tic─tac─toe game on an NxN grid. */ -$=copies('─', 9) /*eyecatcher literal for error messages*/ -oops =$ '***error*** '; cell@ ="cell number" /*a couple of literals for some SAYs. */ -sing='│─┼'; jam="║"; bar='═'; junc="╬"; dbl=jam || bar || junc -sw=linesize() - 1 /*obtain width of the terminal (less 1)*/ +$=copies('─', 9) /*eyecatcher for error messages, prompt*/ +oops = $ '***error*** ' /*literal for when an error happens. */ +single = '│─┼'; jam= "║"; bar= '═'; junc= "╬"; dbl=jam || bar || junc +sw = linesize() - 1 /*obtain width of the terminal (less 1)*/ parse arg N hm cm .,@. /*obtain optional arguments from the CL*/ if N=='' | N=="," then N=3; oN=N /*N not specified? Then use default.*/ -N=abs(N); NN=N*N; middle=NN%2+N%2 /*if N < 0, then computer goes first. */ -if N<2 then do; say oops 'tic─tac─toe grid is too small: ' N; exit; end -pad=left('', sw%NN) /*display padding: 6x6 in 80 columns.*/ -if hm=='' then hm="X"; if cm=='' then cm="O" /*define the markers: Human, computer*/ -hm=aChar(hm,'human'); cm=aChar(cm,'computer') /*process/define markers for players. */ -parse upper value hm cm with uh uc /*use uppercase values is markers: X x*/ + N = abs(N) /*if N < 0. then computer goes first. */ + NN = N*N /*calculate the square of N. */ +middle = NN % 2 + N % 2 /* " " middle " the grid. */ +if N<2 then do; say oops 'tic─tac─toe grid is too small: ' N; exit 13; end +pad=left('', sw % NN) /*display padding: 6x6 in 80 columns.*/ +if hm=='' then hm= "X"; /*define the marker for a human. */ +if cm=='' then cm= "O" /* " " " " the computer. */ + hm= aChar(hm, 'human') /*determine if the marker is legitimate*/ + cm= aChar(cm, 'computer') /* " " " " " " */ +parse upper value hm cm with uh uc /*use uppercase values is markers: X x*/ if uh==uc then cm=word('O X', 1 + (uh=="O") ) /*The human wants Hal's marker? Swap. */ -if oN<0 then call Hmove middle /*Hal moves first? Then choose middling*/ - else call showGrid /*showGrid also checks for wins & draws*/ - do forever /*'til the cows come home (or QUIT). */ - call CBLF /*process carbon-based lifeform's move.*/ - call Hal /*determine Hal's (the computer) move.*/ - end /*forever*/ /*showGrid subroutine does wins & draws*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -ab: parse arg bx; if bx\==' ' then return bx /*test if the marker isn't a blank.*/ - say oops 'character code for' whoseX "marker can't be a blank." - exit /*stick a fork in it, we're all done. */ +if oN<0 then call Hmove middle /*Hal moves first? Then choose middling*/ + else call showGrid /*showGrid also checks for wins & draws*/ + +/*tic─tac─toe game───►*/ do forever /*'til the cows come home (or QUIT). */ +/*tic─tac─toe game───►*/ call CBLF /*process carbon─based lifeform's move.*/ +/*tic─tac─toe game───►*/ call Hal /*determine Hal's (the computer) move.*/ +/*tic─tac─toe game───►*/ end /*forever*/ /*showGrid subroutine does wins & draws*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ aChar: parse arg x,whoseX; L=length(x) /*process markers.*/ - if L==1 then return ab(x) /*1 char, as is. */ - if L==2 & datatype(x,'X') then return ab(x2c(x)) /*2 chars, hex. */ - if L==3 & datatype(x,'W') then return ab(d2c(x)) /*3 chars, decimal*/ - say oops 'illegal character or character code for' whoseX "marker: " x - exit /*stick a fork in it, we're all done. */ + if L==1 then return testB( x ) /*1 char, as is. */ + if L==2 & datatype(x, 'X') then return testB( x2c(x) ) /*2 chars, hex. */ + if L==3 & datatype(x, 'W') & , /*3 chars, decimal*/ + x>=0 & x<256 then return testB( d2c(x) ) /*···and in range.*/ + say oops 'illegal character or character code for' whoseX "marker: " x + exit 13 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -CBLF : prompt='Please enter a' cell@ "to place your next marker ["hm'] (or Quit):' - do forever; say $ prompt; parse pull x 1 ux 1 ox; upper ux - if datatype(ox,'W') then ox=ox/1 /*maybe normalize cell number: +0007. */ - select - when abbrev('QUIT',ux,1) then call tell 'quitting.' - when x='' then iterate /*Nada? Try again.*/ - when words(x)\==1 then say oops "too many" cell# 'specified:' x - when \datatype(x,'N') then say oops cell@ "isn't numeric: " x - when \datatype(x,'W') then say oops cell@ "isn't an integer: " x - when x=0 then say oops cell@ "can't be zero: " x - when x<0 then say oops cell@ "can't be negative: " x - when x>NN then say oops cell@ "can't exceed " NN - when @.ox\=='' then say oops cell@ "is already occupied: " x - otherwise leave /*forever*/ +CBLF: prompt='Please enter a cell number to place your next marker ['hm"] (or Quit):" + + do forever; say $ prompt + parse pull x 1 ux 1 ox; upper ux /*get versions of answer; uppercase ux*/ + if datatype(ox, 'W') then ox=ox / 1 /*normalize cell number: +0007 ───► 7 */ + /*(division by unity normalizes a num.)*/ + select /*perform some validations of X (cell#)*/ + when abbrev('QUIT',ux,1) then call tell 'quitting.' + when x='' then iterate /*Nada? Try again.*/ + when words(x)\==1 then say oops "too many" cell# 'specified:' x + when \datatype(x, 'N') then say oops "cell number isn't numeric: " x + when \datatype(x, 'W') then say oops "cell number isn't an integer: " x + when x=0 then say oops "cell number can't be zero: " x + when x<0 then say oops "cell number can't be negative: " x + when x>NN then say oops "cell number can't exceed " NN + when @.ox\=='' then say oops "cell number is already occupied: " x + otherwise leave /*forever*/ end /*select*/ + end /*forever*/ + /* [↓] OX is a normalized version of X*/ @.ox=hm /*place a marker for the human (CLBF). */ call showGrid /*and display the tic─tac─toe grid. */ return /*──────────────────────────────────────────────────────────────────────────────────────*/ Hal: select /*Hal tries various moves. */ - when win(cm,N-1) then call Hmove , ec /*is this the winning move?*/ - when win(hm,N-1) then call Hmove , ec /* " " a blocking " */ - when @.middle=='' then call Hmove middle /*pick the center move. */ - when @.N.N=='' then call Hmove , N N /*bottom right corner move.*/ - when @.N.1=='' then call Hmove , N 1 /* " left " " */ - when @.1.N=='' then call Hmove , 1 N /* top right " " */ - when @.1.1=='' then call Hmove , 1 1 /* " left " " */ - otherwise call Hmove , ac /*pick a blank cell " */ + when win(cm, N-1) then call Hmove , ec /*is this the winning move?*/ + when win(hm, N-1) then call Hmove , ec /* " " a blocking " */ + when @.middle== '' then call Hmove middle /*pick the center cell. */ + when @.N.N == '' then call Hmove , N N /*bottom right corner cell.*/ + when @.N.1 == '' then call Hmove , N 1 /* " left " " */ + when @.1.N == '' then call Hmove , 1 N /* top right " " */ + when @.1.1 == '' then call Hmove , 1 1 /* " left " " */ + otherwise call Hmove , ac /*pick a blank cell in grid*/ end /*select*/ return /*──────────────────────────────────────────────────────────────────────────────────────*/ -Hmove: parse arg Hplace,dr dc; if Hplace=='' then Hplace = (dr-1)*N + dc +Hmove: parse arg Hplace,dr dc; if Hplace=='' then Hplace = (dr - 1)*N + dc @.Hplace=cm /*place computer's marker. */ - say; say $ 'computer places a marker ['cm"] at" cell@ ' ' Hplace + say; say $ 'computer places a marker ['cm"] at cell number " Hplace call showGrid return /*──────────────────────────────────────────────────────────────────────────────────────*/ -showGrid: _=0; open=0; cW=5; cH=3 /*cell width, cell height.*/ - do r=1 for N; do c=1 for N; _=_+1; @.r.c=@._; open=open|@._==''; end - end /*r*/ +showGrid: _=0; cW=5; cH=3; open=0 /*cell width, cell height.*/ + do r=1 for N /*construct array of cells.*/ + do c=1 for N; _=_ + 1; @.r.c=@._; open=open | @._=='' + end /*c*/ + end /*r*/ /* [↑] OPEN≡a cell is open*/ say /* [↑] create grid coörds.*/ z=0; do j=1 for N /* [↓] show grids&markers.*/ do t=1 for cH; _=; __= /*MK is a marker in a cell.*/ - do k=1 for N; if t==2 then z=z+1; mk=; c#= - if t==2 then do; mk=@.z; c#=z; end /*c# is cell number*/ - _= _||jam||center(mk,cW); __= __ || jam || center(c#, cW) + do k=1 for N; if t==2 then z=z + 1; mk=; c#= + if t==2 then do; mk=@.z; c#=z /*c# is cell number*/ + end + _= _ || jam || center(mk, cW) + __= __ || jam || center(c#, cW) end /*k*/ - say pad substr(_,2) pad translate(substr(__,2), sing,dbl) - end /*t*/ - if j==N then leave; _= - do b=1 for N; _=_ || junc || copies(bar, cW); end /*b*/ - say pad substr(_,2) pad translate(substr(_,2), sing, dbl) + say pad substr(_, 2) pad translate( substr(__, 2), single, dbl) + end /*t*/ /* [↑] show a line*/ + if j==N then leave + _= + do b=1 for N; _=_ || junc || copies(bar, cW) + end /*b*/ /* [↑] a grid part*/ + say pad substr(_, 2) pad translate( substr(_, 2), single, dbl) end /*j*/ say - if win(hm) then call tell 'You ('hm") won!" + if win(hm) then call tell 'You ('hm") won"copies('!',random(1, 5) ) if win(cm) then call tell 'The computer ('cm") won." - if \open then call tell 'This tic─tac─toe game is a draw.' + if \open then call tell 'This tic─tac─toe game is a draw (a cat scratch).' return /*──────────────────────────────────────────────────────────────────────────────────────*/ -tell: do 4; say; end; say center(' 'arg(1)" ", sw, '─'); do 5; say; end; exit +tell: do 4; say; end; say center(' 'arg(1)" ", sw, '─'); do 5; say; end; exit /*──────────────────────────────────────────────────────────────────────────────────────*/ -win: parse arg wm,w; if w=='' then w=N /*see if there are W of markers*/ - ac=; do r=1 for N; _=0; ec= /*see if any rows are a winner*/ - do c=1 for N; _=_+ (@.r.c==wm); if @.r.c=='' then ec=r c; end - if ec\=='' then ac=ec; if _==N | (_>=w & ec\=='') then return 1 - end /*r*/ /*w=N-1? Checking for near win*/ - do c=1 for N; _=0; ec= /*see if any cols are a winner*/ - do r=1 for N; _=_+ (@.r.c==wm); if @.r.c=='' then ec=r c; end - if ec\=='' then ac=ec; if _==N | (_>=w & ec\=='') then return 1 - end /*r*/ /*EC is a R,C version of cell #*/ - _=0; ec= /*A winning descending diag. ? */ - do d=1 for N; _=_+ (@.d.d==wm); if @.d.d=='' then ec=d d; end - if _==N | (_>=w & ec\=='') then return 1 - _=0; ec=; r=0 /*A winning ascending diagonal?*/ - do c=N for N by -1; r=r+1; _=_+ (@.r.c==wm); if @.r.c=='' then ec=r c - end /*r*/ - if _==N | (_>=w & ec\=='') then return 1 - return 0 +testB: parse arg bx; if bx\==' ' then return bx /*test if the marker isn't a blank.*/ + say oops 'character code for' whoseX "marker can't be a blank." + exit 13 /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +win: parse arg wm,w; if w=='' then w=N /* [↓] see if there is a win. */ + ac= /* [↓] EC ≡ means Empty Cell. */ + do r=1 for N; _=0; ec= /*see if any rows are a winner*/ + do c=1 for N; _=_ + (@.r.c==wm) /*count the # of markers in col*/ + if @.r.c=='' then ec=r c /*Cell empty? Then remember it*/ + end /*c*/ /* [↓] AX≡means avaiable cell.*/ + if ec\=='' then ac=ec /*Found an empty? Then use it.*/ + if _==N | (_>=w & ec\=='') then return 1=1 /*a winner has been determined.*/ + end /*r*/ /*w=N-1? Checking for near win*/ + + do c=1 for N; _=0; ec= /*see if any cols are a winner*/ + do r=1 for N; _=_ + (@.r.c==wm) /*count the # of markers in row*/ + if @.r.c=='' then ec=r c /*Cell empty? Then remember it*/ + end /*r*/ + if ec\=='' then ac=ec /*Found an empty? Then remember*/ + if _==N | (_>=w & ec\=='') then return 1=1 /*a winner has been determined.*/ + end /*c*/ + _=0 + ec= /*EC≡location of an empty cell.*/ + do d=1 for N; _=_ + (@.d.d==wm) /*A winning descending diag. ? */ + if @.d.d=='' then ec=d d /*Empty cell? Then note cell #*/ + end /*d*/ + + if _==N | (_>=w & ec\=='') then return 1=1 /*a winner has been determined.*/ + _=0; r=1 + do c=N for N by -1; _=_ + (@.r.c==wm) /*A winning ascending diagonal?*/ + if @.r.c=='' then ec=r c /*Empty cell? Then note cell #*/ + r=r + 1 /*bump the counter for the rows*/ + end /*c*/ + + if _==N | (_>=w & ec\=='') then return 1=1 /*a winner has been determined.*/ + return 0 /*no winner " " " */ diff --git a/Task/Tic-tac-toe/Scala/tic-tac-toe.scala b/Task/Tic-tac-toe/Scala/tic-tac-toe.scala index a05aea7754..197bf17f9f 100644 --- a/Task/Tic-tac-toe/Scala/tic-tac-toe.scala +++ b/Task/Tic-tac-toe/Scala/tic-tac-toe.scala @@ -39,7 +39,7 @@ class Board(aBoard : List[Char] = BaseBoard) { } -object TicTacToe extends Application { +object TicTacToe extends App { def play(board : Board, turn : Char) { diff --git a/Task/Tic-tac-toe/VBA/tic-tac-toe.vba b/Task/Tic-tac-toe/VBA/tic-tac-toe.vba new file mode 100644 index 0000000000..1dcb0d331e --- /dev/null +++ b/Task/Tic-tac-toe/VBA/tic-tac-toe.vba @@ -0,0 +1,126 @@ +Option Explicit + +Private Lines(1 To 3, 1 To 3) As String +Private Nb As Byte, player As Byte +Private GameWin As Boolean, GameOver As Boolean + +Sub Main_TicTacToe() +Dim p As String + + InitLines + printLines Nb + Do + p = WhoPlay + Debug.Print p & " play" + If p = "Human" Then + Call HumanPlay + GameWin = IsWinner("X") + Else + Call ComputerPlay + GameWin = IsWinner("O") + End If + If Not GameWin Then GameOver = IsEnd + Loop Until GameWin Or GameOver + If Not GameOver Then + Debug.Print p & " Win !" + Else + Debug.Print "Game Over!" + End If +End Sub + +Sub InitLines(Optional S As String) +Dim i As Byte, j As Byte + Nb = 0: player = 0 + For i = LBound(Lines, 1) To UBound(Lines, 1) + For j = LBound(Lines, 2) To UBound(Lines, 2) + Lines(i, j) = "#" + Next j + Next i +End Sub + +Sub printLines(Nb As Byte) +Dim i As Byte, j As Byte, strT As String + Debug.Print "Loop " & Nb + For i = LBound(Lines, 1) To UBound(Lines, 1) + For j = LBound(Lines, 2) To UBound(Lines, 2) + strT = strT & Lines(i, j) + Next j + Debug.Print strT + strT = vbNullString + Next i +End Sub + +Function WhoPlay(Optional S As String) As String + If player = 0 Then + player = 1 + WhoPlay = "Human" + Else + player = 0 + WhoPlay = "Computer" + End If +End Function + +Sub HumanPlay(Optional S As String) +Dim L As Byte, C As Byte, GoodPlay As Boolean + + Do + L = Application.InputBox("Choose the row", "Numeric only", Type:=1) + If L > 0 And L < 4 Then + C = Application.InputBox("Choose the column", "Numeric only", Type:=1) + If C > 0 And C < 4 Then + If Lines(L, C) = "#" And Not Lines(L, C) = "X" And Not Lines(L, C) = "O" Then + Lines(L, C) = "X" + Nb = Nb + 1 + printLines Nb + GoodPlay = True + End If + End If + End If + Loop Until GoodPlay +End Sub + +Sub ComputerPlay(Optional S As String) +Dim L As Byte, C As Byte, GoodPlay As Boolean + + Randomize Timer + Do + L = Int((Rnd * 3) + 1) + C = Int((Rnd * 3) + 1) + If Lines(L, C) = "#" And Not Lines(L, C) = "X" And Not Lines(L, C) = "O" Then + Lines(L, C) = "O" + Nb = Nb + 1 + printLines Nb + GoodPlay = True + End If + Loop Until GoodPlay +End Sub + +Function IsWinner(S As String) As Boolean +Dim i As Byte, j As Byte, Ch As String, strTL As String, strTC As String + + Ch = String(UBound(Lines, 1), S) + 'check lines & columns + For i = LBound(Lines, 1) To UBound(Lines, 1) + For j = LBound(Lines, 2) To UBound(Lines, 2) + strTL = strTL & Lines(i, j) + strTC = strTC & Lines(j, i) + Next j + If strTL = Ch Or strTC = Ch Then IsWinner = True: Exit For + strTL = vbNullString: strTC = vbNullString + Next i + 'check diagonales + strTL = Lines(1, 1) & Lines(2, 2) & Lines(3, 3) + strTC = Lines(1, 3) & Lines(2, 2) & Lines(3, 1) + If strTL = Ch Or strTC = Ch Then IsWinner = True +End Function + +Function IsEnd() As Boolean +Dim i As Byte, j As Byte + + For i = LBound(Lines, 1) To UBound(Lines, 1) + For j = LBound(Lines, 2) To UBound(Lines, 2) + If Lines(i, j) = "#" Then Exit Function + Next j + Next i + IsEnd = True +End Function diff --git a/Task/Time-a-function/Elena/time-a-function.elena b/Task/Time-a-function/Elena/time-a-function.elena new file mode 100644 index 0000000000..9ff629dacd --- /dev/null +++ b/Task/Time-a-function/Elena/time-a-function.elena @@ -0,0 +1,23 @@ +import system'calendar. +import system'routines. +import system'threading. +import system'math. +import extensions. + +someProcess = +[ + thread sleep(1000). + + Range new(0,10000); filterBy(:x)(x mod:2 == 0); summarize. +]. + +program = +[ + var start := now. + + someProcess eval. + + var end := now. + + console printLine("Time elapsed in msec:",(end - start) milliseconds). +]. diff --git a/Task/Tokenize-a-string/360-Assembly/tokenize-a-string.360 b/Task/Tokenize-a-string/360-Assembly/tokenize-a-string.360 new file mode 100644 index 0000000000..743247605c --- /dev/null +++ b/Task/Tokenize-a-string/360-Assembly/tokenize-a-string.360 @@ -0,0 +1,83 @@ +* Tokenize a string - 08/06/2018 +TOKSTR CSECT + USING TOKSTR,R13 base register + B 72(R15) skip savearea + DC 17F'0' savearea + SAVE (14,12) save previous context + ST R13,4(R15) link backward + ST R15,8(R13) link forward + LR R13,R15 set addressability + MVC N,=A(1) n=1 + LA R7,1 i1=1 + LA R6,1 i=1 + DO WHILE=(C,R6,LE,LENS) do i=1 to length(s); + LA R4,S-1 @s-1 + AR R4,R6 +i + MVC C,0(R4) c=substr(s,i,1) + IF CLI,C,EQ,C',' THEN if c=',' then do + BAL R14,TOK call tok + LR R2,R8 i2 + SR R2,R7 i2-i1 + LA R2,1(R2) i2-i1+1 + L R1,N n + SLA R1,1 *2 + STH R2,TALEN-2(R1) talen(n)=i2-i1+1 + L R2,N n + LA R2,1(R2) n+1 + ST R2,N n=n+1 + LA R7,1(R6) i1=i+1 + ENDIF , endif + LA R6,1(R6) i++ + ENDDO , enddo i + BAL R14,TOK call tok + LR R2,R8 i2 + SR R2,R7 i2-i1 + LA R2,1(R2) i2-i1+1 + L R1,N n + SLA R1,1 *2 + STH R2,TALEN-2(R1) talen(n)=i2-i1+1 + LA R11,PG pgi=@pg + LA R6,1 i=1 + DO WHILE=(C,R6,LE,N) do i=1 to n + LR R1,R6 i + SLA R1,1 *2 + LH R10,TALEN-2(R1) l=talen(i) + LR R1,R6 i + SLA R1,3 *8 + LA R4,TABLE-8(R1) @table(i) + LR R2,R10 l + BCTR R2,0 ~ + EX R2,MVCX output table(i) length(l) + AR R11,R10 pgi=pgi+l + IF C,R6,NE,N THEN if i^=n then + MVC 0(1,R11),=C'.' output '.' + LA R11,1(R11) pgi=pgi+1 + ENDIF , endif + LA R6,1(R6) i++ + ENDDO , enddo i + XPRNT PG,L'PG print + L R13,4(0,R13) restore previous savearea pointer + RETURN (14,12),RC=0 restore registers from calling sav +TOK LR R5,R6 i <-- + BCTR R5,0 i-1 | + LR R8,R5 i2=i-1 + SR R5,R7 i2-i1 + LA R5,1(R5) l=i2-i1+1 source length + L R1,N n + SLA R1,3 *8 + LA R2,TABLE-8(R1) @table(n) + LA R4,S-1 @s-1 + AR R4,R7 @s+i1-1 + LA R3,8 target length + MVCL R2,R4 table(n)=substr(s,i1,i2-i1+1) | + BR R14 End TOK subroutine <-- +MVCX MVC 0(0,R11),0(R4) output table(i) +S DC CL80'Hello,How,Are,You,Today' <== input string == +LENS DC F'23' length(s) <== +TABLE DC 8CL8' ' table(8) +TALEN DC 8H'0' talen(8) +C DS CL1 char +N DS F number of tokens +PG DC CL80' ' buffer + YREGS + END TOKSTR diff --git a/Task/Tokenize-a-string/Ada/tokenize-a-string.ada b/Task/Tokenize-a-string/Ada/tokenize-a-string.ada index 7d375c4c7b..8be83b5ac3 100644 --- a/Task/Tokenize-a-string/Ada/tokenize-a-string.ada +++ b/Task/Tokenize-a-string/Ada/tokenize-a-string.ada @@ -1,24 +1,17 @@ -with Ada.Text_IO, Ada.Strings.Fixed, Ada.Containers.Indefinite_Vectors; -use Ada.Text_IO, Ada.Strings.Fixed, Ada.Containers; +with Ada.Text_IO, Ada.Containers.Indefinite_Vectors; +use Ada.Text_IO, Ada.Containers; procedure tokenize is package String_Vector is new Indefinite_Vectors (Natural,String); use String_Vector; - procedure Parse (s : String; v : in out Vector) is - i : Integer := Index (s,","); - begin - if s'Length > 0 then - if i < s'First then - v.Append (s); - else - v.Append (s (s'First..i-1)); - Parse ( s(i+1..s'Last), v); - end if; - end if; - end Parse; - v : Vector; + s : String := "Hello,How,Are,You,Today" & ","; + current : Positive := s'First; + v : Vector; begin - Parse ("Hello,How,Are,You,Today,,",v); - for s of v loop - put(s&"."); - end loop; + for i in s'range loop + if s (i) = ',' or i = s'last then + v.append (s (current .. i-1)); + current := i + 1; + end if; + end loop; + for s of v loop put(s & "."); end loop; end tokenize; diff --git a/Task/Tokenize-a-string/Astro/tokenize-a-string.astro b/Task/Tokenize-a-string/Astro/tokenize-a-string.astro index d52871edd1..18899930bd 100644 --- a/Task/Tokenize-a-string/Astro/tokenize-a-string.astro +++ b/Task/Tokenize-a-string/Astro/tokenize-a-string.astro @@ -1,3 +1,3 @@ let text = 'Hello,How,Are,You,Today' -let tokens = text.split /,/ -print join('.', tokens) +let tokens = text.split(/,/) +print tokens.join(with: '.') diff --git a/Task/Tokenize-a-string/Falcon/tokenize-a-string.falcon b/Task/Tokenize-a-string/Falcon/tokenize-a-string.falcon new file mode 100644 index 0000000000..68bed10439 --- /dev/null +++ b/Task/Tokenize-a-string/Falcon/tokenize-a-string.falcon @@ -0,0 +1,13 @@ +/* created by Aykayayciti Earl Lamont Montgomery +April 9th, 2018 */ + +a = [] +a = strSplit("Hello,How,Are,You,Today", ",") +index = 0 +start = 0 +b = "" +for index in [ start : len(a)-1 : 1 ] + b = b + a[index] + "." +end + +> b diff --git a/Task/Tokenize-a-string/Gambas/tokenize-a-string.gambas b/Task/Tokenize-a-string/Gambas/tokenize-a-string.gambas new file mode 100644 index 0000000000..734aeb3837 --- /dev/null +++ b/Task/Tokenize-a-string/Gambas/tokenize-a-string.gambas @@ -0,0 +1,6 @@ +Public Sub Main() +Dim sString As String[] = Split("Hello,How,Are,You,Today") + +Print sString.Join(".") + +End diff --git a/Task/Tokenize-a-string/Maple/tokenize-a-string.maple b/Task/Tokenize-a-string/Maple/tokenize-a-string.maple new file mode 100644 index 0000000000..ae7c86265c --- /dev/null +++ b/Task/Tokenize-a-string/Maple/tokenize-a-string.maple @@ -0,0 +1 @@ +StringTools:-Join(StringTools:-Split("Hello,How,Are,You,Today", ","),"."); diff --git a/Task/Tokenize-a-string/Nial/tokenize-a-string-1.nial b/Task/Tokenize-a-string/Nial/tokenize-a-string-1.nial new file mode 100644 index 0000000000..8e8c5f0378 --- /dev/null +++ b/Task/Tokenize-a-string/Nial/tokenize-a-string-1.nial @@ -0,0 +1,4 @@ + s := 'Hello,How,Are,You,Today' ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +|H|e|l|l|o|,|H|o|w|,|A|r|e|,|Y|o|u|,|T|o|d|a|y| ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ diff --git a/Task/Tokenize-a-string/Nial/tokenize-a-string-2.nial b/Task/Tokenize-a-string/Nial/tokenize-a-string-2.nial new file mode 100644 index 0000000000..089ba634ff --- /dev/null +++ b/Task/Tokenize-a-string/Nial/tokenize-a-string-2.nial @@ -0,0 +1,6 @@ + t := s eachall = `, cut s ++-----------+-------+-------+-------+-----------+ +|+-+-+-+-+-+|+-+-+-+|+-+-+-+|+-+-+-+|+-+-+-+-+-+| +||H|e|l|l|o|||H|o|w|||A|r|e|||Y|o|u|||T|o|d|a|y|| +|+-+-+-+-+-+|+-+-+-+|+-+-+-+|+-+-+-+|+-+-+-+-+-+| ++-----------+-------+-------+-------+-----------+ diff --git a/Task/Tokenize-a-string/Nial/tokenize-a-string-3.nial b/Task/Tokenize-a-string/Nial/tokenize-a-string-3.nial new file mode 100644 index 0000000000..c5058cb5a4 --- /dev/null +++ b/Task/Tokenize-a-string/Nial/tokenize-a-string-3.nial @@ -0,0 +1,4 @@ + u := front content (cart t `.) ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +|H|e|l|l|o|.|H|o|w|.|A|r|e|.|Y|o|u|.|T|o|d|a|y| ++-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ diff --git a/Task/Tokenize-a-string/Nial/tokenize-a-string-4.nial b/Task/Tokenize-a-string/Nial/tokenize-a-string-4.nial new file mode 100644 index 0000000000..2e645c487d --- /dev/null +++ b/Task/Tokenize-a-string/Nial/tokenize-a-string-4.nial @@ -0,0 +1,8 @@ + s:='Hello,How,Are,You,Today' +Hello,How,Are,You,Today + t:= s eachall = `, cut s ++-----+---+---+---+-----+ +|Hello|How|Are|You|Today| ++-----+---+---+---+-----+ + u:=front content (cart t `.) +Hello.How.Are.You.Today diff --git a/Task/Tokenize-a-string/Red/tokenize-a-string.red b/Task/Tokenize-a-string/Red/tokenize-a-string.red new file mode 100644 index 0000000000..d6cbe8dc5d --- /dev/null +++ b/Task/Tokenize-a-string/Red/tokenize-a-string.red @@ -0,0 +1,8 @@ +str: "Hello,How,Are,You,Today" +>> tokens: split str "," +>> probe tokens +["Hello" "How" "Are" "You" "Today"] + +>> periods: replace/all form tokens " " "." ;The word FORM converts the list series to a string removing quotes. +>> print periods ;then REPLACE/ALL spaces with period +Hello.How.Are.You.Today diff --git a/Task/Tokenize-a-string/VBA/tokenize-a-string.vba b/Task/Tokenize-a-string/VBA/tokenize-a-string.vba new file mode 100644 index 0000000000..a8779aad2b --- /dev/null +++ b/Task/Tokenize-a-string/VBA/tokenize-a-string.vba @@ -0,0 +1,13 @@ +Sub Main() +Dim temp() As String + temp = Tokenize("Hello,How,Are,You,Today", ",") + Display temp, Space(5) +End Sub + +Private Function Tokenize(strS As String, sep As String) As String() + Tokenize = Split(strS, sep) +End Function + +Private Sub Display(arr() As String, sep As String) + Debug.Print Join(arr, sep) +End Sub diff --git a/Task/Top-rank-per-group/Aime/top-rank-per-group.aime b/Task/Top-rank-per-group/Aime/top-rank-per-group.aime index 4c9167462c..b55bfacb2e 100644 --- a/Task/Top-rank-per-group/Aime/top-rank-per-group.aime +++ b/Task/Top-rank-per-group/Aime/top-rank-per-group.aime @@ -2,16 +2,15 @@ void Add_Employee(record employees, text name, text id, integer salary, text department) { - employees[name] = l_effect(name, id, salary, department); + employees[name] = list(name, id, salary, department); } void collect(record top, record employees) { - text name; list l; - for (name, l in employees) { + for (, l in employees) { list department; integer i, salary; @@ -29,7 +28,7 @@ collect(record top, record employees) l_l_list(department, i, l); if (~department == N + 1) { - l_delete(department, N); + department.delete(N); } } } @@ -41,12 +40,11 @@ print(record top) list employees; for (department, employees in top) { - integer i; list l; - o_plan("Department ", department, "\n"); + o_("Department ", department, "\n"); - for (i, l in employees) { + for (, l in employees) { o_form(" ~ | ~ | ~\n", l[0], l[1], l[2]); } } diff --git a/Task/Top-rank-per-group/Ceylon/top-rank-per-group.ceylon b/Task/Top-rank-per-group/Ceylon/top-rank-per-group.ceylon new file mode 100644 index 0000000000..5af50c5c1a --- /dev/null +++ b/Task/Top-rank-per-group/Ceylon/top-rank-per-group.ceylon @@ -0,0 +1,42 @@ +class Employee(name, id, salary, dept) { + shared String name; + shared String id; + shared Integer salary; + shared String dept; + + string => "``name`` ``id`` $``salary``.00 ``dept``"; +} + +Employee[] employees = [ + Employee("Tyler Bennett", "E10297", 32000, "D101"), + Employee("John Rappl", "E21437", 47000, "D050"), + Employee("George Woltman", "E00127", 53500, "D101"), + Employee("Adam Smith", "E63535", 18000, "D202"), + Employee("Claire Buckman", "E39876", 27800, "D202"), + Employee("David McClellan", "E04242", 41500, "D101"), + Employee("Rich Holcomb", "E01234", 49500, "D202"), + Employee("Nathan Adams", "E41298", 21900, "D050"), + Employee("Richard Potter", "E43128", 15900, "D101"), + Employee("David Motsinger", "E27002", 19250, "D202"), + Employee("Tim Sampair", "E03033", 27000, "D101"), + Employee("Kim Arlich", "E10001", 57000, "D190"), + Employee("Timothy Grove", "E16398", 29900, "D190") +]; + +"This is the main function." +shared void run() { + + value topRanked = topSalaries(employees, 3); + + for (dept -> staff in topRanked) { + print(dept); + for (employee in staff) { + print("\t``employee``"); + } + } +} + +Map topSalaries({Employee*} employees, Integer n) => map { + for (dept -> staff in employees.group(Employee.dept)) + dept -> staff.sort(byDecreasing(Employee.salary)).take(n) +}; diff --git a/Task/Top-rank-per-group/Perl-6/top-rank-per-group.pl6 b/Task/Top-rank-per-group/Perl-6/top-rank-per-group.pl6 index 0d545119e2..ae45a2dfe6 100644 --- a/Task/Top-rank-per-group/Perl-6/top-rank-per-group.pl6 +++ b/Task/Top-rank-per-group/Perl-6/top-rank-per-group.pl6 @@ -16,7 +16,7 @@ my @data = do for q:to/---/.lines -> $line { $%( < Id Salary Dept Name > Z=> - $line.split(/ \t+ /) + $line.split(/ \s\s+ /) ) } diff --git a/Task/Top-rank-per-group/R/top-rank-per-group-5.r b/Task/Top-rank-per-group/R/top-rank-per-group-5.r new file mode 100644 index 0000000000..55f90c3e83 --- /dev/null +++ b/Task/Top-rank-per-group/R/top-rank-per-group-5.r @@ -0,0 +1,6 @@ +library(dplyr) +dfr %>% + group_by(Department) %>% + mutate(r=rank(-Salary)) %>% + filter(r<3) %>% + arrange(Department,-Salary) diff --git a/Task/Top-rank-per-group/Ring/top-rank-per-group.ring b/Task/Top-rank-per-group/Ring/top-rank-per-group.ring new file mode 100644 index 0000000000..de08247055 --- /dev/null +++ b/Task/Top-rank-per-group/Ring/top-rank-per-group.ring @@ -0,0 +1,62 @@ +# Project : Top rank per group +# Date : 2017/12/10 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +load "stdlib.ring" +salary = "Tyler Bennett,E10297,32000,D101 +John Rappl,E21437,47000,D050 +George Woltman,E00127,53500,D101 +Adam Smith,E63535,18000,D202 +Claire Buckman,E39876,27800,D202 +David McClellan,E04242,41500,D101 +Rich Holcomb,E01234,49500,D202 +Nathan Adams,E41298,21900,D050 +Richard Potter,E43128,15900,D101 +David Motsinger,E27002,19250,D202 +Tim Sampair,E03033,27000,D101 +Kim Arlich,E10001,57000,D190 +Timothy Grove,E16398,29900,D190" + +temp = substr(salary, ",", nl) +temp = str2list(temp) +depsal = newlist(13,4) +for n = 1 to len(temp) + n1 = ceil(n/4) + n2 = n%4 + if n2 = 0 + n2 = 4 + ok + depsal[n1][n2] = temp[n] +next +for n = 1 to len(depsal)-1 + for m = n+1 to len(depsal) + if strcmp(depsal[m][4], depsal[n][4]) < 0 + tmp = depsal[n] + depsal[n] = depsal[m] + depsal[m] = tmp + ok + next +next +for n = 1 to len(depsal)-1 + for m = n+1 to len(depsal) + if (depsal[m][4] = depsal[n][4]) and (depsal[m][3] > depsal[n][3]) + tmp = depsal[n] + depsal[n] = depsal[m] + depsal[m] = tmp + ok + next +next +see "Department : " + depsal[1][4] + nl +see "Name " + "Id " + "Salary" + nl + nl +see "" + depsal[1][1] + " " + depsal[1][2] + " " + depsal[1][3]+ nl +for n = 1 to len(depsal)-1 + if (depsal[n+1][4] != depsal[n][4]) + see nl + see "Department : " + depsal[n+1][4] + nl + see "Name " + "Id " + "Salary" + nl + nl + see "" + depsal[n+1][1] + " " + depsal[n+1][2] + " " + depsal[n+1][3]+ nl + else + see "" + depsal[n+1][1] + " " + depsal[n+1][2] + " " + depsal[n+1][3]+ nl + ok +next diff --git a/Task/Topic-variable/AppleScript/topic-variable-1.applescript b/Task/Topic-variable/AppleScript/topic-variable-1.applescript index d6a8a12542..3d60b45c5f 100644 --- a/Task/Topic-variable/AppleScript/topic-variable-1.applescript +++ b/Task/Topic-variable/AppleScript/topic-variable-1.applescript @@ -23,13 +23,11 @@ end squareRoot -- A list of functions applied to a list of arguments -- (<*> | ap) :: [(a -> b)] -> [a] -> [b] on ap(fs, xs) - set intFs to length of fs - set intXs to length of xs set lst to {} - repeat with i from 1 to intFs - tell mReturn(item i of fs) - repeat with j from 1 to intXs - set end of lst to |λ|(contents of (item j of xs)) + repeat with f in fs + tell mReturn(contents of f) + repeat with x in xs + set end of lst to |λ|(contents of x) end repeat end tell end repeat diff --git a/Task/Topic-variable/Scala/topic-variable.scala b/Task/Topic-variable/Scala/topic-variable.scala new file mode 100644 index 0000000000..467a964ec2 --- /dev/null +++ b/Task/Topic-variable/Scala/topic-variable.scala @@ -0,0 +1,13 @@ +object TopicVar extends App { + class SuperString(val org: String){ + def it(): Unit = println(org) + } + + new SuperString("FvdB"){it()} + new SuperString("FvdB"){println(org)} + + Seq(1).foreach {println} + Seq(2).foreach {println(_)} + Seq(4).foreach { it => println(it)} + Seq(8).foreach { it => println(it + it)} +} diff --git a/Task/Topological-sort/C-sharp/topological-sort-1.cs b/Task/Topological-sort/C-sharp/topological-sort-1.cs new file mode 100644 index 0000000000..6e3bfab49b --- /dev/null +++ b/Task/Topological-sort/C-sharp/topological-sort-1.cs @@ -0,0 +1,139 @@ +namespace Algorithms +{ + using System; + using System.Collections.Generic; + using System.Linq; + + public class TopologicalSorter + { + private class Relations + { + public int Dependencies = 0; + public HashSet Dependents = new HashSet(); + } + + private Dictionary _map = new Dictionary(); + + public void Add(ValueType obj) + { + if (!_map.ContainsKey(obj)) _map.Add(obj, new Relations()); + } + + public void Add(ValueType obj, ValueType dependency) + { + if (dependency.Equals(obj)) return; + + if (!_map.ContainsKey(dependency)) _map.Add(dependency, new Relations()); + + var dependents = _map[dependency].Dependents; + + if (!dependents.Contains(obj)) + { + dependents.Add(obj); + + if (!_map.ContainsKey(obj)) _map.Add(obj, new Relations()); + + ++_map[obj].Dependencies; + } + } + + public void Add(ValueType obj, IEnumerable dependencies) + { + foreach (var dependency in dependencies) Add(obj, dependency); + } + + public void Add(ValueType obj, params ValueType[] dependencies) + { + Add(obj, dependencies as IEnumerable); + } + + public Tuple, IEnumerable> Sort() + { + List sorted = new List(), cycled = new List(); + var map = _map.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + + sorted.AddRange(map.Where(kvp => kvp.Value.Dependencies == 0).Select(kvp => kvp.Key)); + + for (int idx = 0; idx < sorted.Count; ++idx) sorted.AddRange(map[sorted[idx]].Dependents.Where(k => --map[k].Dependencies == 0)); + + cycled.AddRange(map.Where(kvp => kvp.Value.Dependencies != 0).Select(kvp => kvp.Key)); + + return new Tuple, IEnumerable>(sorted, cycled); + } + + public void Clear() + { + _map.Clear(); + } + } + +} + +/* + Example usage with Task object +*/ + +namespace ExampleApplication +{ + using Algorithms; + using System; + using System.Collections.Generic; + using System.Linq; + + public class Task + { + public string Message; + } + + class Program + { + static void Main(string[] args) + { + List tasks = new List + { + new Task{ Message = "A - depends on B and C" }, //0 + new Task{ Message = "B - depends on none" }, //1 + new Task{ Message = "C - depends on D and E" }, //2 + new Task{ Message = "D - depends on none" }, //3 + new Task{ Message = "E - depends on F, G and H" }, //4 + new Task{ Message = "F - depends on I" }, //5 + new Task{ Message = "G - depends on none" }, //6 + new Task{ Message = "H - depends on none" }, //7 + new Task{ Message = "I - depends on none" }, //8 + }; + + TopologicalSorter resolver = new TopologicalSorter(); + + // now setting relations between them as described above + resolver.Add(tasks[0], new[] { tasks[1], tasks[2] }); + //resolver.Add(tasks[1]); // no need for this since the task was already mentioned as a dependency + resolver.Add(tasks[2], new[] { tasks[3], tasks[4] }); + //resolver.Add(tasks[3]); // no need for this since the task was already mentioned as a dependency + resolver.Add(tasks[4], tasks[5], tasks[6], tasks[7]); + resolver.Add(tasks[5], tasks[8]); + //resolver.Add(tasks[6]); // no need for this since the task was already mentioned as a dependency + //resolver.Add(tasks[7]); // no need for this since the task was already mentioned as a dependency + + //resolver.Add(tasks[3], tasks[0]); // uncomment this line to test cycled dependency + + var result = resolver.Sort(); + var sorted = result.Item1; + var cycled = result.Item2; + + if (!cycled.Any()) + { + foreach (var d in sorted) Console.WriteLine(d.Message); + } + else + { + Console.Write("Cycled dependencies detected: "); + + foreach (var d in cycled) Console.Write($"{d.Message[0]} "); + + Console.WriteLine(); + } + + Console.WriteLine("exiting..."); + } + } +} diff --git a/Task/Topological-sort/C-sharp/topological-sort-2.cs b/Task/Topological-sort/C-sharp/topological-sort-2.cs new file mode 100644 index 0000000000..a781071420 --- /dev/null +++ b/Task/Topological-sort/C-sharp/topological-sort-2.cs @@ -0,0 +1,10 @@ +B - depends on none +D - depends on none +G - depends on none +H - depends on none +I - depends on none +F - depends on I +E - depends on F, G and H +C - depends on D and E +A - depends on B and C +exiting... diff --git a/Task/Topological-sort/C-sharp/topological-sort-3.cs b/Task/Topological-sort/C-sharp/topological-sort-3.cs new file mode 100644 index 0000000000..d004b14877 --- /dev/null +++ b/Task/Topological-sort/C-sharp/topological-sort-3.cs @@ -0,0 +1,2 @@ +Cycled dependencies detected: A C D +exiting... diff --git a/Task/Topological-sort/D/topological-sort.d b/Task/Topological-sort/D/topological-sort.d index 73bb400cd0..8068e276f8 100644 --- a/Task/Topological-sort/D/topological-sort.d +++ b/Task/Topological-sort/D/topological-sort.d @@ -30,7 +30,7 @@ string[][] topoSort(TDependencies d) pure /*nothrow @safe*/ { TDependencies dd; foreach (immutable item, const dep; d) if (!ordered.canFind(item)) - dd[item] = dep.filter!(s => !ordered.canFind(s)).array; + dd[item] = dep.dup.filter!(s => !ordered.canFind(s)).array; d = dd; } diff --git a/Task/Topological-sort/Java/topological-sort.java b/Task/Topological-sort/Java/topological-sort.java index a81c90b4f0..9bf483efc1 100644 --- a/Task/Topological-sort/Java/topological-sort.java +++ b/Task/Topological-sort/Java/topological-sort.java @@ -16,7 +16,7 @@ public class TopologicalSort { {8, 1}, {8, 10}, {9, 1}, {9, 10}, {10, 1}, - {11, 1}, {11, 10}, + {11, 1}, {12, 0}, {12, 1}, {13, 1} }); diff --git a/Task/Topological-sort/Julia/topological-sort.julia b/Task/Topological-sort/Julia/topological-sort.julia new file mode 100644 index 0000000000..ab73381835 --- /dev/null +++ b/Task/Topological-sort/Julia/topological-sort.julia @@ -0,0 +1,37 @@ +function toposort(data::Dict{T,Set{T}}) where T + data = copy(data) + for (k, v) in data + delete!(v, k) + end + extraitems = setdiff(reduce(∪, values(data)), keys(data)) + for item in extraitems + data[item] = Set{T}() + end + rst = Vector{T}() + while true + ordered = Set(item for (item, dep) in data if isempty(dep)) + if isempty(ordered) break end + append!(rst, ordered) + data = Dict{T,Set{T}}(item => setdiff(dep, ordered) for (item, dep) in data if item ∉ ordered) + end + @assert isempty(data) "a cyclic dependency exists amongst $(keys(data))" + return rst +end + +data = Dict{String,Set{String}}( + "des_system_lib" => Set(split("std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee")), + "dw01" => Set(split("ieee dw01 dware gtech")), + "dw02" => Set(split("ieee dw02 dware")), + "dw03" => Set(split("std synopsys dware dw03 dw02 dw01 ieee gtech")), + "dw04" => Set(split("dw04 ieee dw01 dware gtech")), + "dw05" => Set(split("dw05 ieee dware")), + "dw06" => Set(split("dw06 ieee dware")), + "dw07" => Set(split("ieee dware")), + "dware" => Set(split("ieee dware")), + "gtech" => Set(split("ieee gtech")), + "ramlib" => Set(split("std ieee")), + "std_cell_lib" => Set(split("ieee std_cell_lib")), + "synopsys" => Set(), + ) + +println("# Topologically sorted:\n - ", join(toposort(data), "\n - ")) diff --git a/Task/Topological-sort/Kotlin/topological-sort.kotlin b/Task/Topological-sort/Kotlin/topological-sort.kotlin new file mode 100644 index 0000000000..009845cc92 --- /dev/null +++ b/Task/Topological-sort/Kotlin/topological-sort.kotlin @@ -0,0 +1,69 @@ +// version 1.1.51 + +val s = "std, ieee, des_system_lib, dw01, dw02, dw03, dw04, dw05, " + + "dw06, dw07, dware, gtech, ramlib, std_cell_lib, synopsys" + +val deps = mutableListOf( + 2 to 0, 2 to 14, 2 to 13, 2 to 4, 2 to 3, 2 to 12, 2 to 1, + 3 to 1, 3 to 10, 3 to 11, + 4 to 1, 4 to 10, + 5 to 0, 5 to 14, 5 to 10, 5 to 4, 5 to 3, 5 to 1, 5 to 11, + 6 to 1, 6 to 3, 6 to 10, 6 to 11, + 7 to 1, 7 to 10, + 8 to 1, 8 to 10, + 9 to 1, 9 to 10, + 10 to 1, + 11 to 1, + 12 to 0, 12 to 1, + 13 to 1 +) + +class Graph(s: String, edges: List>) { + + val vertices = s.split(", ") + val numVertices = vertices.size + val adjacency = List(numVertices) { BooleanArray(numVertices) } + + init { + for (edge in edges) adjacency[edge.first][edge.second] = true + } + + fun hasDependency(r: Int, todo: List): Boolean { + for (c in todo) if (adjacency[r][c]) return true + return false + } + + fun topoSort(): List? { + val result = mutableListOf() + val todo = MutableList(numVertices) { it } + try { + outer@ while(!todo.isEmpty()) { + for ((i, r) in todo.withIndex()) { + if (!hasDependency(r, todo)) { + todo.removeAt(i) + result.add(vertices[r]) + continue@outer + } + } + throw Exception("Graph has cycles") + } + } + catch (e: Exception) { + println(e) + return null + } + return result + } +} + +fun main(args: Array) { + val g = Graph(s, deps) + println("Topologically sorted order:") + println(g.topoSort()) + println() + // now insert 3 to 6 at index 10 of deps + deps.add(10, 3 to 6) + val g2 = Graph(s, deps) + println("Following the addition of dw04 to the dependencies of dw01:") + println(g2.topoSort()) +} diff --git a/Task/Topological-sort/REXX/topological-sort.rexx b/Task/Topological-sort/REXX/topological-sort.rexx index 319a61f2b7..e8d122a732 100644 --- a/Task/Topological-sort/REXX/topological-sort.rexx +++ b/Task/Topological-sort/REXX/topological-sort.rexx @@ -1,62 +1,46 @@ /*REXX pgm does a topological sort (orders such that no item precedes a dependent item).*/ -idep.=0; ipos.=0; iord.=0 /*initialize some stemmed arrays to 0.*/ -label= 'DES_SYSTEM_LIB DW01 DW02 DW03 DW04 DW05 DW06 DW07 DWARE GTECH RAMLIB', - 'STD_CELL_LIB SYNOPSYS STD IEEE' - -icode=1 14 13 12 1 3 2 11 15 0 2 15 2 9 10 0 3 15 3 9 0 4 14 213 9 4 3 2 15 10 0 5 5 15 2, +iDep.=0; iPos.=0; iOrd.=0 /*initialize some stemmed arrays to 0.*/ +nL=15; nd=44; nc=69 /* " " "parms" and indices.*/ +label= 'DES_SYSTEM_LIB DW01 DW02 DW03 DW04 DW05 DW06 DW07 DWARE GTECH RAMLIB', + 'STD_CELL_LIB SYNOPSYS STD IEEE' +iCode=1 14 13 12 1 3 2 11 15 0 2 15 2 9 10 0 3 15 3 9 0 4 14 213 9 4 3 2 15 10 0 5 5 15 2, 9 10 0 6 6 15 9 0 7 7 15 9 0 8 15 9 0 39 15 9 0 10 15 10 0 11 14 15 0 12 15 12 0 0 - -idep.=0; ipos.=0; iord.=0 /*initialize some stemmed arrays to 0.*/ -nl=15; nd=44; nc=69; j=0; i=0 /* " " "parms" and indices.*/ - -10: i=i+1 - il=word(icode, i) - if il==0 then signal 30 -20: i=i+1 - ir=word(icode, i) - if ir==0 then signal 10 - j=j+1 - idep.j.1=il - idep.j.2=ir - signal 20 -30: call tsort - say '═══compile order═══' - q=0; do o=no by -1 for no; q=q+1 - say word(label, iord.o) - end /*o*/ - if q==0 then q='no' - say ' ('q "libraries found.)" - say - say '═══unordered libraries═══' - q=0; do u=no+1 to nl; q=q+1 - say word(label, iord.u) - end /*u*/ - if q==0 then q='no' - say ' ('q "unordered libraries found.)" +j=0 + do i=1 + iL=word(iCode, i); if iL==0 then leave + do forever; i=i + 1 + iR=word(iCode, i); if iR==0 then leave + j=j + 1 + iDep.j.1= iL + iDep.j.2= iR + end /*forever*/ + end /*i*/ +call tsort +say '═══compile order═══' +@= 'libraries found.)' +#=0; do o=nO by -1 for nO; #= #+1; say word(label, iOrd.o) + end /*o*/; if #==0 then #= 'no' +say ' ('# @; say +say '═══unordered libraries═══' +#=0; do u=nO+1 to nL; #= #+1; say word(label, iOrd.u) + end /*u*/; if #==0 then #= 'no' +say ' ('# "unordered" @ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ -tSort: procedure expose nl nd idep. iord. ipos. no - do i=1 for nl - iord.i=i - ipos.i=i - end /*i*/ +tSort: procedure expose iDep. iOrd. iPos. nd nL nO + do i=1 for nL; iOrd.i=i; iPos.i=i + end /*i*/ k=1 - do forever - j=k - k=nl+1 - do i=1 for nd - il=idep.i.1 - ir=ipos.il - ipl=ipos.il - ipr=ipos.ir - if il==ir | ipl>.k | ipl.k | ipL +#include +#include +#include + +int topswops(int n) { + std::vector list(n); + std::iota(std::begin(list), std::end(list), 1); + int max_steps = 0; + do { + auto temp_list = list; + for (int steps = 1; temp_list[0] != 1; ++steps) { + std::reverse(std::begin(temp_list), std::begin(temp_list) + temp_list[0]); + if (steps > max_steps) max_steps = steps; + } + } while (std::next_permutation(std::begin(list), std::end(list))); + return max_steps; +} + +int main() { + for (int i = 1; i <= 10; ++i) { + std::cout << i << ": " << topswops(i) << std::endl; + } + return 0; +} diff --git a/Task/Topswops/REXX/topswops.rexx b/Task/Topswops/REXX/topswops.rexx index e985a00c90..80e5361ce7 100644 --- a/Task/Topswops/REXX/topswops.rexx +++ b/Task/Topswops/REXX/topswops.rexx @@ -2,7 +2,7 @@ parse arg things .; if things=='' then things=10 do n=1 for things; #=decks(n, n) /*create a (things) number of "decks". */ - mx= n\==1 /*handle the case of a one-card deck.*/ + mx= (n\==1) /*handle the case of a one-card deck.*/ do i=1 for #; p=swops(!.i) /*compute the SWOPS for this iteration.*/ if p>mx then mx=p /*This a new maximum? Use a new max. */ end /*i*/ @@ -16,7 +16,7 @@ decks: procedure expose !.; parse arg x,y,,$ @. /* X things taken Y at .decks: procedure expose !. @. x y $ #; parse arg ? if ?>y then do; _=@.1; do j=2 for y-1; _=_ @.j; end /*j*/; #=#+1; !.#=_ end - else do; qm=?-1 + else do; qm=? - 1 if ?==1 then qs=2 /*don't use 1-swops that start with 1 */ else if @.1==? then qs=2 /*skip the 1-swops: 3 x 1 x ···*/ else qs=1 @@ -24,15 +24,15 @@ decks: procedure expose !.; parse arg x,y,,$ @. /* X things taken Y at do k=1 for qm; if @.k==q then iterate q end /*k*/ @.?=q; call .decks ? + 1 - end /*q*/ + end /*q*/ end return /*──────────────────────────────────────────────────────────────────────────────────────*/ -swops: parse arg z; do u=1; parse var z t .; if length(t)==2 then t=x2d(t) - if word(z, t)==1 then return u /*found unity at T. */ - do h=10 to things; if pos(h, z)==0 then iterate - z=changestr(h, z, d2x(h) ) /* [↑] any H's in Z ? */ - /* [↑] hexify decimal H */ - end /*h*/ - z=reverse(subword(z, 1, t)) subword(z, t+1) - end /*u*/ + +swops: parse arg z; do u=1; parse var z t .; if \datatype(t, 'W') then t=x2d(t) + if word(z, t)==1 then return u /*found unity at T. */ + do h=10 to things; if pos(h, z)==0 then iterate + z=changestr(h, z, d2x(h) ) /* [↑] any H's in Z?*/ + end /*h*/ + z=reverse( subword(z, 1, t) ) subword(z, t + 1) + end /*u*/ diff --git a/Task/Total-circles-area/00DESCRIPTION b/Task/Total-circles-area/00DESCRIPTION index 472005cdab..89783f809c 100644 --- a/Task/Total-circles-area/00DESCRIPTION +++ b/Task/Total-circles-area/00DESCRIPTION @@ -38,6 +38,10 @@ To allow a better comparison of the different implementations, solve the problem The result is 21.56503660... . +;Related task: +*   [[Circles of given radius through two points]]. + + ;See also: * http://www.reddit.com/r/dailyprogrammer/comments/zff9o/9062012_challenge_96_difficult_water_droplets/ * http://stackoverflow.com/a/1667789/10562 diff --git a/Task/Total-circles-area/Julia/total-circles-area.julia b/Task/Total-circles-area/Julia/total-circles-area.julia index 6ffb7e89bd..9355b12a57 100644 --- a/Task/Total-circles-area/Julia/total-circles-area.julia +++ b/Task/Total-circles-area/Julia/total-circles-area.julia @@ -1,43 +1,40 @@ -tic() -# +# Total circles area: https://rosettacode.org/wiki/Total_circles_area +# v0.6 + +xc = [1.6417233788, -1.4944608174, 0.6110294452, 0.3844862411, -0.2495892950, 1.7813504266, + -0.1985249206, -1.7011985145, -0.4319462812, 0.2178372997, -0.6294854565, 1.7952608455, + 1.4168575317, 1.4637371396, -0.5263668798, -1.2197352481, -0.1389358881, 1.5293954595, + -0.5258728625, -0.1403562064, 0.8055826339, -0.6311979224, 1.4685857879, -0.6855727502, + 0.0152957411] +yc = [1.6121789534, 1.2077959613, -0.6907087527, 0.2923344616, -0.3832854473, 1.6178237031, + -0.8343333301, -0.1263820964, 1.4104420482, -0.9499557344, -1.3078893852, 0.6281269104, + 1.0683357171, 0.9463877418, 1.7315156631, 0.9144146579, 0.1092805780, 0.0030278255, + 1.3782633069, 0.2437382535, -0.0482092025, 0.7184578971, -0.8347049536, 1.6465021616, + 0.0638919221] +r = [0.0848270516, 1.1039549836, 0.9089162485, 0.2375743054, 1.0845181219, 0.8162655711, + 0.0538864941, 0.4776976918, 0.7886291537, 0.0357871187, 0.7653357688, 0.2727652452, + 1.1016025378, 1.1846214562, 1.4428514068, 1.0727263474, 0.7350208828, 1.2472867347, + 1.3495508831, 1.3804956588, 0.3327165165, 0.2491045282, 1.3670667538, 1.0593087096, + 0.9771215985] + # Size of my grid -- higher values => higher accuracy. -# -ngrid = 10000; +function main(xc::Vector{<:Real}, yc::Vector{<:Real}, r::Vector{<:Real}, ngrid::Integer=10000) + r2 = r .* r + ncircles = length(xc) -xc = [1.6417233788 -1.4944608174 0.6110294452 0.3844862411 -0.2495892950 1.7813504266 -0.1985249206 -1.7011985145 -0.4319462812 0.2178372997 -0.6294854565 1.7952608455 1.4168575317 1.4637371396 -0.5263668798 -1.2197352481 -0.1389358881 1.5293954595 -0.5258728625 -0.1403562064 0.8055826339 -0.6311979224 1.4685857879 -0.6855727502 0.0152957411]; -yc = [1.6121789534 1.2077959613 -0.6907087527 0.2923344616 -0.3832854473 1.6178237031 -0.8343333301 -0.1263820964 1.4104420482 -0.9499557344 -1.3078893852 0.6281269104 1.0683357171 0.9463877418 1.7315156631 0.9144146579 0.1092805780 0.0030278255 1.3782633069 0.2437382535 -0.0482092025 0.7184578971 -0.8347049536 1.6465021616 0.0638919221]; -r = [0.0848270516 1.1039549836 0.9089162485 0.2375743054 1.0845181219 0.8162655711 0.0538864941 0.4776976918 0.7886291537 0.0357871187 0.7653357688 0.2727652452 1.1016025378 1.1846214562 1.4428514068 1.0727263474 0.7350208828 1.2472867347 1.3495508831 1.3804956588 0.3327165165 0.2491045282 1.3670667538 1.0593087096 0.9771215985]; -r2 = r .* r; - -ncircles = length(xc); - -# -# Compute the bounding box of the circles. -# -xmin = minimum(xc-r); -xmax = maximum(xc+r); -ymin = minimum(yc-r); -ymax = maximum(yc+r); - -# -# Keep a counter. -# -inside = 0; - -# -# For every point in my grid. -# -for x = linspace(xmin,xmax,ngrid) - for y = linspace(ymin,ymax,ngrid) - if any(r2 .> (x - xc).^2 + (y - yc).^2) - inside = inside + 1; - end + # Compute the bounding box of the circles. + xmin = minimum(xc .- r) + xmax = maximum(xc .+ r) + ymin = minimum(yc .- r) + ymax = maximum(yc .+ r) + # Keep a counter. + inside = 0 + # For every point in my grid. + for x in linspace(xmin, xmax, ngrid), y = linspace(ymin, ymax, ngrid) + inside += any(r2 .> (x - xc) .^ 2 + (y - yc) .^ 2) end + boxarea = (xmax - xmin) * (ymax - ymin) + return boxarea * inside / ngrid ^ 2 end -box_area = (xmax-xmin) * (ymax-ymin); - -result = box_area * inside / ngrid^2; -toc() - -println(result) +println(@time main(xc, yc, r, 1000)) diff --git a/Task/Towers-of-Hanoi/ALGOL-68/towers-of-hanoi.alg b/Task/Towers-of-Hanoi/ALGOL-68/towers-of-hanoi-1.alg similarity index 100% rename from Task/Towers-of-Hanoi/ALGOL-68/towers-of-hanoi.alg rename to Task/Towers-of-Hanoi/ALGOL-68/towers-of-hanoi-1.alg diff --git a/Task/Towers-of-Hanoi/ALGOL-68/towers-of-hanoi-2.alg b/Task/Towers-of-Hanoi/ALGOL-68/towers-of-hanoi-2.alg new file mode 100644 index 0000000000..bd753576f5 --- /dev/null +++ b/Task/Towers-of-Hanoi/ALGOL-68/towers-of-hanoi-2.alg @@ -0,0 +1,9 @@ +PROC move = (INT n, from, to, via) VOID: + IF n > 0 THEN + move(n - 1, from, via, to); + printf(($"Move disk "g" from pole "g" to pole "gl$, n, from, to)); + move(n - 1, via, to, from) + FI ; +main: ( + move(4, 1,2,3) +) diff --git a/Task/Towers-of-Hanoi/Befunge/towers-of-hanoi.bf b/Task/Towers-of-Hanoi/Befunge/towers-of-hanoi.bf new file mode 100644 index 0000000000..d686ac83d8 --- /dev/null +++ b/Task/Towers-of-Hanoi/Befunge/towers-of-hanoi.bf @@ -0,0 +1,4 @@ +48*2+1>#v_:!#@_0" ksid evoM">:#,_$:8/:.v +>8v8:<$#<+9-+*2%3\*3/3:,+55.+1%3:$_,#!>#:< +: >/!#^_:0\:8/1-8vv,_$8%:3/1+.>0" gep ot"^ +^++3-%3\*2/3:%8\*<>:^:"from peg "0\*8-1< diff --git a/Task/Towers-of-Hanoi/COBOL/towers-of-hanoi.cobol b/Task/Towers-of-Hanoi/COBOL/towers-of-hanoi-1.cobol similarity index 100% rename from Task/Towers-of-Hanoi/COBOL/towers-of-hanoi.cobol rename to Task/Towers-of-Hanoi/COBOL/towers-of-hanoi-1.cobol diff --git a/Task/Towers-of-Hanoi/COBOL/towers-of-hanoi-2.cobol b/Task/Towers-of-Hanoi/COBOL/towers-of-hanoi-2.cobol new file mode 100644 index 0000000000..a8f45b8c10 --- /dev/null +++ b/Task/Towers-of-Hanoi/COBOL/towers-of-hanoi-2.cobol @@ -0,0 +1,29 @@ +IDENTIFICATION DIVISION. +PROGRAM-ID. towers-of-hanoi. + +PROCEDURE DIVISION. + CALL "move-disk" USING 4, 1, 2, 3 + . +END PROGRAM towers-of-hanoi. + +IDENTIFICATION DIVISION. +PROGRAM-ID. move-disk RECURSIVE. + +DATA DIVISION. +LINKAGE SECTION. +01 n PIC 9 USAGE COMP. +01 from-pole PIC 9 USAGE COMP. +01 to-pole PIC 9 USAGE COMP. +01 via-pole PIC 9 USAGE COMP. + +PROCEDURE DIVISION USING n, from-pole, to-pole, via-pole. + IF n > 0 + SUBTRACT 1 FROM n + CALL "move-disk" USING CONTENT n, from-pole, via-pole, to-pole + ADD 1 TO n + DISPLAY "Move disk number "n " from pole " from-pole " to pole " to-pole + SUBTRACT 1 FROM n + CALL "move-disk" USING CONTENT n, via-pole, to-pole, from-pole + END-IF + . +END PROGRAM move-disk. diff --git a/Task/Towers-of-Hanoi/Elena/towers-of-hanoi.elena b/Task/Towers-of-Hanoi/Elena/towers-of-hanoi.elena new file mode 100644 index 0000000000..f817884468 --- /dev/null +++ b/Task/Towers-of-Hanoi/Elena/towers-of-hanoi.elena @@ -0,0 +1,12 @@ +move = (:n:from:to:via) +[ + if (n == 1) + [ + console printLine("Move disk from pole ",from," to pole ",to). + ]; + [ + move(n-1,from,via,to). + move(1,from,to,via). + move(n-1,via,to,from) + ] +]. diff --git a/Task/Towers-of-Hanoi/Haskell/towers-of-hanoi-4.hs b/Task/Towers-of-Hanoi/Haskell/towers-of-hanoi-4.hs index 6badcd61bf..321f8676cb 100644 --- a/Task/Towers-of-Hanoi/Haskell/towers-of-hanoi-4.hs +++ b/Task/Towers-of-Hanoi/Haskell/towers-of-hanoi-4.hs @@ -2,17 +2,20 @@ import Data.Monoid ((<>), mempty) import Data.List (intercalate, transpose) hanoi :: Int -> t -> t -> t -> [[t]] +hanoi 0 _ _ _ = mempty hanoi n l r m = - if n > 0 - then hanoi (n - 1) l m r <> [[l, r]] <> hanoi (n - 1) m r l - else mempty + hanoi (n - 1) l m r + <> [[l, r]] + <> hanoi (n - 1) m r l --- TEST (hanoi 5) ------------------------------------------------------------- + +showHanoi :: Int -> String +showHanoi n = + let justifyLeft n c s = take n (s <> replicate n c) + in unlines $ intercalate " -> " <$> transpose + ((justifyLeft 6 ' ' <$>) <$> transpose (hanoi n "left" "right" "mid")) + + +-- TEST ------------------------------------------------------------- main :: IO () -main = - mapM_ putStrLn $ - intercalate " -> " <$> - transpose - ((justifyLeft 6 ' ' <$>) <$> transpose (hanoi 5 "left" "right" "mid")) - where - justifyLeft n c s = take n (s <> replicate n c) +main = putStrLn $ showHanoi 5 diff --git a/Task/Towers-of-Hanoi/HolyC/towers-of-hanoi.holyc b/Task/Towers-of-Hanoi/HolyC/towers-of-hanoi.holyc new file mode 100644 index 0000000000..adcfdbcb03 --- /dev/null +++ b/Task/Towers-of-Hanoi/HolyC/towers-of-hanoi.holyc @@ -0,0 +1,9 @@ +U0 Move(U8 n, U8 from, U8 to, U8 via) { + if (n > 0) { + Move(n - 1, from, via, to); + Print("Move disk from pole %d to pole %d\n", from, to); + Move(n - 1, via, to, from); + } +} + +Move(4, 1, 2, 3); diff --git a/Task/Towers-of-Hanoi/MIPS-Assembly/towers-of-hanoi.mips b/Task/Towers-of-Hanoi/MIPS-Assembly/towers-of-hanoi.mips new file mode 100644 index 0000000000..9f09cd58c9 --- /dev/null +++ b/Task/Towers-of-Hanoi/MIPS-Assembly/towers-of-hanoi.mips @@ -0,0 +1,101 @@ +# Towers of Hanoi +# MIPS assembly implementation (tested with MARS) +# Source: https://stackoverflow.com/questions/50382420/hanoi-towers-recursive-solution-using-mips/50383530#50383530 + +.data +prompt: .asciiz "Enter a number: " +part1: .asciiz "\nMove disk " +part2: .asciiz " from rod " +part3: .asciiz " to rod " + +.text +.globl main +main: + li $v0, 4 # print string + la $a0, prompt + syscall + li $v0, 5 # read integer + syscall + + # parameters for the routine + add $a0, $v0, $zero # move to $a0 + li $a1, 'A' + li $a2, 'B' + li $a3, 'C' + + jal hanoi # call hanoi routine + + li $v0, 10 # exit + syscall + +hanoi: + + #save in stack + addi $sp, $sp, -20 + sw $ra, 0($sp) + sw $s0, 4($sp) + sw $s1, 8($sp) + sw $s2, 12($sp) + sw $s3, 16($sp) + + add $s0, $a0, $zero + add $s1, $a1, $zero + add $s2, $a2, $zero + add $s3, $a3, $zero + + addi $t1, $zero, 1 + beq $s0, $t1, output + + recur1: + + addi $a0, $s0, -1 + add $a1, $s1, $zero + add $a2, $s3, $zero + add $a3, $s2, $zero + jal hanoi + + j output + + recur2: + + addi $a0, $s0, -1 + add $a1, $s3, $zero + add $a2, $s2, $zero + add $a3, $s1, $zero + jal hanoi + + exithanoi: + + lw $ra, 0($sp) # restore registers from stack + lw $s0, 4($sp) + lw $s1, 8($sp) + lw $s2, 12($sp) + lw $s3, 16($sp) + + addi $sp, $sp, 20 # restore stack pointer + + jr $ra + + output: + + li $v0, 4 # print string + la $a0, part1 + syscall + li $v0, 1 # print integer + add $a0, $s0, $zero + syscall + li $v0, 4 # print string + la $a0, part2 + syscall + li $v0, 11 # print character + add $a0, $s1, $zero + syscall + li $v0, 4 # print string + la $a0, part3 + syscall + li $v0, 11 # print character + add $a0, $s2, $zero + syscall + + beq $s0, $t1, exithanoi + j recur2 diff --git a/Task/Towers-of-Hanoi/Maple/towers-of-hanoi.maple b/Task/Towers-of-Hanoi/Maple/towers-of-hanoi.maple new file mode 100644 index 0000000000..92bc7d0f6c --- /dev/null +++ b/Task/Towers-of-Hanoi/Maple/towers-of-hanoi.maple @@ -0,0 +1,12 @@ +Hanoi := proc(n::posint,a,b,c) + if n = 1 then + printf("Move disk from tower %a to tower %a.\n",a,c); + else + Hanoi(n-1,a,c,b); + Hanoi(1,a,b,c); + Hanoi(n-1,b,a,c); + fi; +end: + +printf("Moving 2 disks from tower A to tower C using tower B.\n"); +Hanoi(2,A,B,C); diff --git a/Task/Towers-of-Hanoi/Modula-2/towers-of-hanoi.mod2 b/Task/Towers-of-Hanoi/Modula-2/towers-of-hanoi.mod2 new file mode 100644 index 0000000000..16d0a3eba6 --- /dev/null +++ b/Task/Towers-of-Hanoi/Modula-2/towers-of-hanoi.mod2 @@ -0,0 +1,20 @@ +MODULE Towers; +FROM FormatString IMPORT FormatString; +FROM Terminal IMPORT WriteString,ReadChar; + +PROCEDURE Move(n,from,to,via : INTEGER); +VAR buf : ARRAY[0..63] OF CHAR; +BEGIN + IF n>0 THEN + Move(n-1, from, via, to); + FormatString("Move disk %i from pole %i to pole %i\n", buf, n, from, to); + WriteString(buf); + Move(n-1, via, to, from) + END +END Move; + +BEGIN + Move(3, 1, 3, 2); + + ReadChar +END Towers. diff --git a/Task/Towers-of-Hanoi/REXX/towers-of-hanoi-2.rexx b/Task/Towers-of-Hanoi/REXX/towers-of-hanoi-2.rexx index 1de5796929..46ac85b68a 100644 --- a/Task/Towers-of-Hanoi/REXX/towers-of-hanoi-2.rexx +++ b/Task/Towers-of-Hanoi/REXX/towers-of-hanoi-2.rexx @@ -4,7 +4,7 @@ if N=='' | N=="," then N=3 /*Not specified? Then use the sw=80; wp=sw%3-1; blanks=left('', wp) /*define some default REXX variables. */ c.1= sw % 3 % 2 /* [↑] SW: assume default Screen Width*/ c.2= sw % 2 - 1 -c.3= sw - 1 - c.1 - 1 +c.3= sw - 1 - c.1 #=0; z=2**N-1; moveK=z /*#moves; min# of moves; where to move.*/ @abc='abcdefghijklmnopqrstuvwxyN' /*dithering chars when many disks used.*/ ebcdic= ('f0'x==0) /*determine if EBCDIC or ASCII machine.*/ diff --git a/Task/Towers-of-Hanoi/Stata/towers-of-hanoi.stata b/Task/Towers-of-Hanoi/Stata/towers-of-hanoi.stata new file mode 100644 index 0000000000..4a429bb28e --- /dev/null +++ b/Task/Towers-of-Hanoi/Stata/towers-of-hanoi.stata @@ -0,0 +1,17 @@ +function hanoi(n, a, b, c) { + if (n>0) { + hanoi(n-1, a, c, b) + printf("Move from %f to %f\n", a, b) + hanoi(n-1, c, b, a) + } +} + +hanoi(3, 1, 2, 3) + +Move from 1 to 2 +Move from 1 to 3 +Move from 2 to 3 +Move from 1 to 2 +Move from 3 to 1 +Move from 3 to 2 +Move from 1 to 2 diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Elena/trabb-pardo-knuth-algorithm.elena b/Task/Trabb-Pardo-Knuth-algorithm/Elena/trabb-pardo-knuth-algorithm.elena new file mode 100644 index 0000000000..5fb2972b24 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/Elena/trabb-pardo-knuth-algorithm.elena @@ -0,0 +1,32 @@ +import system'math +import extensions. + +program = +[ + array inputs := real<>(11). + console printLine("Please enter 11 numbers :"). + 0 till:11 do(:i) + [ + inputs[i] := console readLine; toReal. + ]. + + console printLine("Evaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :"). + 10 to:0 do(:i) + [ + var r1 := inputs[i] absolute; sqrt. + var r2 := inputs[i] power(3). + var r :=inputs[i] /*absolute;*/ sqrt + 5*r2. + + real result := (inputs[i] absolute; sqrt) + 5 * (inputs[i] power(3)). + + console print("f(", inputs[i], ")="). + + if (result > 400) + [ + console printLine("Overflow!") + ]; + [ + console printLine(result). + ] + ] +]. diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Factor/trabb-pardo-knuth-algorithm.factor b/Task/Trabb-Pardo-Knuth-algorithm/Factor/trabb-pardo-knuth-algorithm.factor new file mode 100644 index 0000000000..8fd6a73c40 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/Factor/trabb-pardo-knuth-algorithm.factor @@ -0,0 +1,24 @@ +USING: formatting io kernel math math.functions math.parser +prettyprint sequences splitting ; +IN: rosetta-code.trabb-pardo-knuth + +CONSTANT: threshold 400 +CONSTANT: prompt "Please enter 11 numbers: " + +: fn ( x -- y ) [ abs 0.5 ^ ] [ 3 ^ 5 * ] bi + ; + +: overflow? ( x -- ? ) threshold > ; + +: get-input ( -- seq ) + prompt write flush readln " " split dup length 11 = + [ drop get-input ] unless ; + +: ?result ( ..a quot: ( ..a -- ..b ) -- ..b ) + [ "f(%u) = " sprintf ] swap bi dup overflow? + [ drop "overflow" ] [ "%.3f" sprintf ] if append ; inline + +: main ( -- ) + get-input reverse + [ string>number [ fn ] ?result print ] each ; + +MAIN: main diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Maple/trabb-pardo-knuth-algorithm.maple b/Task/Trabb-Pardo-Knuth-algorithm/Maple/trabb-pardo-knuth-algorithm.maple new file mode 100644 index 0000000000..948248a5de --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/Maple/trabb-pardo-knuth-algorithm.maple @@ -0,0 +1,10 @@ +seqn := ListTools:-Reverse([parse(Maplets[Display](Maplets:-Elements:-Maplet(Maplets:-Elements:-InputDialog['ID1']("Enter a sequence of numbers separated by comma", 'onapprove' = Maplets:-Elements:-Shutdown(['ID1']), 'oncancel' = Maplets:-Elements:-Shutdown())))[1])]): +f:= x -> abs(x)^0.5 + 5*x^3: +for item in seqn do + result := f(item): + if (result > 400) then + print("Alert: Overflow."): + else + print(result): + end if: +end do: diff --git a/Task/Trabb-Pardo-Knuth-algorithm/PL-M/trabb-pardo-knuth-algorithm.plm b/Task/Trabb-Pardo-Knuth-algorithm/PL-M/trabb-pardo-knuth-algorithm.plm new file mode 100644 index 0000000000..ee9660134d --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/PL-M/trabb-pardo-knuth-algorithm.plm @@ -0,0 +1,28 @@ +TPK: DO; + /* external I/O and real mathematical routines */ + WRITE$STRING: PROCEDURE( S ) EXTERNAL; DECLARE S POINTER; END; + WRITE$REAL: PROCEDURE( R ) EXTERNAL; DECLARE R REAL; END; + WRITE$NL: PROCEDURE EXTERNAL; END; + READ$REAL: PROCEDURE( R ) REAL EXTERNAL; DECLARE R POINTER; END; + REAL$ABS: PROCEDURE( R ) REAL EXTERNAL; DECLARE R REAL; END; + REAL$SQRT: PROCEDURE( R ) REAL EXTERNAL; DECLARE R REAL; END; + /* end external routines */ + + F: PROCEDURE( T ) REAL; + DECLARE T REAL; + RETURN REAL$SQRT(REAL$ABS(T))+5*T*T*T; + END F; + MAIN: PROCEDURE; + DECLARE Y REAL, A( 11 ) REAL, I INTEGER; + DO I = 0 TO 10; + CALL READ$REAL( @A( I ) ); + END; + DO I = 10 TO 0 BY -1; + Y = F( A( I ) ); + IF Y > 400.0 THEN CALL WRITE$STRING( @( 'TOO LARGE', 0 ) ); + ELSE CALL WRITE$REAL( Y ); + CALL WRITE$NL(); + END; + END MAIN; + +END TPK; diff --git a/Task/Trabb-Pardo-Knuth-algorithm/REXX/trabb-pardo-knuth-algorithm.rexx b/Task/Trabb-Pardo-Knuth-algorithm/REXX/trabb-pardo-knuth-algorithm.rexx index fd38fa70f8..123e006856 100644 --- a/Task/Trabb-Pardo-Knuth-algorithm/REXX/trabb-pardo-knuth-algorithm.rexx +++ b/Task/Trabb-Pardo-Knuth-algorithm/REXX/trabb-pardo-knuth-algorithm.rexx @@ -1,50 +1,48 @@ /*REXX program implements the Trabb─Pardo-Knuth algorithm for N numbers (default is 11).*/ -parse arg N .; if N=='' | N=="," then N=11 /*Not specified? Then use the default.*/ -maxValue=400 /*the maximum value f(x) can have. */ - wid= 20 /* ··· but only show this many digits.*/ - frac= 5 /* ··· show this # of fractional digs.*/ numeric digits 200 /*the number of digits precision to use*/ +parse arg N .; if N=='' | N=="," then N=11 /*Not specified? Then use the default.*/ +maxValue= 400 /*the maximum value f(x) can have. */ + wid= 20 /* ··· but only show this many digits.*/ + frac= 5 /* ··· show this # of fractional digs.*/ say ' _____ ' /* ◄───── display a vinculum.*/ say 'function: ƒ(x) ≡ √ │x│ + (5 * x^3)' prompt= 'enter ' N " numbers for the Trabb─Pardo─Knuth algorithm: (or Quit)" -/*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ */ - do ask=0; say; say prompt; say; pull $; say /* ▒ */ - if abbrev('QUIT',$,1) then do; say 'quitting.'; exit 1; end /* ▒ */ - ok=0 /* ▒ */ - select /*validate there're N numbers.*/ /* ▒ */ - when $='' then say "no numbers entered" /* ▒ */ - when words($)N then say "too many numbers entered" /* ▒ */ - otherwise ok=1 /* ▒ */ - end /*select*/ /* ▒ */ - if \ok then iterate /* [↓] is max width.*/ /* ▒ */ - w=0; do v=1 for N; _=word($,v); w=max(w,length(_)) /* ▒ */ - if datatype(_,'N') then iterate /*numeric ? */ /* ▒ */ - say _ "isn't numeric"; iterate ask /* ▒ */ - end /*v*/ /* ▒ */ - leave /* ▒ */ - end /*ask*/ /* ▒ */ -/*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ */ + do ask=0; say; /*░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░*/ + say prompt; say; pull $; say /*░*/ + if abbrev('QUIT',$,1) then do; say 'quitting.'; exit 1; end /*░*/ + ok=0 /*░*/ + select /*validate there're N numbers.*/ /*░*/ + when $='' then say "no numbers entered" /*░*/ + when words($)N then say "too many numbers entered" /*░*/ + otherwise ok=1 /*░*/ + end /*select*/ /*░*/ + if \ok then iterate /* [↓] W=max width. */ /*░*/ + w=0; do v=1 for N; _=word($, v); w=max(w, length(_) ) /*░*/ + if datatype(_, 'N') then iterate /*numeric ?*/ /*░*/ + say _ "isn't numeric"; iterate ask /*░*/ + end /*v*/ /*░*/ + leave /*░*/ + end /*ask*/ /*░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░*/ -say 'numbers entered: ' $ +say 'numbers entered: ' $ say - do i=N by -1 to 1; #=word($,i)/1 /*process the numbers in reverse. */ + do i=N by -1 for N; #=word($, i) / 1 /*process the numbers in reverse. */ g = fmt( f( # ) ) /*invoke function ƒ with arg number.*/ gw=right( 'ƒ('#") ", w+7) /*nicely formatted ƒ(number). */ - if g>maxValue then say gw "is > " maxValue ' ['space(g)"]" - else say gw " = " g - end /*i*/ /* [+] display the result to terminal.*/ + if g>maxValue then say gw "is > " maxValue ' ['space(g)"]" + else say gw " = " g + end /*i*/ /* [↑] display the result to terminal.*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ f: procedure; parse arg x; return sqrt( abs(x) ) + 5 * x**3 /*──────────────────────────────────────────────────────────────────────────────────────*/ -fmt: z=right(translate(format(arg(1),wid,frac),'e',"E"),wid) /*right adjust; use e*/ +fmt: z=right(translate(format(arg(1), wid, frac), 'e', "E"), wid) /*right adjust; use e*/ if pos(.,z)\==0 then z=left(strip(strip(z,'T',0),"T",.),wid) /*strip trailing 0 &.*/ - return right(z,wid-4*(pos('e',z)==0)) /*adjust: no exponent*/ + return right(z, wid - 4*(pos('e', z)==0) ) /*adjust: no exponent*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); m.=9; numeric form; h=d+6 numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g *.5'e'_ % 2 - do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/ - do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/ - return g + 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/Trabb-Pardo-Knuth-algorithm/Ring/trabb-pardo-knuth-algorithm.ring b/Task/Trabb-Pardo-Knuth-algorithm/Ring/trabb-pardo-knuth-algorithm.ring index e607bb9d49..4c79e26534 100644 --- a/Task/Trabb-Pardo-Knuth-algorithm/Ring/trabb-pardo-knuth-algorithm.ring +++ b/Task/Trabb-Pardo-Knuth-algorithm/Ring/trabb-pardo-knuth-algorithm.ring @@ -1,12 +1,31 @@ -decimals(7) -s = [4,3,4,2,1,1,2,3,4,5] +# Project : Trabb Pardo–Knuth algorithm +# Date : 2017/10/06 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : -for i = 10 to 1 step -1 - see "f(" + s[i] + ")="; - x = f(s[i]) - if x > 400 see "--- too large ---" + nl - else see x + nl ok +decimals(3) +x = list(11) +for n=1 to 11 + x[n] = n next -func f n - return sqrt(fabs(n))+5*pow(n,3) +s = [-5, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6] +for i = 1 to 11 + see string(i) + " => " + s[i] + nl +next +see copy("-", 20) + nl +i = i - 1 + +while i > 0 + see "f(" + string(s[i]) + ") = " + x = f(s[i]) + if x > 400 + see "-=< overflow >=-" + nl + else + see x + nl + ok + i = i - 1 +end + +func f(n) + return sqrt(fabs(n)) + 5 * pow(n, 3) diff --git a/Task/Tree-traversal/Elena/tree-traversal.elena b/Task/Tree-traversal/Elena/tree-traversal.elena new file mode 100644 index 0000000000..8b8bbf37d3 --- /dev/null +++ b/Task/Tree-traversal/Elena/tree-traversal.elena @@ -0,0 +1,103 @@ +import extensions. +import extensions'routines. +import system'collections. + +class Node +{ + type rprop value :: _value. + type rprop left :: _left. + type rprop right :: _right. + + constructor new(IntNumber value) + [ + _value := value. + ] + + constructor new(IntNumber value, Node left) + [ + _value := value. + _left := left. + ] + + constructor new(IntNumber value, Node left, Node right) + [ + _value := value. + _left :=left. + _right :=right. + ] + + Preorder = BaseEnumerable:: + { + enumerator = CompoundEnumerator new(SingleEnumerable new(_value), _left Preorder \ back:$nil, _right Preorder \ back:$nil). + }. + + Inorder = BaseEnumerable:: + { + enumerator + [ + if ($nil != _left) + [ + ^ CompoundEnumerator new(_left Inorder, SingleEnumerable new(_value), _right Inorder \ back:$nil). + ]; + [ + ^ SingleEnumerable new(_value) + ] + ] + }. + + Postorder = BaseEnumerable:: + { + enumerator + [ + if ($nil == _left) + [ + ^ SingleEnumerable new(_value) + ]; + if ($nil == _right) + [ + ^ CompoundEnumerator new(_left Postorder, SingleEnumerable new(_value)). + ]; + [ + ^ CompoundEnumerator new(_left Postorder, _right Postorder, SingleEnumerable new(_value)). + ] + ] + }. + + LevelOrder = BaseEnumerable:: + { + queue queue := (queue(4)) push:$self. + + enumerator = Enumerator:: + { + next = queue isNotEmpty. + + get + [ + type item := queue pop. + type left := item left. + type right := item right. + + if ($nil != left) + [ + queue push(left). + ]. + if ($nil != right) + [ + queue push(right). + ]. + + ^ item value. + ] + }. + }. +} + +program = +[ + var tree := Node new(1, Node new(2, Node new(4, Node new(7)), Node new(5)), Node new(3, Node new(6, Node new(8), Node new(9)))). + + console printLine("Preorder :", tree Preorder). + console printLine("Inorder :", tree Inorder). + console printLine("Postorder :", tree Postorder). + console printLine("LevelOrder:", tree LevelOrder). +]. diff --git a/Task/Trigonometric-functions/Modula-2/trigonometric-functions.mod2 b/Task/Trigonometric-functions/Modula-2/trigonometric-functions.mod2 new file mode 100644 index 0000000000..7dd508ef4a --- /dev/null +++ b/Task/Trigonometric-functions/Modula-2/trigonometric-functions.mod2 @@ -0,0 +1,46 @@ +MODULE Trig; +FROM RealMath IMPORT pi,sin,cos,tan,arctan,arccos,arcsin; +FROM RealStr IMPORT RealToStr; +FROM Terminal IMPORT WriteString,WriteLn,ReadChar; + +PROCEDURE WriteReal(v : REAL); +VAR buf : ARRAY[0..31] OF CHAR; +BEGIN + RealToStr(v, buf); + WriteString(buf) +END WriteReal; + +VAR theta : REAL; +BEGIN + theta := pi / 4.0; + + WriteString("theta: "); + WriteReal(theta); + WriteLn; + + WriteString("sin: "); + WriteReal(sin(theta)); + WriteLn; + + WriteString("cos: "); + WriteReal(cos(theta)); + WriteLn; + + WriteString("tan: "); + WriteReal(tan(theta)); + WriteLn; + + WriteString("arcsin: "); + WriteReal(arcsin(sin(theta))); + WriteLn; + + WriteString("arccos: "); + WriteReal(arccos(cos(theta))); + WriteLn; + + WriteString("arctan: "); + WriteReal(arctan(tan(theta))); + WriteLn; + + ReadChar +END Trig. diff --git a/Task/Truncatable-primes/Factor/truncatable-primes.factor b/Task/Truncatable-primes/Factor/truncatable-primes.factor new file mode 100644 index 0000000000..d04dee38dc --- /dev/null +++ b/Task/Truncatable-primes/Factor/truncatable-primes.factor @@ -0,0 +1,36 @@ +USING: formatting fry grouping.extras kernel literals math +math.parser math.primes sequences ; +IN: rosetta-code.truncatable-primes + +CONSTANT: primes $[ 1,000,000 primes-upto reverse ] + +: number>digits ( n -- B{} ) number>string string>digits ; + +: no-zeros? ( seq -- ? ) [ zero? not ] all? ; + +: all-prime? ( seq -- ? ) [ prime? ] all? ; + +: truncate ( seq quot -- seq' ) call( seq -- seq' ) + [ 10 digits>integer ] map ; + +: truncate-right ( seq -- seq' ) [ head-clump ] truncate ; + +: truncate-left ( seq -- seq' ) [ tail-clump ] truncate ; + +: truncatable-prime? ( n quot -- ? ) [ number>digits ] dip + '[ @ all-prime? ] [ no-zeros? ] bi and ; inline + +: right-truncatable-prime? ( n -- ? ) [ truncate-right ] + truncatable-prime? ; + +: left-truncatable-prime? ( n -- ? ) [ truncate-left ] + truncatable-prime? ; + +: find-truncatable-primes ( -- ltp rtp ) + primes [ [ left-truncatable-prime? ] find nip ] + [ [ right-truncatable-prime? ] find nip ] bi ; + +: main ( -- ) find-truncatable-primes + "Left: %d\nRight: %d\n" printf ; + +MAIN: main diff --git a/Task/Truncatable-primes/Maple/truncatable-primes.maple b/Task/Truncatable-primes/Maple/truncatable-primes.maple new file mode 100644 index 0000000000..c7ff86bca5 --- /dev/null +++ b/Task/Truncatable-primes/Maple/truncatable-primes.maple @@ -0,0 +1,50 @@ +MaxTruncatablePrime := proc({left::truefalse:=FAIL, right::truefalse:=FAIL}, $) +local i, j, c, p, b, n, sdprimes, dir; +local tprimes := table(); + if left = true and right = true then + error "invalid input"; + elif right = true then + dir := "right"; + else + dir := "left"; + end if; + b := 10; + n := 6; + sdprimes := select(isprime, [seq(1..b-1)]); + for p in sdprimes do + if assigned(tprimes[p]) then + next; + end if; + i := ilog[b](p)+1; + j := 1; + while p < b^n do + if dir = "left" then + c := j*b^i + p; + else + c := p*b + j; + end if; + if j >= b or c > b^n then # we have tried all 1 digit extensions of p, add p to tprimes and move back 1 digit + tprimes[p] := p; + if i = 1 then # if we are at the first digit, go to the next 1 digit prime + break; + end if; + i := i - 1; + j := 1; + if dir = "left" then + p := p - iquo(p, b^i)*b^i; + else + p := iquo(p, b); + end if; + elif assigned(tprimes[c]) then + j := j + 1; + elif isprime(c) then + p := c; + i := i + 1; + j := 1; + else + j := j+1; + end if; + end do; + end do; + return max(indices(tprimes, 'nolist')); +end proc; diff --git a/Task/Truncatable-primes/Ring/truncatable-primes.ring b/Task/Truncatable-primes/Ring/truncatable-primes.ring new file mode 100644 index 0000000000..48c3a7a59e --- /dev/null +++ b/Task/Truncatable-primes/Ring/truncatable-primes.ring @@ -0,0 +1,56 @@ +# Project : Truncatable primes +# Date : 2017/10/15 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +for n = 1000000 to 1 step -1 + flag = 1 + flag2 = 1 + strn = string(n) + for nr = 1 to len(strn) + if strn[nr] = "0" + flag2 = 0 + ok + next + if flag2 = 1 + for m = 1 to len(strn) + strp = right(strn, m) + if isprime(number(strp)) + else + flag = 0 + exit + ok + next + if flag = 1 + nend = n + exit + ok + ok +next +see "Largest left truncatable prime : " + nend + nl + +for n = 1000000 to 1 step -1 + flag = 1 + strn = string(n) + for m = 1 to len(strn) + strp = left(strn, len(strn) - m + 1) + if isprime(number(strp)) + else + flag = 0 + exit + ok + next + if flag = 1 + nend = n + exit + ok +next +see "Largest right truncatable prime : " + nend + nl + +func isprime num + if (num <= 1) return 0 ok + if (num % 2 = 0 and num != 2) return 0 ok + for i = 3 to floor(num / 2) -1 step 2 + if (num % i = 0) return 0 ok + next + return 1 diff --git a/Task/Truncate-a-file/Clojure/truncate-a-file.clj b/Task/Truncate-a-file/Clojure/truncate-a-file.clj new file mode 100644 index 0000000000..284ed9c625 --- /dev/null +++ b/Task/Truncate-a-file/Clojure/truncate-a-file.clj @@ -0,0 +1,5 @@ +(defn truncate [file size] + (with-open [chan (.getChannel (java.io.FileOutputStream. file true))] + (.truncate chan size))) + +(truncate "truncate_test.txt" 2) diff --git a/Task/Twelve-statements/Clojure/twelve-statements.clj b/Task/Twelve-statements/Clojure/twelve-statements.clj new file mode 100644 index 0000000000..5eb54a3093 --- /dev/null +++ b/Task/Twelve-statements/Clojure/twelve-statements.clj @@ -0,0 +1,20 @@ +(use '[clojure.math.combinatorics] + +(defn xor? [& args] + (odd? (count (filter identity args)))) + +(defn twelve-statements [] + (for [[a b c d e f g h i j k l] (selections [true false] 12) + :when (true? a) + :when (if (= 3 (count (filter true? [g h i j k l]))) (true? b) (false? b)) + :when (if (= 2 (count (filter true? [b d f h j l]))) (true? c) (false? c)) + :when (if (or (false? e) (every? true? [e f g])) (true? d) (false? d)) + :when (if (every? false? [b c d]) (true? e) (false? e)) + :when (if (= 4 (count (filter true? [a c e g i k]))) (true? f) (false? f)) + :when (if (xor? (true? b) (true? c)) (true? g) (false? g)) + :when (if (or (false? g) (every? true? [e f g])) (true? h) (false? h)) + :when (if (= 3 (count (filter true? [a b c d e f]))) (true? i) (false? i)) + :when (if (every? true? [k l]) (true? j) (false? j)) + :when (if (= 1 (count (filter true? [g h i]))) (true? k) (false? k)) + :when (if (= 4 (count (filter true? [a b c d e f g h i j k]))) (true? l) (false? l))] + [a b c d e f g h i j k l])) diff --git a/Task/Twelve-statements/Elena/twelve-statements.elena b/Task/Twelve-statements/Elena/twelve-statements.elena index a4966e0645..d930d07603 100644 --- a/Task/Twelve-statements/Elena/twelve-statements.elena +++ b/Task/Twelve-statements/Elena/twelve-statements.elena @@ -47,7 +47,7 @@ program = 0 till(2 power int:12) do(:n) [ var bits := BitArray32 new:n; top:12; toArray. - var results := puzzle selectBy(:r)( r eval:bits ); toArray. + var results := puzzle selectBy(:r)( r(bits) ); toArray. var counts := bits zip:results by(:b:r)( b xor:r; toBit ); summarize. diff --git a/Task/Twelve-statements/Pascal/twelve-statements.pascal b/Task/Twelve-statements/Pascal/twelve-statements.pascal new file mode 100644 index 0000000000..6e1e31225d --- /dev/null +++ b/Task/Twelve-statements/Pascal/twelve-statements.pascal @@ -0,0 +1,132 @@ +PROGRAM TwelveStatements; + +{ + This program searches through the 4095 possible sets + of 12 statements for any which may be self-consistent. +} + +CONST + max12b = 4095; { Largest 12 byte number. } + +TYPE + statnum = 1..12; { statement numbers } + statset = set of statnum; { sets of statements } + +VAR { global variables for use in main algorithm } + trialNumber: integer; + trialSet, testResults: statset; + +function Convert(n: integer): statset; +{ + Converts an integer into a set of statements. + For each "1" in the last 12 bits of + the integer's binary representation, + a statement number is put into the set. +} +var + i: statnum; + s: statset; +begin + s := []; { Empty set. } + for i := 12 downto 1 do begin + if (n mod 2) = 1 then s := s + [i]; + n := n div 2 + end; + Convert := s +end; + +procedure Express(truths: statset); +{ + Writes the statement number of each "truth", + with at least one space in front, + all on one line. +} +var n: statnum; +begin + for n := 1 to 12 do + if n in truths then write(n:3); + writeln +end; + +function Count(truths: statset): integer; +{ Counts the statement numbers in the set. } +var + s: statnum; + i: integer; +begin + i := 0; + for s := 1 to 12 do if s in truths then i := i + 1; + Count := i +end; + +function Test(truths: statset): statset; +{ + Starts with a set of supposedly true statements + and checks which of the 12 statements can actually + be confirmed about the set itself. +} +var + evens, odds, confirmations: statset; +begin + evens := [2, 4, 6, 8, 10, 12]; + odds := [1, 3, 5, 7, 9, 11]; + + { Statement 1 is necessarily true. } + confirmations := [1]; + + { Statement 2 } + if Count(truths * [7..12]) = 3 + then confirmations := confirmations + [2]; + + { Statement 3 } + if Count(truths * evens) = 2 + then confirmations := confirmations + [3]; + + { Statement 4 is true if 6 and 7 are true, or if 5 is false. } + if ([6, 7] <= truths) or not (5 in truths) + then confirmations := confirmations + [4]; + + { Statement 5 } + if [2, 3, 4] <= truths + then confirmations := confirmations + [5]; + + { Statement 6 } + if Count(truths * odds) = 4 + then confirmations := confirmations + [6]; + + { Statement 7 } + if (2 in truths) xor (3 in truths) + then confirmations := confirmations + [7]; + + { Statement 8 is true if 5 and 6 are true, or if 7 is false. } + if ([5, 6] <= truths) or not (7 in truths) + then confirmations := confirmations + [8]; + + { Statement 9 } + if Count(truths * [1..6]) = 3 + then confirmations := confirmations + [9]; + + { Statement 10 } + if [11, 12] <= truths + then confirmations := confirmations + [10]; + + { Statement 11 } + if Count(truths * [7, 8, 9]) = 1 + then confirmations := confirmations + [11]; + + { Statement 12 } + if Count(truths - [12]) = 4 + then confirmations := confirmations + [12]; + + Test := confirmations +end; + +BEGIN { Main algorithm. } + for trialNumber := 1 to max12b do begin + trialSet := Convert(trialNumber); + testResults := Test(trialSet); + if testResults = trialSet then Express(trialSet) + end; + writeln('Done. Press ENTER.'); + readln +END. diff --git a/Task/Twelve-statements/Scala/twelve-statements.scala b/Task/Twelve-statements/Scala/twelve-statements.scala new file mode 100644 index 0000000000..065996435c --- /dev/null +++ b/Task/Twelve-statements/Scala/twelve-statements.scala @@ -0,0 +1,81 @@ +class LogicPuzzle { + val s = new Array[Boolean](13) + var count = 0 + + def check2: Boolean = { + var count = 0 + for (k <- 7 to 12) if (s(k)) count += 1 + + s(2) == (count == 3) + } + + def check3: Boolean = { + var count = 0 + for (k <- 2 to 12 by 2) if (s(k)) count += 1 + + s(3) == (count == 2) + } + + def check4: Boolean = s(4) == (!s(5) || s(6) && s(7)) + + def check5: Boolean = s(5) == (!s(2) && !s(3) && !s(4)) + + def check6: Boolean = { + var count = 0 + for (k <- 1 to 11 by 2) if (s(k)) count += 1 + s(6) == (count == 4) + } + + def check7: Boolean = s(7) == ((s(2) || s(3)) && !(s(2) && s(3))) + + def check8: Boolean = s(8) == (!s(7) || s(5) && s(6)) + + def check9: Boolean = { + var count = 0 + for (k <- 1 to 6) if (s(k)) count += 1 + + s(9) == (count == 3) + } + + def check10: Boolean = s(10) == (s(11) && s(12)) + + def check11: Boolean = { + var count = 0 + for (k <- 7 to 9) if (s(k)) count += 1 + + s(11) == (count == 1) + } + + def check12: Boolean = { + var count = 0 + for (k <- 1 to 11) if (s(k)) count += 1 + s(12) == (count == 4) + } + + def check(): Unit = { + if (check2 && check3 && check4 && check5 && check6 && check7 && check8 && check9 && check10 && check11 && check12) { + for (k <- 1 to 12) if (s(k)) print(k + " ") + println() + count += 1 + } + } + + def recurseAll(k: Int): Unit = { + if (k == 13) check() + else { + s(k) = false + recurseAll(k + 1) + s(k) = true + recurseAll(k + 1) + } + } +} + +object LogicPuzzle extends App { + val p = new LogicPuzzle + p.s(1) = true + p.recurseAll(2) + println() + println(s"${p.count} Solutions found.") + +} diff --git a/Task/Twelve-statements/Sidef/twelve-statements.sidef b/Task/Twelve-statements/Sidef/twelve-statements.sidef index 600ab7d515..3302467008 100644 --- a/Task/Twelve-statements/Sidef/twelve-statements.sidef +++ b/Task/Twelve-statements/Sidef/twelve-statements.sidef @@ -1,17 +1,17 @@ var conditions = [ { false }, {|a| a.len == 13 }, - {|a| Math.sum(a[7..12]) == 3 }, - {|a| Math.sum(a[2..12 `by` 2]) == 2 }, + {|a| [a[7..12]].count(true) == 3 }, + {|a| [a[2..12 `by` 2]].count(true) == 2 }, {|a| a[5] ? (a[6] && a[7]) : true }, {|a| !a[2] && !a[3] && !a[4] }, - {|a| Math.sum(a[1..11 `by` 2]) == 4 }, + {|a| [a[1..11 `by` 2]].count(true) == 4 }, {|a| a[2] == true^a[3] }, {|a| a[7] ? (a[5] && a[6]) : true }, - {|a| Math.sum(a[1..6]) == 3 }, - {|a| Math.sum(a[11,12]) == 2 }, - {|a| Math.sum(a[7..9]) == 1 }, - {|a| Math.sum(a[1..11]) == 4 }, + {|a| [a[1..6]].count(true) == 3 }, + {|a| [a[11,12]].count(true) == 2 }, + {|a| [a[7..9]].count(true) == 1 }, + {|a| [a[1..11]].count(true) == 4 }, ] func miss(args) { @@ -19,7 +19,7 @@ func miss(args) { } for k in (^(1<<12)) { - var t = ("0%012b" % k -> chars.map {|bit| bit == '1' ? true : false }) + var t = ("0%012b" % k -> chars.map {|bit| bit == '1' }) var no = miss(t) no.len == 0 && say "Solution: true statements are #{1..12->grep{t[_]}.join(' ')}" no.len == 1 && say "1 miss (#{no[0]}): true statements are #{1..12->grep{t[_]}.join(' ')}" diff --git a/Task/URL-decoding/BaCon/url-decoding.bacon b/Task/URL-decoding/BaCon/url-decoding.bacon new file mode 100644 index 0000000000..ded6e50580 --- /dev/null +++ b/Task/URL-decoding/BaCon/url-decoding.bacon @@ -0,0 +1,14 @@ +FUNCTION Url_Decode$(url$) + + LOCAL result$ + + SPLIT url$ BY "%" TO item$ SIZE total + FOR x = 1 TO total-1 + result$ = result$ & CHR$(DEC(LEFT$(item$[x], 2))) & MID$(item$[x], 3) + NEXT + RETURN item$[0] & result$ + +END FUNCTION + +PRINT Url_Decode$("http%3A%2F%2Ffoo%20bar%2F") +PRINT Url_Decode$("google.com/search?q=%60Abdu%27l-Bah%C3%A1") diff --git a/Task/URL-decoding/Factor/url-decoding.factor b/Task/URL-decoding/Factor/url-decoding.factor new file mode 100644 index 0000000000..510d2275bc --- /dev/null +++ b/Task/URL-decoding/Factor/url-decoding.factor @@ -0,0 +1,6 @@ +USING: io kernel urls.encoding ; +IN: rosetta-code.url-decoding + +"http%3A%2F%2Ffoo%20bar%2F" +"google.com/search?q=%60Abdu%27l-Bah%C3%A1" +[ url-decode print ] bi@ diff --git a/Task/URL-decoding/Lingo/url-decoding-1.lingo b/Task/URL-decoding/Lingo/url-decoding-1.lingo new file mode 100644 index 0000000000..a3e5e0bf34 --- /dev/null +++ b/Task/URL-decoding/Lingo/url-decoding-1.lingo @@ -0,0 +1,24 @@ +---------------------------------------- +-- URL decodes a string +-- @param {string} str +-- @return {string} +---------------------------------------- +on urldecode (str) + res = "" + ba = bytearray() + len = str.length + repeat with i = 1 to len + c = str.char[i] + if (c = "%") then + -- fastest hex-to-dec conversion hack based on Lingo's rgb object + ba.writeInt8(rgb(str.char[i+1..i+2]).blue) + i = i + 2 + else if (c = "+") then + ba.writeInt8(32) + else + ba.writeInt8(chartonum(c)) + end if + end repeat + ba.position = 1 + return ba.readRawString(ba.length) +end diff --git a/Task/URL-decoding/Lingo/url-decoding-2.lingo b/Task/URL-decoding/Lingo/url-decoding-2.lingo new file mode 100644 index 0000000000..c98bc0f8a1 --- /dev/null +++ b/Task/URL-decoding/Lingo/url-decoding-2.lingo @@ -0,0 +1,2 @@ +put urldecode("http%3A%2F%2Ffoo%20bar%2F") +put urldecode("google.com/search?q=%60Abdu%27l-Bah%C3%A1") diff --git a/Task/URL-decoding/Perl-6/url-decoding.pl6 b/Task/URL-decoding/Perl-6/url-decoding.pl6 new file mode 100644 index 0000000000..3a44699731 --- /dev/null +++ b/Task/URL-decoding/Perl-6/url-decoding.pl6 @@ -0,0 +1,9 @@ +my $url = "http%3A%2F%2Ffoo%20bar%2F"; + +say $url.subst: :g, + /'%'(<:hexdigit>**2)/, + -> ($ord ) { chr(:16(~$ord)) } + +# Alternately, you can use an in-place substitution: +$url ~~ s:g[ '%' (<:hexdigit> ** 2) ] = chr :16(~$0); +say $url; diff --git a/Task/URL-decoding/UNIX-Shell/url-decoding-1.sh b/Task/URL-decoding/UNIX-Shell/url-decoding-1.sh new file mode 100644 index 0000000000..e8c56574f5 --- /dev/null +++ b/Task/URL-decoding/UNIX-Shell/url-decoding-1.sh @@ -0,0 +1 @@ +urldecode() { local u="${1//+/ }"; printf '%b' "${u//%/\\x}"; } diff --git a/Task/URL-decoding/UNIX-Shell/url-decoding-2.sh b/Task/URL-decoding/UNIX-Shell/url-decoding-2.sh new file mode 100644 index 0000000000..f4f0eb018f --- /dev/null +++ b/Task/URL-decoding/UNIX-Shell/url-decoding-2.sh @@ -0,0 +1,5 @@ +urldecode http%3A%2F%2Ffoo%20bar%2F +http://foo bar/ + +urldecode google.com/search?q=%60Abdu%27l-Bah%C3%A1 +google.com/search?q=`Abdu'l-Bahároot@ diff --git a/Task/URL-decoding/UNIX-Shell/url-decoding.sh b/Task/URL-decoding/UNIX-Shell/url-decoding-3.sh similarity index 100% rename from Task/URL-decoding/UNIX-Shell/url-decoding.sh rename to Task/URL-decoding/UNIX-Shell/url-decoding-3.sh diff --git a/Task/Ulam-spiral--for-primes-/00DESCRIPTION b/Task/Ulam-spiral--for-primes-/00DESCRIPTION index 815b09059a..2fd7b53a8c 100644 --- a/Task/Ulam-spiral--for-primes-/00DESCRIPTION +++ b/Task/Ulam-spiral--for-primes-/00DESCRIPTION @@ -2,7 +2,7 @@ An Ulam spiral (of primes numbers) is a method of visualizing prime numbers when An Ulam spiral is also known as a   ''prime spiral''. -The first grid (green) is shown with all numbers (primes and non-primes) shown, starting at   '''1'''. +The first grid (green) is shown with sequential integers,   starting at   '''1'''. In an Ulam spiral of primes, only the primes are shown (usually indicated by some glyph such as a dot or asterisk),   and all non-primes as shown as a blank   (or some other whitespace). @@ -102,7 +102,8 @@ You should demonstrate the generator by showing at Ulam prime spiral large enoug ;Related tasks: *   [[Spiral matrix]] *   [[Zig-zag matrix]] -*   [[Identity_matrix]] +*   [[Identity matrix]] +*   [[Sequence of primes by Trial Division]] ;See also diff --git a/Task/Ulam-spiral--for-primes-/C/ulam-spiral--for-primes--1.c b/Task/Ulam-spiral--for-primes-/C/ulam-spiral--for-primes--1.c index 0d2e571173..da12d46a79 100644 --- a/Task/Ulam-spiral--for-primes-/C/ulam-spiral--for-primes--1.c +++ b/Task/Ulam-spiral--for-primes-/C/ulam-spiral--for-primes--1.c @@ -36,7 +36,7 @@ int ulam_get_map(int x, int y, int n) int mx = abs(x), my = abs(y); int l = 2 * max(mx, my); - int d = y > x ? l * 3 + x + y : l - x - y; + int d = y >= x ? l * 3 + x + y : l - x - y; return pow(l - 1, 2) + d; } diff --git a/Task/Ulam-spiral--for-primes-/JavaScript/ulam-spiral--for-primes-.js b/Task/Ulam-spiral--for-primes-/JavaScript/ulam-spiral--for-primes-.js new file mode 100644 index 0000000000..cb41ed111c --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/JavaScript/ulam-spiral--for-primes-.js @@ -0,0 +1,107 @@ + + +Ulam Spiral + + + + Plot/print style: + Plot  + Print *  + Print numbers  + +

Ulam Spiral

+ + + diff --git a/Task/Ulam-spiral--for-primes-/Julia/ulam-spiral--for-primes-.julia b/Task/Ulam-spiral--for-primes-/Julia/ulam-spiral--for-primes-.julia new file mode 100644 index 0000000000..0785612d83 --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/Julia/ulam-spiral--for-primes-.julia @@ -0,0 +1,31 @@ +using Primes + +function ulamspiral(ord::Int) + # Possible directions + dirs = [[0, 1], [-1, 0], [0, -1], [1, 0]] + # fdir = ["→", "↑", "←", "↓"] # for debug pourpose + cur = maxsteps = 1 # starting direction & starting max steps + steps = n = 0 # starting steps & starting number in cell + pos = [ord ÷ 2 + 1, isodd(ord) ? ord ÷ 2 + 1 : ord ÷ 2] # starting position + M = Matrix{Bool}(ord, ord) # result matrix + while n < ord ^ 2 # main loop (stop when the matrix is filled) + n += 1 + M[pos[1], pos[2]] = isprime(n) + steps += 1 + # Debug print + # @printf("M[%i, %i] = %5s (%2i), step %i/%i, nxt %s\n", pos[1], pos[2], isprime(n), n, steps, maxsteps, fdir[cur]) + pos .+= dirs[cur] # increment position + if steps == maxsteps # if reached max number of steps in that direction... + steps = 0 # ...reset steps + if iseven(cur) maxsteps += 1 end # if the current direction is even increase the number of steps + cur += 1 # change direction + if cur > 4 cur -= 4 end # correct overflow + end + end + return M +end + +mprint(m::Matrix) = for i in 1:size(m, 1) println(join(el ? " ∙ " : " " for el in m[i, :]), '\n') end + +M = ulamspiral(9) +mprint(M) diff --git a/Task/Ulam-spiral--for-primes-/Racket/ulam-spiral--for-primes-.rkt b/Task/Ulam-spiral--for-primes-/Racket/ulam-spiral--for-primes-.rkt index dfc21a2dab..110db3c819 100644 --- a/Task/Ulam-spiral--for-primes-/Racket/ulam-spiral--for-primes-.rkt +++ b/Task/Ulam-spiral--for-primes-/Racket/ulam-spiral--for-primes-.rkt @@ -5,14 +5,14 @@ (let* ((y (- y (quotient n 2))) (x (- x (quotient (sub1 n) 2))) (l (* 2 (if (> (abs x) (abs y)) (abs x) (abs y)))) - (d (if (> y x) (+ (* l 3) x y) (- l x y)))) + (d (if (>= y x) (+ (* l 3) x y) (- l x y)))) (+ (sqr (- l 1)) d start -1))) (define (show-spiral n #:symbol (smb "# ") #:start (start 1) #:space (space (and smb (make-string (string-length smb) #\space)))) - (define top (+ start (sqr n) 1)) + (define top (+ start (* n n) 1)) (define cell (cell-fn n start)) (define print-cell (if smb @@ -23,7 +23,7 @@ (display (if p? (~a #:width max-len i #:align 'right) space)) (display #\space))))) - (for* ((y (in-range 1 (add1 n))) #:when (unless (= y 1) (newline)) (x (in-range 1 (add1 n)))) + (for* ((y (in-range 0 n)) #:when (unless (= y 0) (newline)) (x (in-range 0 n))) (define c (cell x y)) (define p? (prime? c)) (print-cell c p?)) @@ -33,4 +33,4 @@ (show-spiral 10 #:symbol "♞" #:space "♘") ; black are the primes (show-spiral 50 #:symbol "*" #:start 42) ; for filling giant terminals -; (show_spiral 1001 "*" 42) +; (show-spiral 1001 #:symbol "*" #:start 42) diff --git a/Task/Ulam-spiral--for-primes-/Ring/ulam-spiral--for-primes-.ring b/Task/Ulam-spiral--for-primes-/Ring/ulam-spiral--for-primes-.ring new file mode 100644 index 0000000000..ab7ef60663 --- /dev/null +++ b/Task/Ulam-spiral--for-primes-/Ring/ulam-spiral--for-primes-.ring @@ -0,0 +1,104 @@ +# Project : Ulam spiral (for primes) +# Date : 2018/06/11 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : + +load "guilib.ring" +load "stdlib.ring" + +paint = null + +new qapp + { + win1 = new qwidget() { + setwindowtitle("Ulam spiral") + setgeometry(100,100,560,600) + label1 = new qlabel(win1) { + setgeometry(10,10,800,600) + settext("") + } + new qpushbutton(win1) { + setgeometry(220,500,100,30) + settext("draw") + setclickevent("draw()") + } + show() + } + exec() + } + +func draw + p1 = new qpicture() + color = new qcolor() { + setrgb(0,0,255,255) + } + pen = new qpen() { + setcolor(color) + setwidth(1) + } + paint = new qpainter() { + begin(p1) + setpen(pen) + + usn = 81 + ulamspiral(usn) + + endpaint() + } + label1 { setpicture(p1) show() } + return + +func ulamspiral(nr) + button = list(nr) + win1{ + sizenew = sqrt(nr) + for n = 1 to nr + col = n%9 + if col = 0 col = 9 ok + row = ceil(n/9) + + button[n] = new qpushbutton(win1) + { + setgeometry(60+col*40,60+row*40,40,40) + setclickevent("movetile(" + string(n) +")") + show() + } + next + n = 9 + result = newlist(n,n) + k = 1 + top = 1 + bottom = n + left = 1 + right = n + while (k<=n*n) + for i=left to right + result[top][i]=k + k = k + 1 + next + top = top + 1 + for i=top to bottom + result[i][right]=k + k = k + 1 + next + right = right - 1 + for i=right to left step -1 + result[bottom][i]=k + k = k + 1 + next + bottom = bottom - 1 + for i=bottom to top step -1 + result[i][left] = k + k = k + 1 + next + left = left + 1 + end + for m = 1 to n + for p = 1 to n + pos = (m-1)*n + p + if isprime(result[m][p]) + button[pos] {settext(string(result[m][p]))} + ok + next + next + } diff --git a/Task/Unbias-a-random-generator/Aime/unbias-a-random-generator.aime b/Task/Unbias-a-random-generator/Aime/unbias-a-random-generator.aime index 86935b9ece..d4432614e9 100644 --- a/Task/Unbias-a-random-generator/Aime/unbias-a-random-generator.aime +++ b/Task/Unbias-a-random-generator/Aime/unbias-a-random-generator.aime @@ -1,7 +1,7 @@ integer biased(integer bias) { - return 1 ^ min(drand(bias - 1), 1); + 1 ^ min(drand(bias - 1), 1); } integer @@ -12,7 +12,7 @@ unbiased(integer bias) while ((a = biased(bias)) == biased(bias)) { } - return a; + a; } integer @@ -23,21 +23,17 @@ main(void) n = 10000; b = 3; while (b <= 6) { - i = 0; - cb = 0; - cu = 0; - while (i < n) { + i = cb = cu = 0; + while ((i += 1) <= n) { cb += biased(b); cu += unbiased(b); - - i += 1; } o_form("bias ~: /d2p2/%% vs /d2p2/%%\n", b, 100r * cb / n, - 100r * cu / n); + 100r * cu / n); b += 1; } - return 0; + 0; } diff --git a/Task/Unbias-a-random-generator/Elena/unbias-a-random-generator.elena b/Task/Unbias-a-random-generator/Elena/unbias-a-random-generator.elena new file mode 100644 index 0000000000..71629094ba --- /dev/null +++ b/Task/Unbias-a-random-generator/Elena/unbias-a-random-generator.elena @@ -0,0 +1,45 @@ +import extensions. + +int extension $op +{ + bool randN + = randomGenerator nextInt(self) == 0. + + bool unbiased + [ + bool flip1 := self randN. + bool flip2 := self randN. + + while (flip1 == flip2) + [ + flip1 := self randN. + flip2 := self randN. + ]. + + ^ flip1 + ] +} + +program = +[ + 3 to:6 do(:n) + [ + int biasedZero := 0. + int biasedOne := 0. + int unbiasedZero := 0. + int unbiasedOne := 0. + + 0 till:100000 do(:i) + [ + if (n randN) [ biasedOne += 1 ]; [ biasedZero += 1 ]. + if (n unbiased) [ unbiasedOne += 1 ]; [ unbiasedZero += 1 ] + ]. + + console + printLineFormatted("(N = {0}):" padRight(17) + "# of 0"$9"# of 1"$9"% of 0"$9"% of 1", n); + printLineFormatted("Biased:" padRight(15) + "{0}"$9"{1}"$9"{2}"$9"{3}", + biasedZero, biasedOne, biasedZero / 1000, biasedOne / 1000); + printLineFormatted("Unbiased:" padRight(15) + "{0}"$9"{1}"$9"{2}"$9"{3}", + unbiasedZero, unbiasedOne, unbiasedZero / 1000, unbiasedOne / 1000). + ] +]. diff --git a/Task/Unbias-a-random-generator/Java/unbias-a-random-generator.java b/Task/Unbias-a-random-generator/Java/unbias-a-random-generator-1.java similarity index 100% rename from Task/Unbias-a-random-generator/Java/unbias-a-random-generator.java rename to Task/Unbias-a-random-generator/Java/unbias-a-random-generator-1.java diff --git a/Task/Unbias-a-random-generator/Java/unbias-a-random-generator-2.java b/Task/Unbias-a-random-generator/Java/unbias-a-random-generator-2.java new file mode 100644 index 0000000000..e3c6811573 --- /dev/null +++ b/Task/Unbias-a-random-generator/Java/unbias-a-random-generator-2.java @@ -0,0 +1,28 @@ +// version 1.1.2 + +fun biased(n: Int) = Math.random() < 1.0 / n + +fun unbiased(n: Int): Boolean { + var a: Boolean + var b: Boolean + do { + a = biased(n) + b = biased(n) + } + while (a == b) + return a +} + +fun main(args: Array) { + val m = 50_000 + val f = "%d: %2.2f%% %2.2f%%" + for (n in 3..6) { + var c1 = 0 + var c2 = 0 + for (i in 0 until m) { + if (biased(n)) c1++ + if (unbiased(n)) c2++ + } + println(f.format(n, 100.0 * c1 / m, 100.0 * c2 / m)) + } +} diff --git a/Task/Unbias-a-random-generator/Julia/unbias-a-random-generator.julia b/Task/Unbias-a-random-generator/Julia/unbias-a-random-generator.julia new file mode 100644 index 0000000000..4fce3b98c7 --- /dev/null +++ b/Task/Unbias-a-random-generator/Julia/unbias-a-random-generator.julia @@ -0,0 +1,20 @@ +randN(N) = () -> rand(1:N) == 1 ? 1 : 0 +function unbiased(biased::Function) + this, that = biased(), biased() + while this == that this, that = biased(), biased() end + return this +end + +@printf "%2s | %10s | %5s | %5s | %8s" "N" "bias./unb." "1s" "0s" "pct ratio" +const nrep = 10000 +for N in 3:6 + biased = randN(N) + + v = collect(biased() for __ in 1:nrep) + v1, v0 = count(v .== 1), count(v .== 0) + @printf("%2i | %10s | %5i | %5i | %5.2f%%\n", N, "biased", v1, v0, 100 * v1 / nrep) + + v = collect(unbiased(biased) for __ in 1:nrep) + v1, v0 = count(v .== 1), count(v .== 0) + @printf("%2i | %10s | %5i | %5i | %5.2f%%\n", N, "unbiased", v1, v0, 100 * v1 / nrep) +end diff --git a/Task/Unbias-a-random-generator/REXX/unbias-a-random-generator.rexx b/Task/Unbias-a-random-generator/REXX/unbias-a-random-generator.rexx index 91de0fc50b..85bf9a6668 100644 --- a/Task/Unbias-a-random-generator/REXX/unbias-a-random-generator.rexx +++ b/Task/Unbias-a-random-generator/REXX/unbias-a-random-generator.rexx @@ -4,7 +4,7 @@ if #=='' | #=="," then #=1000 /*#: the number of SAMPLES to if R=='' | R=="," then R=6 /*R: the high number for the range. */ if datatype(seed, 'W') then call random ,,seed /*Specified? Then use for RANDOM seed.*/ dash='─'; @b="biased"; @ub='un'@b /*literals for the SAY column headers. */ -say left('',5) ctr('N',5) ctr(@b) ctr(@b"%") ctr(@ub) ctr(@ub'%') ctr("samples") +say left('',5) ctr("N",5) ctr(@b) ctr(@b'%') ctr(@ub) ctr(@ub"%") ctr('samples') dash= do N=3 to R; b=0; u=0 do j=1 for #; b=b + randN(N); u=u + unbiased() diff --git a/Task/Unbias-a-random-generator/Rust/unbias-a-random-generator.rust b/Task/Unbias-a-random-generator/Rust/unbias-a-random-generator.rust new file mode 100644 index 0000000000..5f63b00f2d --- /dev/null +++ b/Task/Unbias-a-random-generator/Rust/unbias-a-random-generator.rust @@ -0,0 +1,39 @@ +#![feature(inclusive_range_syntax)] + +extern crate rand; + +use rand::Rng; + +fn rand_n(rng: &mut R, n: u32) -> usize { + rng.gen_weighted_bool(n) as usize // maps `false` to 0 and `true` to 1 +} + +fn unbiased(rng: &mut R, n: u32) -> usize { + let mut bit = rand_n(rng, n); + while bit == rand_n(rng, n) { + bit = rand_n(rng, n); + } + bit +} + +fn main() { + const SAMPLES: usize = 100_000; + let mut rng = rand::weak_rng(); + + println!(" Bias rand_n unbiased"); + for n in 3..=6 { + let mut count_biased = 0; + let mut count_unbiased = 0; + for _ in 0..SAMPLES { + count_biased += rand_n(&mut rng, n); + count_unbiased += unbiased(&mut rng, n); + } + + let b_percentage = 100.0 * count_biased as f64 / SAMPLES as f64; + let ub_percentage = 100.0 * count_unbiased as f64 / SAMPLES as f64; + println!( + "bias {}: {:0.2}% {:0.2}%", + n, b_percentage, ub_percentage + ); + } +} diff --git a/Task/Undefined-values/Perl-6/undefined-values-4.pl6 b/Task/Undefined-values/Perl-6/undefined-values-4.pl6 index 643924d905..6f6b9d5c0c 100644 --- a/Task/Undefined-values/Perl-6/undefined-values-4.pl6 +++ b/Task/Undefined-values/Perl-6/undefined-values-4.pl6 @@ -1,7 +1,6 @@ my Int:D $i = 1; # if $i has to be defined you must provide a default value multi sub foo(Int:D $i where * != 0){ (0..100).roll / $i } # we will never divide by 0 multi sub foo(Int:U $i){ die 'WELP! $i is undefined' } # because undefinedness is deadly -multi sub foo(Int:_ where * == 0){ die q{I'm sorry, Dave, I'm afraid I can't do that.} } with $i { say 'defined' } # as "if" is looking for Bool::True, "with" is looking for *.defined with 0 { say '0 may not divide but it is defined' } diff --git a/Task/Undefined-values/Ring/undefined-values.ring b/Task/Undefined-values/Ring/undefined-values.ring new file mode 100644 index 0000000000..775f9f2103 --- /dev/null +++ b/Task/Undefined-values/Ring/undefined-values.ring @@ -0,0 +1,11 @@ +# Project : Undefined values +# Date : 2018/03/27 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : + +test() +func test + x=10 y=20 + see islocal("x") + nl + + islocal("y") + nl + + islocal("z") + nl diff --git a/Task/Unicode-strings/D/unicode-strings.d b/Task/Unicode-strings/D/unicode-strings.d new file mode 100644 index 0000000000..3df07ff61f --- /dev/null +++ b/Task/Unicode-strings/D/unicode-strings.d @@ -0,0 +1,22 @@ +import std.stdio; +import std.uni; // standard package for normalization, composition/decomposition, etc.. +import std.utf; // standard package for decoding/encoding, etc... + +void main() { + // normal identifiers are allowed + int a; + // unicode characters are allowed for identifers + int δ; + + char c; // 1 to 4 byte unicode character + wchar w; // 2 or 4 byte unicode character + dchar d; // 4 byte unicode character + + writeln("some text"); // strings by default are UTF8 + writeln("some text"c); // optional suffix for UTF8 + writeln("こんにちは"c); // unicode charcters are just fine (stored in the string type) + writeln("Здравствуйте"w); // also avaiable are UTF16 string (stored in the wstring type) + writeln("שלום"d); // and UTF32 strings (stored in the dstring type) + + // escape sequences like what is defined in C are also allowed inside of strings and characters. +} diff --git a/Task/Unicode-variable-names/00DESCRIPTION b/Task/Unicode-variable-names/00DESCRIPTION index 11cbc2bd13..fa269e8bd7 100644 --- a/Task/Unicode-variable-names/00DESCRIPTION +++ b/Task/Unicode-variable-names/00DESCRIPTION @@ -5,6 +5,7 @@ :* Increment it :* Print its value. -;Cf.: + +;Related task: * [[Case-sensitivity of identifiers]]

diff --git a/Task/Unicode-variable-names/BaCon/unicode-variable-names.bacon b/Task/Unicode-variable-names/BaCon/unicode-variable-names.bacon new file mode 100644 index 0000000000..e9c5717e5e --- /dev/null +++ b/Task/Unicode-variable-names/BaCon/unicode-variable-names.bacon @@ -0,0 +1,9 @@ +PRAGMA COMPILER clang + +DECLARE Δ TYPE int + +Δ = 1 + +INCR Δ + +PRINT Δ diff --git a/Task/Unicode-variable-names/C/unicode-variable-names.c b/Task/Unicode-variable-names/C/unicode-variable-names.c new file mode 100644 index 0000000000..0eaa9d1ac9 --- /dev/null +++ b/Task/Unicode-variable-names/C/unicode-variable-names.c @@ -0,0 +1,13 @@ +/*Abhishek Ghosh, 5th October 2017*/ + +#include + +int main() { + int Δ = 1; + + Δ++; + + printf("%d",Δ); + + return 0; +} diff --git a/Task/Unicode-variable-names/Stata/unicode-variable-names.stata b/Task/Unicode-variable-names/Stata/unicode-variable-names.stata new file mode 100644 index 0000000000..3ec5f37460 --- /dev/null +++ b/Task/Unicode-variable-names/Stata/unicode-variable-names.stata @@ -0,0 +1,13 @@ +sca Δ=10 +sca Δ=Δ+1 +di Δ + +local Δ=20 +local ++Δ +di `Δ' + +mata +Δ=30 +Δ++ +Δ +end diff --git a/Task/Universal-Turing-machine/Kotlin/universal-turing-machine.kotlin b/Task/Universal-Turing-machine/Kotlin/universal-turing-machine.kotlin new file mode 100644 index 0000000000..1f179bde0a --- /dev/null +++ b/Task/Universal-Turing-machine/Kotlin/universal-turing-machine.kotlin @@ -0,0 +1,172 @@ +// version 1.2.10 + +enum class Dir { LEFT, RIGHT, STAY } + +class Rule( + val state1: String, + val symbol1: Char, + val symbol2: Char, + val dir: Dir, + val state2: String +) + +class Tape( + var symbol: Char, + var left: Tape? = null, + var right: Tape? = null +) + +class Turing( + val states: List, + val finalStates: List, + val symbols: CharArray, + val blank: Char, + var state: String, + tapeInput: CharArray, + rules: List +) { + var tape: Tape? = null + val transitions = Array(states.size) { arrayOfNulls(symbols.size) } + + init { + for (i in 0 until tapeInput.size) { + move(Dir.RIGHT) + tape!!.symbol = tapeInput[i] + } + if (tapeInput.size == 0) move(Dir.RIGHT) + while (tape!!.left != null) tape = tape!!.left + for (i in 0 until rules.size) { + val rule = rules[i] + transitions[stateIndex(rule.state1)][symbolIndex(rule.symbol1)] = rule + } + } + + private fun stateIndex(state: String): Int { + val i = states.indexOf(state) + return if (i >= 0) i else 0 + } + + private fun symbolIndex(symbol: Char): Int { + val i = symbols.indexOf(symbol) + return if (i >= 0) i else 0 + } + + private fun move(dir: Dir) { + val orig = tape + when (dir) { + Dir.RIGHT -> { + if (orig != null && orig.right != null) { + tape = orig.right + } + else { + tape = Tape(blank) + if (orig != null) { + tape!!.left = orig + orig.right = tape + } + } + } + + Dir.LEFT -> { + if (orig != null && orig.left != null) { + tape = orig.left + } + else { + tape = Tape(blank) + if (orig != null) { + tape!!.right = orig + orig.left = tape + } + } + } + + Dir.STAY -> {} + } + } + + fun printState() { + print("%-10s ".format(state)) + var t = tape + while (t!!.left != null ) t = t.left + while (t != null) { + if (t == tape) print("[${t.symbol}]") + else print(" ${t.symbol} ") + t = t.right + } + println() + } + + fun run(maxLines: Int = 20) { + var lines = 0 + while (true) { + printState() + for (finalState in finalStates) { + if (finalState == state) return + } + if (++lines == maxLines) { + println("(Only the first $maxLines lines displayed)") + return + } + val rule = transitions[stateIndex(state)][symbolIndex(tape!!.symbol)] + tape!!.symbol = rule!!.symbol2 + move(rule.dir) + state = rule.state2 + } + } +} + +fun main(args: Array) { + println("Simple incrementer") + Turing( + states = listOf("q0", "qf"), + finalStates = listOf("qf"), + symbols = charArrayOf('B', '1'), + blank = 'B', + state = "q0", + tapeInput = charArrayOf('1', '1', '1'), + rules = listOf( + Rule("q0", '1', '1', Dir.RIGHT, "q0"), + Rule("q0", 'B', '1', Dir.STAY, "qf") + ) + ).run() + + println("\nThree-state busy beaver") + Turing( + states = listOf("a", "b", "c", "halt"), + finalStates = listOf("halt"), + symbols = charArrayOf('0', '1'), + blank = '0', + state = "a", + tapeInput = charArrayOf(), + rules = listOf( + Rule("a", '0', '1', Dir.RIGHT, "b"), + Rule("a", '1', '1', Dir.LEFT, "c"), + Rule("b", '0', '1', Dir.LEFT, "a"), + Rule("b", '1', '1', Dir.RIGHT, "b"), + Rule("c", '0', '1', Dir.LEFT, "b"), + Rule("c", '1', '1', Dir.STAY, "halt") + ) + ).run() + + println("\nFive-state two-symbol probable busy beaver") + Turing( + states = listOf("A", "B", "C", "D", "E", "H"), + finalStates = listOf("H"), + symbols = charArrayOf('0', '1'), + blank = '0', + state = "A", + tapeInput = charArrayOf(), + rules = listOf( + Rule("A", '0', '1', Dir.RIGHT, "B"), + Rule("A", '1', '1', Dir.LEFT, "C"), + Rule("B", '0', '1', Dir.RIGHT, "C"), + Rule("B", '1', '1', Dir.RIGHT, "B"), + Rule("C", '0', '1', Dir.RIGHT, "D"), + Rule("C", '1', '0', Dir.LEFT, "E"), + Rule("D", '0', '1', Dir.LEFT, "A"), + Rule("D", '1', '1', Dir.LEFT, "D"), + Rule("E", '0', '1', Dir.STAY, "H"), + Rule("E", '1', '0', Dir.LEFT, "A") + ) + ).run() +} diff --git a/Task/Universal-Turing-machine/Perl-6/universal-turing-machine.pl6 b/Task/Universal-Turing-machine/Perl-6/universal-turing-machine.pl6 index 34011fa031..40d9a935c9 100644 --- a/Task/Universal-Turing-machine/Perl-6/universal-turing-machine.pl6 +++ b/Task/Universal-Turing-machine/Perl-6/universal-turing-machine.pl6 @@ -2,73 +2,82 @@ sub run_utm(:$state! is copy, :$blank!, :@rules!, :@tape = [$blank], :$halt, :$p $pos += @tape if $pos < 0; die "Bad initial position" unless $pos ~~ ^@tape; - step: - print "$state\t"; - for ^@tape { - my $v = @tape[$_]; - print $_ == $pos ?? "[$v]" !! " $v "; - } - print "\n"; +STEP: loop { + print "$state\t"; + for ^@tape { + my $v = @tape[$_]; + print $_ == $pos ?? "[$v]" !! " $v "; + } + print "\n"; - return if $state eq $halt; - for @rules -> @rule { - my ($s0, $v0, $v1, $dir, $s1) = @rule; - next unless $s0 eq $state and @tape[$pos] eq $v0; + last if $state eq $halt; - @tape[$pos] = $v1; + for @rules -> @rule { + my ($s0, $v0, $v1, $dir, $s1) = @rule; + next unless $s0 eq $state and @tape[$pos] eq $v0; - given $dir { - when 'left' { - if $pos == 0 { unshift @tape, $blank } - else { $pos-- } - } - when 'right' { - push @tape, $blank if ++$pos >= @tape; - } - } + @tape[$pos] = $v1; - $state = $s1; - goto step; + given $dir { + when 'left' { + if $pos == 0 { unshift @tape, $blank } + else { $pos-- } + } + when 'right' { + push @tape, $blank if ++$pos >= @tape; + } + } + + $state = $s1; + next STEP; + + } + die 'No matching rules'; } - die "No matching rules"; } say "incr machine"; run_utm :halt, - :state, - :tape[1,1,1], - :blank, - :rules[ [< q0 1 1 right q0 >], - [< q0 B 1 stay qf >] ]; + :state, + :tape[1,1,1], + :blank, + :rules[ + [< q0 1 1 right q0 >], + [< q0 B 1 stay qf >] + ]; say "\nbusy beaver"; run_utm :halt, - :state
, - :blank<0>, - :rules[ [< a 0 1 right b >], - [< a 1 1 left c >], - [< b 0 1 left a >], - [< b 1 1 right b >], - [< c 0 1 left b >], - [< c 1 1 stay halt >] ]; + :state, + :blank<0>, + :rules[ + [< a 0 1 right b >], + [< a 1 1 left c >], + [< b 0 1 left a >], + [< b 1 1 right b >], + [< c 0 1 left b >], + [< c 1 1 stay halt >] + ]; say "\nsorting test"; run_utm :halt, - :state, - :blank<0>, - :tape[< 2 2 2 1 2 2 1 2 1 2 1 2 1 2 >], - :rules[ [< A 1 1 right A >], - [< A 2 3 right B >], - [< A 0 0 left E >], - [< B 1 1 right B >], - [< B 2 2 right B >], - [< B 0 0 left C >], - [< C 1 2 left D >], - [< C 2 2 left C >], - [< C 3 2 left E >], - [< D 1 1 left D >], - [< D 2 2 left D >], - [< D 3 1 right A >], - [< E 1 1 left E >], - [< E 0 0 right STOP >] ]; + :state, + :blank<0>, + :tape[< 2 2 2 1 2 2 1 2 1 2 1 2 1 2 >], + :rules[ + [< A 1 1 right A >], + [< A 2 3 right B >], + [< A 0 0 left E >], + [< B 1 1 right B >], + [< B 2 2 right B >], + [< B 0 0 left C >], + [< C 1 2 left D >], + [< C 2 2 left C >], + [< C 3 2 left E >], + [< D 1 1 left D >], + [< D 2 2 left D >], + [< D 3 1 right A >], + [< E 1 1 left E >], + [< E 0 0 right STOP >] + ]; diff --git a/Task/Unix-ls/D/unix-ls.d b/Task/Unix-ls/D/unix-ls.d index 507681b3d7..efd5dff194 100644 --- a/Task/Unix-ls/D/unix-ls.d +++ b/Task/Unix-ls/D/unix-ls.d @@ -1,6 +1,6 @@ void main() { - import std.stdio, std.file, std.path; + import std.stdio, std.file, std.path, std.array, std.algorithm; - foreach (const string path; dirEntries(getcwd, SpanMode.shallow)) + foreach (const string path; dirEntries(getcwd, SpanMode.shallow).array.sort) path.baseName.writeln; } diff --git a/Task/Unix-ls/Erlang/unix-ls.erl b/Task/Unix-ls/Erlang/unix-ls.erl new file mode 100644 index 0000000000..cc28a832db --- /dev/null +++ b/Task/Unix-ls/Erlang/unix-ls.erl @@ -0,0 +1,14 @@ +1> Ls = fun(Dir) -> +1> {ok, DirContents} = file:list_dir(Dir), +1> [io:format("~s~n", [X]) || X <- lists:sort(DirContents)] +1> end. +#Fun +2> Ls("foo"). +bar +[ok] +3> Ls("foo/bar"). +1 +2 +a +b +[ok,ok,ok,ok] diff --git a/Task/Unix-ls/Kotlin/unix-ls.kotlin b/Task/Unix-ls/Kotlin/unix-ls.kotlin new file mode 100644 index 0000000000..873fd669b7 --- /dev/null +++ b/Task/Unix-ls/Kotlin/unix-ls.kotlin @@ -0,0 +1,18 @@ +// Version 1.2.41 + +import java.io.File + +fun ls(directory: String) { + val d = File(directory) + if (!d.isDirectory) { + println("$directory is not a directory") + return + } + d.listFiles().map { it.name } + .sortedBy { it.toLowerCase() } // case insensitive + .forEach { println(it) } +} + +fun main(args: Array) { + ls(".") // list files in current directory, say +} diff --git a/Task/Unix-ls/Standard-ML/unix-ls-1.ml b/Task/Unix-ls/Standard-ML/unix-ls-1.ml new file mode 100644 index 0000000000..d432431830 --- /dev/null +++ b/Task/Unix-ls/Standard-ML/unix-ls-1.ml @@ -0,0 +1 @@ +OS.Process.system "ls -a" diff --git a/Task/Unix-ls/Standard-ML/unix-ls-2.ml b/Task/Unix-ls/Standard-ML/unix-ls-2.ml new file mode 100644 index 0000000000..07a4ab65ef --- /dev/null +++ b/Task/Unix-ls/Standard-ML/unix-ls-2.ml @@ -0,0 +1,15 @@ +local (* make a sort function *) + val rec insert = fn s :string =>fn [] => [s] + | ll as h::t => if s<=h then s::ll else h::insert s t; +in + val rec sort = fn [] => [] | h::t => insert h (sort t) +end; + +open Posix.FileSys ; +val istream = opendir "." ; +val ll = ref [readdir istream] ; +while ( isSome (hd (!ll)) ) do ( ll:=readdir istream :: !ll ); +val result = List.map valOf (tl (!ll)); +closedir istream ; + +sort result; diff --git a/Task/Update-a-configuration-file/Kotlin/update-a-configuration-file.kotlin b/Task/Update-a-configuration-file/Kotlin/update-a-configuration-file.kotlin new file mode 100644 index 0000000000..823f29146a --- /dev/null +++ b/Task/Update-a-configuration-file/Kotlin/update-a-configuration-file.kotlin @@ -0,0 +1,100 @@ +// version 1.2.0 + +import java.io.File + +class ConfigData( + val favouriteFruit: String, + val needsPeeling: Boolean, + val seedsRemoved: Boolean, + val numberOfBananas: Int, + val numberOfStrawberries: Int +) + +fun updateConfigFile(fileName: String, cData: ConfigData) { + val inp = File(fileName) + val lines = inp.readLines() + val tempFileName = "temp_$fileName" + val out = File(tempFileName) + val pw = out.printWriter() + var hadFruit = false + var hadPeeling = false + var hadSeeds = false + var hadBananas = false + var hadStrawberries = false + + for (line in lines) { + if (line.isEmpty() || line[0] == '#') { + pw.println(line) + continue + } + val ln = line.trimStart(';').trim(' ', '\t').toUpperCase() + if (ln.isEmpty()) continue + if (ln.take(14) == "FAVOURITEFRUIT") { + if (hadFruit) continue + hadFruit = true + pw.println("FAVOURITEFRUIT ${cData.favouriteFruit}") + } + else if (ln.take(12) == "NEEDSPEELING") { + if (hadPeeling) continue + hadPeeling = true + if (cData.needsPeeling) + pw.println("NEEDSPEELING") + else + pw.println("; NEEDSPEELING") + } + else if (ln.take(12) == "SEEDSREMOVED") { + if (hadSeeds) continue + hadSeeds = true + if (cData.seedsRemoved) + pw.println("SEEDSREMOVED") + else + pw.println("; SEEDSREMOVED") + } + else if(ln.take(15) == "NUMBEROFBANANAS") { + if (hadBananas) continue + hadBananas = true + pw.println("NUMBEROFBANANAS ${cData.numberOfBananas}") + } + else if(ln.take(20) == "NUMBEROFSTRAWBERRIES") { + if (hadStrawberries) continue + hadStrawberries = true + pw.println("NUMBEROFSTRAWBERRIES ${cData.numberOfStrawberries}") + } + } + + if (!hadFruit) { + pw.println("FAVOURITEFRUIT ${cData.favouriteFruit}") + } + + if (!hadPeeling) { + if (cData.needsPeeling) + pw.println("NEEDSPEELING") + else + pw.println("; NEEDSPEELING") + } + + if (!hadSeeds) { + if (cData.seedsRemoved) + pw.println("SEEDSREMOVED") + else + pw.println("; SEEDSREMOVED") + } + + if (!hadBananas) { + pw.println("NUMBEROFBANANAS ${cData.numberOfBananas}") + } + + if (!hadStrawberries) { + pw.println("NUMBEROFSTRAWBERRIES ${cData.numberOfStrawberries}") + } + + pw.close() + inp.delete() + out.renameTo(inp) +} + +fun main(args: Array) { + val fileName = "config.txt" + val cData = ConfigData("banana", false, true, 1024, 62000) + updateConfigFile(fileName, cData) +} diff --git a/Task/Update-a-configuration-file/Perl-6/update-a-configuration-file.pl6 b/Task/Update-a-configuration-file/Perl-6/update-a-configuration-file.pl6 index b743a51268..3279f23303 100644 --- a/Task/Update-a-configuration-file/Perl-6/update-a-configuration-file.pl6 +++ b/Task/Update-a-configuration-file/Perl-6/update-a-configuration-file.pl6 @@ -1,13 +1,11 @@ -#!/usr/bin/env perl6 +use File::Temp; -my $tmpfile = tmpfile; +my ($tmpfile, $out) = tempfile; sub MAIN ($file, *%changes) { %changes.=map({; .key.uc => .value }); my %seen; - my $out = open $tmpfile, :w; - for $file.IO.lines { when /:s ^ ('#' .* | '') $/ { say $out: ~$0; @@ -27,16 +25,11 @@ sub MAIN ($file, *%changes) { say $out: format-line .key, |(.value ~~ Bool ?? (Nil, .value) !! (.value, True)) for %changes; - move $tmpfile, $file; + $out.close; + + copy $tmpfile, $file; } -END { unlink $tmpfile if $tmpfile.IO.e } - - sub format-line ($key, $value, $enabled) { ("; " if !$enabled) ~ $key.uc ~ (" $value" if defined $value); } - -sub tmpfile { - $*SPEC.catfile: $*SPEC.tmpdir, ("a".."z").roll(20).join -} diff --git a/Task/Use-another-language-to-call-a-function/Kotlin/use-another-language-to-call-a-function-1.kotlin b/Task/Use-another-language-to-call-a-function/Kotlin/use-another-language-to-call-a-function-1.kotlin new file mode 100644 index 0000000000..9b27cc4773 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Kotlin/use-another-language-to-call-a-function-1.kotlin @@ -0,0 +1,14 @@ +// Kotlin Native v0.6 + +import kotlinx.cinterop.* +import platform.posix.* + +fun query(data: CPointer, length: CPointer): Int { + val s = "Here am I" + val strLen = s.length + val bufferSize = length.pointed.value + if (strLen > bufferSize) return 0 // buffer not large enough + for (i in 0 until strLen) data[i] = s[i].toByte() + length.pointed.value = strLen.signExtend() + return 1 +} diff --git a/Task/Use-another-language-to-call-a-function/Kotlin/use-another-language-to-call-a-function-2.kotlin b/Task/Use-another-language-to-call-a-function/Kotlin/use-another-language-to-call-a-function-2.kotlin new file mode 100644 index 0000000000..19c7deee4e --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Kotlin/use-another-language-to-call-a-function-2.kotlin @@ -0,0 +1,35 @@ +#ifndef KONAN_LIBQUERY_H +#define KONAN_LIBQUERY_H +#ifdef __cplusplus +extern "C" { +#endif +typedef unsigned char libQuery_KBoolean; +typedef char libQuery_KByte; +typedef unsigned short libQuery_KChar; +typedef short libQuery_KShort; +typedef int libQuery_KInt; +typedef long long libQuery_KLong; +typedef float libQuery_KFloat; +typedef double libQuery_KDouble; +typedef void* libQuery_KNativePtr; +struct libQuery_KType; +typedef struct libQuery_KType libQuery_KType; + +typedef struct { + /* Service functions. */ + void (*DisposeStablePointer)(libQuery_KNativePtr ptr); + void (*DisposeString)(const char* string); + libQuery_KBoolean (*IsInstance)(libQuery_KNativePtr ref, const libQuery_KType* type); + + /* User functions. */ + struct { + struct { + libQuery_KInt (*query)(void* data, void* length); + } root; + } kotlin; +} libQuery_ExportedSymbols; +extern libQuery_ExportedSymbols* libQuery_symbols(void); +#ifdef __cplusplus +} /* extern "C" */ +#endif +#endif /* KONAN_LIBQUERY_H */ diff --git a/Task/Use-another-language-to-call-a-function/Kotlin/use-another-language-to-call-a-function-3.kotlin b/Task/Use-another-language-to-call-a-function/Kotlin/use-another-language-to-call-a-function-3.kotlin new file mode 100644 index 0000000000..7d6dce39a7 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Kotlin/use-another-language-to-call-a-function-3.kotlin @@ -0,0 +1,25 @@ +#include +#include +#include "libQuery_api.h" + +static int Query (char * Data, size_t * Length) +{ + return libQuery_symbols() -> kotlin.root.query(Data, Length); +} + +int main (int argc, char * argv []) +{ + char Buffer [1024]; + size_t Size = sizeof (Buffer); + + if (0 == Query (Buffer, &Size)) + { + printf ("failed to call Query\n"); + } + else + { + char * Ptr = Buffer; + while (Size-- > 0) putchar (*Ptr++); + putchar ('\n'); + } +} diff --git a/Task/Use-another-language-to-call-a-function/Scala/use-another-language-to-call-a-function-1.scala b/Task/Use-another-language-to-call-a-function/Scala/use-another-language-to-call-a-function-1.scala new file mode 100644 index 0000000000..a058da8ac8 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Scala/use-another-language-to-call-a-function-1.scala @@ -0,0 +1,12 @@ +/* Query.scala */ +object Query { + def call(data: Array[Byte], length: Array[Int]): Boolean = { + val message = "Here am I" + val mb = message.getBytes("utf-8") + if (length(0) >= mb.length) { + length(0) = mb.length + System.arraycopy(mb, 0, data, 0, mb.length) + true + } else false + } +} diff --git a/Task/Use-another-language-to-call-a-function/Scala/use-another-language-to-call-a-function-2.scala b/Task/Use-another-language-to-call-a-function/Scala/use-another-language-to-call-a-function-2.scala new file mode 100644 index 0000000000..2ca7175587 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Scala/use-another-language-to-call-a-function-2.scala @@ -0,0 +1,105 @@ +/* query-jni.c */ +#include +#include +#include + +static JavaVM *jvm = NULL; +static JNIEnv *jenv = NULL; + +static void die(const char *message) { + fprintf(stderr, "%s\n", message); + exit(1); +} + +static void oom(void) { + die("Query: out of memory"); +} + +static void except(void) { + if ((*jenv)->ExceptionCheck(jenv)) + die("Query: unexpected Java exception"); +} + +static void do_at_exit(void) { + (*jvm)->DestroyJavaVM(jvm); +} + +static void require_jvm(void) { + JavaVMInitArgs args; + + if (jvm) + return; + + args.version = JNI_VERSION_1_4; + args.nOptions = 0; + args.options = NULL; + args.ignoreUnrecognized = JNI_FALSE; + if (JNI_CreateJavaVM(&jvm, (void **)&jenv, &args) != JNI_OK) + die("Query: can't create Java VM"); + atexit(do_at_exit); +} + +int Query(char *data, size_t *length) { + jclass cQuery; + jmethodID mcall; + jintArray jlength; + jint jlength0; + jbyteArray jdata; + jboolean result; + + jlength0 = (jint)length[0]; + if ((size_t)jlength0 != length[0]) + die("Query: length is too large for Scala array"); + + require_jvm(); + + /* Create a local frame for references to Scala objects. */ + if ((*jenv)->PushLocalFrame(jenv, 16)) + oom(); + + /* Look for class Query, static boolean call(byte[], int[]) */ + cQuery = (*jenv)->FindClass(jenv, "Query"); + if (cQuery == NULL) + die("Query: can't find Query.class"); + mcall = (*jenv)->GetStaticMethodID(jenv, cQuery, "call", "([B[I)Z"); + if (mcall == NULL) + die("Query: missing call() method"); + + /* + * Make arguments to Query.call(). We can't pass data[] and + * length[] to Scala, so we make new Scala arrays jdata[] and + * jlength[]. + */ + jdata = (*jenv)->NewByteArray(jenv, (jsize)jlength0); + if (jdata == NULL) + oom(); + jlength = (*jenv)->NewIntArray(jenv, 1); + if (jlength == NULL) + oom(); + + /* Set jlength[0] = length[0]. */ + (*jenv)->SetIntArrayRegion(jenv, jlength, 0, 1, &jlength0); + except(); + + /* + * Call our Scala method. + */ + result = (*jenv)->CallStaticBooleanMethod + (jenv, cQuery, mcall, jdata, jlength); + except(); + + /* + * Set length[0] = jlength[0]. + * Copy length[0] bytes from jdata[] to data[]. + */ + (*jenv)->GetIntArrayRegion(jenv, jlength, 0, 1, &jlength0); + except(); + length[0] = (size_t)jlength0; + (*jenv)->GetByteArrayRegion + (jenv, jdata, 0, (jsize)jlength0, (jbyte *)data); + + /* Drop our local frame and its references. */ + (*jenv)->PopLocalFrame(jenv, NULL); + + return (int)result; +} diff --git a/Task/Use-another-language-to-call-a-function/Scala/use-another-language-to-call-a-function-3.scala b/Task/Use-another-language-to-call-a-function/Scala/use-another-language-to-call-a-function-3.scala new file mode 100644 index 0000000000..94c9f555b7 --- /dev/null +++ b/Task/Use-another-language-to-call-a-function/Scala/use-another-language-to-call-a-function-3.scala @@ -0,0 +1,22 @@ +# Makefile + +# Edit these lines to match your JDK. +JAVA_HOME = /Library/Java/Home +CPPFLAGS = -I$(JAVA_HOME)/include +LIBS = -framework JavaVM +JAVAC = $(JAVA_HOME)/bin/javac +CC = cc + +all: calljava Query.class + +calljava: main.o query-jni.o + $(CC) -o calljava main.o query-jni.o $(LIBS) + +.SUFFIXES: .c .class .java .o +.c.o: + $(CC) $(CPPFLAGS) -c $< +.java.class: + $(JAVAC) $< + +clean: + rm -f calljava main.o query-jni.o Query.class diff --git a/Task/User-input-Graphical/Perl-6/user-input-graphical.pl6 b/Task/User-input-Graphical/Perl-6/user-input-graphical.pl6 index 393eeb4915..60cdbf9a1b 100644 --- a/Task/User-input-Graphical/Perl-6/user-input-graphical.pl6 +++ b/Task/User-input-Graphical/Perl-6/user-input-graphical.pl6 @@ -1,10 +1,11 @@ use GTK::Simple; +use GTK::Simple::App; my GTK::Simple::App $app .= new( title => 'User Interaction' ); -$app.border_width = 20; +$app.border-width = 20; -$app.set_content( +$app.set-content( GTK::Simple::VBox.new( my $ = GTK::Simple::Label.new( text => 'Enter a string.' ), my $str = GTK::Simple::Entry.new, diff --git a/Task/User-input-Text/HolyC/user-input-text.holyc b/Task/User-input-Text/HolyC/user-input-text.holyc new file mode 100644 index 0000000000..13d12c6f3f --- /dev/null +++ b/Task/User-input-Text/HolyC/user-input-text.holyc @@ -0,0 +1,10 @@ +U8 *s; +s = GetStr("Enter a string: "); + +U32 *n; +do { + n = GetStr("Enter 75000: "); +} while(Str2I64(n) != 75000); + +Print("Your string: %s\n", s); +Print("75000: %d\n", Str2I64(n)); diff --git a/Task/User-input-Text/Julia/user-input-text.julia b/Task/User-input-Text/Julia/user-input-text.julia index d4c396c238..fa25fd9c57 100644 --- a/Task/User-input-Text/Julia/user-input-text.julia +++ b/Task/User-input-Text/Julia/user-input-text.julia @@ -1,10 +1,10 @@ print("String? ") -y = chomp(readline()) +y = readline() println("Your input was \"", y, "\".\n") print("Integer? ") -y = chomp(readline()) +y = readline() try - y = parseint(y) + y = parse(Int, y) println("Your input was \"", y, "\".\n") catch println("Sorry, but \"", y, "\" does not compute as an integer.") diff --git a/Task/User-input-Text/REXX/user-input-text.rexx b/Task/User-input-Text/REXX/user-input-text.rexx index d2e9a8bd9b..b6d93da749 100644 --- a/Task/User-input-Text/REXX/user-input-text.rexx +++ b/Task/User-input-Text/REXX/user-input-text.rexx @@ -1,10 +1,10 @@ -/*REXX pgm prompts and gets a string and also the # 75000 from terminal.*/ -say 'Please enter a string:'; parse pull userString -say 'You entered this string:' userString /* show it on the console */ - /* [↑] string can be any length.*/ - do until userNumber=75000 /*repeat this loop until correct.*/ - say /*display blank line to terminal.*/ - say 'Please enter the number 75000' /*display a nice prompt message. */ - parse pull userNumber /*obtain the user text from term.*/ - end /*until ··· */ /*check if the response is legit.*/ - /*stick a fork in it, we're done.*/ +/*REXX program prompts & reads/obtains a string, and also the number 75000 from terminal*/ +say 'Please enter a string:' /*issue a prompt message to the term. */ +parse pull userString /*the (char) string can be any length. */ + /* [↑] the string could be null/empty.*/ + do until userNumber=75000 /*repeat this loop until satisfied. */ + say /*display a blank line to the terminal.*/ + say 'Please enter the number 75000' /*display a nice prompt message to term*/ + parse pull userNumber /*obtain the user text from terminal. */ + end /*until*/ /*check if the response is legitimate. */ + /*stick a fork in it, we're all done. */ diff --git a/Task/User-input-Text/Red/user-input-text.red b/Task/User-input-Text/Red/user-input-text.red new file mode 100644 index 0000000000..3763bc0d23 --- /dev/null +++ b/Task/User-input-Text/Red/user-input-text.red @@ -0,0 +1 @@ +n: ask "Please enter # 75000: " str: ask "Please enter any string: " diff --git a/Task/Vampire-number/Factor/vampire-number.factor b/Task/Vampire-number/Factor/vampire-number.factor new file mode 100644 index 0000000000..bbe6b4df04 --- /dev/null +++ b/Task/Vampire-number/Factor/vampire-number.factor @@ -0,0 +1,44 @@ +USING: combinators.short-circuit fry io kernel lists lists.lazy math +math.combinatorics math.functions math.primes.factors math.statistics +math.text.utils prettyprint sequences sets ; +IN: rosetta-code.vampire-number + +: digits ( n -- m ) + log10 floor >integer 1 + ; + +: same-digits? ( n n1 n2 -- ? ) + [ 1 digit-groups ] tri@ append [ histogram ] bi@ = ; + +: half-len-factors ( n -- seq ) + [ divisors ] [ digits ] bi 2/ '[ digits _ = ] filter ; + +: same-digit-factors ( n -- seq ) + dup half-len-factors 2 [ first2 same-digits? ] with filter ; + +: under-two-trailing-zeros? ( seq -- ? ) + [ 10 mod ] map [ 0 = ] count 2 < ; + +: tentative-fangs ( n -- seq ) + same-digit-factors [ under-two-trailing-zeros? ] filter ; + +: fangs ( n -- seq ) + [ tentative-fangs ] [ ] bi '[ product _ = ] filter ; + +: vampire? ( n -- ? ) + { [ digits even? ] [ fangs empty? not ] } 1&& ; + +: first25 ( -- seq ) + 25 0 lfrom [ vampire? ] lfilter ltake list>array ; + +: .vamp-with-fangs ( n -- ) + [ pprint bl ] [ fangs [ pprint bl ] each ] bi nl ; + +: part1 ( -- ) + first25 [ .vamp-with-fangs ] each ; + +: part2 ( -- ) { 16758243290880 24959017348650 14593825548650 } + [ dup vampire? [ .vamp-with-fangs ] [ drop ] if ] each ; + +: main ( -- ) part1 part2 ; + +MAIN: main diff --git a/Task/Vampire-number/Perl/vampire-number.pl b/Task/Vampire-number/Perl/vampire-number-1.pl similarity index 100% rename from Task/Vampire-number/Perl/vampire-number.pl rename to Task/Vampire-number/Perl/vampire-number-1.pl diff --git a/Task/Vampire-number/Perl/vampire-number-2.pl b/Task/Vampire-number/Perl/vampire-number-2.pl new file mode 100644 index 0000000000..c4f235064a --- /dev/null +++ b/Task/Vampire-number/Perl/vampire-number-2.pl @@ -0,0 +1,45 @@ +use ntheory qw(sqrtint logint divisors); + +sub is_vampire { + my ($n) = @_; + + return if (length($n) % 2 or $n < 0); + + my $l1 = 10**logint(sqrtint($n), 10); + my $l2 = sqrtint($n); + + my $s = join('', sort split(//, $n)); + + my @fangs; + + foreach my $d (divisors($n)) { + + $d < $l1 and next; + $d > $l2 and last; + + my $t = $n / $d; + + next if ($d % 10 == 0 and $t % 10 == 0); + next if (join('', sort split(//, "$d$t")) ne $s); + + push @fangs, [$d, $t]; + } + + return @fangs; +} + +print "First 25 Vampire Numbers:\n"; + +for (my ($n, $i) = (1, 1) ; $i <= 25 ; ++$n) { + if (my @fangs = is_vampire($n)) { + printf("%2d. %6s : %s\n", $i++, $n, join(' ', map { "[@$_]" } @fangs)); + } +} + +print "\nIndividual tests:\n"; + +foreach my $n (16758243290880, 24959017348650, 14593825548650) { + my @fangs = is_vampire($n); + print("$n: ", (@fangs ? join(' ', map { "[@$_]" } @fangs) + : "is not a vampire number"), "\n"); +} diff --git a/Task/Vampire-number/REXX/vampire-number.rexx b/Task/Vampire-number/REXX/vampire-number.rexx index 0fc1125f9e..b368b3b9ee 100644 --- a/Task/Vampire-number/REXX/vampire-number.rexx +++ b/Task/Vampire-number/REXX/vampire-number.rexx @@ -6,37 +6,35 @@ parse arg N .; if N=='' | N=="," then N=25 /*Not specified? Then use the #=0 /*num. of vampire numbers found, so far*/ if N>0 then do j=1260 until # >= N /*search until N vampire numbers found.*/ if length(j) // 2 then do; j=j*10 - 1; iterate; end /*adjust J*/ - _=right(J,1); if jq then iterate - if q*d//9\==(q+d)//9 then iterate /*modulo 9 congruence test. */ - if verify(q, ?) \==0 then iterate - if right(q, 1) ==0 then if right(d, 1)==0 then iterate - if length(q)\==w then iterate - dq=d || q; t=? - do i=1 for L; p=pos( substr(dq, i, 1), t) - if p==0 then iterate d; t=delstr(t, p, 1) - end /*i*/ - !!=!! '['d"∙"q']' - end /*d*/ - return !! + beg=max(bot, 10**(w-1)); if inc=2 then if beg//2==0 then beg=beg + 1 + /* [↑] odd BEG if odd INC*/ + do d=beg to min(top, 10**w - 1) by inc + if ? // d \==0 then iterate /*? not ÷ by D? Then skip,*/ + q=? % d; if d>q then iterate /*is D > Q Then skip.*/ + if q*d//9 \== (q+d)//9 then iterate /*modulo 9 congruence test. */ + if length(q) \==w then iterate /*Len of Q ^= W? Then skip.*/ + if right(q, 1) ==0 then if right(d, 1) ==0 then iterate + dq=d || q + t=?; do i=1 for L; p=pos( substr(dq, i, 1), t) + if p==0 then iterate d; t=delstr(t, p, 1) + end /*i*/ + a=a '['d"∙"q']' + end /*d*/ + return a diff --git a/Task/Vampire-number/Ring/vampire-number.ring b/Task/Vampire-number/Ring/vampire-number.ring new file mode 100644 index 0000000000..1686dca04a --- /dev/null +++ b/Task/Vampire-number/Ring/vampire-number.ring @@ -0,0 +1,82 @@ +# Project : Vampire number +# Date : 2018/02/01 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : + +for p = 10 to 127000 + vampire(p) +next + +func vampire(listnum) + sum = 0 + flag = 1 + list = list(len(string(listnum))) + total = newlist(len(list),2) + for n = 1 to len(string(listnum)) + liststr = string(listnum) + list[n] = liststr[n] + next + + for perm = 1 to fact(len(list)) + numstr = substr(list2str(list), nl, "") + num1 = number(left(numstr,len(numstr)/2)) + num2 = number(right(numstr,len(numstr)/2)) + if (listnum = num1 * num2) + for n = 1 to len(total) + if (num1 = total[n][2] and num2 = total[n][1]) or + (num1 = total[n][1] and num2 = total[n][2]) + flag = 0 + ok + next + if flag = 1 + sum = sum + 1 + total[sum][1] = num1 + total[sum][2] = num2 + see "" + listnum + ": [" + num1 + "," + num2 + "]" + nl + ok + ok + nextPermutation(list) + next + +func nextPermutation(a) + elementcount = len(a) + if elementcount < 1 then return ok + pos = elementcount-1 + while a[pos] >= a[pos+1] + pos -= 1 + if pos <= 0 permutationReverse(a, 1, elementcount) + return ok + end + last = elementcount + while a[last] <= a[pos] + last -= 1 + end + temp = a[pos] + a[pos] = a[last] + a[last] = temp + permutationReverse(a, pos+1, elementcount) + + func permutationReverse a, first, last + while first < last + temp = a[first] + a[first] = a[last] + a[last] = temp + first += 1 + last -= 1 + end + +func fact(nr) + if nr = 1 + return 1 + else + return nr * fact(nr-1) + ok + +func newlist(x,y) + if isstring(x) x=0+x ok + if isstring(y) y=0+y ok + alist = list(x) + for t in alist + t = list(y) + next + return alist diff --git a/Task/Vampire-number/Sidef/vampire-number.sidef b/Task/Vampire-number/Sidef/vampire-number.sidef new file mode 100644 index 0000000000..94ddbcad74 --- /dev/null +++ b/Task/Vampire-number/Sidef/vampire-number.sidef @@ -0,0 +1,39 @@ +func is_vampire (n) { + return [] if n.ilog10.is_even + + var l1 = n.isqrt.ilog10.ipow10 + var l2 = n.isqrt + + var s = n.digits.sort.join + + gather { + n.divisors.each { |d| + + d < l1 && next + d > l2 && break + + var t = n/d + + next if (d%%10 && t%%10) + next if ("#{d}#{t}".sort != s) + + take([d, t]) + } + } +} + +say "First 25 Vampire Numbers:" + +with (1) { |i| + for (var n = 1; i <= 25; ++n) { + var fangs = is_vampire(n) + printf("%2d. %6s : %s\n", i++, n, fangs.join(' ')) if fangs + } +} + +say "\nIndividual tests:" + +[16758243290880, 24959017348650, 14593825548650].each { |n| + var fangs = is_vampire(n) + say "#{n}: #{fangs ? fangs.join(', ') : 'is not a vampire number'}" +} diff --git a/Task/Van-der-Corput-sequence/Julia/van-der-corput-sequence.julia b/Task/Van-der-Corput-sequence/Julia/van-der-corput-sequence.julia index 6e98e2939e..2d668704cb 100644 --- a/Task/Van-der-Corput-sequence/Julia/van-der-corput-sequence.julia +++ b/Task/Van-der-Corput-sequence/Julia/van-der-corput-sequence.julia @@ -1,11 +1,7 @@ -function vdc{T<:Integer}(n::T, b::T) - sum([d*float(b)^-i for (i, d) in enumerate(digits(n, b))]) -end +vandercorput(num::Integer, base::Integer) = sum(d * Float64(base) ^ -ex for (ex, d) in enumerate(digits(num, base))) -for i in 2:9 - print(" Base ", i) - for j in 0:9 - print(@sprintf(" %8.6f", vdc(j, i))) - end - println() +for base in 2:9 + @printf("%10s %i:", "Base", base) + for num in 0:9 @printf("%7.3f", vandercorput(num, base)) end + println(" [...]") end diff --git a/Task/Van-der-Corput-sequence/Modula-2/van-der-corput-sequence.mod2 b/Task/Van-der-Corput-sequence/Modula-2/van-der-corput-sequence.mod2 new file mode 100644 index 0000000000..38543e7163 --- /dev/null +++ b/Task/Van-der-Corput-sequence/Modula-2/van-der-corput-sequence.mod2 @@ -0,0 +1,50 @@ +MODULE Sequence; +FROM FormatString IMPORT FormatString; +FROM Terminal IMPORT WriteString,WriteLn,ReadChar; + +PROCEDURE vc(n,base : INTEGER; VAR num,denom : INTEGER); +VAR p,q : INTEGER; +BEGIN + p := 0; + q := 1; + + WHILE n#0 DO + p := p * base + (n MOD base); + q := q * base; + n := n DIV base + END; + + num := p; + denom := q; + + WHILE p#0 DO + n := p; + p := q MOD p; + q := n + END; + + num := num DIV q; + denom := denom DIV q +END vc; + +VAR + buf : ARRAY[0..31] OF CHAR; + d,n,i,b : INTEGER; +BEGIN + FOR b:=2 TO 5 DO + FormatString("base %i:", buf, b); + WriteString(buf); + FOR i:=0 TO 9 DO + vc(i,b,n,d); + IF n#0 THEN + FormatString(" %i/%i", buf, n, d); + WriteString(buf) + ELSE + WriteString(" 0") + END + END; + WriteLn + END; + + ReadChar +END Sequence. diff --git a/Task/Van-der-Corput-sequence/REXX/van-der-corput-sequence-2.rexx b/Task/Van-der-Corput-sequence/REXX/van-der-corput-sequence-2.rexx index 47e31ce713..e27ff03bfa 100644 --- a/Task/Van-der-Corput-sequence/REXX/van-der-corput-sequence-2.rexx +++ b/Task/Van-der-Corput-sequence/REXX/van-der-corput-sequence-2.rexx @@ -6,47 +6,48 @@ if a=='' | a=="," then parse value 0 10 with a b /*Not specified? Then use the if b=='' | b=="," then b=a /* " " " " " " */ if r=='' | r=="," then r=2 /* " " " " " " */ z= /*a placeholder for a list of numbers. */ - do j=a to b /*traipse through the range of integers*/ - _=VdC( abs(j), abs(r) ) /*convert the ABSolute value of integer*/ - _=substr('-', 2+sign(j) )_ /*if needed, keep the leading - sign.*/ - if r>0 then say _ /*if positive base, then just show it. */ - else z=z _ /* ··· else append (build) a list. */ - end /*j*/ + do j=a to b /*traipse through the range of integers*/ + _=VdC( abs(j), abs(r) ) /*convert the ABSolute value of integer*/ + _=substr('-', 2 + sign(j) )_ /*if needed, keep the leading - sign.*/ + if r>0 then say _ /*if positive base, then just show it. */ + else z=z _ /* ··· else append (build) a list. */ + end /*j*/ if z\=='' then say strip(z) /*if a list is wanted, then display it.*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ base: procedure; parse arg x, toB, inB /*get a number, toBase, and inBase. */ - /*┌───────────────────────────────────────────────────────────────────┐ - ┌─┘ Input to this function: x (is required & must be an integer).└─┐ - │ toBase the base to convert X to. │ - │ inBase the base X is expressed in. │ - │ │ - │ toBase or inBase can be omitted which causes the default of 10 │ - └─┐ to be used. Both have a limit of: 2 ──► 90.┌─┘ - └───────────────────────────────────────────────────────────────────┘*/ - @abc= 'abcdefghijklmnopqrstuvwxyz' /*the Latin lowercase alphabet chars. */ - @abcU=@abc; upper @abcU /*go whole hog and extend characters. */ - @@@= 0123456789 || @abc || @abcU /*prefix them with some numeric digits.*/ + /*╔══════════════════════════════════════════════════════════════════════════════════╗ + ║ Input to this function: x (X is required and it must be an integer). ║ + ║ toBase the base to convert X to (default=10). ║ + ║ inBase the base X is expressed in (default=10). ║ + ║ ║ + ║ toBase & inBase have a limit of: 2 ──► 90 ║ + ╚══════════════════════════════════════════════════════════════════════════════════╝*/ + @abc= 'abcdefghijklmnopqrstuvwxyz' /*the lowercase Latin alphabet letters.*/ + @abcU=@abc; upper @abcU /*go whole hog & extend with uppercase.*/ + @@@= 0123456789 || @abc || @abcU /*prefix them with the decimal digits. */ @@@= @@@'<>[]{}()?~!@#$%^&*_+-=|\/;:`' /*add some special characters as well, */ - /*special characters should be viewable*/ - numeric digits 1000 /*what the hey, support biggy numbers.*/ + /*──those chars should all be viewable.*/ + numeric digits 1000 /*what the hey, support bigun' numbers.*/ maxB=length(@@@) /*maximum base (radix) supported here. */ - if toB=='' then toB=10 /*if skipped, then assume default (10)*/ + if toB=='' then toB=10 /*if omitted, then assume default (10)*/ if inB=='' then inB=10 /* " " " " " " */ #=0 /* [↓] convert base inB X ──► base 10*/ - do j=1 for length(x) + do j=1 for length(x) /*process each "numeral" in the string.*/ _=substr(x, j, 1) /*pick off a "digit" (numeral) from X.*/ v=pos(_, @@@) /*get the value of this "digit"/numeral*/ - if v==0|v>inB then call erd x,j,inB /*is it an illegal "digit" (numeral) ? */ - #=#*inB + v - 1 /*construct new number, digit by digit.*/ + if v==0 | v>inB then call erd /*is it an illegal "digit" (numeral) ? */ + #=# * inB + v - 1 /*construct new number, digit by digit.*/ end /*j*/ y= /* [↓] convert base 10 # ──► base toB.*/ - do while #>=toB /*deconstruct the new number (#). */ - y=substr(@@@, #//toB + 1, 1)y /* construct the output number, ··· */ + do while #>=toB /*deconstruct the new number (#). */ + y=substr(@@@, # // toB + 1, 1)y /* construct the output number, ··· */ #=# % toB /* ··· and also whittle down #. */ end /*while*/ - return substr(@@@, #+1, 1)y + return substr(@@@, # + 1, 1)y /*return a constructed "numeric" string*/ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +erd: say 'the character ' v " isn't a legal numeral for base " inB'.'; exit 13 /*──────────────────────────────────────────────────────────────────────────────────────*/ VdC: return '.'reverse(base(arg(1), arg(2))) /*convert the #, reverse the #, append.*/ diff --git a/Task/Van-der-Corput-sequence/Stata/van-der-corput-sequence-2.stata b/Task/Van-der-Corput-sequence/Stata/van-der-corput-sequence-2.stata index 81a440f061..218f287b55 100644 --- a/Task/Van-der-Corput-sequence/Stata/van-der-corput-sequence-2.stata +++ b/Task/Van-der-Corput-sequence/Stata/van-der-corput-sequence-2.stata @@ -10,4 +10,6 @@ st_store(k,2,0.5*runiform(2500,1)) st_store(k,3,0.5:+0.5*halton(2500,1)) end twoway scatter y x, msize(tiny) color(blue) /// - || scatter z x, msize(tiny) color(green) + || scatter z x, msize(tiny) color(green) legend(off) xtitle("") /// + title(Distribution: Van der Corput (top) vs pseudorandom) /// + ylabel(, angle(0) format(%3.1f)) diff --git a/Task/Variable-length-quantity/00DESCRIPTION b/Task/Variable-length-quantity/00DESCRIPTION index cd5b7c7620..24f721b9af 100644 --- a/Task/Variable-length-quantity/00DESCRIPTION +++ b/Task/Variable-length-quantity/00DESCRIPTION @@ -1,6 +1,9 @@ Implement some operations on [[wp:Variable-length quantity|variable-length quantities]], at least including conversions from a normal number in the language to the binary representation of the variable-length quantity for that number, and ''vice versa''. Any variants are acceptable. -'''Task :''' With above operations, + +;Task: +With above operations, *convert these two numbers 0x200000 (2097152 in decimal) and 0x1fffff (2097151 in decimal) into sequences of octets (an eight-bit byte); *display these sequences of octets; *convert these sequences of octets back to numbers, and check that they are equal to original numbers. +

diff --git a/Task/Variable-length-quantity/Julia/variable-length-quantity.julia b/Task/Variable-length-quantity/Julia/variable-length-quantity.julia index f719f0dd48..7184987625 100644 --- a/Task/Variable-length-quantity/Julia/variable-length-quantity.julia +++ b/Task/Variable-length-quantity/Julia/variable-length-quantity.julia @@ -1,34 +1,31 @@ -type VLQ - q::Array{Uint8,1} +mutable struct VLQ + quant::Vector{UInt8} end -function VLQ{T<:Integer}(n::T) - q = uint8(digits(n, 128)) - for i in 2:length(q) - q[i] |= 0x80 - end - VLQ(reverse(q)) +function VLQ(n::T) where T <: Integer + quant = UInt8.(digits(n, 128)) + @inbounds for i in 2:length(quant) quant[i] |= 0x80 end + VLQ(reverse(quant)) end -function Base.uint(vlq::VLQ) - q = reverse(vlq.q) - n = shift!(q) - p = one(Uint64) - for i in q +import Base.UInt64 +function Base.UInt64(vlq::VLQ) + quant = reverse(vlq.quant) + n = shift!(quant) + p = one(UInt64) + for i in quant p *= 0x80 - n += p*(i&0x7f) + n += p * ( i & 0x7f) end return n end -test = [0x00200000, 0x001fffff, 0x00000000, 0x0000007f, - 0x00000080, 0x00002000, 0x00003fff, 0x00004000, - 0x08000000, 0x0fffffff] +const test = [0x00200000, 0x001fffff, 0x00000000, 0x0000007f, + 0x00000080, 0x00002000, 0x00003fff, 0x00004000, + 0x08000000, 0x0fffffff] for i in test - q = VLQ(i) - j = uint(q) - print(@sprintf " 0x%x => " i) - print(@sprintf "[%s]" join(["0x"*hex(r, 2) for r in q.q], ", ")) - println(@sprintf " => 0x%x" j) + vlq = VLQ(i) + j = UInt(vlq) + @printf "0x%-8x => [%-25s] => 0x%x\n" i join(("0x" * hex(r, 2) for r in vlq.quant), ", ") j end diff --git a/Task/Variable-size-Set/Scala/variable-size-set.scala b/Task/Variable-size-Set/Scala/variable-size-set.scala new file mode 100644 index 0000000000..e289079ef1 --- /dev/null +++ b/Task/Variable-size-Set/Scala/variable-size-set.scala @@ -0,0 +1,7 @@ +/* Ranges for variables of the primitive numeric types */ +println(s"A Byte variable has a range of : ${Byte.MinValue} to ${Byte.MaxValue}") +println(s"A Short variable has a range of : ${Short.MinValue} to ${Short.MaxValue}") +println(s"An Int variable has a range of : ${Int.MinValue} to ${Int.MaxValue}") +println(s"A Long variable has a range of : ${Long.MinValue} to ${Long.MaxValue}") +println(s"A Float variable has a range of : ${Float.MinValue} to ${Float.MaxValue}") +println(s"A Double variable has a range of : ${Double.MinValue} to ${Double.MaxValue}") diff --git a/Task/Variables/Falcon/variables.falcon b/Task/Variables/Falcon/variables.falcon new file mode 100644 index 0000000000..dac3216a4c --- /dev/null +++ b/Task/Variables/Falcon/variables.falcon @@ -0,0 +1,26 @@ +/* partially created by Aykayayciti Earl Lamont Montgomery +April 9th, 2018 */ + +/* global and local scrope + from the Falcon survival + guide book */ +// global scope +sqr = 1.41 + +function square( x ) + // local scope + sqr = x * x + return sqr +end + + +number = square( 8 ) * sqr + + +a = [1, 2, 3] // array +b = 1 // variable declaration +e = 1.0 // float +f = "string" // string + +/* There are plenty more +data types in Falcon */ diff --git a/Task/Variables/HicEst/variables.hicest b/Task/Variables/HicEst/variables.hicest new file mode 100644 index 0000000000..9fba6b1dab --- /dev/null +++ b/Task/Variables/HicEst/variables.hicest @@ -0,0 +1,33 @@ +! Strings and arrays must be declared. +! Everything else is 8-byte float, READ/WRITE converts + CHARACTER str="abcdef", str2*345, str3*1E6/"xyz"/ + REAL, PARAMETER :: named_constant = 3.1415 + REAL :: n=2, cols=4, vec(cols), mtx(n, cols) + DATA vec/2,3,4,5/, mtx/1,2,3.1415,4, 5,6,7,8/ + + named = ALIAS(alpha, beta, gamma) ! gamma == named(3) + ALIAS(vec,n, subvec,2) ! share subvec and vec(n...n+1) + ALIAS(str,3, substr,n) ! share substr and str(3:3+n-1) + + a = EXP(b + c) ! assign/initialze a=1, b=0, c=0 + str = "blahblah" ! truncate/expand if needed + beta = "blahblah" ! illegal + + CALL noArguments_noUSE ! global scope SUBROUTINE + CALL Arguments_or_USE(a) ! local scope SUBROUTINE + t = func() ! local scope FUNCTION + +SUBROUTINE noArguments_noUSE() ! all global + vec2 = $ ! 1,2,3,... +END + +SUBROUTINE Arguments_or_USE(var) ! all local + USE : vec ! use global object + var = SUM(vec) + t = TIME() ! local, static, USEd by func() +END + +FUNCTION func() ! all local + USE Arguments_or_USE : t ! use local object + func = t +END diff --git a/Task/Variables/HolyC/variables-1.holyc b/Task/Variables/HolyC/variables-1.holyc new file mode 100644 index 0000000000..398ae02b6d --- /dev/null +++ b/Task/Variables/HolyC/variables-1.holyc @@ -0,0 +1 @@ +U8 i; diff --git a/Task/Variables/HolyC/variables-2.holyc b/Task/Variables/HolyC/variables-2.holyc new file mode 100644 index 0000000000..30306a9217 --- /dev/null +++ b/Task/Variables/HolyC/variables-2.holyc @@ -0,0 +1,2 @@ +U8 b1 = 8; +U8 b2 = b1 * 10; diff --git a/Task/Variables/HolyC/variables-3.holyc b/Task/Variables/HolyC/variables-3.holyc new file mode 100644 index 0000000000..222653325d --- /dev/null +++ b/Task/Variables/HolyC/variables-3.holyc @@ -0,0 +1 @@ +U8 uint1, uint2, uint3; diff --git a/Task/Variables/HolyC/variables-4.holyc b/Task/Variables/HolyC/variables-4.holyc new file mode 100644 index 0000000000..8ee92e75dd --- /dev/null +++ b/Task/Variables/HolyC/variables-4.holyc @@ -0,0 +1 @@ +U8 *str = "The HolyC Language"; diff --git a/Task/Variables/HolyC/variables-5.holyc b/Task/Variables/HolyC/variables-5.holyc new file mode 100644 index 0000000000..42df93c8ff --- /dev/null +++ b/Task/Variables/HolyC/variables-5.holyc @@ -0,0 +1,13 @@ +global gvar # a global + +procedure main(arglist) # arglist is a parameter of main +local a,b,i,x # a, b, i, x are locals withing main +static y # a static (silly in main) + +x := arglist[1] +a := 1.0 +i := 10 +b := [x,a,i,b] + +# ... rest of program +end diff --git a/Task/Variables/Perl-6/variables-2.pl6 b/Task/Variables/Perl-6/variables-2.pl6 index de7aae8fd5..2b3b9bf1ec 100644 --- a/Task/Variables/Perl-6/variables-2.pl6 +++ b/Task/Variables/Perl-6/variables-2.pl6 @@ -1,6 +1,6 @@ say ++$; # this is an anonymous state variable say ++$; # this is a different anonymous state variable, prefix:<++> forces it into numerical context and defaults it to 0 -say $+=2 for 1..10 # here we do something useful with another anonymous variable +say $+=2 for 1..10; # here we do something useful with another anonymous variable sub foo { $^a * $^b } # for positional arguments we often can't be bothered to declare them or to give them fancy names say foo 3, 4; diff --git a/Task/Variables/Python/variables.py b/Task/Variables/Python/variables.py new file mode 100644 index 0000000000..c909923e5b --- /dev/null +++ b/Task/Variables/Python/variables.py @@ -0,0 +1,8 @@ +# these examples, respectively, refer to integer, float, boolean, and string objects +example1 = 3 +example2 = 3.0 +example3 = True +example4 = "hello" + +# example1 now refers to a string object. +example1 = "goodbye" diff --git a/Task/Variables/REXX/variables-1.rexx b/Task/Variables/REXX/variables-1.rexx index b307fbdcf2..e7fdc0d685 100644 --- a/Task/Variables/REXX/variables-1.rexx +++ b/Task/Variables/REXX/variables-1.rexx @@ -4,7 +4,7 @@ cc = 2*10 /*assigns chars 20 ───► CC dd = 'Adam' /*assigns chars Adam ───► DD */ ee = "Adam" /*same as above ───► EE */ ff = 10. /*assigns chars 10. ───► FF */ -gg='10.' /*same as above ───► GG */ +gg = '10.' /*same as above ───► GG */ hh = "+10" /*assigns chars +10 ───► hh */ ii = 1e1 /*assigns chars 1e1 ───► ii */ jj = +.1e+2 /*assigns chars .1e+2 ───► jj */ diff --git a/Task/Variables/Visual-Basic-.NET/variables.visual b/Task/Variables/Visual-Basic-.NET/variables.visual new file mode 100644 index 0000000000..121416284e --- /dev/null +++ b/Task/Variables/Visual-Basic-.NET/variables.visual @@ -0,0 +1,4 @@ +Dim wholeNumber as Integer = 3 +Dim realNumber as Double = 3.0 +Dim isRaining as Boolean = False +Dim greeting as String = "Hello, this is World speaking." diff --git a/Task/Variadic-function/Aime/variadic-function-2.aime b/Task/Variadic-function/Aime/variadic-function-2.aime index 4d0b361210..70668a267e 100644 --- a/Task/Variadic-function/Aime/variadic-function-2.aime +++ b/Task/Variadic-function/Aime/variadic-function-2.aime @@ -1,17 +1,7 @@ void output_date(date d) { - o_integer(d_year(d)); - o_byte('/'); - o_finteger(2, d_y_month(d)); - o_byte('/'); - o_finteger(2, d_m_day(d)); -} - -void -output_real(real x) -{ - o_real(8, x); + o_form("~%//f2/%//f2/", d.year, d.y_month, d.m_day); } void @@ -20,33 +10,23 @@ g(...) integer i; record r; - r_put(r, "integer", o_integer); - r_put(r, "real", output_real); - r_put(r, "text", o_text); - r_put(r, "date", output_date); + r["integer"] = o_integer; + r["real"] = o_; + r["text"] = o_text; + r["date"] = output_date; i = 0; while (i < count()) { - call(r_query(r, __type($i)), $i); - o_byte('\n'); - i += 1; + r[__type($i)]($i); + o_byte('\n'); + i += 1; } } -date -now(void) -{ - date d; - - d_now(d); - - return d; -} - integer main(void) { - g("X.1", 707, .5, now()); + g("X.1", 707, .5, date().now); return 0; } diff --git a/Task/Variadic-function/Batch-File/variadic-function.bat b/Task/Variadic-function/Batch-File/variadic-function.bat new file mode 100644 index 0000000000..0e13f2889a --- /dev/null +++ b/Task/Variadic-function/Batch-File/variadic-function.bat @@ -0,0 +1,13 @@ +@echo off + +:_main +call:_variadicfunc arg1 "arg 2" arg-3 +pause>nul + +:_variadicfunc +setlocal +for %%i in (%*) do echo %%~i +exit /b + +:: Note: if _variadicfunc was called from cmd.exe with arguments parsed to it, it would only need to contain: +:: @for %%i in (%*) do echo %%i diff --git a/Task/Variadic-function/Elena/variadic-function.elena b/Task/Variadic-function/Elena/variadic-function.elena index 6d27a5043a..2558500a94 100644 --- a/Task/Variadic-function/Elena/variadic-function.elena +++ b/Task/Variadic-function/Elena/variadic-function.elena @@ -3,7 +3,7 @@ import extensions. extension variadicOp { - generic printAll args:list + generic printAll(object<> list) [ list forEach(:v) [ diff --git a/Task/Variadic-function/Factor/variadic-function-1.factor b/Task/Variadic-function/Factor/variadic-function-1.factor new file mode 100644 index 0000000000..92254cbca9 --- /dev/null +++ b/Task/Variadic-function/Factor/variadic-function-1.factor @@ -0,0 +1 @@ +MACRO: variadic-print ( n -- quot ) [ print ] n*quot ; diff --git a/Task/Variadic-function/Factor/variadic-function-2.factor b/Task/Variadic-function/Factor/variadic-function-2.factor new file mode 100644 index 0000000000..fb9269fd98 --- /dev/null +++ b/Task/Variadic-function/Factor/variadic-function-2.factor @@ -0,0 +1,13 @@ +IN: scratchpad "apple" "banana" "cucumber" + +--- Data stack: +"apple" +"banana" +"cucumber" + +IN: scratchpad 2 variadic-print +cucumber +banana + +--- Data stack: +"apple" diff --git a/Task/Variadic-function/Ring/variadic-function.ring b/Task/Variadic-function/Ring/variadic-function.ring new file mode 100644 index 0000000000..8540044200 --- /dev/null +++ b/Task/Variadic-function/Ring/variadic-function.ring @@ -0,0 +1,26 @@ +# Project : Variadic function +# Date : 2017/11/13 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +sum([1,2]) +sum([1,2,3]) +nums = [1,2,3,4] +sum(nums) + +func sum(nums) + total = 0 + for num = 1 to len(nums) + total = total + num + next + showarray(nums) + see " " + total + nl + +func showarray(vect) + see "[" + svect = "" + for n = 1 to len(vect) + svect = svect + vect[n] + " " + next + svect = left(svect, len(svect) - 1) + see "" + svect + "]" diff --git a/Task/Vector-products/Factor/vector-products.factor b/Task/Vector-products/Factor/vector-products.factor new file mode 100644 index 0000000000..aa5eed493f --- /dev/null +++ b/Task/Vector-products/Factor/vector-products.factor @@ -0,0 +1,31 @@ +USING: arrays io locals math prettyprint sequences ; +IN: rosetta-code.vector-products + +: dot-product ( a b -- dp ) [ * ] 2map sum ; + +:: cross-product ( a b -- cp ) + a first :> a1 a second :> a2 a third :> a3 + b first :> b1 b second :> b2 b third :> b3 + a2 b3 * a3 b2 * - ! X + a3 b1 * a1 b3 * - ! Y + a1 b2 * a2 b1 * - ! Z + 3array ; + +: scalar-triple-product ( a b c -- stp ) + cross-product dot-product ; + +: vector-triple-product ( a b c -- vtp ) + cross-product cross-product ; + +[let + { 3 4 5 } :> a + { 4 3 5 } :> b + { -5 -12 -13 } :> c + "a: " write a . + "b: " write b . + "c: " write c . nl + "a . b: " write a b dot-product . + "a x b: " write a b cross-product . + "a . (b x c): " write a b c scalar-triple-product . + "a x (b x c): " write a b c vector-triple-product . +] diff --git a/Task/Vector-products/Julia/vector-products.julia b/Task/Vector-products/Julia/vector-products.julia index 670b3bdea2..9ef41167ab 100644 --- a/Task/Vector-products/Julia/vector-products.julia +++ b/Task/Vector-products/Julia/vector-products.julia @@ -1,26 +1,20 @@ -function scltrip{T<:Number}(a::AbstractArray{T,1}, - b::AbstractArray{T,1}, - c::AbstractArray{T,1}) - dot(a, cross(b, c)) +function scalarproduct(a::AbstractVector{T}, b::AbstractVector{T}, c::AbstractVector{T}) where {T<:Number} + return dot(a, cross(b, c)) end -function vectrip{T<:Number}(a::AbstractArray{T,1}, - b::AbstractArray{T,1}, - c::AbstractArray{T,1}) - cross(a, cross(b, c)) +function vectorproduct(a::AbstractVector{T}, b::AbstractVector{T}, c::AbstractVector{T}) where {T<:Number} + return cross(a, cross(b, c)) end -a = [3, 4, 5] -b = [4, 3, 5] -c = [-5, -12, -13] +const a = [3, 4, 5] +const b = [4, 3, 5] +const c = [-5, -12, -13] println("Test Vectors:") -println(" a = ", a) -println(" b = ", a) -println(" c = ", a) +@show a b c println("\nVector Products:") -println(" a dot b = ", dot(a, b)) -println(" a cross b = ", cross(a, b)) -println(" a dot b cross c = ", scltrip(a, b, c)) -println(" a cross b cross c = ", vectrip(a, b, c)) +@show dot(a, b) +@show cross(a, b) +@show scalarproduct(a, b, c) +@show vectorproduct(a, b, c) diff --git a/Task/Vector-products/Modula-2/vector-products.mod2 b/Task/Vector-products/Modula-2/vector-products.mod2 new file mode 100644 index 0000000000..b7d4864ae1 --- /dev/null +++ b/Task/Vector-products/Modula-2/vector-products.mod2 @@ -0,0 +1,83 @@ +MODULE VectorProducts; +FROM RealStr IMPORT RealToStr; +FROM Terminal IMPORT WriteString,WriteLn,ReadChar; + +PROCEDURE WriteReal(r : REAL); +VAR buf : ARRAY[0..31] OF CHAR; +BEGIN + RealToStr(r, buf); + WriteString(buf) +END WriteReal; + +TYPE Vector = RECORD + a,b,c : REAL; +END; + +PROCEDURE Dot(u,v : Vector) : REAL; +BEGIN + RETURN u.a * v.a + + u.b * v.b + + u.c * v.c +END Dot; + +PROCEDURE Cross(u,v : Vector) : Vector; +BEGIN + RETURN Vector{ + u.b*v.c - u.c*v.b, + u.c*v.a - u.a*v.c, + u.a*v.b - u.b*v.a + } +END Cross; + +PROCEDURE ScalarTriple(u,v,w : Vector) : REAL; +BEGIN + RETURN Dot(u, Cross(v, w)) +END ScalarTriple; + +PROCEDURE VectorTriple(u,v,w : Vector) : Vector; +BEGIN + RETURN Cross(u, Cross(v, w)) +END VectorTriple; + +PROCEDURE WriteVector(v : Vector); +BEGIN + WriteString("<"); + WriteReal(v.a); + WriteString(", "); + WriteReal(v.b); + WriteString(", "); + WriteReal(v.c); + WriteString(">") +END WriteVector; + +VAR a,b,c : Vector; +BEGIN + a := Vector{3.0, 4.0, 5.0}; + b := Vector{4.0, 3.0, 5.0}; + c := Vector{-5.0, -12.0, -13.0}; + + WriteVector(a); + WriteString(" dot "); + WriteVector(b); + WriteString(" = "); + WriteReal(Dot(a,b)); + WriteLn; + + WriteVector(a); + WriteString(" cross "); + WriteVector(b); + WriteString(" = "); + WriteVector(Cross(a,b)); + WriteLn; + + WriteVector(a); + WriteString(" cross ("); + WriteVector(b); + WriteString(" cross "); + WriteVector(c); + WriteString(") = "); + WriteVector(VectorTriple(a,b,c)); + WriteLn; + + ReadChar +END VectorProducts. diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/Kotlin/verify-distribution-uniformity-chi-squared-test.kotlin b/Task/Verify-distribution-uniformity-Chi-squared-test/Kotlin/verify-distribution-uniformity-chi-squared-test.kotlin new file mode 100644 index 0000000000..17defb0b9b --- /dev/null +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/Kotlin/verify-distribution-uniformity-chi-squared-test.kotlin @@ -0,0 +1,77 @@ +// version 1.1.51 + +typealias Func = (Double) -> Double + +fun gammaLanczos(x: Double): Double { + var xx = x + val p = doubleArrayOf( + 0.99999999999980993, + 676.5203681218851, + -1259.1392167224028, + 771.32342877765313, + -176.61502916214059, + 12.507343278686905, + -0.13857109526572012, + 9.9843695780195716e-6, + 1.5056327351493116e-7 + ) + val g = 7 + if (xx < 0.5) return Math.PI / (Math.sin(Math.PI * xx) * gammaLanczos(1.0 - xx)) + xx-- + var a = p[0] + val t = xx + g + 0.5 + for (i in 1 until p.size) a += p[i] / (xx + i) + return Math.sqrt(2.0 * Math.PI) * Math.pow(t, xx + 0.5) * Math.exp(-t) * a +} + +fun integrate(a: Double, b: Double, n: Int, f: Func): Double { + val h = (b - a) / n + var sum = 0.0 + for (i in 0 until n) { + val x = a + i * h + sum += (f(x) + 4.0 * f(x + h / 2.0) + f(x + h)) / 6.0 + } + return sum * h +} + +fun gammaIncompleteQ(a: Double, x: Double): Double { + val aa1 = a - 1.0 + fun f0(t: Double) = Math.pow(t, aa1) * Math.exp(-t) + val h = 1.5e-2 + var y = aa1 + while ((f0(y) * (x - y) > 2.0e-8) && y < x) y += 0.4 + if (y > x) y = x + return 1.0 - integrate(0.0, y, (y / h).toInt(), ::f0) / gammaLanczos(a) +} + +fun chi2UniformDistance(ds: DoubleArray): Double { + val expected = ds.average() + val sum = ds.map { val x = it - expected; x * x }.sum() + return sum / expected +} + +fun chi2Probability(dof: Int, distance: Double) = + gammaIncompleteQ(0.5 * dof, 0.5 * distance) + +fun chiIsUniform(ds: DoubleArray, significance: Double):Boolean { + val dof = ds.size - 1 + val dist = chi2UniformDistance(ds) + return chi2Probability(dof, dist) > significance +} + +fun main(args: Array) { + val dsets = listOf( + doubleArrayOf(199809.0, 200665.0, 199607.0, 200270.0, 199649.0), + doubleArrayOf(522573.0, 244456.0, 139979.0, 71531.0, 21461.0) + ) + for (ds in dsets) { + println("Dataset: ${ds.asList()}") + val dist = chi2UniformDistance(ds) + val dof = ds.size - 1 + print("DOF: $dof Distance: ${"%.4f".format(dist)}") + val prob = chi2Probability(dof, dist) + print(" Probability: ${"%.6f".format(prob)}") + val uniform = if (chiIsUniform(ds, 0.05)) "Yes" else "No" + println(" Uniform? $uniform\n") + } +} diff --git a/Task/Verify-distribution-uniformity-Naive/Julia/verify-distribution-uniformity-naive.julia b/Task/Verify-distribution-uniformity-Naive/Julia/verify-distribution-uniformity-naive.julia new file mode 100644 index 0000000000..b0648e2e34 --- /dev/null +++ b/Task/Verify-distribution-uniformity-Naive/Julia/verify-distribution-uniformity-naive.julia @@ -0,0 +1,15 @@ +function distcheck(f::Function, rep::Int=10000, Δ::Int=3) + smpl = f(rep) + counts = Dict(k => count(smpl .== k) for k in unique(smpl)) + expected = rep / length(counts) + lbound = expected * (1 - 0.01Δ) + ubound = expected * (1 + 0.01Δ) + noobs = count(x -> !(lbound ≤ x ≤ ubound), values(counts)) + if noobs > 0 warn(@sprintf "%2.4f%% values out of bounds" noobs / rep) end + return counts +end + +# Dice5 check +distcheck(x -> rand(1:5, x)) +# Dice7 check +distcheck(dice7) diff --git a/Task/Video-display-modes/Kotlin/video-display-modes.kotlin b/Task/Video-display-modes/Kotlin/video-display-modes.kotlin new file mode 100644 index 0000000000..c59b97b267 --- /dev/null +++ b/Task/Video-display-modes/Kotlin/video-display-modes.kotlin @@ -0,0 +1,25 @@ +// version 1.1.51 + +import java.util.Scanner + +fun runSystemCommand(command: String) { + val proc = Runtime.getRuntime().exec(command) + Scanner(proc.inputStream).use { + while (it.hasNextLine()) println(it.nextLine()) + } + proc.waitFor() + println() +} + +fun main(args: Array) { + // query supported display modes + runSystemCommand("xrandr -q") + Thread.sleep(3000) + + // change display mode to 1024x768 say (no text output) + runSystemCommand("xrandr -s 1024x768") + Thread.sleep(3000) + + // change it back again to 1366x768 (or whatever is optimal for your system) + runSystemCommand("xrandr -s 1366x768") +} diff --git a/Task/Video-display-modes/Perl-6/video-display-modes.pl6 b/Task/Video-display-modes/Perl-6/video-display-modes.pl6 new file mode 100644 index 0000000000..4028338559 --- /dev/null +++ b/Task/Video-display-modes/Perl-6/video-display-modes.pl6 @@ -0,0 +1,16 @@ +my @info = QX('xrandr -q').lines; + +@info[0] ~~ /(\d+) ' x ' (\d+)/; +my $current = "$0x$1"; + +my @resolutions; +@resolutions.push: $0 if $_ ~~ /^\s+(\d+'x'\d+)/ for @info; + +QX("xrandr -s @resolutions[*-1]"); +say "Current resolution {@resolutions[*-1]}."; +for 9 ... 1 { + print "\rChanging back in $_ seconds..."; + sleep 1; +} +QX("xrandr -s $current"); +say "\rResolution returned to {$current}. "; diff --git a/Task/Video-display-modes/Scala/video-display-modes.scala b/Task/Video-display-modes/Scala/video-display-modes.scala new file mode 100644 index 0000000000..22a624e766 --- /dev/null +++ b/Task/Video-display-modes/Scala/video-display-modes.scala @@ -0,0 +1,27 @@ +object VideoDisplayModes extends App { + + import java.util.Scanner + + def runSystemCommand(command: String) { + val proc = Runtime.getRuntime.exec(command) + + val a: Unit = { + val a = new Scanner(proc.getInputStream) + while (a.hasNextLine) println(a.nextLine()) + } + proc.waitFor() + println() + } + + // query supported display modes + runSystemCommand("xrandr -q") + Thread.sleep(3000) + + // change display mode to 1024x768 say (no text output) + runSystemCommand("xrandr -s 1024x768") + Thread.sleep(3000) + + // change it back again to 1366x768 (or whatever is optimal for your system) + runSystemCommand("xrandr -s 1366x768") + +} diff --git a/Task/Vigen-re-cipher-Cryptanalysis/Go/vigen-re-cipher-cryptanalysis.go b/Task/Vigen-re-cipher-Cryptanalysis/Go/vigen-re-cipher-cryptanalysis.go new file mode 100644 index 0000000000..eeda4498ab --- /dev/null +++ b/Task/Vigen-re-cipher-Cryptanalysis/Go/vigen-re-cipher-cryptanalysis.go @@ -0,0 +1,119 @@ +package main + +import ( + "fmt" + "strings" +) + +var encoded = + "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" + + "VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD" + + "ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS" + + "FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG" + + "ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ" + + "ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS" + + "JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT" + + "LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST" + + "MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH" + + "QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV" + + "RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW" + + "TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO" + + "SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR" + + "ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX" + + "BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB" + + "BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA" + + "FWAML ZZRXJ EKAHV FASMU LVVUT TGK" + +var freq = [26]float64{ + 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, + 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, + 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, + 0.00978, 0.02360, 0.00150, 0.01974, 0.00074, +} + +func sum(a []float64) (sum float64) { + for _, f := range a { + sum += f + } + return +} + +func bestMatch(a []float64) int { + sum := sum(a) + bestFit, bestRotate := 1e100, 0 + for rotate := 0; rotate < 26; rotate++ { + fit := 0.0 + for i := 0; i < 26; i++ { + d := a[(i+rotate)%26]/sum - freq[i] + fit += d * d / freq[i] + } + if fit < bestFit { + bestFit, bestRotate = fit, rotate + } + } + return bestRotate +} + +func freqEveryNth(msg []int, key []byte) float64 { + l := len(msg) + interval := len(key) + out := make([]float64, 26) + accu := make([]float64, 26) + for j := 0; j < interval; j++ { + for k := 0; k < 26; k++ { + out[k] = 0.0 + } + for i := j; i < l; i += interval { + out[msg[i]]++ + } + rot := bestMatch(out) + key[j] = byte(rot + 65) + for i := 0; i < 26; i++ { + accu[i] += out[(i+rot)%26] + } + } + sum := sum(accu) + ret := 0.0 + for i := 0; i < 26; i++ { + d := accu[i]/sum - freq[i] + ret += d * d / freq[i] + } + return ret +} + +func decrypt(text, key string) string { + var sb strings.Builder + ki := 0 + for _, c := range text { + if c < 'A' || c > 'Z' { + continue + } + ci := (c - rune(key[ki]) + 26) % 26 + sb.WriteRune(ci + 65) + ki = (ki + 1) % len(key) + } + return sb.String() +} + +func main() { + enc := strings.Replace(encoded, " ", "", -1) + txt := make([]int, len(enc)) + for i := 0; i < len(txt); i++ { + txt[i] = int(enc[i] - 'A') + } + bestFit, bestKey := 1e100, "" + fmt.Println(" Fit Length Key") + for j := 1; j <= 26; j++ { + key := make([]byte, j) + fit := freqEveryNth(txt, key) + sKey := string(key) + fmt.Printf("%f %2d %s", fit, j, sKey) + if fit < bestFit { + bestFit, bestKey = fit, sKey + fmt.Print(" <--- best so far") + } + fmt.Println() + } + fmt.Println("\nBest key :", bestKey) + fmt.Printf("\nDecrypted text:\n%s\n", decrypt(enc, bestKey)) +} diff --git a/Task/Vigen-re-cipher-Cryptanalysis/Haskell/vigen-re-cipher-cryptanalysis.hs b/Task/Vigen-re-cipher-Cryptanalysis/Haskell/vigen-re-cipher-cryptanalysis.hs new file mode 100644 index 0000000000..686cfc80ce --- /dev/null +++ b/Task/Vigen-re-cipher-Cryptanalysis/Haskell/vigen-re-cipher-cryptanalysis.hs @@ -0,0 +1,98 @@ +{-# LANGUAGE TupleSections #-} +import Data.List(transpose, nub, sort, maximumBy) +import Data.Ord (comparing) +import Data.Char (ord) +import Data.Map (Map, fromListWith, toList, findWithDefault) + +average :: Fractional a => [a] -> a +average as = sum as / fromIntegral (length as) + +-- Create a map from each entry in list to the number of occurrences of +-- that entry in the list. +countEntries :: Ord a => [a] -> Map a Int +countEntries = fromListWith (+) . fmap (,1) + +-- Break a string up into substrings of n chars. +breakup :: Int -> [a] -> [[a]] +breakup _ [] = [] +breakup n as = + let (h, r) = splitAt n as + in h:breakup n r + +-- Dole out elements of a string over a n element distribution. +distribute :: [a] -> Int -> [[a]] +distribute as n = transpose $ breakup n as + +-- The probability that members of a pair of characters taken randomly +-- from a given string are equal. +coincidence :: (Ord a, Fractional b) => [a] -> b +coincidence str = + let charCounts = snd <$> toList (countEntries str) + strln = length str + d = fromIntegral $ strln * (strln - 1) + n = fromIntegral $ sum $ fmap (\cc -> cc * (cc-1)) charCounts + in n / d + +-- Use the average probablity of coincidence for all the members of +-- a distribution to rate the distribution - the higher the better. +-- The correlation increases artificially for smaller +-- pieces/longer keys, so weigh against them a little +rate :: (Ord a, Fractional b) => [[a]] -> b +rate d = average (fmap coincidence d) - fromIntegral (length d) / 3000.0 + +-- Multiply elements of lists together and add up the results. +dot :: Num a => [a] -> [a] -> a +dot v0 v1 = sum $ zipWith (*) v0 v1 + +-- Given two lists of floats, rotate one of them by the number of +-- characters indicated by letter and then 'dot' them together. +rotateAndDot :: Num a => [a] -> [a] -> Char -> a +rotateAndDot v0 v1 letter = dot v0 (drop (ord letter - ord 'A') (cycle v1)) + +-- Find decoding offset that results in best match +-- between actual char frequencies and expected frequencies. +getKeyChar :: RealFrac a => [a] -> String -> Char +getKeyChar expected sample = + let charCounts = countEntries sample + countInSample c = findWithDefault 0 c charCounts + actual = fmap (fromIntegral . countInSample) ['A'..'Z'] + in maximumBy (comparing $ rotateAndDot expected actual) ['A'..'Z'] + +main = do + let cr = filter (/=' ') crypt + -- Assume that if there are less than 20 characters + -- per column, the key's too long to guess + distributions = fmap (distribute cr) [1..length cr `div` 20] + bestDistribution = maximumBy (comparing rate) distributions + key = fmap (getKeyChar englishFrequencies) bestDistribution + alphaSum a b = ['A'..'Z'] !! ((ord b - ord a) `mod` 26) + mapM_ putStrLn ["Key: " ++ key, "Decrypted Text: " ++ zipWith alphaSum (cycle key) cr] + +englishFrequencies = + [ 0.08167, 0.01492, 0.02782, 0.04253, + 0.12702, 0.02228, 0.02015, 0.06094, + 0.06966, 0.00153, 0.00772, 0.04025, + 0.02406, 0.06749, 0.07507, 0.01929, + 0.00095, 0.05987, 0.06327, 0.09056, + 0.02758, 0.00978, 0.02360, 0.00150, + 0.01974, 0.00074 ] + +crypt = "\ + \MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH\ + \VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD\ + \ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS\ + \FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG\ + \ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ\ + \ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS\ + \JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT\ + \LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST\ + \MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH\ + \QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV\ + \RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW\ + \TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO\ + \SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR\ + \ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX\ + \BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB\ + \BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA\ + \FWAML ZZRXJ EKAHV FASMU LVVUT TGK\ + \" diff --git a/Task/Vigen-re-cipher-Cryptanalysis/Java/vigen-re-cipher-cryptanalysis.java b/Task/Vigen-re-cipher-Cryptanalysis/Java/vigen-re-cipher-cryptanalysis.java new file mode 100644 index 0000000000..990fee4f98 --- /dev/null +++ b/Task/Vigen-re-cipher-Cryptanalysis/Java/vigen-re-cipher-cryptanalysis.java @@ -0,0 +1,108 @@ +public class Vig{ +static String encodedMessage = + "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML ZZRXJ EKAHV FASMU LVVUT TGK"; + +final static double freq[] = { + 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015, + 0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749, + 0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758, + 0.00978, 0.02360, 0.00150, 0.01974, 0.00074 +}; + + +public static void main(String[] args) { + int lenghtOfEncodedMessage = encodedMessage.length(); + char[] encoded = new char [lenghtOfEncodedMessage] ; + char[] key = new char [lenghtOfEncodedMessage] ; + + encodedMessage.getChars(0, lenghtOfEncodedMessage, encoded, 0); + int txt[] = new int[lenghtOfEncodedMessage]; + int len = 0, j; + + double fit, best_fit = 1e100; + + for (j = 0; j < lenghtOfEncodedMessage; j++) + if (Character.isUpperCase(encoded[j])) + txt[len++] = encoded[j] - 'A'; + + for (j = 1; j < 30; j++) { + fit = freq_every_nth(txt, len, j, key); + System.out.printf("%f, key length: %2d ", fit, j); + System.out.print(key); + if (fit < best_fit) { + best_fit = fit; + System.out.print(" <--- best so far"); + } + System.out.print("\n"); + + } +} + + + static String decrypt(String text, final String key) { + String res = ""; + text = text.toUpperCase(); + for (int i = 0, j = 0; i < text.length(); i++) { + char c = text.charAt(i); + if (c < 'A' || c > 'Z') continue; + res += (char)((c - key.charAt(j) + 26) % 26 + 'A'); + j = ++j % key.length(); + } + return res; + } + +static int best_match(final double []a, final double []b) { + double sum = 0, fit, d, best_fit = 1e100; + int i, rotate, best_rotate = 0; + for (i = 0; i < 26; i++) + sum += a[i]; + for (rotate = 0; rotate < 26; rotate++) { + fit = 0; + for (i = 0; i < 26; i++) { + d = a[(i + rotate) % 26] / sum - b[i]; + fit += d * d / b[i]; + } + + if (fit < best_fit) { + best_fit = fit; + best_rotate = rotate; + } + } + + return best_rotate; +} + +static double freq_every_nth(final int []msg, int len, int interval, char[] key) { + double sum, d, ret; + double [] accu = new double [26]; + double [] out = new double [26]; + int i, j, rot; + + for (j = 0; j < interval; j++) { + for (i = 0; i < 26; i++) + out[i] = 0; + for (i = j; i < len; i += interval) + out[msg[i]]++; + rot = best_match(out, freq); + try{ + key[j] = (char)(rot + 'A'); + } catch (Exception e) { + System.out.print(e.getMessage()); + } + for (i = 0; i < 26; i++) + accu[i] += out[(i + rot) % 26]; + } + + for (i = 0, sum = 0; i < 26; i++) + sum += accu[i]; + + for (i = 0, ret = 0; i < 26; i++) { + d = accu[i] / sum - freq[i]; + ret += d * d / freq[i]; + } + + key[interval] = '\0'; + return ret; +} + +} diff --git a/Task/Vigen-re-cipher/Applesoft-BASIC/vigen-re-cipher.applesoft b/Task/Vigen-re-cipher/Applesoft-BASIC/vigen-re-cipher.applesoft new file mode 100644 index 0000000000..9b4f9a3e28 --- /dev/null +++ b/Task/Vigen-re-cipher/Applesoft-BASIC/vigen-re-cipher.applesoft @@ -0,0 +1,28 @@ + 100 : + 110 REM VIGENERE CIPHER + 120 : + 200 REM SET-UP + 210 K$ = "LEMON": PRINT "KEY: "; K$ + 220 PT$ = "ATTACK AT DAWN": PRINT "PLAIN TEXT: ";PT$ + 230 DEF FN MOD(A) = A - INT (A / 26) * 26 + 300 REM ENCODING + 310 K = 1 + 320 FOR I = 1 TO LEN (PT$) + 330 IF ASC ( MID$ (PT$,I,1)) < 65 + OR ASC ( MID$ (PT$,I,1)) > 90 THEN NEXT I + 340 TV = ASC ( MID$ (PT$,I,1)) - 65 + 350 KV = ASC ( MID$ (K$,K,1)) - 65 + 360 CT$ = CT$ + CHR$ ( FN MOD(TV + KV) + 65) + 370 K = K + 1: IF K > LEN (K$) THEN K = 1 + 380 NEXT I + 390 PRINT "CIPHER TEXT: ";CT$ + 400 REM DECODING + 410 K = 1 + 420 FOR I = 1 TO LEN (CT$) + 430 TV = ASC ( MID$ (CT$,I,1)) - 65 + 440 KV = ASC ( MID$ (K$,K,1)) - 65 + 450 T = TV - KV: IF T < 0 THEN T = T + 26 + 460 DT$ = DT$ + CHR$ (T + 65) + 470 K = K + 1: IF K > LEN (K$) THEN K = 1 + 480 NEXT I + 490 PRINT "DECRYPTED TEXT: ";DT$ diff --git a/Task/Vigen-re-cipher/Elena/vigen-re-cipher.elena b/Task/Vigen-re-cipher/Elena/vigen-re-cipher.elena new file mode 100644 index 0000000000..c7dd7be4da --- /dev/null +++ b/Task/Vigen-re-cipher/Elena/vigen-re-cipher.elena @@ -0,0 +1,48 @@ +import system'text. +import system'math. +import system'routines. +import extensions. + +class VCipher +{ + literal encrypt(LiteralValue txt, LiteralValue pw, IntNumber d) + [ + var output := TextBuilder new. + int pwi := 0. + + literal $pw := pw upperCase. + + txt upperCase; forEach(:t) + [ + if(t >= $65) + [ + int tmp := t toInt - 65 + d * ($pw[pwi] toInt - 65). + if (tmp < 0) + [ + tmp += 26 + ]. + output write((65 + tmp mod:26) toChar). + pwi += 1. + if (pwi == $pw length) [ pwi := 0 ] + ] + ]. + + ^ output literal + ] +} + +program = +[ + var v := VCipher new. + + var s0 := "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!". + var pw := "VIGENERECIPHER". + + console printLine(s0,'newLine,pw,'newLine). + var s1 := v encrypt(s0, pw, 1). + console printLine("Encrypted:",s1). + s1 := v encrypt(s1, "VIGENERECIPHER", -1). + console printLine("Decrypted:",s1). + console printLine("Press any key to continue.."). + console readKey. +]. diff --git a/Task/Vigen-re-cipher/Factor/vigen-re-cipher.factor b/Task/Vigen-re-cipher/Factor/vigen-re-cipher.factor new file mode 100644 index 0000000000..c11f85487d --- /dev/null +++ b/Task/Vigen-re-cipher/Factor/vigen-re-cipher.factor @@ -0,0 +1,30 @@ +USING: arrays ascii formatting kernel math math.functions +math.order sequences ; +IN: rosetta-code.vigenere-cipher + +: mult-pad ( key input -- x ) + [ length ] bi@ 2dup < [ swap ] when / ceiling ; + +: lengthen-pad ( key input -- rep-key input ) + [ mult-pad ] 2keep [ concat ] dip + [ length ] keep [ head ] dip ; + +: normalize ( str -- only-upper-letters ) + >upper [ LETTER? ] filter ; + +: vigenere-encrypt ( key input -- ecrypted ) + [ normalize ] bi@ lengthen-pad + [ [ CHAR: A - ] map ] bi@ [ + 26 mod CHAR: A + ] 2map ; + +: vigenere-decrypt ( key input -- decrypted ) + [ normalize ] bi@ lengthen-pad [ [ CHAR: A - ] map ] bi@ + [ - 26 - abs 26 mod CHAR: A + ] 2map ; + +: main ( -- ) + "Vigenere cipher" dup + "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!" + 2dup "Key: %s\nInput: %s\n" printf + vigenere-encrypt dup "Encrypted: %s\n" printf + vigenere-decrypt "Decrypted: %s\n" printf ; + +MAIN: main diff --git a/Task/Vigen-re-cipher/Julia/vigen-re-cipher.julia b/Task/Vigen-re-cipher/Julia/vigen-re-cipher.julia index 304fb28082..60d0b47970 100644 --- a/Task/Vigen-re-cipher/Julia/vigen-re-cipher.julia +++ b/Task/Vigen-re-cipher/Julia/vigen-re-cipher.julia @@ -1,41 +1,46 @@ -function encrypt(msg::ASCIIString, key::ASCIIString) - msg = uppercase(join(filter(isalpha, collect(msg)))) - len = length(msg) - key = uppercase(join(filter(isalpha, collect(key)))) +function encrypt(msg::AbstractString, key::AbstractString) + msg = uppercase(join(filter(isalpha, collect(msg)))) + key = uppercase(join(filter(isalpha, collect(key)))) + msglen = length(msg) + keylen = length(key) - if length(key) < len - key = (key^(div(len - length(key), length(key)) + 2))[1:len] + if keylen < msglen + key = repeat(key, div(msglen - keylen, keylen) + 2)[1:msglen] end - enc = Array(Char, len) + enc = Vector{Char}(msglen) - for i=1:length(msg) + @inbounds for i in 1:length(msg) enc[i] = Char((Int(msg[i]) + Int(key[i]) - 130) % 26 + 65) end - join(enc) + return join(enc) end -function decrypt(enc::ASCIIString, key::ASCIIString) - enc = uppercase(join(filter(isalpha, collect(enc)))) - len = length(enc) - key = uppercase(join(filter(isalpha, collect(key)))) +function decrypt(enc::AbstractString, key::AbstractString) + enc = uppercase(join(filter(isalpha, collect(enc)))) + key = uppercase(join(filter(isalpha, collect(key)))) + msglen = length(enc) + keylen = length(key) - if length(key) < len - key = (key^(div(len - length(key), length(key)) + 2))[1:len] + if keylen < msglen + key = repeat(key, div(msglen - keylen, keylen) + 2)[1:msglen] end - msg = Array(Char, len) + msg = Vector{Char}(msglen) - for i=1:length(enc) + @inbounds for i in 1:length(enc) msg[i] = Char((Int(enc[i]) - Int(key[i]) + 26) % 26 + 65) end - join(msg) + return join(msg) end -const msg = "Attack at dawn." +const messages = ("Attack at dawn.", "Don't attack.", "The war is over.") const key = "LEMON" -println(encrypt(msg, key)) -println(decrypt(encrypt(msg, key), key)) +for msg in messages + enc = encrypt(msg, key) + dec = decrypt(enc, key) + println("Original: $msg\n -> encrypted: $enc\n -> decrypted: $dec") +end diff --git a/Task/Vigen-re-cipher/REXX/vigen-re-cipher-1.rexx b/Task/Vigen-re-cipher/REXX/vigen-re-cipher-1.rexx index 05d254fe6d..9d4b8e0d81 100644 --- a/Task/Vigen-re-cipher/REXX/vigen-re-cipher-1.rexx +++ b/Task/Vigen-re-cipher/REXX/vigen-re-cipher-1.rexx @@ -2,18 +2,16 @@ @.1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' L=length(@.1) do j=2 to L; jm=j-1; q=@.jm - @.j=substr(q, 2, L-1)left(q, 1) + @.j=substr(q, 2, L - 1)left(q, 1) end /*j*/ cypher = space('WHOOP DE DOO NO BIG DEAL HERE OR THERE', 0) oMsg = 'People solve problems by trial and error; judgement helps pick the trial.' oMsgU = oMsg; upper oMsgU cypher_= copies(cypher, length(oMsg) % length(cypher) ) -say ' original text =' oMsg - xMsg=Ncypher(oMsgU) -say ' cyphered text =' xMsg - bMsg=Dcypher(xMsg) -say 're-cyphered text =' bMsg + say ' original text =' oMsg + xMsg= Ncypher(oMsgU); say ' cyphered text =' xMsg + bMsg= Dcypher(xMsg) ; say 're-cyphered text =' bMsg exit /*──────────────────────────────────────────────────────────────────────────────────────*/ Ncypher: parse arg x; nMsg=; #=1 /*unsupported char? ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/ @@ -23,7 +21,7 @@ Ncypher: parse arg x; nMsg=; #=1 /*unsupported char? ↓↓↓↓ return nMsg /*──────────────────────────────────────────────────────────────────────────────────────*/ Dcypher: parse arg x; dMsg= - do i=1 for length(x); j=pos(substr(cypher_, i, 1), @.1) - dMsg=dMsg || substr(@.1, pos( substr(x, i, 1), @.j), 1) + do i=1 for length(x); j=pos(substr(cypher_, i, 1), @.1) + dMsg=dMsg || substr(@.1, pos( substr(x, i, 1), @.j), 1 ) end /*j*/ return dMsg diff --git a/Task/Vigen-re-cipher/REXX/vigen-re-cipher-2.rexx b/Task/Vigen-re-cipher/REXX/vigen-re-cipher-2.rexx index 67d65f04b2..19a37acf19 100644 --- a/Task/Vigen-re-cipher/REXX/vigen-re-cipher-2.rexx +++ b/Task/Vigen-re-cipher/REXX/vigen-re-cipher-2.rexx @@ -2,28 +2,26 @@ @abc= 'abcdefghijklmnopqrstuvwxyz'; @abcU=@abc; upper @abcU @.1 = @abcU || @abc'0123456789~`!@#$%^&*()_-+={}|[]\:;<>?,./" ''' L=length(@.1) - do j=2 to length(@.1); jm=j-1; q=@.jm - @.j=substr(q, 2, L-1)left(q, 1) + do j=2 to length(@.1); jm=j - 1; q=@.jm + @.j=substr(q, 2, L - 1)left(q, 1) end /*j*/ cypher = space('WHOOP DE DOO NO BIG DEAL HERE OR THERE', 0) oMsg = 'Making things easy is just knowing the shortcuts. --- Gerard J. Schildberger' cypher_= copies(cypher, length(oMsg) % length(cypher) ) -say ' original text =' oMsg - xMsg=Ncypher(oMsg) -say ' cyphered text =' xMsg - bMsg=Dcypher(xMsg) -say 're-cyphered text =' bMsg + say ' original text =' oMsg + xMsg= Ncypher(oMsg); say ' cyphered text =' xMsg + bMsg= Dcypher(xMsg); say 're-cyphered text =' bMsg exit /*──────────────────────────────────────────────────────────────────────────────────────*/ Ncypher: parse arg x; nMsg=; #=1 /*unsupported char? ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/ do i=1 for length(x); j=pos(substr(x,i,1), @.1); if j==0 then iterate - nMsg=nMsg || substr(@.j, pos( substr( cypher_, #, 1), @.1), 1); #=#+1 + nMsg=nMsg || substr(@.j, pos( substr( cypher_, #, 1), @.1), 1); #=# + 1 end /*j*/ return nMsg /*──────────────────────────────────────────────────────────────────────────────────────*/ Dcypher: parse arg x; dMsg= - do i=1 for length(x); j=pos(substr(cypher_, i, 1), @.1) - dMsg=dMsg || substr(@.1, pos( substr(x, i, 1), @.j), 1) + do i=1 for length(x); j=pos(substr(cypher_, i, 1), @.1) + dMsg=dMsg || substr(@.1, pos( substr(x, i, 1), @.j), 1 ) end /*j*/ return dMsg diff --git a/Task/Vigen-re-cipher/Red/vigen-re-cipher.red b/Task/Vigen-re-cipher/Red/vigen-re-cipher.red new file mode 100644 index 0000000000..37811b41cb --- /dev/null +++ b/Task/Vigen-re-cipher/Red/vigen-re-cipher.red @@ -0,0 +1,77 @@ +Red [needs: 'view] + +CRLF: copy "^M^/" ;; constant for 0D 0A line feed +;;------------------------------------ +crypt: func ["function to en- or decrypt message from textarea tx1" + /decrypt "decrypting switch/refinement" ][ +;;------------------------------------ + +;; when decrypting we have to remove the superflous newlines +;; and undo the base64 encoding first ... +txt: either decrypt [ ;; message to en- or decrypt + s: copy tx1/text + ;; newline could be single 0a byte or crlf sequence when copied from clipboard... + debase replace/all s either find s CRLF [CRLF ] [ newline ] "" +] [ + tx1/text ;; plaintext message +] + +txt: to-binary txt ;; handle message as binary +key: to-binary key1/text ;; handle key also as binary + +bin: copy either decrypt [ "" ][ #{} ] ;; buffer for output + +code: copy #{} ;; temp field to collect utf8 bytes when decrypting + +;; loop over length of binary! message ... +repeat pos length? txt [ + k: to-integer key/(1 + modulo pos length? key) ;; get corresponding key byte + c: to-integer txt/:pos ;; get integer value from message byte at position pos + + either decrypt [ ;; decrypting ? + c: modulo ( 256 + c - k ) 256 ;; compute original byte value + case [ + ;; byte starting with 11.... ( >= 192 dec ) is utf8 startbyte + ;; byte starting with 10... ( >= 128 dec) is utf8 follow up byte , below is single ascii byte + ( c >= 192 ) or ( c < 128 ) [ ;; starting utf8 sequence byte or below 128 normal ascii ? + ;; append last code to buffer, maybe normal ascii or utf8 sequence... + if not empty? code [ append bin to-char code ] ;; save previous code first + code: append copy #{} c ;; start new code + ] + true [ append code c ] ;; otherwise utf8 follow up byte, append to startbyte + ] + ][ + append bin modulo ( c + k ) 256 ;; encrypting , simply collect binary bytes + ] +] ;; close repeat loop + +either decrypt [ ;; collect utf-8 characters + append bin to-char code ;; append last code + tx2/text: to-string bin ;; create valid utf8 string when decrypting +][ ;; base64 encoding of crypted binary to get readable text string... + s: enbase copy bin ;; base 64 is default + while [40 < length? s ] [ ;; insert newlines for better "readability" + s: skip s either head? s [40][41] ;; ... every 40 characters + insert s newline + ] + tx2/text: head s ;; reset s pointing to head again + ] +] +;---------------------------------------------------------- +; start of program +;---------------------------------------------------------- +view layout [title "vigenere cyphre" ;Define nice GUI :- ) +;---------------------------------------------------------- + backdrop silver ;; define window background colour + text "message:" pad 99x1 button "get-clip" [tx1/text: read-clipboard] + ;; code in brackets will be executed, when button is clicked: + button "clear" [tx1/text: copy "" ] return + tx1: area 330x80 "" return + text 25x20 "Key:" key1: field 290x20 "secretkey" return + button "crypt" [crypt ] button "decrypt" [crypt/decrypt ] + button "swap" [tx1/text: copy tx2/text tx2/text: copy "" ] return + text "de-/encrypted message:" pad 50x1 button "copy clip" [ write-clipboard tx2/text] + button "clear" [tx2/text: copy "" ] return + tx2: area 330x100 return + pad 270x1 button "Quit " [quit] +] diff --git a/Task/Vigen-re-cipher/Ring/vigen-re-cipher.ring b/Task/Vigen-re-cipher/Ring/vigen-re-cipher.ring new file mode 100644 index 0000000000..89ddcdc5e7 --- /dev/null +++ b/Task/Vigen-re-cipher/Ring/vigen-re-cipher.ring @@ -0,0 +1,48 @@ +# Project : Vigenère cipher +# Date : 2018/01/02 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +key = "LEMON" +plaintext = "ATTACK AT DAWN" +ciphertext = encrypt(plaintext, key) +see "key = "+ key + nl +see "plaintext = " + plaintext + nl +see "ciphertext = " + ciphertext + nl +see "decrypted = " + decrypt(ciphertext, key) + nl + + +func encrypt(plain, key) + o = "" + k = 0 + plain = fnupper(plain) + key = fnupper(key) + for i = 1 to len(plain) + n = ascii(plain[i]) + if n >= 65 and n <= 90 + o = o + char(65 + (n + ascii(key[k+1])) % 26) + k = (k + 1) % len(key) + ok + next + return o + +func decrypt(cipher, key) + o = "" + k = 0 + cipher = fnupper(cipher) + key = fnupper(key) + for i = 1 to len(cipher) + n = ascii(cipher[i]) + o = o + char(65 + (n + 26 - ascii(key[k+1])) % 26) + k = (k + 1) % len(key) + next + return o + +func fnupper(a) + for aa = 1 to len(a) + c = ascii(a[aa]) + if c >= 97 and c <= 122 + a[aa] = char(c-32) + ok + next + return a diff --git a/Task/Vigen-re-cipher/Scala/vigen-re-cipher.scala b/Task/Vigen-re-cipher/Scala/vigen-re-cipher.scala new file mode 100644 index 0000000000..82222ec31b --- /dev/null +++ b/Task/Vigen-re-cipher/Scala/vigen-re-cipher.scala @@ -0,0 +1,34 @@ +object Vigenere { + def encrypt(msg: String, key: String) : String = { + var result: String = "" + var j = 0 + + for (i <- 0 to msg.length - 1) { + val c = msg.charAt(i) + if (c >= 'A' && c <= 'Z') { + result += ((c + key.charAt(j) - 2 * 'A') % 26 + 'A').toChar + j = (j + 1) % key.length + } + } + + return result + } + + def decrypt(msg: String, key: String) : String = { + var result: String = "" + var j = 0 + + for (i <- 0 to msg.length - 1) { + val c = msg.charAt(i) + if (c >= 'A' && c <= 'Z') { + result += ((c - key.charAt(j) + 26) % 26 + 'A').toChar + j = (j + 1) % key.length + } + } + + return result + } +} + +println("Encrypt text ABC => " + Vigenere.encrypt("ABC", "KEY")) +println("Decrypt text KFA => " + Vigenere.decrypt("KFA", "KEY")) diff --git a/Task/Vigen-re-cipher/VBA/vigen-re-cipher.vba b/Task/Vigen-re-cipher/VBA/vigen-re-cipher.vba new file mode 100644 index 0000000000..07c5f7aa07 --- /dev/null +++ b/Task/Vigen-re-cipher/VBA/vigen-re-cipher.vba @@ -0,0 +1,65 @@ +Option Explicit + +Sub test() +Dim Encryp As String + Encryp = Vigenere("Beware the Jabberwock, my son! The jaws that bite, the claws that catch!", "vigenerecipher", True) + Debug.Print "Encrypt:= """ & Encryp & """" + Debug.Print "Decrypt:= """ & Vigenere(Encryp, "vigenerecipher", False) & """" +End Sub + +Private Function Vigenere(sWord As String, sKey As String, Enc As Boolean) As String +Dim bw() As Byte, bk() As Byte, i As Long, c As Long +Const sW As String = "ÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ" +Const sWo As String = "AAAAACEEEEIIIINOOOOOUUUUY" +Const A As Long = 65 +Const N As Long = 26 + + c = Len(sKey) + i = Len(sWord) + sKey = Left(IIf(c < i, StrRept(sKey, (i / c) + 1), sKey), i) + sKey = StrConv(sKey, vbUpperCase) 'Upper case + sWord = StrConv(sWord, vbUpperCase) + sKey = StrReplace(sKey, sW, sWo) 'Replace accented characters + sWord = StrReplace(sWord, sW, sWo) + sKey = RemoveChars(sKey) 'Remove characters (numerics, spaces, comas, ...) + sWord = RemoveChars(sWord) + bk = CharToAscii(sKey) 'To work with Bytes instead of String + bw = CharToAscii(sWord) + For i = LBound(bw) To UBound(bw) + Vigenere = Vigenere & Chr((IIf(Enc, ((bw(i) - A) + (bk(i) - A)), ((bw(i) - A) - (bk(i) - A)) + N) Mod N) + A) + Next i +End Function + +Private Function StrRept(s As String, N As Long) As String +Dim j As Long, c As String + For j = 1 To N + c = c & s + Next + StrRept = c +End Function + +Private Function StrReplace(s As String, What As String, By As String) As String +Dim t() As String, u() As String, i As Long + t = SplitString(What) + u = SplitString(By) + StrReplace = s + For i = LBound(t) To UBound(t) + StrReplace = Replace(StrReplace, t(i), u(i)) + Next i +End Function + +Private Function SplitString(s As String) As String() + SplitString = Split(StrConv(s, vbUnicode), Chr(0)) +End Function + +Private Function RemoveChars(str As String) As String +Dim b() As Byte, i As Long + b = CharToAscii(str) + For i = LBound(b) To UBound(b) + If b(i) >= 65 And b(i) <= 90 Then RemoveChars = RemoveChars & Chr(b(i)) + Next i +End Function + +Private Function CharToAscii(s As String) As Byte() + CharToAscii = StrConv(s, vbFromUnicode) +End Function diff --git a/Task/Vigen-re-cipher/VBScript/vigen-re-cipher.vb b/Task/Vigen-re-cipher/VBScript/vigen-re-cipher-1.vb similarity index 100% rename from Task/Vigen-re-cipher/VBScript/vigen-re-cipher.vb rename to Task/Vigen-re-cipher/VBScript/vigen-re-cipher-1.vb diff --git a/Task/Vigen-re-cipher/VBScript/vigen-re-cipher-2.vb b/Task/Vigen-re-cipher/VBScript/vigen-re-cipher-2.vb new file mode 100644 index 0000000000..35ff2a9d07 --- /dev/null +++ b/Task/Vigen-re-cipher/VBScript/vigen-re-cipher-2.vb @@ -0,0 +1,34 @@ +'vigenere cypher +option explicit +const asca =65 'ascii(a) + +function filter(s) + with new regexp + .pattern="[^A-Z]" + .global=1 + filter=.replace(ucase(s),"") + end with +end function + +function vigenere (s,k,sign) +dim s1,i,a,b + for i=0 to len(s)-1 + a=asc(mid(s,i+1,1))-asca + b=sign * (asc(mid(k,(i mod len(k))+1,1))-asca) + s1=s1 & chr(((a+b+26) mod 26) +asca) + next + vigenere=s1 +end function + +function encrypt(s,k): encrypt=vigenere(s,k,1) :end function +function decrypt(s,k): decrypt=vigenere(s,k,-1) :end function + +'test-------------------------- +dim plaintext,filtered,key,encoded +key="VIGENERECYPHER" +plaintext = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!" +filtered= filter(plaintext) +wscript.echo filtered +encoded=encrypt(filtered,key) +wscript.echo encoded +wscript.echo decrypt(encoded,key) diff --git a/Task/Visualize-a-tree/Kotlin/visualize-a-tree.kotlin b/Task/Visualize-a-tree/Kotlin/visualize-a-tree.kotlin new file mode 100644 index 0000000000..73916135e6 --- /dev/null +++ b/Task/Visualize-a-tree/Kotlin/visualize-a-tree.kotlin @@ -0,0 +1,45 @@ +// version 1.2.0 + +import java.util.Random + +class Stem(var str: String? = null, var next: Stem? = null) + +const val SDOWN = " |" +const val SLAST = " `" +const val SNONE = " " + +val rand = Random() + +fun tree(root: Int, head: Stem?) { + val col = Stem() + var head2 = head + var tail = head + while (tail != null) { + print(tail.str) + if (tail.next == null) break + tail = tail.next + } + println("--$root") + if (root <= 1) return + if (tail != null && tail.str == SLAST) tail.str = SNONE + if (tail == null) { + head2 = col + tail = head2 + } + else { + tail.next = col + } + var root2 = root + while (root2 != 0) { // make a tree by doing something random + val r = 1 + rand.nextInt(root2) + root2 -= r + col.str = if (root2 != 0) SDOWN else SLAST + tree(r, head2) + } + tail.next = null +} + +fun main(args: Array) { + val n = 8 + tree(n, null) +} diff --git a/Task/Vogels-approximation-method/C/vogels-approximation-method.c b/Task/Vogels-approximation-method/C/vogels-approximation-method.c new file mode 100644 index 0000000000..70c3351d7c --- /dev/null +++ b/Task/Vogels-approximation-method/C/vogels-approximation-method.c @@ -0,0 +1,108 @@ +#include +#include + +#define TRUE 1 +#define FALSE 0 +#define N_ROWS 4 +#define N_COLS 5 + +typedef int bool; + +int supply[N_ROWS] = { 50, 60, 50, 50 }; +int demand[N_COLS] = { 30, 20, 70, 30, 60 }; + +int costs[N_ROWS][N_COLS] = { + { 16, 16, 13, 22, 17 }, + { 14, 14, 13, 19, 15 }, + { 19, 19, 20, 23, 50 }, + { 50, 12, 50, 15, 11 } +}; + +bool row_done[N_ROWS] = { FALSE }; +bool col_done[N_COLS] = { FALSE }; + +void diff(int j, int len, bool is_row, int res[3]) { + int i, c, min1 = INT_MAX, min2 = min1, min_p = -1; + for (i = 0; i < len; ++i) { + if((is_row) ? col_done[i] : row_done[i]) continue; + c = (is_row) ? costs[j][i] : costs[i][j]; + if (c < min1) { + min2 = min1; + min1 = c; + min_p = i; + } + else if (c < min2) min2 = c; + } + res[0] = min2 - min1; res[1] = min1; res[2] = min_p; +} + +void max_penalty(int len1, int len2, bool is_row, int res[4]) { + int i, pc = -1, pm = -1, mc = -1, md = INT_MIN; + int res2[3]; + + for (i = 0; i < len1; ++i) { + if((is_row) ? row_done[i] : col_done[i]) continue; + diff(i, len2, is_row, res2); + if (res2[0] > md) { + md = res2[0]; /* max diff */ + pm = i; /* pos of max diff */ + mc = res2[1]; /* min cost */ + pc = res2[2]; /* pos of min cost */ + } + } + + if (is_row) { + res[0] = pm; res[1] = pc; + } + else { + res[0] = pc; res[1] = pm; + } + res[2] = mc; res[3] = md; +} + +void next_cell(int res[4]) { + int i, res1[4], res2[4]; + max_penalty(N_ROWS, N_COLS, TRUE, res1); + max_penalty(N_COLS, N_COLS, FALSE, res2); + + if (res1[3] == res2[3]) { + if (res1[2] < res2[2]) + for (i = 0; i < 4; ++i) res[i] = res1[i]; + else + for (i = 0; i < 4; ++i) res[i] = res2[i]; + return; + } + if (res1[3] > res2[3]) + for (i = 0; i < 4; ++i) res[i] = res2[i]; + else + for (i = 0; i < 4; ++i) res[i] = res1[i]; +} + +int main() { + int i, j, r, c, q, supply_left = 0, total_cost = 0, cell[4]; + int results[N_ROWS][N_COLS] = { 0 }; + + for (i = 0; i < N_ROWS; ++i) supply_left += supply[i]; + while (supply_left > 0) { + next_cell(cell); + r = cell[0]; + c = cell[1]; + q = (demand[c] <= supply[r]) ? demand[c] : supply[r]; + demand[c] -= q; + if (!demand[c]) col_done[c] = TRUE; + supply[r] -= q; + if (!supply[r]) row_done[r] = TRUE; + results[r][c] = q; + supply_left -= q; + total_cost += q * costs[r][c]; + } + + printf(" A B C D E\n"); + for (i = 0; i < N_ROWS; ++i) { + printf("%c", 'W' + i); + for (j = 0; j < N_COLS; ++j) printf(" %2d", results[i][j]); + printf("\n"); + } + printf("\nTotal cost = %d\n", total_cost); + return 0; +} diff --git a/Task/Vogels-approximation-method/Go/vogels-approximation-method.go b/Task/Vogels-approximation-method/Go/vogels-approximation-method.go new file mode 100644 index 0000000000..d7fed3796e --- /dev/null +++ b/Task/Vogels-approximation-method/Go/vogels-approximation-method.go @@ -0,0 +1,139 @@ +package main + +import ( + "fmt" + "math" +) + +var supply = []int{50, 60, 50, 50} +var demand = []int{30, 20, 70, 30, 60} + +var costs = make([][]int, 4) + +var nRows = len(supply) +var nCols = len(demand) + +var rowDone = make([]bool, nRows) +var colDone = make([]bool, nCols) +var results = make([][]int, nRows) + +func init() { + costs[0] = []int{16, 16, 13, 22, 17} + costs[1] = []int{14, 14, 13, 19, 15} + costs[2] = []int{19, 19, 20, 23, 50} + costs[3] = []int{50, 12, 50, 15, 11} + + for i := 0; i < len(results); i++ { + results[i] = make([]int, nCols) + } +} + +func nextCell() []int { + res1 := maxPenalty(nRows, nCols, true) + res2 := maxPenalty(nCols, nRows, false) + switch { + case res1[3] == res2[3]: + if res1[2] < res2[2] { + return res1 + } else { + return res2 + } + case res1[3] > res2[3]: + return res2 + default: + return res1 + } +} + +func diff(j, l int, isRow bool) []int { + min1 := math.MaxInt32 + min2 := min1 + minP := -1 + for i := 0; i < l; i++ { + var done bool + if isRow { + done = colDone[i] + } else { + done = rowDone[i] + } + if done { + continue + } + var c int + if isRow { + c = costs[j][i] + } else { + c = costs[i][j] + } + if c < min1 { + min2, min1, minP = min1, c, i + } else if c < min2 { + min2 = c + } + } + return []int{min2 - min1, min1, minP} +} + +func maxPenalty(len1, len2 int, isRow bool) []int { + md := math.MinInt32 + pc, pm, mc := -1, -1, -1 + for i := 0; i < len1; i++ { + var done bool + if isRow { + done = rowDone[i] + } else { + done = colDone[i] + } + if done { + continue + } + res := diff(i, len2, isRow) + if res[0] > md { + md = res[0] // max diff + pm = i // pos of max diff + mc = res[1] // min cost + pc = res[2] // pos of min cost + } + } + if isRow { + return []int{pm, pc, mc, md} + } + return []int{pc, pm, mc, md} +} + +func main() { + supplyLeft := 0 + for i := 0; i < len(supply); i++ { + supplyLeft += supply[i] + } + totalCost := 0 + for supplyLeft > 0 { + cell := nextCell() + r, c := cell[0], cell[1] + q := demand[c] + if q > supply[r] { + q = supply[r] + } + demand[c] -= q + if demand[c] == 0 { + colDone[c] = true + } + supply[r] -= q + if supply[r] == 0 { + rowDone[r] = true + } + results[r][c] = q + supplyLeft -= q + totalCost += q * costs[r][c] + } + + fmt.Println(" A B C D E") + for i, result := range results { + fmt.Printf("%c", 'W' + i) + for _, item := range result { + fmt.Printf(" %2d", item) + } + fmt.Println() + } + fmt.Println("\nTotal cost =", totalCost) +} diff --git a/Task/Vogels-approximation-method/Sidef/vogels-approximation-method.sidef b/Task/Vogels-approximation-method/Sidef/vogels-approximation-method.sidef new file mode 100644 index 0000000000..7f3e39b182 --- /dev/null +++ b/Task/Vogels-approximation-method/Sidef/vogels-approximation-method.sidef @@ -0,0 +1,72 @@ +var costs = :( + W => :(A => 16, B => 16, C => 13, D => 22, E => 17), + X => :(A => 14, B => 14, C => 13, D => 19, E => 15), + Y => :(A => 19, B => 19, C => 20, D => 23, E => 50), + Z => :(A => 50, B => 12, C => 50, D => 15, E => 11) +) + +var demand = :(A => 30, B => 20, C => 70, D => 30, E => 60) +var supply = :(W => 50, X => 60, Y => 50, Z => 50) + +var cols = demand.keys.sort +var res = :(); costs.each {|k| res{k} = :() } +var g = :(); supply.each {|x| g{x} = costs{x}.keys.sort_by{|g| costs{x}{g} }} + +demand.each {|x| g{x} = costs.keys.sort_by{|g| costs{g}{x} }} + +while (g) { + var d = demand.collect {|x| + [x, var z = costs{g{x}[0]}{x}, g{x}[1] ? costs{g{x}[1]}{x}-z : z] + } + + var s = supply.collect {|x| + [x, var z = costs{x}{g{x}[0]}, g{x}[1] ? costs{x}{g{x}[1]}-z : z] + } + + with (d.max_by { .[2] }) { |dmax| + d.grep! { .[2] == dmax[2] }.min_by! { .[1] } + } + + with (s.max_by { .[2] }) { |dmax| + s.grep! { .[2] == dmax[2] }.min_by! { .[1] } + } + + var (t,f) = (d[2] == s[2] ? ((s[1], d[1])) : ((d[2], s[2]))) + (d,s) = (t > f ? ((d[0], g{d[0]}[0])) : ((g{s[0]}[0],s[0]))) + + var v = (supply{s} `min` demand{d}) + + res{s}{d} := 0 += v + demand{d} -= v + + if (demand{d} == 0) { + supply.grep {|_,n| n != 0 }.each {|x| g{x}.delete(d) } + g.delete(d) + demand.delete(d) + } + + supply{s} -= v + + if (supply{s} == 0) { + demand.grep {|_,n| n != 0 }.each {|x| g{x}.delete(s) } + g.delete(s) + supply.delete(s) + } +} + +say("\t", cols.join("\t")) + +var cost = 0 +costs.keys.sort.each { |g| + print(g, "\t") + cols.each { |n| + if (defined(var y = res{g}{n})) { + print(y) + cost += (y * costs{g}{n}) + } + print("\t") + } + print("\n") +} + +say "\n\nTotal Cost = #{cost}" diff --git a/Task/Voronoi-diagram/Julia/voronoi-diagram-1.julia b/Task/Voronoi-diagram/Julia/voronoi-diagram-1.julia new file mode 100644 index 0000000000..68496294c5 --- /dev/null +++ b/Task/Voronoi-diagram/Julia/voronoi-diagram-1.julia @@ -0,0 +1,13 @@ +using Images +function voronoi(w, h, n_centroids) + dist = (point,vector) -> sqrt.((point[1].-vector[:,1]).^2 .+ (point[2].-vector[:,2]).^2) + dots = [rand(1:h, n_centroids) rand(1:w, n_centroids) rand(RGB{N0f8}, n_centroids)] + img = zeros(RGB{N0f8}, h, w) + for x in 1:h, y in 1:w + distances = dist([x,y],dots) # distance + nn = findmin(distances)[2] + img[x,y] = dots[nn,:][3] + end + return img +end +img = voronoi(800, 600, 200) diff --git a/Task/Voronoi-diagram/Julia/voronoi-diagram-2.julia b/Task/Voronoi-diagram/Julia/voronoi-diagram-2.julia new file mode 100644 index 0000000000..e7b099b43d --- /dev/null +++ b/Task/Voronoi-diagram/Julia/voronoi-diagram-2.julia @@ -0,0 +1,21 @@ +using TestImages, Images +function voronoi_img!(img, n_centroids) + n,m = size(img) + w = minimum([n,m]) + dist = (point,vector) -> sqrt.((point[1].-vector[:,1]).^2 .+ (point[2].-vector[:,2]).^2) + dots = [rand(1:n, n_centroids) rand(1:m, n_centroids)] + c = [] + for i in 1:size(dots,1) + p = dots[i,:] + append!(c, [img[p[1],p[2]]]) + end + dots = [dots c] + + for x in 1:n, y in 1:m + distances = dist([x,y],dots) # distance + nn = findmin(distances)[2] + img[x,y] = dots[nn,:][3] + end +end +img = testimage("mandrill") +voronoi_img!(img, 300) diff --git a/Task/Voronoi-diagram/Perl-6/voronoi-diagram.pl6 b/Task/Voronoi-diagram/Perl-6/voronoi-diagram.pl6 new file mode 100644 index 0000000000..0e3f0c8ee9 --- /dev/null +++ b/Task/Voronoi-diagram/Perl-6/voronoi-diagram.pl6 @@ -0,0 +1,46 @@ +use Image::PNG::Portable; + +my @bars = '▁▂▃▄▅▆▇█▇▆▅▄▃▂▁'.comb; + +my %type = ( # Voronoi diagram type distance calculation + 'Taxicab' => sub ($px, $py, $x, $y) { ($px - $x).abs + ($py - $y).abs }, + 'Euclidean' => sub ($px, $py, $x, $y) { ($px - $x)² + ($py - $y)² }, + 'Minkowski' => sub ($px, $py, $x, $y) { ($px - $x)³.abs + ($py - $y)³.abs }, +); + +my $width = 400; +my $height = 400; +my $dots = 30; + +my @domains = map { Hash.new( + 'x' => (5..$width-5).roll, + 'y' => (5..$height-5).roll, + 'rgb' => [(64..255).roll xx 3] +) }, ^$dots; + +for %type.keys -> $type { + print "\nGenerating $type diagram... ", ' ' x @bars; + my $img = voronoi(@domains, :w($width), :h($height), :$type); + @domains.map: *.&dot($img); + $img.write: "Voronoi-{$type}-perl6.png"; +} + +sub voronoi (@domains, :$w, :$h, :$type) { + my $png = Image::PNG::Portable.new: :width($w), :height($h); + for ^$w -> $x { + print "\b" x 2+@bars, @bars.=rotate(1).join , ' '; + for ^$h -> $y { + my ($, $i) = min @domains.map: { %type{$type}(%($_), %($_), $x, $y), $++ }; + $png.set: $x, $y, |@domains[$i] + } + } + $png +} + +sub dot (%h, $png, $radius = 3) { + for %h - $radius .. %h + $radius -> $x { + for %h - $radius .. %h + $radius -> $y { + $png.set($x, $y, 0, 0, 0) if ( %h - $x + (%h - $y) * i ).abs <= $radius; + } + } +} diff --git a/Task/Voronoi-diagram/Ring/voronoi-diagram.ring b/Task/Voronoi-diagram/Ring/voronoi-diagram.ring new file mode 100644 index 0000000000..d0cf3a65c9 --- /dev/null +++ b/Task/Voronoi-diagram/Ring/voronoi-diagram.ring @@ -0,0 +1,124 @@ +# Project : Voronoi diagram +# Date : 2018/03/30 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : + +load "guilib.ring" +load "stdlib.ring" +paint = null + +new qapp + { + spots = 100 + leftside = 400 + rightside = 400 + + locx = list(spots) + locy = list(spots) + rgb = newlist(spots,3) + seal = newlist(leftside, rightside) + reach = newlist(leftside, rightside) + + win1 = new qwidget() { + setwindowtitle("Voronoi diagram") + setgeometry(100,100,800,600) + label1 = new qlabel(win1) { + setgeometry(10,10,800,600) + settext("") + } + new qpushbutton(win1) { + setgeometry(150,550,100,30) + settext("draw") + setclickevent("draw()") + } + show() + } + exec() + } + +func draw + p1 = new qpicture() + color = new qcolor() { + setrgb(0,0,255,255) + } + pen = new qpen() { + setcolor(color) + setwidth(1) + } + paint = new qpainter() { + begin(p1) + setpen(pen) + + for i =1 to spots + locx[i] = floor(leftside * randomf()) + locy[i] = floor(rightside * randomf()) + rgb[i][1] = floor(256 * randomf()) + rgb[i][2] = floor(256 * randomf()) + rgb[i][3] = floor(256 * randomf()) + next + for x = 1 to leftside + for y = 1 to rightside + reach[x][y] = pow((locx[1] - x),2) + pow((locy[1] - y),2) + seal[x][y] = 1 + next + next + for i = 2 to spots + for x = locx[i] to 0 step -1 + if not (chkpos(i,x,1, rightside-1)) + exit + ok + next + for x = locx[i] + 1 to leftside - 1 + if not (chkpos(i, x, 1, rightside-1)) + exit + ok + next + next + for x = 1 to leftside + for y = 1 to rightside + c1 = rgb[seal[x][y]][1] + c2 = rgb[seal[x][y]][2] + c3 = rgb[seal[x][y]][3] + color = new qcolor() { setrgb(c1,c2,c3,255) } + pen = new qpen() { setcolor(color) setwidth(10) } + setpen(pen) + starty = y + nearest = seal[x][y] + for y = (y + 1) to rightside + if seal[x][y] != nearest + y = y - 1 + exit + ok + next + paint.drawline(x,starty,x,y + 1) + next + next + endpaint() + } + label1 { setpicture(p1) show() } + return + +func chkpos(site,x,starty,endy) + chkpos = 0 + dxsqr = 0 + dxsqr = pow((locx[site]- x),2) + for y = starty to endy + dsqr = pow((locy[site] - y),2) + dxsqr + if x <= leftside and y <= leftside and x > 0 and y > 0 + if dsqr <= reach[x][y] + reach[x][y] = dsqr + seal[x][y] = site + chkpos = 1 + ok + ok + next + return chkpos + +func randomf() + decimals(10) + str = "0." + for i = 1 to 10 + nr = random(9) + str = str + string(nr) + next + return number(str) diff --git a/Task/Voronoi-diagram/Rust/voronoi-diagram.rust b/Task/Voronoi-diagram/Rust/voronoi-diagram.rust new file mode 100644 index 0000000000..7490fae893 --- /dev/null +++ b/Task/Voronoi-diagram/Rust/voronoi-diagram.rust @@ -0,0 +1,180 @@ +extern crate piston; +extern crate opengl_graphics; +extern crate graphics; +extern crate touch_visualizer; + +#[cfg(feature = "include_sdl2")] +extern crate sdl2_window; + +extern crate getopts; +extern crate voronoi; +extern crate rand; + +use touch_visualizer::TouchVisualizer; +use opengl_graphics::{ GlGraphics, OpenGL }; +use graphics::{ Context, Graphics }; +use piston::window::{ Window, WindowSettings }; +use piston::input::*; +use piston::event_loop::*; +#[cfg(feature = "include_sdl2")] +use sdl2_window::Sdl2Window as AppWindow; +use voronoi::{voronoi, Point, make_polygons}; +use rand::Rng; + +static DEFAULT_WINDOW_HEIGHT: u32 = 600; +static DEFAULT_WINDOW_WIDTH: u32 = 600; + +struct Settings { + lines_only: bool, + random_count: usize +} + +fn main() { + let args: Vec = std::env::args().collect(); + let mut opts = getopts::Options::new(); + opts.optflag("l", "lines_only", "Don't color polygons, just outline them"); + opts.optopt("r", "random_count", "On keypress \"R\", put this many random points on-screen", "RANDOMCOUNT"); + let matches = opts.parse(&args[1..]).expect("Failed to parse args"); + + let settings = Settings{ + lines_only: matches.opt_present("l"), + random_count: match matches.opt_str("r") { + None => { 50 }, + Some(s) => { s.parse().expect("Random count of bad format") } + } + }; + + event_loop(&settings); + +} + +fn random_point() -> [f64; 2] { + [rand::thread_rng().gen_range(0., DEFAULT_WINDOW_HEIGHT as f64), rand::thread_rng().gen_range(0., DEFAULT_WINDOW_WIDTH as f64)] +} + +fn random_color() -> [f32; 4] { + [rand::random::(), rand::random::(), rand::random::(), 1.0] +} + +fn random_voronoi(dots: &mut Vec<[f64;2]>, colors: &mut Vec<[f32;4]>, num: usize) { + dots.clear(); + colors.clear(); + + for _ in 0..num { + dots.push(random_point()); + colors.push(random_color()); + } +} + +fn event_loop(settings: &Settings) { + let opengl = OpenGL::V3_2; + let mut window: AppWindow = WindowSettings::new("Interactive Voronoi", [DEFAULT_WINDOW_HEIGHT, DEFAULT_WINDOW_WIDTH]) + .exit_on_esc(true).opengl(opengl).build().unwrap(); + + let ref mut gl = GlGraphics::new(opengl); + let mut touch_visualizer = TouchVisualizer::new(); + let mut events = Events::new(EventSettings::new().lazy(true)); + let mut dots = Vec::new(); + let mut colors = Vec::new(); + + let mut mx = 0.0; + let mut my = 0.0; + + while let Some(e) = events.next(&mut window) { + touch_visualizer.event(window.size(), &e); + if let Some(button) = e.release_args() { + match button { + Button::Keyboard(key) => { + if key == piston::input::keyboard::Key::N { dots.clear(); colors.clear(); } + if key == piston::input::keyboard::Key::R { random_voronoi(&mut dots, &mut colors, settings.random_count); } + } + Button::Mouse(_) => { + dots.push([mx, my]); + colors.push(random_color()); + }, + _ => () + } + }; + e.mouse_cursor(|x, y| { + mx = x; + my = y; + }); + if let Some(args) = e.render_args() { + gl.draw(args.viewport(), |c, g| { + graphics::clear([1.0; 4], g); + let mut vor_pts = Vec::new(); + for d in &dots { + vor_pts.push(Point::new(d[0], d[1])); + } + if vor_pts.len() > 0 { + let vor_diagram = voronoi(vor_pts, DEFAULT_WINDOW_WIDTH as f64); + let vor_polys = make_polygons(&vor_diagram); + for (i, poly) in vor_polys.iter().enumerate() { + if settings.lines_only { + draw_lines_in_polygon(poly, &c, g); + } else { + draw_polygon(poly, &c, g, colors[i]); + } + } + } + for d in &dots { + draw_ellipse(&d, &c, g); + } + }); + } + } + +} + +fn draw_lines_in_polygon( + poly: &Vec, + c: &Context, + g: &mut G, +) +{ + let color = [0.0, 0.0, 1.0, 1.0]; + + for i in 0..poly.len()-1 { + graphics::line( + color, + 2.0, + [poly[i].x.into(), poly[i].y.into(), poly[i+1].x.into(), poly[i+1].y.into()], + c.transform, + g + ) + } +} + +fn draw_polygon( + poly: &Vec, + c: &Context, + g: &mut G, + color: [f32; 4] +) { + let mut polygon_points: Vec<[f64; 2]> = Vec::new(); + + for p in poly { + polygon_points.push([p.x.into(), p.y.into()]); + } + + graphics::polygon( + color, + polygon_points.as_slice(), + c.transform, + g + ) +} + +fn draw_ellipse( + cursor: &[f64; 2], + c: &Context, + g: &mut G, +) { + let color = [0.0, 0.0, 0.0, 1.0]; + graphics::ellipse( + color, + graphics::ellipse::circle(cursor[0], cursor[1], 4.0), + c.transform, + g + ); +} diff --git a/Task/Walk-a-directory-Non-recursively/Julia/walk-a-directory-non-recursively.julia b/Task/Walk-a-directory-Non-recursively/Julia/walk-a-directory-non-recursively.julia new file mode 100644 index 0000000000..035425b597 --- /dev/null +++ b/Task/Walk-a-directory-Non-recursively/Julia/walk-a-directory-non-recursively.julia @@ -0,0 +1,5 @@ +for filename in readdir("/foo/bar") + if endswith(filename, ".mp3") + print(filename) + end +end diff --git a/Task/Walk-a-directory-Recursively/Forth/walk-a-directory-recursively.fth b/Task/Walk-a-directory-Recursively/Forth/walk-a-directory-recursively.fth index eb668135b8..16f68a5cd0 100644 --- a/Task/Walk-a-directory-Recursively/Forth/walk-a-directory-recursively.fth +++ b/Task/Walk-a-directory-Recursively/Forth/walk-a-directory-recursively.fth @@ -1,30 +1,47 @@ +require unix/filestat.fs +require unix/libc.fs + +: $append ( from len to -- ) 2DUP >R >R COUNT + SWAP MOVE R> R@ C@ + R> C! ; + defer ls-filter -: dots? ( name len -- ? ) - dup 1 = if drop c@ [char] . = - else 2 = if dup c@ [char] . = swap 1+ c@ [char] . = and - else drop false then then ; +: dots? ( name len -- ? ) drop c@ [char] . = ; -: ls-r ( dir len -- ) - open-dir if drop exit then ( dirid) +file-stat buffer: statbuf + +: isdir ( addr u -- flag ) + statbuf lstat ?ior statbuf st_mode w@ S_IFMT and S_IFDIR = ; + +: (ls-r) ( dir len -- ) + pad c@ >r pad $append s" /" pad $append + pad count open-dir if drop r> pad c! exit then ( dirid) begin - dup pad 256 rot read-dir throw + dup pad count + 256 rot read-dir throw while - pad over dots? 0= if \ ignore current and parent dirs - pad over recurse - pad over ls-filter if - cr pad swap type + pad count + over dots? 0= if \ ignore all hidden names + dup pad count rot + 2dup ls-filter if + cr 2dup type + then + isdir if + pad count + swap recurse else drop then else drop then repeat - drop close-dir throw ; + drop r> pad c! + close-dir throw +; -: c-file? ( str len -- ? ) +: ls-r ( dir len -- ) 0 pad c! (ls-r) ; + +: c-files ( str len -- ? ) dup 3 < if 2drop false exit then + 1- dup c@ 32 or dup [char] c <> swap [char] h <> and if drop false exit then 1- dup c@ [char] . <> if drop false exit then drop true ; -' c-file? is ls-filter +' c-files is ls-filter -s" ." ls-r +: all-files ( str len -- ? ) 2drop true ; +' all-files is ls-filter + +s" ." ls-r cr diff --git a/Task/Walk-a-directory-Recursively/Julia/walk-a-directory-recursively.julia b/Task/Walk-a-directory-Recursively/Julia/walk-a-directory-recursively.julia new file mode 100644 index 0000000000..de7aba8a26 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Julia/walk-a-directory-recursively.julia @@ -0,0 +1,8 @@ +rootpath = "/home/user/music" +pattern = r".mp3$" + +for (root, dirs, files) in walkdir(rootpath) + for file in files + if ismatch(pattern, file) println(file) end + end +end diff --git a/Task/Walk-a-directory-Recursively/Kotlin/walk-a-directory-recursively.kotlin b/Task/Walk-a-directory-Recursively/Kotlin/walk-a-directory-recursively.kotlin new file mode 100644 index 0000000000..c6df950973 --- /dev/null +++ b/Task/Walk-a-directory-Recursively/Kotlin/walk-a-directory-recursively.kotlin @@ -0,0 +1,14 @@ +// version 1.2.0 + +import java.io.File + +fun walkDirectoryRecursively(dirPath: String, pattern: Regex): Sequence { + val d = File(dirPath) + require (d.exists() && d.isDirectory()) + return d.walk().map { it.name }.filter { it.matches(pattern) }.sorted().distinct() } + +fun main(args: Array) { + val r = Regex("""^v(a|f).*\.h$""") // get all C header files beginning with 'va' or 'vf' + val files = walkDirectoryRecursively("/usr/include", r) + for (file in files) println(file) +} diff --git a/Task/Web-scraping/00DESCRIPTION b/Task/Web-scraping/00DESCRIPTION index 415ccc0a18..fd51c66027 100644 --- a/Task/Web-scraping/00DESCRIPTION +++ b/Task/Web-scraping/00DESCRIPTION @@ -23,13 +23,13 @@ The relevant part of that page source looked like this: What time is it?

US Naval Observatory Master Clock Time

-
Jul. 27, 22:57:22 UTC Universal Time -
Jul. 27, 06:57:22 PM EDT Eastern Time -
Jul. 27, 05:57:22 PM CDT Central Time -
Jul. 27, 04:57:22 PM MDT Mountain Time -
Jul. 27, 03:57:22 PM PDT Pacific Time -
Jul. 27, 02:57:22 PM AKDT Alaska Time -
Jul. 27, 12:57:22 PM HAST Hawaii-Aleutian Time +
Jul. 27, 22:57:22 UTC Universal Time +
Jul. 27, 06:57:22 PM EDT Eastern Time +
Jul. 27, 05:57:22 PM CDT Central Time +
Jul. 27, 04:57:22 PM MDT Mountain Time +
Jul. 27, 03:57:22 PM PDT Pacific Time +
Jul. 27, 02:57:22 PM AKDT Alaska Time +
Jul. 27, 12:57:22 PM HAST Hawaii-Aleutian Time ...
diff --git a/Task/Web-scraping/8th/web-scraping.8th b/Task/Web-scraping/8th/web-scraping.8th index a2a5b2bd8d..37e1ef5f02 100644 --- a/Task/Web-scraping/8th/web-scraping.8th +++ b/Task/Web-scraping/8th/web-scraping.8th @@ -6,7 +6,7 @@ : get-time read-url - /
.*?(\d{2}:\d{2}:\d{2})\sUTC/ + /
.*?(\d{2}:\d{2}:\d{2})\sUTC/ tuck r:match if 1 r:@ . cr then ; diff --git a/Task/Web-scraping/App-Inventor/web-scraping.app b/Task/Web-scraping/App-Inventor/web-scraping.app index f476bf29b1..2f66bdb3d3 100644 --- a/Task/Web-scraping/App-Inventor/web-scraping.app +++ b/Task/Web-scraping/App-Inventor/web-scraping.app @@ -1,9 +1,9 @@ when ScrapeButton.Click do - set ScrapeWeb.Url to SourceTextBox.Text - call ScrapeWeb.Get + set ScrapeWeb.Url to SourceTextBox.Text + call ScrapeWeb.Get when ScrapeWeb.GotText url,responseCode,responseType,responseContent do - initialize local Left to split at first text (text: get responseContent, at: PreTextBox.Text) - initialize local Right to "" in - set Right to select list item (list: get Left, index: 2) - set ResultLabel.Text to select list item (list: split at first (text:get Right, at: PostTextBox.Text), index: 1) + initialize local Left to split at first text (text: get responseContent, at: PreTextBox.Text) + initialize local Right to "" in + set Right to select list item (list: get Left, index: 2) + set ResultLabel.Text to select list item (list: split at first (text:get Right, at: PostTextBox.Text), index: 1) diff --git a/Task/Web-scraping/Cache-ObjectScript/web-scraping.cos b/Task/Web-scraping/Cache-ObjectScript/web-scraping.cos index df372892ca..59e00361c8 100644 --- a/Task/Web-scraping/Cache-ObjectScript/web-scraping.cos +++ b/Task/Web-scraping/Cache-ObjectScript/web-scraping.cos @@ -3,58 +3,58 @@ Class Utils.Net [ Abstract ] ClassMethod ExtractHTMLData(pHost As %String = "", pPath As %String = "", pRegEx As %String = "", Output list As %List) As %Status { - // implement error handling - Try { + // implement error handling + Try { - // some initialisation - Set list="", sc=$$$OK - - // check input parameters - If $Match(pHost, "^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$")=0 { - Set sc=$$$ERROR($$$GeneralError, "Invalid host name.") - Quit - } - - // create http request and get page - Set req=##class(%Net.HttpRequest).%New() - Set req.Server=pHost - Do req.Get(pPath) - - // check for success - If $Extract(req.HttpResponse.StatusCode)'=2 { - Set sc=$$$ERROR($$$GeneralError, "Page not loaded.") - Quit - } - - // read http response stream - Set html=req.HttpResponse.Data - Set html.LineTerminator=$Char(10) - Set sc=html.Rewind() - - // read http response stream - While 'html.AtEnd { - Set line=html.ReadLine(, .sc, .eol) - Set pos=$Locate(line, pRegEx) - If pos { - Set parse=$Piece($Extract(line, pos, *), $Char(9)) - Set slot=$ListLength(list)+1 - Set $List(list, slot)=parse - } - } - - } Catch err { - - // an error has occurred - If err.Name="" { - Set sc=$$$ERROR($$$GeneralError, "Invalid regular expression.") - } Else { - Set sc=$$$ERROR($$$CacheError, $ZError) - } - - } - - // return status - Quit sc + // some initialisation + Set list="", sc=$$$OK + + // check input parameters + If $Match(pHost, "^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$")=0 { + Set sc=$$$ERROR($$$GeneralError, "Invalid host name.") + Quit + } + + // create http request and get page + Set req=##class(%Net.HttpRequest).%New() + Set req.Server=pHost + Do req.Get(pPath) + + // check for success + If $Extract(req.HttpResponse.StatusCode)'=2 { + Set sc=$$$ERROR($$$GeneralError, "Page not loaded.") + Quit + } + + // read http response stream + Set html=req.HttpResponse.Data + Set html.LineTerminator=$Char(10) + Set sc=html.Rewind() + + // read http response stream + While 'html.AtEnd { + Set line=html.ReadLine(, .sc, .eol) + Set pos=$Locate(line, pRegEx) + If pos { + Set parse=$Piece($Extract(line, pos, *), $Char(9)) + Set slot=$ListLength(list)+1 + Set $List(list, slot)=parse + } + } + + } Catch err { + + // an error has occurred + If err.Name="" { + Set sc=$$$ERROR($$$GeneralError, "Invalid regular expression.") + } Else { + Set sc=$$$ERROR($$$CacheError, $ZError) + } + + } + + // return status + Quit sc } } diff --git a/Task/Web-scraping/Ceylon/web-scraping.ceylon b/Task/Web-scraping/Ceylon/web-scraping.ceylon new file mode 100644 index 0000000000..bfd502b43f --- /dev/null +++ b/Task/Web-scraping/Ceylon/web-scraping.ceylon @@ -0,0 +1,31 @@ +import ceylon.uri { + parse +} +import ceylon.http.client { + get +} + +shared void run() { + + // apparently the cgi link is deprecated? + value oldUri = "http://tycho.usno.navy.mil/cgi-bin/timer.pl"; + value newUri = "http://tycho.usno.navy.mil/timer.pl"; + + value contents = downloadContents(newUri); + value time = extractTime(contents); + print(time else "nothing found"); +} + +String downloadContents(String uriString) { + value uri = parse(uriString); + value request = get(uri); + value response = request.execute(); + return response.contents; +} + +String? extractTime(String contents) => + contents + .lines + .filter((String element) => element.contains("UTC")) + .first + ?.substring(4, 21); diff --git a/Task/Web-scraping/Delphi/web-scraping-1.delphi b/Task/Web-scraping/Delphi/web-scraping-1.delphi index c20e7ad15e..6154027105 100644 --- a/Task/Web-scraping/Delphi/web-scraping-1.delphi +++ b/Task/Web-scraping/Delphi/web-scraping-1.delphi @@ -146,7 +146,7 @@ begin for i := 0 to Pred(HTTPResponse.Count) do begin { The line we're looking for is something like this: -
May. 04. 21:55:19 UTC Universal Time } +
May. 04. 21:55:19 UTC Universal Time } // Check each line if Pos('UTC',HTTPResponse[i]) > 0 then diff --git a/Task/Web-scraping/Erlang/web-scraping.erl b/Task/Web-scraping/Erlang/web-scraping.erl index d49899570b..967399c93b 100644 --- a/Task/Web-scraping/Erlang/web-scraping.erl +++ b/Task/Web-scraping/Erlang/web-scraping.erl @@ -4,7 +4,7 @@ -define(Match, "
(.+ UTC)"). main() -> - inets:start(), - {ok, {_Status, _Header, HTML}} = httpc:request(?Url), - {match, [Time]} = re:run(HTML, ?Match, [{capture, all_but_first, binary}]), - io:format("~s~n",[Time]). + inets:start(), + {ok, {_Status, _Header, HTML}} = httpc:request(?Url), + {match, [Time]} = re:run(HTML, ?Match, [{capture, all_but_first, binary}]), + io:format("~s~n",[Time]). diff --git a/Task/Web-scraping/Java/web-scraping.java b/Task/Web-scraping/Java/web-scraping.java index aa447c3a00..96fdd0d45a 100644 --- a/Task/Web-scraping/Java/web-scraping.java +++ b/Task/Web-scraping/Java/web-scraping.java @@ -6,19 +6,19 @@ import java.net.URLConnection; public class WebTime{ - public static void main(String[] args){ - try{ - URL address = new URL( - "http://tycho.usno.navy.mil/cgi-bin/timer.pl"); - URLConnection conn = address.openConnection(); - BufferedReader in = new BufferedReader( - new InputStreamReader(conn.getInputStream())); - String line; - while(!(line = in.readLine()).contains("UTC")); - System.out.println(line.substring(4)); - }catch(IOException e){ - System.err.println("error connecting to server."); - e.printStackTrace(); - } - } + public static void main(String[] args){ + try{ + URL address = new URL( + "http://tycho.usno.navy.mil/cgi-bin/timer.pl"); + URLConnection conn = address.openConnection(); + BufferedReader in = new BufferedReader( + new InputStreamReader(conn.getInputStream())); + String line; + while(!(line = in.readLine()).contains("UTC")); + System.out.println(line.substring(4)); + }catch(IOException e){ + System.err.println("error connecting to server."); + e.printStackTrace(); + } + } } diff --git a/Task/Web-scraping/Julia/web-scraping-1.julia b/Task/Web-scraping/Julia/web-scraping-1.julia index 170b7f8b4c..734da54b71 100644 --- a/Task/Web-scraping/Julia/web-scraping-1.julia +++ b/Task/Web-scraping/Julia/web-scraping-1.julia @@ -8,8 +8,8 @@ function getusnotime() @sprintf "get(%s)\n => %s" url err end isa(s, Requests.Response) || return (s, false) - t = match(r"(?<=
)(.*?UTC)", readall(s)) - isa(t, RegexMatch) || return (@sprintf("raw html:\n %s", readall(s)), false) + t = match(r"(?<=
)(.*?UTC)", readstring(s)) + isa(t, RegexMatch) || return (@sprintf("raw html:\n %s", readstring(s)), false) return (t.match, true) end diff --git a/Task/Web-scraping/Lasso/web-scraping.lasso b/Task/Web-scraping/Lasso/web-scraping.lasso index e401188ab2..47588d0e85 100644 --- a/Task/Web-scraping/Lasso/web-scraping.lasso +++ b/Task/Web-scraping/Lasso/web-scraping.lasso @@ -1,13 +1,13 @@ /* have to be used local(raw_htmlstring = 'What time is it?

US Naval Observatory Master Clock Time

-
Jul. 27, 22:57:22 UTC Universal Time -
Jul. 27, 06:57:22 PM EDT Eastern Time -
Jul. 27, 05:57:22 PM CDT Central Time -
Jul. 27, 04:57:22 PM MDT Mountain Time -
Jul. 27, 03:57:22 PM PDT Pacific Time -
Jul. 27, 02:57:22 PM AKDT Alaska Time -
Jul. 27, 12:57:22 PM HAST Hawaii-Aleutian Time +
Jul. 27, 22:57:22 UTC Universal Time +
Jul. 27, 06:57:22 PM EDT Eastern Time +
Jul. 27, 05:57:22 PM CDT Central Time +
Jul. 27, 04:57:22 PM MDT Mountain Time +
Jul. 27, 03:57:22 PM PDT Pacific Time +
Jul. 27, 02:57:22 PM AKDT Alaska Time +
Jul. 27, 12:57:22 PM HAST Hawaii-Aleutian Time

') */ @@ -16,8 +16,8 @@ local(raw_htmlstring = 'What time is it? local(raw_htmlstring = string(include_url('http://tycho.usno.navy.mil/cgi-bin/timer.pl'))) local( - reg_exp = regexp(-find = `
(.*?) UTC`, -input = #raw_htmlstring, -ignorecase), - datepart_txt = #reg_exp -> find ? #reg_exp -> matchstring(1) | string + reg_exp = regexp(-find = `
(.*?) UTC`, -input = #raw_htmlstring, -ignorecase), + datepart_txt = #reg_exp -> find ? #reg_exp -> matchstring(1) | string ) #datepart_txt diff --git a/Task/Web-scraping/MATLAB/web-scraping.m b/Task/Web-scraping/MATLAB/web-scraping.m index 14d2130cc8..6f704205a5 100644 --- a/Task/Web-scraping/MATLAB/web-scraping.m +++ b/Task/Web-scraping/MATLAB/web-scraping.m @@ -3,6 +3,6 @@ ix = [findstr(s,'
'), length(s)+1]; for k = 2:length(ix) tok = s(ix(k-1)+4:ix(k)-1); if findstr(tok,'UTC') - disp(tok); + disp(tok); end; end; diff --git a/Task/Web-scraping/Maple/web-scraping.maple b/Task/Web-scraping/Maple/web-scraping.maple new file mode 100644 index 0000000000..f3993a8c25 --- /dev/null +++ b/Task/Web-scraping/Maple/web-scraping.maple @@ -0,0 +1,2 @@ +text := URL:-Get("http://tycho.usno.navy.mil/cgi-bin/timer.pl"): +printf(StringTools:-StringSplit(text,"
")[2]); diff --git a/Task/Web-scraping/PHP/web-scraping-2.php b/Task/Web-scraping/PHP/web-scraping-2.php index 664f791861..238385ca31 100644 --- a/Task/Web-scraping/PHP/web-scraping-2.php +++ b/Task/Web-scraping/PHP/web-scraping-2.php @@ -1,7 +1,7 @@ (.*) UTC.*$/su", - "\\1", - file_get_contents('http://tycho.usno.navy.mil/cgi-bin/timer.pl') + "/^.*
(.*) UTC.*$/su", + "\\1", + file_get_contents('http://tycho.usno.navy.mil/cgi-bin/timer.pl') ); diff --git a/Task/Web-scraping/REBOL/web-scraping.rebol b/Task/Web-scraping/REBOL/web-scraping.rebol index df19e68357..c65d3dea08 100644 --- a/Task/Web-scraping/REBOL/web-scraping.rebol +++ b/Task/Web-scraping/REBOL/web-scraping.rebol @@ -1,8 +1,8 @@ REBOL [ - Title: "Web Scraping" - Author: oofoe - Date: 2009-12-07 - URL: http://rosettacode.org/wiki/Web_Scraping + Title: "Web Scraping" + Author: oofoe + Date: 2009-12-07 + URL: http://rosettacode.org/wiki/Web_Scraping ] ; Notice that REBOL understands unquoted URL's: diff --git a/Task/Web-scraping/Scala/web-scraping.scala b/Task/Web-scraping/Scala/web-scraping.scala index 4158fe8625..2fa37611f7 100644 --- a/Task/Web-scraping/Scala/web-scraping.scala +++ b/Task/Web-scraping/Scala/web-scraping.scala @@ -1,10 +1,10 @@ import scala.io.Source object WebTime extends Application { - val text = Source.fromURL("http://tycho.usno.navy.mil/cgi-bin/timer.pl") - val utc = text.getLines.find(_.contains("UTC")) - utc match { - case Some(s) => println(s.substring(4)) - case _ => println("error") - } + val text = Source.fromURL("http://tycho.usno.navy.mil/cgi-bin/timer.pl") + val utc = text.getLines.find(_.contains("UTC")) + utc match { + case Some(s) => println(s.substring(4)) + case _ => println("error") + } } diff --git a/Task/Web-scraping/VBA/web-scraping.vba b/Task/Web-scraping/VBA/web-scraping.vba new file mode 100644 index 0000000000..a0d4350235 --- /dev/null +++ b/Task/Web-scraping/VBA/web-scraping.vba @@ -0,0 +1,38 @@ +Rem add Microsoft VBScript Regular Expression X.X to your Tools References + +Function GetUTC() As String + Url = "http://tycho.usno.navy.mil/cgi-bin/timer.pl" + With CreateObject("MSXML2.XMLHTTP.6.0") + .Open "GET", Url, False + .send + arrt = Split(.responseText, vbLf) + End With + For Each t In arrt + If InStr(t, "UTC") Then + GetUTC = StripHttpTags(t) + + Exit For + End If + Next +End Function + +Function StripHttpTags(s) + With New RegExp + .Global = True + .Pattern = "\<.+?\>" + If .Test(s) Then + StripHttpTags = .Replace(s, "") + Else + StripHttpTags = s + End If + End With +End Function + +Sub getTime() + Rem starting point + Dim ReturnValue As String + ReturnValue = GetUTC + Rem debug.print can be removed + Debug.Print ReturnValue + MsgBox (ReturnValue) +End Sub diff --git a/Task/Web-scraping/VBScript/web-scraping.vb b/Task/Web-scraping/VBScript/web-scraping.vb index ce3a48fd10..57dfb77722 100644 --- a/Task/Web-scraping/VBScript/web-scraping.vb +++ b/Task/Web-scraping/VBScript/web-scraping.vb @@ -1,28 +1,29 @@ -Function GetUTC() - url = "http://tycho.usno.navy.mil/cgi-bin/timer.pl" - With CreateObject("MSXML2.XMLHTTP.6.0") - .open "GET", url, False - .send - arrt = Split(.responseText,vbLf) - End With - For Each t In arrt - If InStr(t,"UTC") Then - GetUTC = StripHttpTags(t) - Exit For - End If - Next +Function GetUTC() As String + Url = "http://tycho.usno.navy.mil/cgi-bin/timer.pl" + With CreateObject("MSXML2.XMLHTTP.6.0") + .Open "GET", Url, False + .send + arrt = Split(.responseText, vbLf) + End With + For Each t In arrt + If InStr(t, "UTC") Then + GetUTC = StripHttpTags(t) + + Exit For + End If + Next End Function Function StripHttpTags(s) - With New RegExp - .Global = True - .Pattern = "\<.+?\>" - If .Test(s) Then - StripHttpTags = .Replace(s,"") - Else - StripHttpTags = s - End If - End With + With New RegExp + .Global = True + .Pattern = "\<.+?\>" + If .Test(s) Then + StripHttpTags = .Replace(s, "") + Else + StripHttpTags = s + End If + End With End Function WScript.StdOut.Write GetUTC diff --git a/Task/Window-creation-X11/C/window-creation-x11-1.c b/Task/Window-creation-X11/C/window-creation-x11-1.c index 0c8afc2468..118790fedc 100644 --- a/Task/Window-creation-X11/C/window-creation-x11-1.c +++ b/Task/Window-creation-X11/C/window-creation-x11-1.c @@ -7,7 +7,7 @@ int main(void) { Display *d; Window w; XEvent e; - char *msg = "Hello, World!"; + const char *msg = "Hello, World!"; int s; d = XOpenDisplay(NULL); diff --git a/Task/Window-creation-X11/Julia/window-creation-x11.julia b/Task/Window-creation-X11/Julia/window-creation-x11.julia new file mode 100644 index 0000000000..78251e2ed5 --- /dev/null +++ b/Task/Window-creation-X11/Julia/window-creation-x11.julia @@ -0,0 +1,40 @@ +using Xlib + +function x11demo() + # Open connection to the server. + dpy = XOpenDisplay(C_NULL) + dpy == C_NULL && error("unable to open display") + scr = DefaultScreen(dpy) + + # Create a window. + win = XCreateSimpleWindow(dpy, RootWindow(dpy, scr), 10, 10, 300, 100, 1, + BlackPixel(dpy, scr), WhitePixel(dpy, scr)) + + # Select the kind of events we are interested in. + XSelectInput(dpy, win, ExposureMask | KeyPressMask) + + # Show or in x11 terms map window. + XMapWindow(dpy, win) + + # Run event loop. + evt = Ref(XEvent()) + while true + XNextEvent(dpy, evt) + + # Draw or redraw the window. + if EventType(evt) == Expose + XFillRectangle(dpy, win, DefaultGC(dpy, scr), 24, 24, 16, 16) + XDrawString(dpy, win, DefaultGC(dpy, scr), 50, 50, "Hello, World! Press any key to exit.") + end + + # Exit whenever a key is pressed. + if EventType(evt) == KeyPress + break + end + end + + # Shutdown server connection + XCloseDisplay(dpy) +end + +x11demo() diff --git a/Task/Window-creation-X11/Perl-6/window-creation-x11.pl6 b/Task/Window-creation-X11/Perl-6/window-creation-x11.pl6 index 288e74ed57..cd83928f42 100644 --- a/Task/Window-creation-X11/Perl-6/window-creation-x11.pl6 +++ b/Task/Window-creation-X11/Perl-6/window-creation-x11.pl6 @@ -1,34 +1,38 @@ use NativeCall; -class Display is repr('CStruct') {} -class GC is repr('CStruct') {} +class Display is repr('CStruct') { + has int32 $!screen; + has int32 $!window; + } +class GC is repr('CStruct') { + has int32 $!context; +} class XEvent is repr('CStruct') { - has int32 $.type; # for 32 bits machine - #has int $.type; # for 64 bits machine + has int32 $.type; method init { $!type = 0 } } -sub XOpenDisplay(Str $name = ':0') returns Display is native('libX11') { * } -sub XDefaultScreen(Display $) returns int is native('libX11') { * } -sub XRootWindow(Display $, int $screen_number) returns int is native('libX11') { * } -sub XBlackPixel(Display $, int $screen_number) returns int is native('libX11') { * } -sub XWhitePixel(Display $, int $screen_number) returns int is native('libX11') { * } +sub XOpenDisplay(Str $name = ':0') returns Display is native('X11') { * } +sub XDefaultScreen(Display $) returns int32 is native('X11') { * } +sub XRootWindow(Display $, int32 $screen_number) returns int32 is native('X11') { * } +sub XBlackPixel(Display $, int32 $screen_number) returns int32 is native('X11') { * } +sub XWhitePixel(Display $, int32 $screen_number) returns int32 is native('X11') { * } sub XCreateSimpleWindow( - Display $, int $parent_window, int $x, int $y, - int $width, int $height, int $border_width, - int $border, int $background -) returns int is native('libX11') { * } -sub XMapWindow(Display $, int $window) is native('libX11') { * } -sub XSelectInput(Display $, int $window, int $mask) is native('libX11') { * } + Display $, int32 $parent_window, int32 $x, int32 $y, + int32 $width, int32 $height, int32 $border_width, + int32 $border, int32 $background +) returns int32 is native('X11') { * } +sub XMapWindow(Display $, int32 $window) is native('X11') { * } +sub XSelectInput(Display $, int32 $window, int32 $mask) is native('X11') { * } sub XFillRectangle( - Display $, int $window, GC $, int $x, int $y, int $width, int $height -) is native('libX11') { * } + Display $, int32 $window, GC $, int32 $x, int32 $y, int32 $width, int32 $height +) is native('X11') { * } sub XDrawString( - Display $, int $window, GC $, int $x, int $y, Str $, int $str_length -) is native('libX11') { * } -sub XDefaultGC(Display $, int $screen) returns GC is native('libX11') { * } -sub XNextEvent(Display $, XEvent $e) is native('libX11') { * } -sub XCloseDisplay(Display $) is native('libX11') { * } + Display $, int32 $window, GC $, int32 $x, int32 $y, Str $, int32 $str_length +) is native('X11') { * } +sub XDefaultGC(Display $, int32 $screen) returns GC is native('X11') { * } +sub XNextEvent(Display $, XEvent $e) is native('X11') { * } +sub XCloseDisplay(Display $) is native('X11') { * } my Display $display = XOpenDisplay() or die "Can not open display"; @@ -48,11 +52,11 @@ my XEvent $e .= new; $e.init; loop { XNextEvent($display, $e); if $e.type == 12 { - XFillRectangle($display, $window, XDefaultGC($display, $screen), 20, 20, 10, 10); - XDrawString($display, $window, XDefaultGC($display, $screen), 10, 50, $msg, my int $ = $msg.chars); + XFillRectangle($display, $window, XDefaultGC($display, $screen), 20, 20, 10, 10); + XDrawString($display, $window, XDefaultGC($display, $screen), 10, 50, $msg, my int $ = $msg.chars); } elsif $e.type == 2 { - last; + last; } } XCloseDisplay($display); diff --git a/Task/Window-creation/J/window-creation-1.j b/Task/Window-creation/J/window-creation-1.j index be65bfe8d1..10afdb0443 100644 --- a/Task/Window-creation/J/window-creation-1.j +++ b/Task/Window-creation/J/window-creation-1.j @@ -1,3 +1 @@ - title=: '"Hamlet -- Act 3, Scene 1"' - text=: '"To be, or not to be: that is the question:"' - wd 'mb ',title,text + wdinfo 'Hamlet';'To be, or not to be: that is the question:' diff --git a/Task/Window-creation/J/window-creation-2.j b/Task/Window-creation/J/window-creation-2.j index c92198c092..23503af728 100644 --- a/Task/Window-creation/J/window-creation-2.j +++ b/Task/Window-creation/J/window-creation-2.j @@ -1,7 +1,6 @@ MINWDW=: noun define pc minwdw; pas 162 85;pcenter; -rem form end; ) minwdw_run=: monad define diff --git a/Task/Window-creation/Perl-6/window-creation.pl6 b/Task/Window-creation/Perl-6/window-creation.pl6 index 5005f576cd..c33ee5090e 100644 --- a/Task/Window-creation/Perl-6/window-creation.pl6 +++ b/Task/Window-creation/Perl-6/window-creation.pl6 @@ -1,16 +1,17 @@ use GTK::Simple; +use GTK::Simple::App; my GTK::Simple::App $app .= new(title => 'Simple GTK Window'); -$app.size_request(250, 100); +$app.size-request(250, 100); -$app.set_content( +$app.set-content( GTK::Simple::VBox.new( my $button = GTK::Simple::Button.new(label => 'Exit'), ) ); -$app.border_width = 40; +$app.border-width = 40; $button.clicked.tap: { $app.exit } diff --git a/Task/Window-creation/Red/window-creation.red b/Task/Window-creation/Red/window-creation.red new file mode 100644 index 0000000000..2251ec751d --- /dev/null +++ b/Task/Window-creation/Red/window-creation.red @@ -0,0 +1 @@ +>>view [] diff --git a/Task/Window-creation/VBA/window-creation.vba b/Task/Window-creation/VBA/window-creation.vba new file mode 100644 index 0000000000..6c75ea59fe --- /dev/null +++ b/Task/Window-creation/VBA/window-creation.vba @@ -0,0 +1,8 @@ +Option Explicit + +Sub InsertForm() +Dim myForm As Object, strname As String + Set myForm = ThisWorkbook.VBProject.VBComponents.Add(3) + strname = myForm.Name + VBA.UserForms.Add(strname).Show +End Sub diff --git a/Task/Window-management/00DESCRIPTION b/Task/Window-management/00DESCRIPTION index c62a187528..f7b407f4ed 100644 --- a/Task/Window-management/00DESCRIPTION +++ b/Task/Window-management/00DESCRIPTION @@ -10,6 +10,7 @@ {{omit from|PHP|PHP cannot create windows by itself}} {{omit from|PostScript}} {{omit from|Retro}} +{{omit from|SQL PL|It does not handle GUI}} {{omit from|TI-83 BASIC|Does not have windows.}} {{omit from|TI-89 BASIC|Does not have windows.}} diff --git a/Task/Window-management/Gambas/window-management.gambas b/Task/Window-management/Gambas/window-management.gambas new file mode 100644 index 0000000000..03d18a14c9 --- /dev/null +++ b/Task/Window-management/Gambas/window-management.gambas @@ -0,0 +1,87 @@ +sWindow As New String[4] +'________________________ +Public Sub Form_Open() + +Manipulate + +End +'________________________ +Public Sub Manipulate() +Dim siDelay As Short = 2 + +Me.Show +Print "Show" +Wait siDelay + +sWindow[0] = Me.Width +sWindow[1] = Me.Height +sWindow[2] = Me.X +sWindow[3] = Me.y + +Me.Hide +Print "Hidden" +CompareWindow +Wait siDelay + +Me.Show +Print "Show" +CompareWindow +Wait siDelay + +Me.Minimized = True +Print "Minimized" +CompareWindow +Wait siDelay + +Me.Show +Print "Show" +CompareWindow +Wait siDelay + +Me.Maximized = True +Print "Maximized" +CompareWindow +Wait siDelay + +Me.Maximized = False +Print "Not Maximized" +CompareWindow +Wait siDelay + +Me.Height = 200 +Me.Width = 300 +Print "Resized" +CompareWindow +Wait siDelay + +Me.x = 10 +Me.Y = 10 +Print "Moved" +CompareWindow +Wait siDelay + +Me.Close + +End +'________________________ +Public Sub CompareWindow() +Dim sNewWindow As New String[4] +Dim siCount As Short +Dim bMatch As Boolean = True + +sNewWindow[0] = Me.Width +sNewWindow[1] = Me.Height +sNewWindow[2] = Me.X +sNewWindow[3] = Me.y + +For siCount = 0 To 3 + If sWindow[siCount] <> sNewWindow[siCount] Then bMatch = False +Next + +If bMatch Then + Print "Windows identities match the original window size" +Else + Print "Windows identities DONOT match the original window size" +End If + +End diff --git a/Task/Wireworld/Elena/wireworld.elena b/Task/Wireworld/Elena/wireworld.elena new file mode 100644 index 0000000000..2371aa9e99 --- /dev/null +++ b/Task/Wireworld/Elena/wireworld.elena @@ -0,0 +1,137 @@ +import extensions. +import cellular. +import system'routines. +import system'threading. +import system'text. + +const int maxX = 48. +const int maxY = 28. + +type listener_func = ListenerFunc. + +limited class ListenerFunc +{ + action eval space:space [] +} + +sealed class Model +{ + space theSpace. + ruleset theRuleSet. + bool started. + + listener_func event onUpdate :: theListener. + + constructor newRandomset ruleset:transformSet + [ + theSpace := IntMatrixSpace new int:maxY int:maxX ruleset:randomSet. + + theRuleSet := transformSet. + + started := false. + ] + + constructor newLoaded ruleset:initSet ruleset:transformSet + [ + theSpace := IntMatrixSpace new int:maxY int:maxX ruleset:initSet. + + theRuleSet := transformSet. + + started := false. + ] + + $onUpdate + [ + if ($nil != theListener) + [ theListener eval space:theSpace ]. + ] + + init + [ + $self $onUpdate. + ] + + run + [ + if (started) + [ theSpace update ruleset:theRuleSet. ]; + [ started := true. ]. + + $self $onUpdate. + ] +} + +const int DELAY = 50. + +symbol testSet = ((0,1,0), + (0,1,0), + (0,1,0)). + +class gameOfLifeRuleSet = BaseRuleSet:: +{ + proceed space:s int:x int:y vint:retVal + [ + int cell := s getAt int:x int:y. + int number := s getLiveCell int:x int:y int:1. // NOTE : number of living cells around the self includes the cell itself + + if ((cell == 0) && (number == 3)) + [ + retVal int := 1 + ]; + if ((cell == 1) && ((number == 4) || (number == 3))) + [ + retVal int := 1 + ]; + [ + retVal int := 0 + ] + ] +}. + +extension space presenterOp +{ + print + [ + console setCursorPosition int:0 int:0. + + int columns := self columns. + int rows := self rows. + + int i := 0. + int j := 0. + while (i < rows) + [ + j := 0. + + while (j < columns) + [ + int cell := self getAt int:i int:j. + + console write((cell == 0)iif(" ","o")). + + j := j + 1. + ]. + + i := i + 1. + console writeLine. + ]. + ] +} + +program = +[ + console clear. + + var model := Model newRandomset ruleset:gameOfLifeRuleSet. + + model onUpdate listener_func(&space:sp)[ sp print ]. + + until (console isKeyAvailable) + [ + model run. + + thread sleep:DELAY. + ]. + + console readChar. +]. diff --git a/Task/Wireworld/Perl-6/wireworld.pl6 b/Task/Wireworld/Perl-6/wireworld.pl6 index 8927e9f755..33c7303d98 100644 --- a/Task/Wireworld/Perl-6/wireworld.pl6 +++ b/Task/Wireworld/Perl-6/wireworld.pl6 @@ -1,44 +1,81 @@ class Wireworld { has @.line; + method height () { @!line.elems } + has int $.width; - multi method new(@line) { self.new: :@line } - multi method new($str ) { self.new: $str.lines } + multi method new(@line) { samewith :@line, :width(max @line».chars) } + multi method new($str ) { samewith $str.lines } method gist { join "\n", @.line } - method postcircumfix:<[ ]>($i) { @.line[$i].comb } - method neighbors($i where ^@.line, $j where ^$.line.pick.chars) + method !neighbors($i where ^$.height, $j where ^$.width) { - my @i = grep any(^@.line), $i «+« (-1, 0, 1); - my @j = grep any(^@.line.pick.chars), $j «+« (-1, 0, 1); - gather for @i X @j -> \i, \j { + my @i = grep ^$.height, $i «+« (-1, 0, 1); + my @j = grep ^$.width, $j «+« (-1, 0, 1); + gather for @i X @j -> (\i, \j) { next if [ i, j ] ~~ [ $i, $j ]; - take self[i][j]; + take @!line[i].comb[j]; } } method succ { - my $succ = self.new: '' xx @.line; - for ^@.line X ^@.line.pick.chars -> $i, $j { - $succ.line[$i] ~= - do given self[$i][$j] { + my @succ; + for ^$.height X ^$.width -> ($i, $j) { + @succ[$i] ~= + do given @!line[$i].comb[$j] { when 'H' { 't' } when 't' { '.' } when '.' { - grep('H', self.neighbors($i, $j)) == 1|2 ?? 'H' !! '.' + grep('H', self!neighbors($i, $j)) == 1|2 ?? 'H' !! '.' } default { ' ' } } } - return $succ; + return self.new: @succ; } } -my $str = -"tH......... -. . - ... -. . -Ht.. ......"; +my %*SUB-MAIN-OPTS; +%*SUB-MAIN-OPTS = True; -my Wireworld $world .= new: $str; -say $world++ for ^3; +multi sub MAIN ( + IO() $filename, + Numeric:D :$interval = 1/4, + Bool :$stop-on-repeat, +) { + run-loop :$interval, :$stop-on-repeat, Wireworld.new: $filename.slurp; +} + +#| run a built-in example +multi sub MAIN ( + Numeric:D :$interval = 1/4, + Bool :$stop-on-repeat, +) { + run-loop :$interval, :$stop-on-repeat, Wireworld.new: Q:to/END/ + tH......... + . . + ... + . . + Ht.. ...... + END +} + +sub run-loop ( + Wireworld:D $initial, + Real:D(Numeric) :$interval = 1/4, + Bool :$stop-on-repeat +){ + my %seen is SetHash; + + for $initial ...^ * eqv * { # generate a sequence (uses .succ) + print "\e[2J"; + say '#' x $initial.width; + .say; + say '#' x $initial.width; + + if $stop-on-repeat { + last if %seen{ .gist }++; + } + + sleep $interval; + } +} diff --git a/Task/Word-wrap/Factor/word-wrap.factor b/Task/Word-wrap/Factor/word-wrap.factor new file mode 100644 index 0000000000..bbadfa4760 --- /dev/null +++ b/Task/Word-wrap/Factor/word-wrap.factor @@ -0,0 +1,12 @@ +USE: wrap.strings +IN: scratchpad "Most languages in widespread use today are applicative languages +: the central construct in the language is some form of function call, where a f +unction is applied to a set of parameters, where each parameter is itself the re +sult of a function call, the name of a variable, or a constant. In stack languag +es, a function call is made by simply writing the name of the function; the para +meters are implicit, and they have to already be on the stack when the call is m +ade. The result of the function call (if any) is then left on the stack after th +e function returns, for the next function to consume, and so on. Because functio +ns are invoked simply by mentioning their name without any additional syntax, Fo +rth and Factor refer to functions as words, because in the syntax they really ar +e just words." [ 60 wrap-string print nl ] [ 45 wrap-string print ] bi diff --git a/Task/Word-wrap/Julia/word-wrap.julia b/Task/Word-wrap/Julia/word-wrap.julia new file mode 100644 index 0000000000..ccfe7936ac --- /dev/null +++ b/Task/Word-wrap/Julia/word-wrap.julia @@ -0,0 +1,12 @@ +using TextWrap + +text = """Reformat the single paragraph in 'text' to fit in lines of no more + than 'width' columns, and return a new string containing the entire + wrapped paragraph. As with wrap(), tabs are expanded and other + whitespace characters converted to space. See TextWrapper class for + available keyword args to customize wrapping behaviour.""" + +println("# Wrapped at 80 chars") +print_wrapped(text, width=80) +println("\n\n# Wrapped at 70 chars") +print_wrapped(text, width=70) diff --git a/Task/Word-wrap/Ring/word-wrap.ring b/Task/Word-wrap/Ring/word-wrap.ring new file mode 100644 index 0000000000..6878cae692 --- /dev/null +++ b/Task/Word-wrap/Ring/word-wrap.ring @@ -0,0 +1,33 @@ +# Project : Word wrap +# Date : 2018/01/02 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +load "stdlib.ring" + +doc = "In olden times when wishing still helped one, there lived a king +whose daughters were all beautiful, but the youngest was so beautiful +that the sun itself, which has seen so much, was astonished whenever +it shone in her face. Close by the king's castle lay a great dark +forest, and under an old lime-tree in the forest was a well, and when +the day was very warm, the king's child went out into the forest and +sat down by the side of the cool fountain, and when she was bored she +took a golden ball, and threw it up on high and caught it, and this +ball was her favorite plaything." + +wordwrap(doc,72) +wordwrap(doc,80) + +func wordwrap(doc, maxline) + words = split(doc, " ") + line = words[1] + for i=2 to len(words) + word = words[i] + if len(line)+len(word)+1 > maxline + see line + nl + line = word + else + line = line + " " + word + ok + next + see line + nl + nl diff --git a/Task/World-Cup-group-stage/Elena/world-cup-group-stage.elena b/Task/World-Cup-group-stage/Elena/world-cup-group-stage.elena new file mode 100644 index 0000000000..87bb82add4 --- /dev/null +++ b/Task/World-Cup-group-stage/Elena/world-cup-group-stage.elena @@ -0,0 +1,50 @@ +import system'routines. +import extensions. + +program = +{ + static games := ("12", "13", "14", "23", "24", "34"). + + static results := "000000". + + nextResult + [ + if (results=="222222") [ ^ false ]. + + results := (results toInt(3) + 1) toLiteral(3); padLeft($48, 6). + + ^ true + ] + + // program entry point + eval + [ + var points := IntMatrix new(4, 10). + + [ + var r := results. + var records := IntArray new(4). + + 0 till:6 do(:i) + [ + (results[i]) => + "2" [ records[games[i][0] toInt - 49] += 3 ]; + "1" [ + records[games[i][0] toInt - 49] += 1. + records[games[i][1] toInt - 49] += 1 + ]; + "0" [ records[games[i][1] toInt - 49] += 3 ]. + ]. + + records := records ascendant. + + 0 to:3 do(:i)[ points[i][records[i]] += 1 ]. + + ] repeatUntil:$($self nextResult). + + 0 repeatTill:4; zip:("1st", "2nd", "3rd", "4th") forEach(:i:l) + [ + console printLine(l,": ", points[3 - i]) + ]. + ] +}. diff --git a/Task/Write-float-arrays-to-a-text-file/COBOL/write-float-arrays-to-a-text-file.cobol b/Task/Write-float-arrays-to-a-text-file/COBOL/write-float-arrays-to-a-text-file.cobol new file mode 100644 index 0000000000..7b484f6bac --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/COBOL/write-float-arrays-to-a-text-file.cobol @@ -0,0 +1,42 @@ + identification division. + program-id. wr-float. + environment division. + input-output section. + file-control. + select report-file assign "float.txt" + organization sequential. + data division. + file section. + fd report-file + report is floats. + working-storage section. + 1 i binary pic 9(4). + 1 x-values comp-2. + 2 value 1.0. + 2 value 2.0. + 2 value 3.0. + 2 value 1.0e11. + 1 redefines x-values comp-2. + 2 x occurs 4. + 1 comp-2. + 2 y occurs 4. + report section. + rd floats. + 1 float-line type de. + 2 line plus 1. + 3 column 1 pic -9.99e+99 source x(i). + 2 column 12 pic -9.9999e+99 source y(i). + procedure division. + begin. + open output report-file + initiate floats + perform varying i from 1 by 1 + until i > 4 + compute y(i) = function sqrt (x(i)) + generate float-line + end-perform + terminate floats + close report-file + stop run + . + end program wr-float. diff --git a/Task/Write-float-arrays-to-a-text-file/Ring/write-float-arrays-to-a-text-file.ring b/Task/Write-float-arrays-to-a-text-file/Ring/write-float-arrays-to-a-text-file.ring new file mode 100644 index 0000000000..7e12f05aac --- /dev/null +++ b/Task/Write-float-arrays-to-a-text-file/Ring/write-float-arrays-to-a-text-file.ring @@ -0,0 +1,24 @@ +# Project : Write float arrays to a text file +# Date : 2018/02/15 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +decimals(13) +x = [1, 2, 3, 100000000000] +y = [1, 1.4142135623730, 1.7320508075688, 316227.76601683] +str = list(4) +fn = "C:\Ring\calmosoft\output.txt" +fp = fopen(fn,"wb") +for i = 1 to 4 + str[i] = string(x[i]) + " | " + string(y[i]) + windowsnl() + fwrite(fp, str[i]) +next +fclose(fp) +fp = fopen("C:\Ring\calmosoft\output.txt","r") +r = "" +while isstring(r) + r = fgetc(fp) + if r = char(10) see nl + else see r ok +end +fclose(fp) diff --git a/Task/Write-language-name-in-3D-ASCII/Modula-2/write-language-name-in-3d-ascii.mod2 b/Task/Write-language-name-in-3D-ASCII/Modula-2/write-language-name-in-3d-ascii.mod2 new file mode 100644 index 0000000000..aeff487bbe --- /dev/null +++ b/Task/Write-language-name-in-3D-ASCII/Modula-2/write-language-name-in-3d-ascii.mod2 @@ -0,0 +1,38 @@ +MODULE Art; +FROM Terminal IMPORT WriteString,WriteLn,ReadChar; + +BEGIN + (* 3D, but does not fit in the terminal window *) + (* + WriteString("_____ ______ ________ ________ ___ ___ ___ ________ _______"); + WriteLn; + WriteString("|\ _ \ _ \|\ __ \|\ ___ \|\ \|\ \|\ \ |\ __ \ / ___ \"); + WriteLn; + WriteString("\ \ \\\__\ \ \ \ \|\ \ \ \_|\ \ \ \\\ \ \ \ \ \ \|\ \ ____________ /__/|_/ /|"); + WriteLn; + WriteString(" \ \ \\|__| \ \ \ \\\ \ \ \ \\ \ \ \\\ \ \ \ \ \ __ \|\____________\__|// / /"); + WriteLn; + WriteString(" \ \ \ \ \ \ \ \\\ \ \ \_\\ \ \ \\\ \ \ \____\ \ \ \ \|____________| / /_/__"); + WriteLn; + WriteString(" \ \__\ \ \__\ \_______\ \_______\ \_______\ \_______\ \__\ \__\ |\________\"); + WriteLn; + WriteString(" \|__| \|__|\|_______|\|_______|\|_______|\|_______|\|__|\|__| \|_______|"); + WriteLn; + *) + + (* Not 3D, but fits in the terminal window *) + WriteString(" __ __ _ _ ___"); + WriteLn; + WriteString(" | \/ | | | | | |__ \"); + WriteLn; + WriteString(" | \ / | ___ __| |_ _| | __ _ ______ ) |"); + WriteLn; + WriteString(" | |\/| |/ _ \ / _` | | | | |/ _` |______/ /"); + WriteLn; + WriteString(" | | | | (_) | (_| | |_| | | (_| | / /_"); + WriteLn; + WriteString(" |_| |_|\___/ \__,_|\__,_|_|\__,_| |____|"); + WriteLn; + + ReadChar +END Art. diff --git a/Task/Write-language-name-in-3D-ASCII/Perl-6/write-language-name-in-3d-ascii.pl6 b/Task/Write-language-name-in-3D-ASCII/Perl-6/write-language-name-in-3d-ascii.pl6 index b87e29b771..2440cd5a35 100644 --- a/Task/Write-language-name-in-3D-ASCII/Perl-6/write-language-name-in-3d-ascii.pl6 +++ b/Task/Write-language-name-in-3D-ASCII/Perl-6/write-language-name-in-3d-ascii.pl6 @@ -1,3 +1,4 @@ +# must be evenly padded with white-space$ my $text = q:to/END/; @@@@@ @@ @@ -13,8 +14,7 @@ END say '' for ^5; for $text.lines -> $_ is copy { - my $/; - my @chars = 「-+ ., ;: '"」.comb.pick(*) xx *; + my @chars = |「-+ ., ;: '"」.comb.pick(*) xx *; s:g [' '] = @chars.shift; print " $_ "; s:g [('@'+)(.)] = @chars.shift ~ $0; diff --git a/Task/Write-to-Windows-event-log/C/write-to-windows-event-log.c b/Task/Write-to-Windows-event-log/C/write-to-windows-event-log.c new file mode 100644 index 0000000000..16e1bd48ae --- /dev/null +++ b/Task/Write-to-Windows-event-log/C/write-to-windows-event-log.c @@ -0,0 +1,18 @@ +/*Abhishek Ghosh, 6th October 2017*/ + +#include +#include + +int main(int argC,char* argV[]) +{ + char str[1000]; + + if(argC!=5) + printf("Usage : %s < Followed by level, id, source string and description>",argV[0]); + else{ + sprintf(str,"EventCreate /t %s /id %s /l APPLICATION /so %s /d \"%s\"",argV[1],argV[2],argV[3],argV[4]); + system(str); + } + + return 0; +} diff --git a/Task/Write-to-Windows-event-log/D/write-to-windows-event-log.d b/Task/Write-to-Windows-event-log/D/write-to-windows-event-log.d new file mode 100644 index 0000000000..1dc499596d --- /dev/null +++ b/Task/Write-to-Windows-event-log/D/write-to-windows-event-log.d @@ -0,0 +1,12 @@ +import std.process; +import std.stdio; + +void main() { + auto cmd = executeShell(`EventCreate /t INFORMATION /id 123 /l APPLICATION /so Dlang /d "Rosetta Code Example"`); + + if (cmd.status == 0) { + writeln("Output: ", cmd.output); + } else { + writeln("Failed to execute command, status=", cmd.status); + } +} diff --git a/Task/Write-to-Windows-event-log/Lingo/write-to-windows-event-log.lingo b/Task/Write-to-Windows-event-log/Lingo/write-to-windows-event-log.lingo new file mode 100644 index 0000000000..8149463dc5 --- /dev/null +++ b/Task/Write-to-Windows-event-log/Lingo/write-to-windows-event-log.lingo @@ -0,0 +1,5 @@ +shell = xtra("Shell").new() +props = [:] +props["operation"] = "runas" +props["parameters"] = "/t INFORMATION /id 123 /l APPLICATION /so Lingo /d ""E&"Rosetta Code Example""E +shell.shell_exec("EventCreate", props) diff --git a/Task/Write-to-Windows-event-log/Perl/write-to-windows-event-log.pl b/Task/Write-to-Windows-event-log/Perl/write-to-windows-event-log.pl new file mode 100644 index 0000000000..a624fd89f9 --- /dev/null +++ b/Task/Write-to-Windows-event-log/Perl/write-to-windows-event-log.pl @@ -0,0 +1,16 @@ +use strict; +use warnings; + +use Win32::EventLog; +my $handle = Win32::EventLog->new("Application"); + +my $event = { + Computer => $ENV{COMPUTERNAME}, + Source => 'Rosettacode', + EventType => EVENTLOG_INFORMATION_TYPE, + Category => 'test', + EventID => 0, + Data => 'a test for rosettacode', + Strings => 'a string test for rosettacode', +}; +$handle->Report($event); diff --git a/Task/Write-to-Windows-event-log/PowerShell/write-to-windows-event-log.psh b/Task/Write-to-Windows-event-log/PowerShell/write-to-windows-event-log-1.psh similarity index 100% rename from Task/Write-to-Windows-event-log/PowerShell/write-to-windows-event-log.psh rename to Task/Write-to-Windows-event-log/PowerShell/write-to-windows-event-log-1.psh diff --git a/Task/Write-to-Windows-event-log/PowerShell/write-to-windows-event-log-2.psh b/Task/Write-to-Windows-event-log/PowerShell/write-to-windows-event-log-2.psh new file mode 100644 index 0000000000..6dff9cfd18 --- /dev/null +++ b/Task/Write-to-Windows-event-log/PowerShell/write-to-windows-event-log-2.psh @@ -0,0 +1,5 @@ + $MessageFreeLula = 'Global unions and union leaders from more than 50 countries came together ' + + 'in Geneva today to stand in solidarity with former Brazilian President Lula, calling for ' + + 'his immediate release from jail and that he be allowed to run in the upcoming elections.' + Write-EventLog -LogName 'System' -Source 'Eventlog' -Message $MessageFreeLula -EventId 13 -EntryType 'Information' + 'SUCCESS: The Lula Livre message (#FreeLula) has been recorded in the system log event.' diff --git a/Task/Write-to-Windows-event-log/PowerShell/write-to-windows-event-log-3.psh b/Task/Write-to-Windows-event-log/PowerShell/write-to-windows-event-log-3.psh new file mode 100644 index 0000000000..9e4c3af060 --- /dev/null +++ b/Task/Write-to-Windows-event-log/PowerShell/write-to-windows-event-log-3.psh @@ -0,0 +1,7 @@ + $MessageFreeLula = 'Global unions and union leaders from more than 50 countries came together ' + + 'in Geneva today to stand in solidarity with former Brazilian President Lula, calling for ' + + 'his immediate release from jail and that he be allowed to run in the upcoming elections.' + New-EventLog -LogName 'Free Lula!' -Source '#FreeLula' + Limit-EventLog -OverflowAction 'OverWriteAsNeeded' -MaximumSize (64KB*13) -LogName 'Free Lula!' + Write-EventLog -LogName 'Free Lula!' -Source '#FreeLula' -Message $MessageFreeLula -EventId 13 -EntryType 'Information' + 'SUCCESS: The Lula Livre message (#FreeLula) has been recorded in the "Free Lula!" log event.' diff --git a/Task/Write-to-Windows-event-log/Scala/write-to-windows-event-log.scala b/Task/Write-to-Windows-event-log/Scala/write-to-windows-event-log.scala new file mode 100644 index 0000000000..fa49a0be8c --- /dev/null +++ b/Task/Write-to-Windows-event-log/Scala/write-to-windows-event-log.scala @@ -0,0 +1,11 @@ +object RegisterWinLogEvent extends App { + + import sys.process._ + + def eventCreate= Seq("EVENTCREATE", "/T", "SUCCESS", "/id", "123", "/l", "APPLICATION", "/so", "Scala RegisterWinLogEvent", "/d", "Rosetta Code Example" ).!! + + println(eventCreate) + + println(s"\nSuccessfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]") + +} diff --git a/Task/XML-DOM-serialization/MATLAB/xml-dom-serialization.m b/Task/XML-DOM-serialization/MATLAB/xml-dom-serialization.m new file mode 100644 index 0000000000..120ec0f4f9 --- /dev/null +++ b/Task/XML-DOM-serialization/MATLAB/xml-dom-serialization.m @@ -0,0 +1,5 @@ +docNode = com.mathworks.xml.XMLUtils.createDocument('root'); +docRootNode = docNode.getDocumentElement; +thisElement = docNode.createElement('element'); +thisElement.appendChild(docNode.createTextNode('Some text here')); +docRootNode.appendChild(thisElement); diff --git a/Task/XML-DOM-serialization/Perl-6/xml-dom-serialization-1.pl6 b/Task/XML-DOM-serialization/Perl-6/xml-dom-serialization-1.pl6 new file mode 100644 index 0000000000..a93bfdd039 --- /dev/null +++ b/Task/XML-DOM-serialization/Perl-6/xml-dom-serialization-1.pl6 @@ -0,0 +1,6 @@ +use XML; +use XML::Writer; + +say my $document = XML::Document.new( + XML::Writer.serialize( :root[ :element['Some text here', ], ] ) +); diff --git a/Task/XML-DOM-serialization/Perl-6/xml-dom-serialization-2.pl6 b/Task/XML-DOM-serialization/Perl-6/xml-dom-serialization-2.pl6 new file mode 100644 index 0000000000..ef25700125 --- /dev/null +++ b/Task/XML-DOM-serialization/Perl-6/xml-dom-serialization-2.pl6 @@ -0,0 +1 @@ +Some text here diff --git a/Task/XML-Input/Julia/xml-input.julia b/Task/XML-Input/Julia/xml-input.julia new file mode 100644 index 0000000000..ae08adcae5 --- /dev/null +++ b/Task/XML-Input/Julia/xml-input.julia @@ -0,0 +1,18 @@ +using LightXML + +let docstr = """ + + + + + + + + """ + + doc = parse_string(docstr) + xroot = root(doc) + for elem in xroot["Student"] + println(attribute(elem, "Name")) + end +end diff --git a/Task/XML-Input/Perl-6/xml-input.pl6 b/Task/XML-Input/Perl-6/xml-input.pl6 index b5c2c5d418..9d4ae6226a 100644 --- a/Task/XML-Input/Perl-6/xml-input.pl6 +++ b/Task/XML-Input/Perl-6/xml-input.pl6 @@ -1,4 +1,3 @@ -use v6; use XML; my $xml = from-xml ' @@ -11,4 +10,4 @@ my $xml = from-xml ' '; -say . for $xml.nodes.grep(*.name eq 'Student') +say . for $xml.nodes.grep(/Student/) diff --git a/Task/XML-Input/REXX/xml-input-1.rexx b/Task/XML-Input/REXX/xml-input-1.rexx index 30c279f5a1..745ab826ed 100644 --- a/Task/XML-Input/REXX/xml-input-1.rexx +++ b/Task/XML-Input/REXX/xml-input-1.rexx @@ -1,18 +1,17 @@ -/*REXX program to extract student names from an XML string(s). */ +/*REXX program extracts student names from an XML string(s). */ g.= -g.1=' ' -g.2=' ' -g.3=' ' -g.4=' ' -g.5=' ' -g.6=' ' -g.7=' ' -g.8=' ' -g.9=' ' +g.1 = ' ' +g.2 = ' ' +g.3 = ' ' +g.4 = ' ' +g.5 = ' ' +g.6 = ' ' +g.7 = ' ' +g.8 = ' ' +g.9 = ' ' - do j=1 while g.j\=='' + do j=1 while g.j\=='' g.j=space(g.j) - parse var g.j 'Name="' studname '"' + parse var g.j 'Name="' studname '"' if studname\=='' then say studname - end /*j*/ - /*stick a fork in it, we're done.*/ + end /*j*/ /*stick a fork in it, we're all done. */ diff --git a/Task/XML-Input/REXX/xml-input-2.rexx b/Task/XML-Input/REXX/xml-input-2.rexx index fe08e878ac..2cc9a59dac 100644 --- a/Task/XML-Input/REXX/xml-input-2.rexx +++ b/Task/XML-Input/REXX/xml-input-2.rexx @@ -1,85 +1,85 @@ -/*REXX program to extract student names from an XML string(s). */ +/*REXX program extracts student names from an XML string(s). */ g.= -g.1=' ' -g.2=' ' -g.3=' ' -g.4=' ' -g.5=' ' -g.6=' ' -g.7=' ' -g.8=' ' -g.9=' ' +g.1 = ' ' +g.2 = ' ' +g.3 = ' ' +g.4 = ' ' +g.5 = ' ' +g.6 = ' ' +g.7 = ' ' +g.8 = ' ' +g.9 = ' ' - do j=1 while g.j\=='' + do j=1 while g.j\=='' g.j=space(g.j) - parse var g.j 'Name="' studname '"' - if studname=='' then iterate - if pos('&',studname)\==0 then studname=xmlTranE(studname) + parse var g.j 'Name="' studname '"' + if studname=='' then iterate + if pos('&', studname)\==0 then studname=xmlTranE(studname) say studname end /*j*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────XML_ subroutine─────────────────────*/ -xml_: parse arg ,_ /*tran an XML entity (&xxxx;) */ -xmlEntity! = '&'_";" -if pos(xmlEntity!,x)\==0 then x=changestr(xmlEntity!,x,arg(1)) -if left(_,2)=='#x' then do - xmlEntity!='&'left(_,3)translate(substr(_,4))";" - x=changestr(xmlEntity!,x,arg(1)) - end -return x -/*──────────────────────────────────XMLTRANE subroutine─────────────────*/ -xmlTranE: procedure; parse arg x /*Following are most of the chars in*/ - /*the DOS (under Windows) codepage. */ -x=XML_('♥',"hearts") ; x=XML_('â',"ETH") ; x=XML_('ƒ',"fnof") ; x=XML_('═',"boxH") -x=XML_('♦',"diams") ; x=XML_('â','#x00e2') ; x=XML_('á',"aacute"); x=XML_('╬',"boxVH") -x=XML_('♣',"clubs") ; x=XML_('â','#x00e9') ; x=XML_('á','#x00e1'); x=XML_('╧',"boxHu") -x=XML_('♠',"spades") ; x=XML_('ä',"auml") ; x=XML_('í',"iacute"); x=XML_('╨',"boxhU") -x=XML_('♂',"male") ; x=XML_('ä','#x00e4') ; x=XML_('í','#x00ed'); x=XML_('╤',"boxHd") -x=XML_('♀',"female") ; x=XML_('à',"agrave") ; x=XML_('ó',"oacute"); x=XML_('╥',"boxhD") -x=XML_('☼',"#x263c") ; x=XML_('à','#x00e0') ; x=XML_('ó','#x00f3'); x=XML_('╙',"boxUr") -x=XML_('↕',"UpDownArrow") ; x=XML_('å',"aring") ; x=XML_('ú',"uacute"); x=XML_('╘',"boxuR") -x=XML_('¶',"para") ; x=XML_('å','#x00e5') ; x=XML_('ú','#x00fa'); x=XML_('╒',"boxdR") -x=XML_('§',"sect") ; x=XML_('ç',"ccedil") ; x=XML_('ñ',"ntilde"); x=XML_('╓',"boxDr") -x=XML_('↑',"uarr") ; x=XML_('ç','#x00e7') ; x=XML_('ñ','#x00f1'); x=XML_('╫',"boxVh") -x=XML_('↑',"uparrow") ; x=XML_('ê',"ecirc") ; x=XML_('Ñ',"Ntilde"); x=XML_('╪',"boxvH") -x=XML_('↑',"ShortUpArrow") ; x=XML_('ê','#x00ea') ; x=XML_('Ñ','#x00d1'); x=XML_('┘',"boxul") -x=XML_('↓',"darr") ; x=XML_('ë',"euml") ; x=XML_('¿',"iquest"); x=XML_('┌',"boxdr") -x=XML_('↓',"downarrow") ; x=XML_('ë','#x00eb') ; x=XML_('⌐',"bnot") ; x=XML_('█',"block") -x=XML_('↓',"ShortDownArrow") ; x=XML_('è',"egrave") ; x=XML_('¬',"not") ; x=XML_('▄',"lhblk") -x=XML_('←',"larr") ; x=XML_('è','#x00e8') ; x=XML_('½',"frac12"); x=XML_('▀',"uhblk") -x=XML_('←',"leftarrow") ; x=XML_('ï',"iuml") ; x=XML_('½',"half") ; x=XML_('α',"alpha") -x=XML_('←',"ShortLeftArrow") ; x=XML_('ï','#x00ef') ; x=XML_('¼',"frac14"); x=XML_('ß',"beta") -x=XML_('1c'x,"rarr") ; x=XML_('î',"icirc") ; x=XML_('¡',"iexcl") ; x=XML_('ß',"szlig") -x=XML_('1c'x,"rightarrow") ; x=XML_('î','#x00ee') ; x=XML_('«',"laqru") ; x=XML_('ß','#x00df') -x=XML_('1c'x,"ShortRightArrow"); x=XML_('ì',"igrave") ; x=XML_('»',"raqru") ; x=XML_('Γ',"Gamma") -x=XML_('!',"excl") ; x=XML_('ì','#x00ec') ; x=XML_('░',"blk12") ; x=XML_('π',"pi") -x=XML_('"',"apos") ; x=XML_('Ä',"Auml") ; x=XML_('▒',"blk14") ; x=XML_('Σ',"Sigma") -x=XML_('$',"dollar") ; x=XML_('Ä','#x00c4') ; x=XML_('▓',"blk34") ; x=XML_('σ',"sigma") -x=XML_("'","quot") ; x=XML_('Å',"Aring") ; x=XML_('│',"boxv") ; x=XML_('µ',"mu") -x=XML_('*',"ast") ; x=XML_('Å','#x00c5') ; x=XML_('┤',"boxvl") ; x=XML_('τ',"tau") -x=XML_('/',"sol") ; x=XML_('É',"Eacute") ; x=XML_('╡',"boxvL") ; x=XML_('Φ',"phi") -x=XML_(':',"colon") ; x=XML_('É','#x00c9') ; x=XML_('╢',"boxVl") ; x=XML_('Θ',"Theta") -x=XML_('<',"lt") ; x=XML_('æ',"aelig") ; x=XML_('╖',"boxDl") ; x=XML_('δ',"delta") -x=XML_('=',"equals") ; x=XML_('æ','#x00e6') ; x=XML_('╕',"boxdL") ; x=XML_('∞',"infin") -x=XML_('>',"gt") ; x=XML_('Æ',"AElig") ; x=XML_('╣',"boxVL") ; x=XML_('φ',"Phi") -x=XML_('?',"quest") ; x=XML_('Æ','#x00c6') ; x=XML_('║',"boxV") ; x=XML_('ε',"epsilon") -x=XML_('@',"commat") ; x=XML_('ô',"ocirc") ; x=XML_('╗',"boxDL") ; x=XML_('∩',"cap") -x=XML_('[',"lbrack") ; x=XML_('ô','#x00f4') ; x=XML_('╝',"boxUL") ; x=XML_('≡',"equiv") -x=XML_('\',"bsol") ; x=XML_('ö',"ouml") ; x=XML_('╜',"boxUl") ; x=XML_('±',"plusmn") -x=XML_(']',"rbrack") ; x=XML_('ö','#x00f6') ; x=XML_('╛',"boxuL") ; x=XML_('±',"pm") -x=XML_('^',"Hat") ; x=XML_('ò',"ograve") ; x=XML_('┐',"boxdl") ; x=XML_('±',"PlusMinus") -x=XML_('`',"grave") ; x=XML_('ò','#x00f2') ; x=XML_('└',"boxur") ; x=XML_('≥',"ge") -x=XML_('{',"lbrace") ; x=XML_('û',"ucirc") ; x=XML_('┴',"bottom"); x=XML_('≤',"le") -x=XML_('{',"lcub") ; x=XML_('û','#x00fb') ; x=XML_('┴',"boxhu") ; x=XML_('÷',"div") -x=XML_('|',"vert") ; x=XML_('ù',"ugrave") ; x=XML_('┬',"boxhd") ; x=XML_('÷',"divide") -x=XML_('|',"verbar") ; x=XML_('ù','#x00f9') ; x=XML_('├',"boxvr") ; x=XML_('≈',"approx") -x=XML_('}',"rbrace") ; x=XML_('ÿ',"yuml") ; x=XML_('─',"boxh") ; x=XML_('∙',"bull") -x=XML_('}',"rcub") ; x=XML_('ÿ','#x00ff') ; x=XML_('┼',"boxvh") ; x=XML_('°',"deg") -x=XML_('Ç',"Ccedil") ; x=XML_('Ö',"Ouml") ; x=XML_('╞',"boxvR") ; x=XML_('·',"middot") -x=XML_('Ç','#x00c7') ; x=XML_('Ö','#x00d6') ; x=XML_('╟',"boxVr") ; x=XML_('·',"middledot") -x=XML_('ü',"uuml") ; x=XML_('Ü',"Uuml") ; x=XML_('╚',"boxUR") ; x=XML_('·',"centerdot") -x=XML_('ü','#x00fc') ; x=XML_('Ü','#x00dc') ; x=XML_('╔',"boxDR") ; x=XML_('·',"CenterDot") -x=XML_('é',"eacute") ; x=XML_('¢',"cent") ; x=XML_('╩',"boxHU") ; x=XML_('√',"radic") -x=XML_('é','#x00e9') ; x=XML_('£',"pound") ; x=XML_('╦',"boxHD") ; x=XML_('²',"sup2") -x=XML_('â',"acirc") ; x=XML_('¥',"yen") ; x=XML_('╠',"boxVR") ; x=XML_('■',"squart ") -return x +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +xml_: parse arg ,_ /*transkate an XML entity (&xxxx;) */ + xmlEntity! = '&'_";" + if pos(xmlEntity!, $)\==0 then $=changestr(xmlEntity!, $, arg(1) ) + if left(_, 2)=='#x' then do + xmlEntity!='&'left(_, 3)translate( substr(_, 4) )";" + $=changestr(xmlEntity!, $, arg(1) ) + end + return $ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +xmlTranE: procedure; parse arg $ /*Following are most of the chars in */ + /*the DOS (under Windows) codepage. */ +$=XML_('â',"ETH") ; $=XML_('ƒ',"fnof") ; $=XML_('═',"boxH") ; $=XML_('♥',"hearts") +$=XML_('â','#x00e2') ; $=XML_('á',"aacute"); $=XML_('╬',"boxVH") ; $=XML_('♦',"diams") +$=XML_('â','#x00e9') ; $=XML_('á','#x00e1'); $=XML_('╧',"boxHu") ; $=XML_('♣',"clubs") +$=XML_('ä',"auml") ; $=XML_('í',"iacute"); $=XML_('╨',"boxhU") ; $=XML_('♠',"spades") +$=XML_('ä','#x00e4') ; $=XML_('í','#x00ed'); $=XML_('╤',"boxHd") ; $=XML_('♂',"male") +$=XML_('à',"agrave") ; $=XML_('ó',"oacute"); $=XML_('╥',"boxhD") ; $=XML_('♀',"female") +$=XML_('à','#x00e0') ; $=XML_('ó','#x00f3'); $=XML_('╙',"boxUr") ; $=XML_('☼',"#x263c") +$=XML_('å',"aring") ; $=XML_('ú',"uacute"); $=XML_('╘',"boxuR") ; $=XML_('↕',"UpDownArrow") +$=XML_('å','#x00e5') ; $=XML_('ú','#x00fa'); $=XML_('╒',"boxdR") ; $=XML_('¶',"para") +$=XML_('ç',"ccedil") ; $=XML_('ñ',"ntilde"); $=XML_('╓',"boxDr") ; $=XML_('§',"sect") +$=XML_('ç','#x00e7') ; $=XML_('ñ','#x00f1'); $=XML_('╫',"boxVh") ; $=XML_('↑',"uarr") +$=XML_('ê',"ecirc") ; $=XML_('Ñ',"Ntilde"); $=XML_('╪',"boxvH") ; $=XML_('↑',"uparrow") +$=XML_('ê','#x00ea') ; $=XML_('Ñ','#x00d1'); $=XML_('┘',"boxul") ; $=XML_('↑',"ShortUpArrow") +$=XML_('ë',"euml") ; $=XML_('¿',"iquest"); $=XML_('┌',"boxdr") ; $=XML_('↓',"darr") +$=XML_('ë','#x00eb') ; $=XML_('⌐',"bnot") ; $=XML_('█',"block") ; $=XML_('↓',"downarrow") +$=XML_('è',"egrave") ; $=XML_('¬',"not") ; $=XML_('▄',"lhblk") ; $=XML_('↓',"ShortDownArrow") +$=XML_('è','#x00e8') ; $=XML_('½',"frac12"); $=XML_('▀',"uhblk") ; $=XML_('←',"larr") +$=XML_('ï',"iuml") ; $=XML_('½',"half") ; $=XML_('α',"alpha") ; $=XML_('←',"leftarrow") +$=XML_('ï','#x00ef') ; $=XML_('¼',"frac14"); $=XML_('ß',"beta") ; $=XML_('←',"ShortLeftArrow") +$=XML_('î',"icirc") ; $=XML_('¡',"iexcl") ; $=XML_('ß',"szlig") ; $=XML_('1c'x,"rarr") +$=XML_('î','#x00ee') ; $=XML_('«',"laqru") ; $=XML_('ß','#x00df') ; $=XML_('1c'x,"rightarrow") +$=XML_('ì',"igrave") ; $=XML_('»',"raqru") ; $=XML_('Γ',"Gamma") ; $=XML_('1c'x,"ShortRightArrow") +$=XML_('ì','#x00ec') ; $=XML_('░',"blk12") ; $=XML_('π',"pi") ; $=XML_('!',"excl") +$=XML_('Ä',"Auml") ; $=XML_('▒',"blk14") ; $=XML_('Σ',"Sigma") ; $=XML_('"',"apos") +$=XML_('Ä','#x00c4') ; $=XML_('▓',"blk34") ; $=XML_('σ',"sigma") ; $=XML_('$',"dollar") +$=XML_('Å',"Aring") ; $=XML_('│',"boxv") ; $=XML_('µ',"mu") ; $=XML_("'","quot") +$=XML_('Å','#x00c5') ; $=XML_('┤',"boxvl") ; $=XML_('τ',"tau") ; $=XML_('*',"ast") +$=XML_('É',"Eacute") ; $=XML_('╡',"boxvL") ; $=XML_('Φ',"phi") ; $=XML_('/',"sol") +$=XML_('É','#x00c9') ; $=XML_('╢',"boxVl") ; $=XML_('Θ',"Theta") ; $=XML_(':',"colon") +$=XML_('æ',"aelig") ; $=XML_('╖',"boxDl") ; $=XML_('δ',"delta") ; $=XML_('<',"lt") +$=XML_('æ','#x00e6') ; $=XML_('╕',"boxdL") ; $=XML_('∞',"infin") ; $=XML_('=',"equals") +$=XML_('Æ',"AElig") ; $=XML_('╣',"boxVL") ; $=XML_('φ',"Phi") ; $=XML_('>',"gt") +$=XML_('Æ','#x00c6') ; $=XML_('║',"boxV") ; $=XML_('ε',"epsilon") ; $=XML_('?',"quest") +$=XML_('ô',"ocirc") ; $=XML_('╗',"boxDL") ; $=XML_('∩',"cap") ; $=XML_('_',"commat") +$=XML_('ô','#x00f4') ; $=XML_('╝',"boxUL") ; $=XML_('≡',"equiv") ; $=XML_('[',"lbrack") +$=XML_('ö',"ouml") ; $=XML_('╜',"boxUl") ; $=XML_('±',"plusmn") ; $=XML_('\',"bsol") +$=XML_('ö','#x00f6') ; $=XML_('╛',"boxuL") ; $=XML_('±',"pm") ; $=XML_(']',"rbrack") +$=XML_('ò',"ograve") ; $=XML_('┐',"boxdl") ; $=XML_('±',"PlusMinus") ; $=XML_('^',"Hat") +$=XML_('ò','#x00f2') ; $=XML_('└',"boxur") ; $=XML_('≥',"ge") ; $=XML_('`',"grave") +$=XML_('û',"ucirc") ; $=XML_('┴',"bottom"); $=XML_('≤',"le") ; $=XML_('{',"lbrace") +$=XML_('û','#x00fb') ; $=XML_('┴',"boxhu") ; $=XML_('÷',"div") ; $=XML_('{',"lcub") +$=XML_('ù',"ugrave") ; $=XML_('┬',"boxhd") ; $=XML_('÷',"divide") ; $=XML_('|',"vert") +$=XML_('ù','#x00f9') ; $=XML_('├',"boxvr") ; $=XML_('≈',"approx") ; $=XML_('|',"verbar") +$=XML_('ÿ',"yuml") ; $=XML_('─',"boxh") ; $=XML_('∙',"bull") ; $=XML_('}',"rbrace") +$=XML_('ÿ','#x00ff') ; $=XML_('┼',"boxvh") ; $=XML_('°',"deg") ; $=XML_('}',"rcub") +$=XML_('Ö',"Ouml") ; $=XML_('╞',"boxvR") ; $=XML_('·',"middot") ; $=XML_('Ç',"Ccedil") +$=XML_('Ö','#x00d6') ; $=XML_('╟',"boxVr") ; $=XML_('·',"middledot") ; $=XML_('Ç','#x00c7') +$=XML_('Ü',"Uuml") ; $=XML_('╚',"boxUR") ; $=XML_('·',"centerdot") ; $=XML_('ü',"uuml") +$=XML_('Ü','#x00dc') ; $=XML_('╔',"boxDR") ; $=XML_('·',"CenterDot") ; $=XML_('ü','#x00fc') +$=XML_('¢',"cent") ; $=XML_('╩',"boxHU") ; $=XML_('√',"radic") ; $=XML_('é',"eacute") +$=XML_('£',"pound") ; $=XML_('╦',"boxHD") ; $=XML_('²',"sup2") ; $=XML_('é','#x00e9') +$=XML_('¥',"yen") ; $=XML_('╠',"boxVR") ; $=XML_('■',"square ") ; $=XML_('â',"acirc") +return $ diff --git a/Task/XML-Input/VBA/xml-input.vba b/Task/XML-Input/VBA/xml-input.vba new file mode 100644 index 0000000000..6ebbd5aba4 --- /dev/null +++ b/Task/XML-Input/VBA/xml-input.vba @@ -0,0 +1,28 @@ +Option Explicit + +Const strXml As String = "" & _ +"" & _ + "" & _ + "" & _ + "" & _ + "" & _ + "" & _ + "" & _ + "" & _ +"" + +Sub Main_Xml() +Dim MyXml As Object +Dim myNodes, myNode + + With CreateObject("MSXML2.DOMDocument") + .LoadXML strXml + Set myNodes = .getElementsByTagName("Student") + End With + If Not myNodes Is Nothing Then + For Each myNode In myNodes + Debug.Print myNode.getAttribute("Name") + Next + End If + Set myNodes = Nothing +End Sub diff --git a/Task/XML-Output/Go/xml-output-3.go b/Task/XML-Output/Go/xml-output-3.go index 30a6a49bc3..d1950c1697 100644 --- a/Task/XML-Output/Go/xml-output-3.go +++ b/Task/XML-Output/Go/xml-output-3.go @@ -1,9 +1,9 @@ package main import ( - "bytes" "encoding/xml" "fmt" + "strings" "text/template" ) @@ -17,7 +17,7 @@ var tmpl = ` ` func xmlEscapeString(s string) string { - var b bytes.Buffer + var b strings.Builder xml.Escape(&b, []byte(s)) return b.String() } @@ -28,7 +28,7 @@ func main() { // Define function required by task description. xRemarks := func(crms []crm) (string, error) { - var b bytes.Buffer + var b strings.Builder err := xt.Execute(&b, crms) return b.String(), err } diff --git a/Task/XML-Output/Perl-6/xml-output-1.pl6 b/Task/XML-Output/Perl-6/xml-output-1.pl6 new file mode 100644 index 0000000000..1f6aa7fba8 --- /dev/null +++ b/Task/XML-Output/Perl-6/xml-output-1.pl6 @@ -0,0 +1,11 @@ +use XML::Writer; + +my @students = + [ Q[April], Q[Bubbly: I'm > Tam and <= Emily] ], + [ Q[Tam O'Shanter], Q[Burns: "When chapman billies leave the street ..."] ], + [ Q[Emily], Q[Short & shrift] ] +; + +my @lines = map { :Character[:name(.[0]), .[1]] }, @students; + +say XML::Writer.serialize( CharacterRemarks => @lines ); diff --git a/Task/XML-Output/Perl-6/xml-output-2.pl6 b/Task/XML-Output/Perl-6/xml-output-2.pl6 new file mode 100644 index 0000000000..a1daa8b5e5 --- /dev/null +++ b/Task/XML-Output/Perl-6/xml-output-2.pl6 @@ -0,0 +1,3 @@ +Bubbly: I'm > Tam and <= Emily +Burns: "When chapman billies leave the street ..." +Short & shrift diff --git a/Task/XML-Output/REXX/xml-output.rexx b/Task/XML-Output/REXX/xml-output.rexx index f534f5f379..0d8853ae4d 100644 --- a/Task/XML-Output/REXX/xml-output.rexx +++ b/Task/XML-Output/REXX/xml-output.rexx @@ -1,18 +1,18 @@ -/*REXX program creates an HTML list of character names and remarks. */ +/*REXX program creates an HTML (XML) list of character names and corresponding remarks. */ charname. = charname.1 = "April" charname.2 = "Tam O'Shanter" charname.3 = "Emily" - do i=1 while charname.i\=='' - say 'charname' i '=' charname.i - end /*i*/; say + do i=1 while charname.i\=='' + say 'charname' i '=' charname.i + end /*i*/; say remark. = remark.1 = "I'm > Tam and <= Emily" remark.2 = "When chapman billies leave the street ..." remark.3 = "Short & shift" - do k=1 while remark.k\=='' - say ' remark' k '=' remark.k - end /*k*/; say + do k=1 while remark.k\=='' + say ' remark' k '=' remark.k + end /*k*/; say items = 0 header = 'CharacterRemarks' header = header'>' @@ -20,97 +20,98 @@ header = header'>' do j=1 while charname.j\=='' _=charname.j if j==1 then call create '<'header - call create ' "' ||, + call create ' "' ||, char2xml(remark.j)'"' end /*j*/ if create.0\==0 then call create '',"gt") ; x=XML_('Æ',"AElig") ; x=XML_('╣',"boxVL") ; x=XML_('φ',"Phi") -x=XML_('?',"quest") ; x=XML_('Æ','#x00c6') ; x=XML_('║',"boxV") ; x=XML_('ε',"epsilon") -x=XML_('@',"commat") ; x=XML_('ô',"ocirc") ; x=XML_('╗',"boxDL") ; x=XML_('∩',"cap") -x=XML_('[',"lbrack") ; x=XML_('ô','#x00f4') ; x=XML_('╝',"boxUL") ; x=XML_('≡',"equiv") -x=XML_('\',"bsol") ; x=XML_('ö',"ouml") ; x=XML_('╜',"boxUl") ; x=XML_('±',"plusmn") -x=XML_(']',"rbrack") ; x=XML_('ö','#x00f6') ; x=XML_('╛',"boxuL") ; x=XML_('±',"pm") -x=XML_('^',"Hat") ; x=XML_('ò',"ograve") ; x=XML_('┐',"boxdl") ; x=XML_('±',"PlusMinus") -x=XML_('`',"grave") ; x=XML_('ò','#x00f2') ; x=XML_('└',"boxur") ; x=XML_('≥',"ge") -x=XML_('{',"lbrace") ; x=XML_('û',"ucirc") ; x=XML_('┴',"bottom"); x=XML_('≤',"le") -x=XML_('{',"lcub") ; x=XML_('û','#x00fb') ; x=XML_('┴',"boxhu") ; x=XML_('÷',"div") -x=XML_('|',"vert") ; x=XML_('ù',"ugrave") ; x=XML_('┬',"boxhd") ; x=XML_('÷',"divide") -x=XML_('|',"verbar") ; x=XML_('ù','#x00f9') ; x=XML_('├',"boxvr") ; x=XML_('≈',"approx") -x=XML_('}',"rbrace") ; x=XML_('ÿ',"yuml") ; x=XML_('─',"boxh") ; x=XML_('∙',"bull") -x=XML_('}',"rcub") ; x=XML_('ÿ','#x00ff') ; x=XML_('┼',"boxvh") ; x=XML_('°',"deg") -x=XML_('Ç',"Ccedil") ; x=XML_('Ö',"Ouml") ; x=XML_('╞',"boxvR") ; x=XML_('·',"middot") -x=XML_('Ç','#x00c7') ; x=XML_('Ö','#x00d6') ; x=XML_('╟',"boxVr") ; x=XML_('·',"middledot") -x=XML_('ü',"uuml") ; x=XML_('Ü',"Uuml") ; x=XML_('╚',"boxUR") ; x=XML_('·',"centerdot") -x=XML_('ü','#x00fc') ; x=XML_('Ü','#x00dc') ; x=XML_('╔',"boxDR") ; x=XML_('·',"CenterDot") -x=XML_('é',"eacute") ; x=XML_('¢',"cent") ; x=XML_('╩',"boxHU") ; x=XML_('√',"radic") -x=XML_('é','#x00e9') ; x=XML_('£',"pound") ; x=XML_('╦',"boxHD") ; x=XML_('²',"sup2") -x=XML_('â',"acirc") ; x=XML_('¥',"yen") ; x=XML_('╠',"boxVR") ; x=XML_('■',"squart ") +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +char2xml: procedure; parse arg $ + amper = pos('&', $)\==0 /* & has to be treated special. */ + semi = pos(';', $)\==0 /* ; " " " " " */ + #=0 /* [↓] find a free/unused character···*/ + if amper then do /* ··· and translate freely. */ + do j=0 for 255; ?=d2c(j); if pos(?, $)==0 then leave + end /*j*/ + $=translate($, ?, "&"); #= j + 1 + end + /* [↓] find a free/unused character···*/ + if semi then do /* ··· and translate freely. */ + do k=# for 255; ?=d2c(k); if pos(?, $)==0 then leave + end /*k*/ + $=translate($, ?, ";") + end -if a then x=xml_(?,"amp") /*if there was an ampersand, translate it*/ -if b then x=xml_(??,"semi") /* " " " " semicolon, " "*/ -return x +/*───── Following are most of the characters in the DOS (or DOS Windows) codepage 437 ──────────*/ + +$=XML_('â',"ETH") ; $=XML_('ƒ',"fnof") ; $=XML_('═',"boxH") ; $=XML_('♥',"hearts") +$=XML_('â','#x00e2') ; $=XML_('á',"aacute"); $=XML_('╬',"boxVH") ; $=XML_('♦',"diams") +$=XML_('â','#x00e9') ; $=XML_('á','#x00e1'); $=XML_('╧',"boxHu") ; $=XML_('♣',"clubs") +$=XML_('ä',"auml") ; $=XML_('í',"iacute"); $=XML_('╨',"boxhU") ; $=XML_('♠',"spades") +$=XML_('ä','#x00e4') ; $=XML_('í','#x00ed'); $=XML_('╤',"boxHd") ; $=XML_('♂',"male") +$=XML_('à',"agrave") ; $=XML_('ó',"oacute"); $=XML_('╥',"boxhD") ; $=XML_('♀',"female") +$=XML_('à','#x00e0') ; $=XML_('ó','#x00f3'); $=XML_('╙',"boxUr") ; $=XML_('☼',"#x263c") +$=XML_('å',"aring") ; $=XML_('ú',"uacute"); $=XML_('╘',"boxuR") ; $=XML_('↕',"UpDownArrow") +$=XML_('å','#x00e5') ; $=XML_('ú','#x00fa'); $=XML_('╒',"boxdR") ; $=XML_('¶',"para") +$=XML_('ç',"ccedil") ; $=XML_('ñ',"ntilde"); $=XML_('╓',"boxDr") ; $=XML_('§',"sect") +$=XML_('ç','#x00e7') ; $=XML_('ñ','#x00f1'); $=XML_('╫',"boxVh") ; $=XML_('↑',"uarr") +$=XML_('ê',"ecirc") ; $=XML_('Ñ',"Ntilde"); $=XML_('╪',"boxvH") ; $=XML_('↑',"uparrow") +$=XML_('ê','#x00ea') ; $=XML_('Ñ','#x00d1'); $=XML_('┘',"boxul") ; $=XML_('↑',"ShortUpArrow") +$=XML_('ë',"euml") ; $=XML_('¿',"iquest"); $=XML_('┌',"boxdr") ; $=XML_('↓',"darr") +$=XML_('ë','#x00eb') ; $=XML_('⌐',"bnot") ; $=XML_('█',"block") ; $=XML_('↓',"downarrow") +$=XML_('è',"egrave") ; $=XML_('¬',"not") ; $=XML_('▄',"lhblk") ; $=XML_('↓',"ShortDownArrow") +$=XML_('è','#x00e8') ; $=XML_('½',"frac12"); $=XML_('▀',"uhblk") ; $=XML_('←',"larr") +$=XML_('ï',"iuml") ; $=XML_('½',"half") ; $=XML_('α',"alpha") ; $=XML_('←',"leftarrow") +$=XML_('ï','#x00ef') ; $=XML_('¼',"frac14"); $=XML_('ß',"beta") ; $=XML_('←',"ShortLeftArrow") +$=XML_('î',"icirc") ; $=XML_('¡',"iexcl") ; $=XML_('ß',"szlig") ; $=XML_('1c'x,"rarr") +$=XML_('î','#x00ee') ; $=XML_('«',"laqru") ; $=XML_('ß','#x00df') ; $=XML_('1c'x,"rightarrow") +$=XML_('ì',"igrave") ; $=XML_('»',"raqru") ; $=XML_('Γ',"Gamma") ; $=XML_('1c'x,"ShortRightArrow") +$=XML_('ì','#x00ec') ; $=XML_('░',"blk12") ; $=XML_('π',"pi") ; $=XML_('!',"excl") +$=XML_('Ä',"Auml") ; $=XML_('▒',"blk14") ; $=XML_('Σ',"Sigma") ; $=XML_('"',"apos") +$=XML_('Ä','#x00c4') ; $=XML_('▓',"blk34") ; $=XML_('σ',"sigma") ; $=XML_('$',"dollar") +$=XML_('Å',"Aring") ; $=XML_('│',"boxv") ; $=XML_('µ',"mu") ; $=XML_("'","quot") +$=XML_('Å','#x00c5') ; $=XML_('┤',"boxvl") ; $=XML_('τ',"tau") ; $=XML_('*',"ast") +$=XML_('É',"Eacute") ; $=XML_('╡',"boxvL") ; $=XML_('Φ',"phi") ; $=XML_('/',"sol") +$=XML_('É','#x00c9') ; $=XML_('╢',"boxVl") ; $=XML_('Θ',"Theta") ; $=XML_(':',"colon") +$=XML_('æ',"aelig") ; $=XML_('╖',"boxDl") ; $=XML_('δ',"delta") ; $=XML_('<',"lt") +$=XML_('æ','#x00e6') ; $=XML_('╕',"boxdL") ; $=XML_('∞',"infin") ; $=XML_('=',"equals") +$=XML_('Æ',"AElig") ; $=XML_('╣',"boxVL") ; $=XML_('φ',"Phi") ; $=XML_('>',"gt") +$=XML_('Æ','#x00c6') ; $=XML_('║',"boxV") ; $=XML_('ε',"epsilon") ; $=XML_('?',"quest") +$=XML_('ô',"ocirc") ; $=XML_('╗',"boxDL") ; $=XML_('∩',"cap") ; $=XML_('_',"commat") +$=XML_('ô','#x00f4') ; $=XML_('╝',"boxUL") ; $=XML_('≡',"equiv") ; $=XML_('[',"lbrack") +$=XML_('ö',"ouml") ; $=XML_('╜',"boxUl") ; $=XML_('±',"plusmn") ; $=XML_('\',"bsol") +$=XML_('ö','#x00f6') ; $=XML_('╛',"boxuL") ; $=XML_('±',"pm") ; $=XML_(']',"rbrack") +$=XML_('ò',"ograve") ; $=XML_('┐',"boxdl") ; $=XML_('±',"PlusMinus") ; $=XML_('^',"Hat") +$=XML_('ò','#x00f2') ; $=XML_('└',"boxur") ; $=XML_('≥',"ge") ; $=XML_('`',"grave") +$=XML_('û',"ucirc") ; $=XML_('┴',"bottom"); $=XML_('≤',"le") ; $=XML_('{',"lbrace") +$=XML_('û','#x00fb') ; $=XML_('┴',"boxhu") ; $=XML_('÷',"div") ; $=XML_('{',"lcub") +$=XML_('ù',"ugrave") ; $=XML_('┬',"boxhd") ; $=XML_('÷',"divide") ; $=XML_('|',"vert") +$=XML_('ù','#x00f9') ; $=XML_('├',"boxvr") ; $=XML_('≈',"approx") ; $=XML_('|',"verbar") +$=XML_('ÿ',"yuml") ; $=XML_('─',"boxh") ; $=XML_('∙',"bull") ; $=XML_('}',"rbrace") +$=XML_('ÿ','#x00ff') ; $=XML_('┼',"boxvh") ; $=XML_('°',"deg") ; $=XML_('}',"rcub") +$=XML_('Ö',"Ouml") ; $=XML_('╞',"boxvR") ; $=XML_('·',"middot") ; $=XML_('Ç',"Ccedil") +$=XML_('Ö','#x00d6') ; $=XML_('╟',"boxVr") ; $=XML_('·',"middledot") ; $=XML_('Ç','#x00c7') +$=XML_('Ü',"Uuml") ; $=XML_('╚',"boxUR") ; $=XML_('·',"centerdot") ; $=XML_('ü',"uuml") +$=XML_('Ü','#x00dc') ; $=XML_('╔',"boxDR") ; $=XML_('·',"CenterDot") ; $=XML_('ü','#x00fc') +$=XML_('¢',"cent") ; $=XML_('╩',"boxHU") ; $=XML_('√',"radic") ; $=XML_('é',"eacute") +$=XML_('£',"pound") ; $=XML_('╦',"boxHD") ; $=XML_('²',"sup2") ; $=XML_('é','#x00e9') +$=XML_('¥',"yen") ; $=XML_('╠',"boxVR") ; $=XML_('■',"square ") ; $=XML_('â',"acirc") + + if amper then $=xml_(?, "amp") /*Was there an ampersand? Translate it*/ + if semi then $=xml_(??, "semi") /* " " " semicolon? " "*/ + return $ +/*──────────────────────────────────────────────────────────────────────────────────────*/ +create: items= items + 1 /*bump the count of items in the list. */ + create.items= arg(1) /*add item to the CREATE list. */ + create.0 = items /*indicate how many items in the list. */ + return +/*──────────────────────────────────────────────────────────────────────────────────────*/ +xml_: parse arg _ /*make an XML entity (&xxxx;) */ + if pos(_, $)\==0 then return changestr(_, $, "&"arg(2)";") + return $ diff --git a/Task/XML-XPath/C/xml-xpath.c b/Task/XML-XPath/C/xml-xpath.c new file mode 100644 index 0000000000..be8c0b1d78 --- /dev/null +++ b/Task/XML-XPath/C/xml-xpath.c @@ -0,0 +1,57 @@ +/*Abhishek Ghosh, 10th March 2018*/ + +#include +#include + +xmlDocPtr getdoc (char *docname) { + xmlDocPtr doc; + doc = xmlParseFile(docname); + + return doc; +} + +xmlXPathObjectPtr getnodeset (xmlDocPtr doc, xmlChar *xpath){ + + xmlXPathContextPtr context; + xmlXPathObjectPtr result; + + context = xmlXPathNewContext(doc); + + result = xmlXPathEvalExpression(xpath, context); + xmlXPathFreeContext(context); + + return result; +} + +int main(int argc, char **argv) { + + if (argc <= 2) { + printf("Usage: %s \n", argv[0]); + return 0; + } + + char *docname; + xmlDocPtr doc; + xmlChar *xpath = (xmlChar*) argv[2]; + xmlNodeSetPtr nodeset; + xmlXPathObjectPtr result; + int i; + xmlChar *keyword; + + docname = argv[1]; + doc = getdoc(docname); + result = getnodeset (doc, xpath); + if (result) { + nodeset = result->nodesetval; + for (i=0; i < nodeset->nodeNr; i++) { + xmlNodePtr titleNode = nodeset->nodeTab[i]; + keyword = xmlNodeListGetString(doc, titleNode->xmlChildrenNode, 1); + printf("Value %d: %s\n",i+1, keyword); + xmlFree(keyword); + } + xmlXPathFreeObject (result); + } + xmlFreeDoc(doc); + xmlCleanupParser(); + return 0; +} diff --git a/Task/XML-XPath/Perl-6/xml-xpath.pl6 b/Task/XML-XPath/Perl-6/xml-xpath.pl6 new file mode 100644 index 0000000000..de61aacebd --- /dev/null +++ b/Task/XML-XPath/Perl-6/xml-xpath.pl6 @@ -0,0 +1,37 @@ +use XML::XPath; + +my $XML = XML::XPath.new(xml => q:to/END/); + +
+ + Invisibility Cream + 14.50 + Makes you invisible + + + Levitation Salve + 23.99 + Levitate yourself for up to 3 hours per application + +
+
+ + Blork and Freen Instameal + 4.95 + A tasty meal in a tablet; just add water + + + Grob winglets + 3.56 + Tender winglets of Grob. Just add water + +
+
+END + +put "First item:\n", $XML.find('//item[1]')[0]; + +put "\nPrice elements:"; +.contents.put for $XML.find('//price').List; + +put "\nName elements:\n", $XML.find('//name')».contents.join: ', '; diff --git a/Task/Xiaolin-Wus-line-algorithm/C/xiaolin-wus-line-algorithm-2.c b/Task/Xiaolin-Wus-line-algorithm/C/xiaolin-wus-line-algorithm-2.c index b62b6488be..6c494fcdc0 100644 --- a/Task/Xiaolin-Wus-line-algorithm/C/xiaolin-wus-line-algorithm-2.c +++ b/Task/Xiaolin-Wus-line-algorithm/C/xiaolin-wus-line-algorithm-2.c @@ -59,7 +59,7 @@ void draw_line_antialias( plot_(xpxl2, ypxl2 + 1, fpart_(yend) * xgap); int x; - for(x=xpxl1+1; x <= (xpxl2-1); x++) { + for(x=xpxl1+1; x < xpxl2; x++) { plot_(x, ipart_(intery), rfpart_(intery)); plot_(x, ipart_(intery) + 1, fpart_(intery)); intery += gradient; @@ -76,7 +76,7 @@ void draw_line_antialias( int ypxl1 = yend; int xpxl1 = ipart_(xend); plot_(xpxl1, ypxl1, rfpart_(xend)*ygap); - plot_(xpxl1, ypxl1+1, fpart_(xend)*ygap); + plot_(xpxl1 + 1, ypxl1, fpart_(xend)*ygap); double interx = xend + gradient; yend = round_(y2); @@ -85,10 +85,10 @@ void draw_line_antialias( int ypxl2 = yend; int xpxl2 = ipart_(xend); plot_(xpxl2, ypxl2, rfpart_(xend) * ygap); - plot_(xpxl2, ypxl2 + 1, fpart_(xend) * ygap); + plot_(xpxl2 + 1, ypxl2, fpart_(xend) * ygap); int y; - for(y=ypxl1+1; y <= (ypxl2-1); y++) { + for(y=ypxl1+1; y < ypxl2; y++) { plot_(ipart_(interx), y, rfpart_(interx)); plot_(ipart_(interx) + 1, y, fpart_(interx)); interx += gradient; diff --git a/Task/Xiaolin-Wus-line-algorithm/Julia/xiaolin-wus-line-algorithm.julia b/Task/Xiaolin-Wus-line-algorithm/Julia/xiaolin-wus-line-algorithm.julia new file mode 100644 index 0000000000..efdbdc2587 --- /dev/null +++ b/Task/Xiaolin-Wus-line-algorithm/Julia/xiaolin-wus-line-algorithm.julia @@ -0,0 +1,75 @@ +using Images + +fpart(x) = mod(x, one(x)) +rfpart(x) = one(x) - fpart(x) + +function drawline!(img::Matrix{Gray{N0f8}}, x0::Integer, y0::Integer, x1::Integer, y1::Integer) + steep = abs(y1 - y0) > abs(x1 - x0) + + if steep + x0, y0 = y0, x0 + x1, y1 = y1, x1 + end + if x0 > x1 + x0, x1 = x1, x0 + y0, y1 = y1, y0 + end + + dx = x1 - x0 + dy = y1 - y0 + grad = dy / dx + + if iszero(dx) + grad = oftype(grad, 1.0) + end + + # handle first endpoint + xend = round(Int, x0) + yend = y0 + grad * (xend - x0) + xgap = rfpart(x0 + 0.5) + xpxl1 = xend + ypxl1 = floor(Int, yend) + + if steep + img[ypxl1, xpxl1] = rfpart(yend) * xgap + img[ypxl1+1, xpxl1] = fpart(yend) * xgap + else + img[xpxl1, ypxl1 ] = rfpart(yend) * xgap + img[xpxl1, ypxl1+1] = fpart(yend) * xgap + end + intery = yend + grad # first y-intersection for the main loop + + # handle second endpoint + xend = round(Int, x1) + yend = y1 + grad * (xend - x1) + xgap = fpart(x1 + 0.5) + xpxl2 = xend + ypxl2 = floor(Int, yend) + if steep + img[ypxl2, xpxl2] = rfpart(yend) * xgap + img[ypxl2+1, xpxl2] = fpart(yend) * xgap + else + img[xpxl2, ypxl2 ] = rfpart(yend) * xgap + img[xpxl2, ypxl2+1] = fpart(yend) * xgap + end + + # main loop + if steep + for x in xpxl1+1:xpxl2-1 + img[floor(Int, intery), x] = rfpart(intery) + img[floor(Int, intery)+1, x] = fpart(intery) + intery += grad + end + else + for x in xpxl1+1:xpxl2-1 + img[x, floor(Int, intery) ] = rfpart(intery) + img[x, floor(Int, intery)+1] = fpart(intery) + intery += grad + end + end + + return img +end + +img = fill(Gray(1.0N0f8), 250, 250); +drawline!(img, 8, 8, 192, 154) diff --git a/Task/Xiaolin-Wus-line-algorithm/REXX/xiaolin-wus-line-algorithm.rexx b/Task/Xiaolin-Wus-line-algorithm/REXX/xiaolin-wus-line-algorithm.rexx index 5be0e1e5ac..71354aa4f8 100644 --- a/Task/Xiaolin-Wus-line-algorithm/REXX/xiaolin-wus-line-algorithm.rexx +++ b/Task/Xiaolin-Wus-line-algorithm/REXX/xiaolin-wus-line-algorithm.rexx @@ -1,4 +1,4 @@ -/*REXX program plots/draws (ASCII) a line using the Xiaolin Wu line algorithm. */ +/*REXX program plots/draws (ASCII) a line using the Xiaolin Wu line algorithm. */ background= '·' /*background character: a middle-dot. */ image.= background /*fill the array with middle-dots. */ plotC= '░▒▓█' /*characters used for plotting points. */ @@ -17,11 +17,11 @@ minX=0; minY=0 /*use these as the limits for p maxX=0; maxY=0 /* " " " " " " " */ call drawLine xi, yi, xf, yf /*invoke subroutine and graph the line.*/ border=2 /*allow additional space (plot border).*/ -minX=minX - border * 2; maxX=maxX+border * 2 /*preserve screen's aspect ratio {*2}.*/ -minY=minY - border ; maxY=maxY+border - do y=maxY to minY by -1; _= /*construct a row.*/ - do x=minX to maxX; _=_ || image.x.y; end /*x*/ - say _ /*display the constructed row to term. */ +minX=minX - border * 2; maxX=maxX + border * 2 /*preserve screen's aspect ratio {*2}.*/ +minY=minY - border ; maxY=maxY + border + do y=maxY to minY by -1; $= /*construct a row.*/ + do x=minX to maxX; $=$ || image.x.y; end /*x*/ + say $ /*display the constructed row to term. */ end /*y*/ /*graph is cropped by the MINs and MAXs*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ @@ -42,19 +42,19 @@ drawLine: parse arg x1,y1,x2,y2; switchXY=0; dx=x2-x1 call plotXY xpx12, ypx12 , brite(1 - fpart(yend*xgap)), switchXY call plotXY xpx12, ypx12+1, brite( fpart(yend*xgap)), switchXY - do x=xpx11+1 to xpx12-1 /*◄───draw the line.═════════════*/ - !intery=floor(intery) - call plotXY x, !intery , brite(1 - fpart(intery)), switchXY - call plotXY x, !intery+1, brite( fpart(intery)), switchXY - intery=intery + gradient - end /*x*/ + do x=xpx11+1 to xpx12-1 /*◄═════════════════draw the line.═════════════*/ + !intery=floor(intery) + call plotXY x, !intery , brite(1 - fpart(intery)), switchXY + call plotXY x, !intery+1, brite( fpart(intery)), switchXY + intery=intery + gradient + end /*x*/ return /*──────────────────────────────────────────────────────────────────────────────────────*/ brite: return substr(background || plotC, 1 + round( abs( arg(1) ) * length(plotC)), 1) -floor: parse arg ?; _=trunc(?); return _ - (?<0) * (?\=_) -fpart: parse arg ?; return abs(? - trunc(?)) +floor: parse arg #; _=trunc(#); return _ - (#<0) * (#\=_) +fpart: parse arg #; return abs(# - trunc(#) ) round: return format(arg(1), , word(arg(2) 0, 1) ) /*──────────────────────────────────────────────────────────────────────────────────────*/ plotXY: parse arg xx,yy,bc,switchYX; if switchYX then parse arg yy,xx - image.xx.yy=bc; minX=min(minX, xx); maxX=max(maxX,xx) - minY=min(minY, yy); maxY=max(maxY,yy); return + image.xx.yy=bc; minX=min(minX, xx); maxX=max(maxX,xx) + minY=min(minY, yy); maxY=max(maxY,yy); return diff --git a/Task/Y-combinator/Elena/y-combinator.elena b/Task/Y-combinator/Elena/y-combinator.elena index bad9d303b9..aebe9ce19f 100644 --- a/Task/Y-combinator/Elena/y-combinator.elena +++ b/Task/Y-combinator/Elena/y-combinator.elena @@ -3,14 +3,14 @@ import extensions. singleton YCombinator { fix : func - = (:f)[(:x)[ x eval:x ] eval(:g)[ f eval(:x)[(g eval:g) eval:x] ]] eval:func. + = (:f)[(:x)[ x(x) ] eval(:g)[ f eval(:x)[(g(g)) eval:x] ]] eval:func. } program = [ - var fib := YCombinator fix(:f)((:i)( (i <= 1) ifTrue:[^i] ifFalse:[^f eval(i-1) + f eval(i-2) ] )). - var fact := YCombinator fix(:f)((:i)((i == 0) ifTrue:[^1] ifFalse:[^f eval(i-1) * i] )). + var fib := YCombinator fix(:f)((:i)( (i <= 1) ifTrue:[^i] ifFalse:[^f(i-1) + f(i-2) ] )). + var fact := YCombinator fix(:f)((:i)((i == 0) ifTrue:[^1] ifFalse:[^f(i-1) * i] )). - console printLine("fib(10)=",fib eval(10)). - console printLine("fact(10)=",fact eval(10)). + console printLine("fib(10)=",fib(10)). + console printLine("fact(10)=",fact(10)). ]. diff --git a/Task/Y-combinator/Elm/y-combinator.elm b/Task/Y-combinator/Elm/y-combinator.elm new file mode 100644 index 0000000000..bd88855320 --- /dev/null +++ b/Task/Y-combinator/Elm/y-combinator.elm @@ -0,0 +1,18 @@ +import Html exposing (text) + +type Mu a b = Roll (Mu a b -> a -> b) + +unroll : Mu a b -> (Mu a b -> a -> b) +unroll (Roll x) = x + +fix : ((a -> b) -> (a -> b)) -> (a -> b) +fix f = let g r = f (\v -> unroll r r v) + in g (Roll g) + +fac : Int -> Int +fac = fix <| + \f n -> if n <= 0 + then 1 + else n * f (n - 1) + +main = text <| toString <| fac 5 diff --git a/Task/Y-combinator/Kitten/y-combinator.kitten b/Task/Y-combinator/Kitten/y-combinator.kitten new file mode 100644 index 0000000000..c42b1c75d3 --- /dev/null +++ b/Task/Y-combinator/Kitten/y-combinator.kitten @@ -0,0 +1,18 @@ +define y (S..., (S..., (S... -> T...) -> T...) -> T...): + -> f; { f y } f call + +define fac (Int32, (Int32 -> Int32) -> Int32): + -> x, rec; + if (x <= 1) { 1 } else { (x - 1) rec call * x } + +define fib (Int32, (Int32 -> Int32) -> Int32): + -> x, rec; + if (x <= 2): + 1 + else: + (x - 1) rec call -> a; + (x - 2) rec call -> b; + a + b + +5 \fac y say // 120 +10 \fib y say // 55 diff --git a/Task/Y-combinator/Python/y-combinator-3.py b/Task/Y-combinator/Python/y-combinator-3.py new file mode 100644 index 0000000000..cd6b6dd463 --- /dev/null +++ b/Task/Y-combinator/Python/y-combinator-3.py @@ -0,0 +1 @@ +Y = lambda b: ((lambda f: b(lambda *x: f(f)(*x)))((lambda f: b(lambda *x: f(f)(*x))))) diff --git a/Task/Y-combinator/Rust/y-combinator.rust b/Task/Y-combinator/Rust/y-combinator.rust index b098980cb3..9ffa9624d8 100644 --- a/Task/Y-combinator/Rust/y-combinator.rust +++ b/Task/Y-combinator/Rust/y-combinator.rust @@ -13,9 +13,18 @@ trait Apply { fn apply( &self, &Apply, T ) -> R; } -impl Apply for F where F: Fn( &Apply, T ) -> R { +// In Rust, closures fall into three kinds: FnOnce, FnMut and Fn. +// FnOnce assumed to be able to be called just once if it is not Clone. It is impossible to +// write recursive FnOnce that is not Clone. +// All FnMut are also FnOnce, although you can call them multiple times, they are not allow to +// have a reference to themselves. So it is also not possible to write recursive FnMut closures +// that is not Clone. +// All Fn are also FnMut, and all closures of Fn are also Clone. However, programmers can create +// Fn objects that are not Clone +// The following address all closures that is Clone, and those are Fn. +impl Apply for F where F: FnOnce( &Apply, T ) -> R + Clone { fn apply( &self, f: &Apply, t: T ) -> R { - self( f, t ) + (self.clone())( f, t ) // If we were to pass in self as f, we get - // NOTE: Each letter is an individual symbol. @@ -24,13 +33,19 @@ impl Apply for F where F: Fn( &Apply, T ) -> R { // => λs.ss } } - -// Here you take a reference to the function you want to recurse, AND the input, and return the result. -// But, you are NOT a recursive version of the given function... -// You CAN, of course, wrap this in a closure. -fn y_apply( f: &F, t: T ) -> R where F: Fn( &Fn( T ) -> R, T ) -> R { - ( &|x: &Apply, y| x.apply( x, y ) ) - .apply( &|x: &Apply, y| f( &|z| x.apply( x, z ), y ), t ) +//This will work for all Fn objects, not just closures +//And it is a little bit more efficient for Fn closures as it do not clone itself. +//However under 1.26 it is not possible to define both. We will +//need to wait for specialization. +//impl Apply for F where F: Fn( &Apply, T ) -> R { +// fn apply( &self, f: &Apply, t: T ) -> R { +// self( f, t ) +//} +//Before 1.26 we have some limitations and so we need some workarounds. But now impl Trait is stable and we can +// write the following: +fn y(f:impl FnOnce(&Fn(T) -> R, T) -> R + Clone) -> impl FnOnce(T) -> R { + |t| (|x: &Apply,y| x.apply(x,y)) + (&move |x:&Apply,y| f(&|z| x.apply(x,z), y), t) // NOTE: Each letter is an individual symbol. // (λx.(λy.xxy))(λx.(λy.f(λz.xxz)y))t @@ -38,34 +53,35 @@ fn y_apply( f: &F, t: T ) -> R where F: Fn( &Fn( T ) -> R, T ) -> R { // => (Yf)t } -// The static lifetime bounds on the type parameters 'T' and 'R' guarantee that those types will not - -// - contain any references that will have a lifetime less than 'static. -// If the types are allowed to have references that have a lifetime shorter than 'static, those references - -// - may become invalid while you still you have the returned value. -// You need to have the lifetimes be 'static, because, unlike before, you RETURN a recursive version of the function... -fn y( f: Box R, T ) -> R> ) -> Box R> { - Box::new( move |t: T| ( &|x: &Apply, y| x.apply( x, y ) ) - .apply( &|x: &Apply, y| f( &|z| x.apply( x, z ), y ), t ) ) - - // NOTE: Each letter is an individual symbol. - // (λt(λx.(λy.xxy))(λx.(λy.f(λz.xxz)y)))t - // => (λx.xx)(λx.f(xx)) - // => Yf -} +//Previous version removed as they are just hacks when impl Trait is not available. fn fac( n: usize ) -> usize { - let almost_fac = Box::new( |f: &Fn( usize ) -> usize, x| if x == 0 { 1 } else { x * f( x - 1 ) } ); + let almost_fac = |f: &Fn( usize ) -> usize, x| if x == 0 { 1 } else { x * f( x - 1 ) }; let fac = y( almost_fac ); fac( n ) } fn fib( n: usize ) -> usize { - let almost_fib = Box::new( |f: &Fn( usize ) -> usize, x| if x < 2 { x } else { f( x - 2 ) + f( x - 1 ) } ); + let almost_fib = |f: &Fn( usize ) -> usize, x| if x < 2 { 1 } else { f( x - 2 ) + f( x - 1 ) }; let fib = y( almost_fib ); fib( n ) } +fn optimal_fib( n: usize ) -> usize { + let almost_fib = |f: &Fn( (usize,usize,usize) ) -> usize, (i0,i1,x)| + { + match x { + 0 => i0, + 1 => i1, + x => f((i1,i0+i1, x-1)) + } + }; + let fib = |x|y( almost_fib )((1,1,x)); + fib( n ) +} + fn main() { println!( "{}", fac( 10 ) ); println!( "{}", fib( 10 ) ); + println!( "{}", optimal_fib( 10 ) ); } diff --git a/Task/Y-combinator/Scheme/y-combinator-1.ss b/Task/Y-combinator/Scheme/y-combinator-1.ss index 91a35b32aa..9dbfad04ab 100644 --- a/Task/Y-combinator/Scheme/y-combinator-1.ss +++ b/Task/Y-combinator/Scheme/y-combinator-1.ss @@ -4,6 +4,7 @@ (lambda (g) (h (lambda args (apply (g g) args))))))) +;; head-recursive factorial (define fac (Y (lambda (f) @@ -12,6 +13,16 @@ 1 (* x (f (- x 1)))))))) +;; tail-recursive factorial +(define (fac2 n) + (letrec ((tail-fac + (Y (lambda (f) + (lambda (n acc) + (if (zero? n) + acc + (f (- n 1) (* n acc)))))))) + (tail-fac n 1))) + (define fib (Y (lambda (f) diff --git a/Task/Y-combinator/SuperCollider/y-combinator.supercollider b/Task/Y-combinator/SuperCollider/y-combinator.supercollider index 1ea3e0bd5a..bb6f4b19b2 100644 --- a/Task/Y-combinator/SuperCollider/y-combinator.supercollider +++ b/Task/Y-combinator/SuperCollider/y-combinator.supercollider @@ -9,6 +9,13 @@ z = { |f| }; ) +// the same in a shorter form + +( +r = { |x| x.(x) }; +z = { |f| r.({ |y| f.(r.(y).(_)) }) }; +) + // factorial k = { |f| { |x| if(x < 2, 1, { x * f.(x - 1) }) } }; @@ -30,10 +37,3 @@ g = z.(k); g.(3) (1..10).collect(g) // [ 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 ] - -// a shorter form - -( -r = { |x| x.(x) }; -z = { |f| r.({ |y| f.(r.(y).(_)) }) }; -) diff --git a/Task/Yahoo--search-interface/Kotlin/yahoo--search-interface.kotlin b/Task/Yahoo--search-interface/Kotlin/yahoo--search-interface.kotlin new file mode 100644 index 0000000000..e647ab7578 --- /dev/null +++ b/Task/Yahoo--search-interface/Kotlin/yahoo--search-interface.kotlin @@ -0,0 +1,45 @@ +// version 1.2.0 + +import java.net.URL + +val rx = Regex("""
.+?(.*?).+?class="abstract ellipsis">(.*?)

""") + +class YahooResult(var title: String, var link: String, var text: String) { + + override fun toString() = "\nTitle: $title\nLink : $link\nText : $text" +} + +class YahooSearch(val query: String, val page: Int = 0) { + + private val content: String + + init { + val yahoo = "http://search.yahoo.com/search?" + val url = URL("${yahoo}p=$query&b=${page * 10 + 1}") + content = url.readText() + } + + val results: MutableList + get() { + val list = mutableListOf() + for (mr in rx.findAll(content)) { + val title = mr.groups[2]!!.value.replace("", "").replace("", "") + val link = mr.groups[1]!!.value + val text = mr.groups[3]!!.value.replace("", "").replace("", "") + list.add (YahooResult(title, link, text)) + } + return list + } + + fun nextPage() = YahooSearch(query, page + 1) + + fun getPage(newPage: Int) = YahooSearch(query, newPage) +} + +fun main(args: Array) { + for (page in 0..1) { + val x = YahooSearch("rosettacode", page) + println("\nPAGE ${page + 1} =>") + for (result in x.results.take(3)) println(result) + } +} diff --git a/Task/Yin-and-yang/Julia/yin-and-yang.julia b/Task/Yin-and-yang/Julia/yin-and-yang.julia new file mode 100644 index 0000000000..93558cd1d9 --- /dev/null +++ b/Task/Yin-and-yang/Julia/yin-and-yang.julia @@ -0,0 +1,20 @@ +function yinyang(n::Int=3) + radii = (i * n for i in (1, 3, 6)) + ranges = collect(collect(-r:r) for r in radii) + squares = collect(collect((x, y) for x in rnge, y in rnge) for rnge in ranges) + circles = collect(collect((x, y) for (x,y) in sqrpoints if hypot(x, y) ≤ radius) + for (sqrpoints, radius) in zip(squares, radii)) + m = Dict((x, y) => ' ' for (x, y) in squares[end]) + for (x, y) in circles[end] m[(x, y)] = x > 0 ? '·' : '*' end + for (x, y) in circles[end-1] + m[(x, y + 3n)] = '*' + m[(x, y - 3n)] = '·' + end + for (x, y) in circles[end-2] + m[(x, y + 3n)] = '·' + m[(x, y - 3n)] = '*' + end + return join((join(m[(x, y)] for x in reverse(ranges[end])) for y in ranges[end]), '\n') +end + +println(yinyang(4)) diff --git a/Task/Yin-and-yang/Perl-6/yin-and-yang-1.pl6 b/Task/Yin-and-yang/Perl-6/yin-and-yang-1.pl6 index 533ed1e968..a63e99bc06 100644 --- a/Task/Yin-and-yang/Perl-6/yin-and-yang-1.pl6 +++ b/Task/Yin-and-yang/Perl-6/yin-and-yang-1.pl6 @@ -16,9 +16,10 @@ sub yin_yang ($rad, $cx, $cy, :$fill = 'white', :$stroke = 'black', :$angle = 90 say ' -'; +'; -yin_yang(40, 50, 50); -yin_yang(20, 120, 120); +yin_yang(100, 130, 130); +yin_yang(50, 300, 300); say ''; diff --git a/Task/Yin-and-yang/Perl-6/yin-and-yang-2.pl6 b/Task/Yin-and-yang/Perl-6/yin-and-yang-2.pl6 index 98f6eeeb99..03157ebc13 100644 --- a/Task/Yin-and-yang/Perl-6/yin-and-yang-2.pl6 +++ b/Task/Yin-and-yang/Perl-6/yin-and-yang-2.pl6 @@ -1,5 +1,3 @@ -sub cheat_harder ($scale) { - ""; -} +sub cheat_harder ($scale) { ""; } -say '


', cheat_harder(700), cheat_harder(350), '
'; +say '
', cheat_harder(700), cheat_harder(350), '
'; diff --git a/Task/Yin-and-yang/REXX/yin-and-yang.rexx b/Task/Yin-and-yang/REXX/yin-and-yang.rexx index c485bc2b30..b388191161 100644 --- a/Task/Yin-and-yang/REXX/yin-and-yang.rexx +++ b/Task/Yin-and-yang/REXX/yin-and-yang.rexx @@ -1,4 +1,4 @@ -/*REXX program creates and displays an ASCII art version of the Yin─Yang symbol.*/ +/*REXX program creates & displays an ASCII art version of the Yin─Yang (taijitu) symbol.*/ parse arg s1 s2 . /*obtain optional arguments from the CL*/ if s1=='' | s1=="," then s1=17 /*Not defined? Then use the default. */ if s2=='' | s2=="," then s2=s1 % 2 /* " " " " " " */ diff --git a/Task/Zebra-puzzle/ALGOL-68/zebra-puzzle.alg b/Task/Zebra-puzzle/ALGOL-68/zebra-puzzle.alg new file mode 100644 index 0000000000..4222092053 --- /dev/null +++ b/Task/Zebra-puzzle/ALGOL-68/zebra-puzzle.alg @@ -0,0 +1,140 @@ +BEGIN + # attempt to solve Einstein's Riddle - the Zebra puzzle # + INT unknown = 0, same = -1; + INT english = 1, swede = 2, dane = 3, norwegian = 4, german = 5; + INT dog = 1, birds = 2, cats = 3, horse = 4, zebra = 5; + INT red = 1, green = 2, white = 3, yellow = 4, blue = 5; + INT tea = 1, coffee = 2, milk = 3, beer = 4, water = 5; + INT pall mall = 1, dunhill = 2, blend = 3, blue master = 4, prince = 5; + []STRING nationality = ( "unknown", "english", "swede", "dane", "norwegian", "german" ); + []STRING animal = ( "unknown", "dog", "birds", "cats", "horse", "ZEBRA" ); + []STRING colour = ( "unknown", "red", "green", "white", "yellow", "blue" ); + []STRING drink = ( "unknown", "tea", "coffee", "milk", "beer", "water" ); + []STRING smoke = ( "unknown", "pall mall", "dunhill", "blend", "blue master", "prince" ); + MODE HOUSE = STRUCT( INT nationality, animal, colour, drink, smoke ); + # returns TRUE if a field in a house could be set to value, FALSE otherwise # + PROC can set = ( INT field, INT value )BOOL: field = unknown OR value = same; + # returns TRUE if the fields of house h could be set to those of # + # suggestion s, FALSE otherwise # + OP XOR = ( HOUSE h, HOUSE s )BOOL: + ( can set( nationality OF h, nationality OF s ) AND can set( animal OF h, animal OF s ) + AND can set( colour OF h, colour OF s ) AND can set( drink OF h, drink OF s ) + AND can set( smoke OF h, smoke OF s ) + ) # XOR # ; + # sets a field in a house to value if it is unknown # + PROC set = ( REF INT field, INT value )VOID: IF field = unknown AND value /= same THEN field := value FI; + # sets the unknown fields in house h to the non-same fields of suggestion s # + OP +:= = ( REF HOUSE h, HOUSE s )VOID: + ( set( nationality OF h, nationality OF s ); set( animal OF h, animal OF s ) + ; set( colour OF h, colour OF s ); set( drink OF h, drink OF s ) + ; set( smoke OF h, smoke OF s ) + ) # +:= # ; + # sets a field in a house to unknown if the value is not same # + PROC reset = ( REF INT field, INT value )VOID: IF value /= same THEN field := unknown FI; + # sets fields in house h to unknown if the suggestion s is not same # + OP -:= = ( REF HOUSE h, HOUSE s )VOID: + ( reset( nationality OF h, nationality OF s ); reset( animal OF h, animal OF s ) + ; reset( colour OF h, colour OF s ); reset( drink OF h, drink OF s ) + ; reset( smoke OF h, smoke OF s ) + ) # -:= # ; + # attempts a partial solution for the house at pos # + PROC try = ( INT pos, HOUSE suggestion, PROC VOID continue )VOID: + IF pos >= LWB house AND pos <= UPB house THEN + IF house[ pos ] XOR suggestion THEN + house[ pos ] +:= suggestion; continue; house[ pos ] -:= suggestion + FI + FI # try # ; + # attempts a partial solution for the neighbours of a house # + PROC left or right = ( INT pos, BOOL left, BOOL right, HOUSE neighbour suggestion + , PROC VOID continue )VOID: + ( IF left THEN try( pos - 1, neighbour suggestion, continue ) FI + ; IF right THEN try( pos + 1, neighbour suggestion, continue ) FI + ) # left or right # ; + # attempts a partial solution for all houses and possibly their neighbours # + PROC any2 = ( REF INT number, HOUSE suggestion + , BOOL left, BOOL right, HOUSE neighbour suggestion + , PROC VOID continue )VOID: + FOR pos TO UPB house DO + IF house[ pos ] XOR suggestion THEN + number := pos; + house[ number ] +:= suggestion; + IF NOT left AND NOT right THEN # neighbours not involved # + continue + ELSE # try one or both neighbours # + left or right( pos, left, right, neighbour suggestion, continue ) + FI; + house[ number ] -:= suggestion + FI + OD # any2 # ; + # attempts a partial solution for all houses # + PROC any = ( HOUSE suggestion, PROC VOID continue )VOID: + any2( LOC INT, suggestion, FALSE, FALSE, SKIP, continue ); + # find solution(s) # + INT blend pos; + INT solutions := 0; + # There are five houses. # + [ 1 : 5 ]HOUSE house; + FOR h TO UPB house DO house[ h ] := ( unknown, unknown, unknown, unknown, unknown ) OD; + # In the middle house they drink milk. # + drink OF house[ 3 ] := milk; + # The Norwegian lives in the first house. # + nationality OF house[ 1 ] := norwegian; + # The Norwegian lives next to the blue house. # + colour OF house[ 2 ] := blue; + # They drink coffee in the green house. # + # The green house is immediately to the left of the white house. # + any2( LOC INT, ( same, same, green, coffee, same ) + , FALSE, TRUE, ( same, same, white, same, same ), VOID: + # In a house next to the house where they have a horse, # + # they smoke Dunhill. # + # In the yellow house they smoke Dunhill. # + any2( LOC INT, ( same, horse, same, same, same ) + , TRUE, TRUE, ( same, same, yellow, same, dunhill ), VOID: + # The English man lives in the red house. # + any( ( english, same, red, same, same ), VOID: + # The man who smokes Blend lives in the house next to the # + # house with cats. # + any2( blend pos, ( same, same, same, same, blend ) + , TRUE, TRUE, ( same, cats, same, same, same ), VOID: + # They drink water in a house next to the house where # + # they smoke Blend. # + left or right( blend pos, TRUE, TRUE, ( same, same, same, water, same ), VOID: + # The Dane drinks tea. # + any( ( dane, same, same, tea, same ), VOID: + # The man who smokes Blue Master drinks beer. # + any( ( same, same, same, beer, blue master ), VOID: + # The Swede has a dog. # + any( ( swede, dog, same, same, same ), VOID: + # The German smokes Prince. # + any( ( german, same, same, same, prince ), VOID: + # The man who smokes Pall Mall has birds. # + any( ( same, birds, same, same, pall mall ), VOID: + # if we can place the zebra, we have a solution # + any( ( same, zebra, same, same, same ), VOID: + ( solutions +:= 1; + FOR h TO UPB house DO + print( ( whole( h, 0 ) + , " ", nationality[ 1 + nationality OF house[ h ] ] + , ", ", animal [ 1 + animal OF house[ h ] ] + , ", ", colour [ 1 + colour OF house[ h ] ] + , ", ", drink [ 1 + drink OF house[ h ] ] + , ", ", smoke [ 1 + smoke OF house[ h ] ] + , newline + ) + ) + OD; + print( ( newline ) ) + ) + ) # zebra # + ) # pall mall # + ) # german # + ) # swede # + ) # beer # + ) # dane # + ) # blend L/R # + ) # blend # + ) # red # + ) # horse # + ) # green # ; + print( ( "solutions: ", whole( solutions, 0 ), newline ) ) +END diff --git a/Task/Zebra-puzzle/Julia/zebra-puzzle.julia b/Task/Zebra-puzzle/Julia/zebra-puzzle.julia new file mode 100644 index 0000000000..1788b79193 --- /dev/null +++ b/Task/Zebra-puzzle/Julia/zebra-puzzle.julia @@ -0,0 +1,51 @@ +function make(str, test = (_) -> true) + collect( filter(test, permutations(split(str))) ) +end + +men = make("danish english german norwegian swedish", + x -> "norwegian" == x[1]) + +drinks = make("beer coffee milk tea water", x -> "milk" == x[3]) + +colors = make("blue green red white yellow", + x -> 1 == findfirst(x, "white") - findfirst(x, "green")) + +pets = make("birds cats dog horse zebra") + +smokes = make("blend blue-master dunhill pall-mall prince") + +function eq(x, xs, y, ys) + findfirst(xs, x) == findfirst(ys, y) +end + +function adj(x, xs, y, ys) + 1 == abs(findfirst(xs, x) - findfirst(ys, y)) +end + +for m = men, c = colors + if eq("red",c, "english",m) && adj("norwegian",m, "blue",c) + for d = drinks + if eq("danish",m, "tea",d) && eq("coffee",d,"green",c) + for s = smokes + if eq("yellow",c,"dunhill",s) && + eq("blue-master",s,"beer",d) && + eq("german",m,"prince",s) + for p = pets + if eq("birds",p,"pall-mall",s) && + eq("swedish",m,"dog",p) && + adj("blend",s,"cats",p) && + adj("horse",p,"dunhill",s) + println("Zebra is owned by ", m[findfirst(p,"zebra")]) + println("Houses:") + for line = mapslices(xs -> join( map(s->rpad(s,12), xs)), + [p m c d s], 2) + println(line) + end + end + end + end + end + end + end + end +end diff --git a/Task/Zebra-puzzle/Nial/zebra-puzzle.nial b/Task/Zebra-puzzle/Nial/zebra-puzzle.nial new file mode 100644 index 0000000000..998d2ef217 --- /dev/null +++ b/Task/Zebra-puzzle/Nial/zebra-puzzle.nial @@ -0,0 +1,55 @@ +remove is op x xs {filter (not (x =)) xs} + +append_map is transformer func op seq { \ + reduce (op x xs { (func x) link xs}) (seq append []) } + +permutations is op seq { \ + if empty seq then [[]] else \ + (append_map \ + (op head {each (op tail {head hitch tail}) \ + (permutations (remove head seq))}) \ + seq) \ + endif} + +f is find +tokenize is op str{string_split ' ' str} +mk is tr pred op str {filter pred permutations tokenize str} +eq is op x xs y ys{f x xs = f y ys} +adj is op x xs y ys{1 = abs(f x xs - f y ys)} + +run is { \ + men := mk (op xs {0 = f 'norwegian' xs}) \ + 'danish english german norwegian swedish'; \ + colors := mk (op xs {1 = ((f 'white' xs) - (f 'green' xs))}) \ + 'blue green red white yellow'; \ + drinks := mk (op xs {2 = f 'milk' xs}) 'beer coffee milk tea water'; \ + pets := mk (op xs {l}) 'birds cats dog horse zebra'; \ + smokes := mk (op xs {l}) 'blend blue-master dunhill pall-mall prince'; \ + for m with men do \ + for c with colors do \ + if (eq 'english' m 'red' c) and \ + (adj 'norwegian' m 'blue' c) then \ + for d with drinks do \ + if (eq 'danish' m 'tea' d) and \ + (eq 'coffee' d 'green' c) then \ + for s with smokes do \ + if (eq 'yellow' c 'dunhill' s) and \ + (eq 'blue-master' s 'beer' d) and \ + (eq 'german' m 'prince' s) then \ + for p with pets do \ + if (eq 'birds' p 'pall-mall' s) and \ + (eq 'swedish' m 'dog' p) and \ + (adj 'blend' s 'cats' p) and \ + (adj 'horse' p 'dunhill' s) then \ + write (0 blend (p m c d s)) \ + endif \ + endfor \ + endif \ + endfor \ + endif \ + endfor \ + endif \ + endfor \ + endfor } + +abs(time - (run; time)) diff --git a/Task/Zebra-puzzle/REXX/zebra-puzzle.rexx b/Task/Zebra-puzzle/REXX/zebra-puzzle.rexx index 3614621220..587058924e 100644 --- a/Task/Zebra-puzzle/REXX/zebra-puzzle.rexx +++ b/Task/Zebra-puzzle/REXX/zebra-puzzle.rexx @@ -1,9 +1,8 @@ /* REXX --------------------------------------------------------------- * Solve the Zebra Puzzle *--------------------------------------------------------------------*/ - oid='zebra.txt'; 'erase' oid Call mk_perm /* compute all permutations */ - Call encode /* encode the elements of the specifucations */ + Call encode /* encode the elements of the specifications */ /* ex2 .. eg16 the formalized specifications */ solutions=0 Call time 'R' @@ -42,7 +41,7 @@ ||left(animal.ai,11) Call out ol.i End - solutions+=1 + solutions=solutions+1 End End /* animal_i */ End @@ -50,7 +49,7 @@ End End /* drink_i */ End - End /* colr_i */ + End /* color_i */ End End /* nation_i */ Say 'Number of solutions =' solutions @@ -167,4 +166,4 @@ encode: out: Say arg(1) - Return lineout(oid,arg(1)) + Return diff --git a/Task/Zebra-puzzle/Ruby/zebra-puzzle.rb b/Task/Zebra-puzzle/Ruby/zebra-puzzle-1.rb similarity index 100% rename from Task/Zebra-puzzle/Ruby/zebra-puzzle.rb rename to Task/Zebra-puzzle/Ruby/zebra-puzzle-1.rb diff --git a/Task/Zebra-puzzle/Ruby/zebra-puzzle-2.rb b/Task/Zebra-puzzle/Ruby/zebra-puzzle-2.rb new file mode 100644 index 0000000000..5ad64d9419 --- /dev/null +++ b/Task/Zebra-puzzle/Ruby/zebra-puzzle-2.rb @@ -0,0 +1,24 @@ +class String; def brk; split(/(?=[A-Z])/); end; end +men,drinks,colors,pets,smokes = "NorwegianGermanDaneSwedeEnglish + MilkTeaBeerWaterCoffeeGreenWhiteRedYellowBlueZebraDogCatsHorseBirds + PallmallDunhillBlendBluemasterPrince".delete(" \n"). + brk.each_slice(5).map{|e| e.permutation.to_a}; +men.select!{|x| "Norwegian"==x[0]}; +drinks.select!{|x| "Milk"==x[2]}; +colors.select!{|x| x.join[/GreenWhite/]}; + +dis = proc{|s,*a| s.brk.map{|w| a.map{|p| p.index(w)}. + compact[0]}.each_slice(2).map{|a,b| (a-b).abs}} + +men.each{|m| colors.each{|c| + next unless dis["RedEnglishBlueNorwegian",c,m]==[0,1] + drinks.each{|d| next unless dis["DaneTeaCoffeeGreen",m,d,c]==[0,0] + smokes.each{|s| + next unless dis["YellowDunhillBluemasterBeerGermanPrince", + c,s,d,m]==[0,0,0] + pets.each{|p| + next unless dis["SwedeDogBirdsPallmallCatsBlendHorseDunhill", + m,p,s]==[0,0,1,1] + x = [p,m,c,d,s].transpose + puts "The #{x.find{|y|y[0]=="Zebra"}[1]} owns the zebra.", + x.map{|y| y.map{|z| z.ljust(11)}.join}}}}}} diff --git a/Task/Zebra-puzzle/Scala/zebra-puzzle-1.scala b/Task/Zebra-puzzle/Scala/zebra-puzzle-1.scala index e76db093a7..3b14d38470 100644 --- a/Task/Zebra-puzzle/Scala/zebra-puzzle-1.scala +++ b/Task/Zebra-puzzle/Scala/zebra-puzzle-1.scala @@ -8,22 +8,8 @@ */ object Einstein extends App { - class House(val nationality: String, val color: String, val beverage: String, val animal: String, val brand: String) { - override def toString = { f"$nationality%10s, ${color + ", "}%-8s$beverage,\t$animal,\t$brand." } - - def totalUnEqual(home2: House) = - this.animal != home2.animal && - this.beverage != home2.beverage && - this.brand != home2.brand && - this.color != home2.color && - this.nationality != home2.nationality - - //** Checks if the this green house is next to the other white house*/ - def checkAdjacentWhite(home2: House) = (this.color == "Green") == (home2.color == "White") // #5 - } - val possibleMembers = for { // pair clues results in 78 members - nationality <- List("Norweigan", "German", "Dane", "Englishman", "Swede") + nationality <- List("Norwegian", "German", "Dane", "Englishman", "Swede") color <- List("Red", "Green", "Yellow", "White", "Blue") beverage <- List("Milk", "Coffee", "Tea", "Beer", "Water") animal <- List("Dog", "Horse", "Birds", "Cats", "Zebra") @@ -37,6 +23,22 @@ object Einstein extends App { if (brand == "Blue Master") == (beverage == "Beer") // #13 if (brand == "Prince") == (nationality == "German") // #14 } yield new House(nationality, color, beverage, animal, brand) + val members = for { // Neighborhood clues + h1 <- housesLeftOver().filter(p => (p.nationality == "Norwegia" /* #10 */) && (p.color != "Green") /* #5a */) // 28 + h3 <- housesLeftOver(h1).filter(p => p.beverage == "Milk") // #9 // 24 + h2 <- housesLeftOver(h1, h3).filter(_.color == "Blue") // #15 + if matchMiddleBrandAnimal(h1, h2, h3, "Blend", "Cats") // #11 + if matchCornerBrandAnimal(h1, h2, "Horse", "Dunhill") // #12 + h4 <- housesLeftOver(h1, h2, h3).filter(_.checkAdjacentWhite(h3) /* #5 */) + h5 <- housesLeftOver(h1, h2, h3, h4) + + // Redundant tests + if h2.checkAdjacentWhite(h1) + if h3.checkAdjacentWhite(h2) + if matchCornerBrandAnimal(h5, h4, "Horse", "Dunhill") + if matchMiddleBrandAnimal(h2, h3, h4, "Blend", "Cats") + if matchMiddleBrandAnimal(h3, h4, h5, "Blend", "Cats") + } yield Seq(h1, h2, h3, h4, h5) def matchMiddleBrandAnimal(home1: House, home2: House, home3: House, brand: String, animal: String) = (home1.animal == animal || home2.brand != brand || home3.animal == animal) && @@ -49,28 +51,28 @@ object Einstein extends App { possibleMembers.filter(house => pickedHouses.forall(_.totalUnEqual(house))) } - val members = for { // Neighborhood clues - h1 <- housesLeftOver().filter(p => (p.nationality == "Norweigan" /* #10 */ ) && (p.color != "Green") /* #5a */ ) // 28 - h3 <- housesLeftOver(h1).filter(p => p.beverage == "Milk") // #9 // 24 - h2 <- housesLeftOver(h1, h3).filter(_.color == "Blue") // #15 - if matchMiddleBrandAnimal(h1, h2, h3, "Blend", "Cats") // #11 - if matchCornerBrandAnimal(h1, h2, "Horse", "Dunhill") // #12 - h4 <- housesLeftOver(h1, h2, h3).filter(_.checkAdjacentWhite(h3) /* #5 */ ) - h5 <- housesLeftOver(h1, h2, h3, h4) + class House(val nationality: String, val color: String, val beverage: String, val animal: String, val brand: String) { + override def toString = { + f"$nationality%10s, ${color + ", "}%-8s$beverage,\t$animal,\t$brand." + } - // Redundant tests - if h2.checkAdjacentWhite(h1) - if h3.checkAdjacentWhite(h2) - if matchCornerBrandAnimal(h5, h4, "Horse", "Dunhill") - if matchMiddleBrandAnimal(h2, h3, h4, "Blend", "Cats") - if matchMiddleBrandAnimal(h3, h4, h5, "Blend", "Cats") - } yield Seq(h1, h2, h3, h4, h5) + def totalUnEqual(home2: House) = + this.animal != home2.animal && + this.beverage != home2.beverage && + this.brand != home2.brand && + this.color != home2.color && + this.nationality != home2.nationality - // Main program - val beest = "Zebra" - members.flatMap(p => p.filter(p => p.animal == beest)). - foreach(s => println(s"The ${s.nationality} is the owner of the ${beest.toLowerCase}.")) + //** Checks if the this green house is next to the other white house*/ + def checkAdjacentWhite(home2: House) = (this.color == "Green") == (home2.color == "White") // #5 + } - println(s"The ${members.size} solution(s) are:") - members.foreach(solution => solution.zipWithIndex.foreach(h => println("House " + (h._2 + 1) + " " + h._1))) -} + { // Main program + val beest = "Zebra" + members.flatMap(p => p.filter(p => p.animal == beest)). + foreach(s => println(s"The ${s.nationality} is the owner of the ${beest.toLowerCase}.")) + + println(s"The ${members.size} solution(s) are:") + members.foreach(solution => solution.zipWithIndex.foreach(h => println(s"House ${h._2 + 1} ${h._1}"))) + } +} // loc 58 diff --git a/Task/Zebra-puzzle/Scala/zebra-puzzle-2.scala b/Task/Zebra-puzzle/Scala/zebra-puzzle-2.scala index 9118407dbb..ed2288a753 100644 --- a/Task/Zebra-puzzle/Scala/zebra-puzzle-2.scala +++ b/Task/Zebra-puzzle/Scala/zebra-puzzle-2.scala @@ -78,8 +78,7 @@ object Einstein extends App { // print each row including a column header ((1 to 5).map(n => s"House $n") +: solution).map(_.map(pretty)).map(x => (pretty(labels.next) +: x).mkString(" ")).foreach(println) - println() - println(s"The ${solution(1)(solution(3).indexOf("Fish"))} owns the Fish") + println(s"\nThe ${solution(1)(solution(3).indexOf("Fish"))} owns the Fish") } -} +}// loc 38 diff --git a/Task/Zeckendorf-arithmetic/D/zeckendorf-arithmetic.d b/Task/Zeckendorf-arithmetic/D/zeckendorf-arithmetic.d new file mode 100644 index 0000000000..0a6c50f54f --- /dev/null +++ b/Task/Zeckendorf-arithmetic/D/zeckendorf-arithmetic.d @@ -0,0 +1,172 @@ +import std.stdio; + +int inv(int a) { + return a ^ -1; +} + +class Zeckendorf { + private int dVal; + private int dLen; + + private void a(int n) { + auto i = n; + while (true) { + if (dLen < i) dLen = i; + auto j = (dVal >> (i * 2)) & 3; + switch(j) { + case 0: + case 1: + return; + case 2: + if (((dVal >> ((i + 1) * 2)) & 1) != 1) return; + dVal += 1 << (i * 2 + 1); + return; + case 3: + dVal = dVal & (3 << (i * 2)).inv(); + b((i + 1) * 2); + break; + default: + assert(false); + } + i++; + } + } + + private void b(int pos) { + if (pos == 0) { + this++; + return; + } + if (((dVal >> pos) & 1) == 0) { + dVal += 1 << pos; + a(pos / 2); + if (pos > 1) a(pos / 2 - 1); + } else { + dVal = dVal & (1 << pos).inv(); + b(pos + 1); + b(pos - (pos > 1 ? 2 : 1)); + } + } + + private void c(int pos) { + if (((dVal >> pos) & 1) == 1) { + dVal = dVal & (1 << pos).inv(); + return; + } + c(pos + 1); + if (pos > 0) { + b(pos - 1); + } else { + ++this; + } + } + + this(string x = "0") { + int q = 1; + int i = x.length - 1; + dLen = i / 2; + while (i >= 0) { + dVal += (x[i] - '0') * q; + q *= 2; + i--; + } + } + + auto opUnary(string op : "++")() { + dVal += 1; + a(0); + return this; + } + + void opOpAssign(string op : "+")(Zeckendorf rhs) { + foreach (gn; 0..(rhs.dLen + 1) * 2) { + if (((rhs.dVal >> gn) & 1) == 1) { + b(gn); + } + } + } + + void opOpAssign(string op : "-")(Zeckendorf rhs) { + foreach (gn; 0..(rhs.dLen + 1) * 2) { + if (((rhs.dVal >> gn) & 1) == 1) { + c(gn); + } + } + while ((((dVal >> dLen * 2) & 3) == 0) || (dLen == 0)) { + dLen--; + } + } + + void opOpAssign(string op : "*")(Zeckendorf rhs) { + auto na = rhs.dup; + auto nb = rhs.dup; + Zeckendorf nt; + auto nr = "0".Z; + foreach (i; 0..(dLen + 1) * 2) { + if (((dVal >> i) & 1) > 0) nr += nb; + nt = nb.dup; + nb += na; + na = nt.dup; + } + dVal = nr.dVal; + dLen = nr.dLen; + } + + void toString(scope void delegate(const(char)[]) sink) const { + if (dVal == 0) { + sink("0"); + return; + } + sink(dig1[(dVal >> (dLen * 2)) & 3]); + foreach_reverse (i; 0..dLen) { + sink(dig[(dVal >> (i * 2)) & 3]); + } + } + + Zeckendorf dup() { + auto z = "0".Z; + z.dVal = dVal; + z.dLen = dLen; + return z; + } + + enum dig = ["00", "01", "10"]; + enum dig1 = ["", "1", "10"]; +} + +auto Z(string val) { + return new Zeckendorf(val); +} + +void main() { + writeln("Addition:"); + auto g = "10".Z; + g += "10".Z; + writeln(g); + g += "10".Z; + writeln(g); + g += "1001".Z; + writeln(g); + g += "1000".Z; + writeln(g); + g += "10101".Z; + writeln(g); + writeln(); + + writeln("Subtraction:"); + g = "1000".Z; + g -= "101".Z; + writeln(g); + g = "10101010".Z; + g -= "1010101".Z; + writeln(g); + writeln(); + + writeln("Multiplication:"); + g = "1001".Z; + g *= "101".Z; + writeln(g); + g = "101010".Z; + g += "101".Z; + writeln(g); +} diff --git a/Task/Zeckendorf-arithmetic/Java/zeckendorf-arithmetic.java b/Task/Zeckendorf-arithmetic/Java/zeckendorf-arithmetic.java new file mode 100644 index 0000000000..eca3f24b8b --- /dev/null +++ b/Task/Zeckendorf-arithmetic/Java/zeckendorf-arithmetic.java @@ -0,0 +1,186 @@ +import java.util.List; + +public class Zeckendorf implements Comparable { + private static List dig = List.of("00", "01", "10"); + private static List dig1 = List.of("", "1", "10"); + + private String x; + private int dVal = 0; + private int dLen = 0; + + public Zeckendorf() { + this("0"); + } + + public Zeckendorf(String x) { + this.x = x; + + int q = 1; + int i = x.length() - 1; + dLen = i / 2; + while (i >= 0) { + dVal += (x.charAt(i) - '0') * q; + q *= 2; + i--; + } + } + + private void a(int n) { + int i = n; + while (true) { + if (dLen < i) dLen = i; + int j = (dVal >> (i * 2)) & 3; + switch (j) { + case 0: + case 1: + return; + case 2: + if (((dVal >> ((i + 1) * 2)) & 1) != 1) return; + dVal += 1 << (i * 2 + 1); + return; + case 3: + int temp = 3 << (i * 2); + temp ^= -1; + dVal = dVal & temp; + b((i + 1) * 2); + break; + } + i++; + } + } + + private void b(int pos) { + if (pos == 0) { + Zeckendorf thiz = this; + thiz.inc(); + return; + } + if (((dVal >> pos) & 1) == 0) { + dVal += 1 << pos; + a(pos / 2); + if (pos > 1) a(pos / 2 - 1); + } else { + int temp = 1 << pos; + temp ^= -1; + dVal = dVal & temp; + b(pos + 1); + b(pos - (pos > 1 ? 2 : 1)); + } + } + + private void c(int pos) { + if (((dVal >> pos) & 1) == 1) { + int temp = 1 << pos; + temp ^= -1; + dVal = dVal & temp; + return; + } + c(pos + 1); + if (pos > 0) { + b(pos - 1); + } else { + Zeckendorf thiz = this; + thiz.inc(); + } + } + + public Zeckendorf inc() { + dVal++; + a(0); + return this; + } + + public void plusAssign(Zeckendorf other) { + for (int gn = 0; gn < (other.dLen + 1) * 2; gn++) { + if (((other.dVal >> gn) & 1) == 1) { + b(gn); + } + } + } + + public void minusAssign(Zeckendorf other) { + for (int gn = 0; gn < (other.dLen + 1) * 2; gn++) { + if (((other.dVal >> gn) & 1) == 1) { + c(gn); + } + } + while ((((dVal >> dLen * 2) & 3) == 0) || (dLen == 0)) { + dLen--; + } + } + + public void timesAssign(Zeckendorf other) { + Zeckendorf na = other.copy(); + Zeckendorf nb = other.copy(); + Zeckendorf nt; + Zeckendorf nr = new Zeckendorf(); + for (int i = 0; i < (dLen + 1) * 2; i++) { + if (((dVal >> i) & 1) > 0) { + nr.plusAssign(nb); + } + nt = nb.copy(); + nb.plusAssign(na); + na = nt.copy(); + } + dVal = nr.dVal; + dLen = nr.dLen; + } + + private Zeckendorf copy() { + Zeckendorf z = new Zeckendorf(); + z.dVal = dVal; + z.dLen = dLen; + return z; + } + + @Override + public int compareTo(Zeckendorf other) { + return ((Integer) dVal).compareTo(other.dVal); + } + + @Override + public String toString() { + if (dVal == 0) { + return "0"; + } + + int idx = (dVal >> (dLen * 2)) & 3; + StringBuilder stringBuilder = new StringBuilder(dig1.get(idx)); + for (int i = dLen - 1; i >= 0; i--) { + idx = (dVal >> (i * 2)) & 3; + stringBuilder.append(dig.get(idx)); + } + return stringBuilder.toString(); + } + + public static void main(String[] args) { + System.out.println("Addition:"); + Zeckendorf g = new Zeckendorf("10"); + g.plusAssign(new Zeckendorf("10")); + System.out.println(g); + g.plusAssign(new Zeckendorf("10")); + System.out.println(g); + g.plusAssign(new Zeckendorf("1001")); + System.out.println(g); + g.plusAssign(new Zeckendorf("1000")); + System.out.println(g); + g.plusAssign(new Zeckendorf("10101")); + System.out.println(g); + + System.out.println("\nSubtraction:"); + g = new Zeckendorf("1000"); + g.minusAssign(new Zeckendorf("101")); + System.out.println(g); + g = new Zeckendorf("10101010"); + g.minusAssign(new Zeckendorf("1010101")); + System.out.println(g); + + System.out.println("\nMultiplication:"); + g = new Zeckendorf("1001"); + g.timesAssign(new Zeckendorf("101")); + System.out.println(g); + g = new Zeckendorf("101010"); + g.plusAssign(new Zeckendorf("101")); + System.out.println(g); + } +} diff --git a/Task/Zeckendorf-arithmetic/Kotlin/zeckendorf-arithmetic.kotlin b/Task/Zeckendorf-arithmetic/Kotlin/zeckendorf-arithmetic.kotlin new file mode 100644 index 0000000000..a5eb9fdb1d --- /dev/null +++ b/Task/Zeckendorf-arithmetic/Kotlin/zeckendorf-arithmetic.kotlin @@ -0,0 +1,156 @@ +// version 1.1.51 + +class Zeckendorf(x: String = "0") : Comparable { + + var dVal = 0 + var dLen = 0 + + private fun a(n: Int) { + var i = n + while (true) { + if (dLen < i) dLen = i + val j = (dVal shr (i * 2)) and 3 + when (j) { + 0, 1 -> return + + 2 -> { + if (((dVal shr ((i + 1) * 2)) and 1) != 1) return + dVal += 1 shl (i * 2 + 1) + return + } + + 3 -> { + dVal = dVal and (3 shl (i * 2)).inv() + b((i + 1) * 2) + } + } + i++ + } + } + + private fun b(pos: Int) { + if (pos == 0) { + var thiz = this + ++thiz + return + } + if (((dVal shr pos) and 1) == 0) { + dVal += 1 shl pos + a(pos / 2) + if (pos > 1) a(pos / 2 - 1) + } + else { + dVal = dVal and (1 shl pos).inv() + b(pos + 1) + b(pos - (if (pos > 1) 2 else 1)) + } + } + + private fun c(pos: Int) { + if (((dVal shr pos) and 1) == 1) { + dVal = dVal and (1 shl pos).inv() + return + } + c(pos + 1) + if (pos > 0) b(pos - 1) else { var thiz = this; ++thiz } + } + + init { + var q = 1 + var i = x.length - 1 + dLen = i / 2 + while (i >= 0) { + dVal += (x[i] - '0').toInt() * q + q *= 2 + i-- + } + } + + operator fun inc(): Zeckendorf { + dVal += 1 + a(0) + return this + } + + operator fun plusAssign(other: Zeckendorf) { + for (gn in 0 until (other.dLen + 1) * 2) { + if (((other.dVal shr gn) and 1) == 1) b(gn) + } + } + + operator fun minusAssign(other: Zeckendorf) { + for (gn in 0 until (other.dLen + 1) * 2) { + if (((other.dVal shr gn) and 1) == 1) c(gn) + } + while ((((dVal shr dLen * 2) and 3) == 0) || (dLen == 0)) dLen-- + } + + operator fun timesAssign(other: Zeckendorf) { + var na = other.copy() + var nb = other.copy() + var nt: Zeckendorf + var nr = "0".Z + for (i in 0..(dLen + 1) * 2) { + if (((dVal shr i) and 1) > 0) nr += nb + nt = nb.copy() + nb += na + na = nt.copy() + } + dVal = nr.dVal + dLen = nr.dLen + } + + override operator fun compareTo(other: Zeckendorf) = dVal.compareTo(other.dVal) + + override fun toString(): String { + if (dVal == 0) return "0" + val sb = StringBuilder(dig1[(dVal shr (dLen * 2)) and 3]) + for (i in dLen - 1 downTo 0) { + sb.append(dig[(dVal shr (i * 2)) and 3]) + } + return sb.toString() + } + + fun copy(): Zeckendorf { + val z = "0".Z + z.dVal = dVal + z.dLen = dLen + return z + } + + companion object { + val dig = listOf("00", "01", "10") + val dig1 = listOf("", "1", "10") + } +} + +val String.Z get() = Zeckendorf(this) + +fun main(args: Array) { + println("Addition:") + var g = "10".Z + g += "10".Z + println(g) + g += "10".Z + println(g) + g += "1001".Z + println(g) + g += "1000".Z + println(g) + g += "10101".Z + println(g) + println("\nSubtraction:") + g = "1000".Z + g -= "101".Z + println(g) + g = "10101010".Z + g -= "1010101".Z + println(g) + println("\nMultiplication:") + g = "1001".Z + g *= "101".Z + println(g) + g = "101010".Z + g += "101".Z + println(g) +} diff --git a/Task/Zeckendorf-number-representation/AppleScript/zeckendorf-number-representation.applescript b/Task/Zeckendorf-number-representation/AppleScript/zeckendorf-number-representation.applescript index ecce2cd245..f364234690 100644 --- a/Task/Zeckendorf-number-representation/AppleScript/zeckendorf-number-representation.applescript +++ b/Task/Zeckendorf-number-representation/AppleScript/zeckendorf-number-representation.applescript @@ -1,23 +1,24 @@ +-- ZECKENDORF NUMBERS -------------------------------------------------------- + -- zeckendorf :: Int -> String on zeckendorf(n) script f - on lambda(n, x) + on |λ|(n, x) if n < x then [n, 0] else [n - x, 1] end if - end lambda + end |λ| end script if n = 0 then {0} as string else - item 2 of mapAccumL(f, n, _reverse(tail(fibUntil(n)))) as string + item 2 of mapAccumL(f, n, |reverse|(just of tailMay(fibUntil(n)))) as string end if end zeckendorf - -- fibUntil :: Int -> [Int] on fibUntil(n) set xs to {} @@ -25,104 +26,36 @@ on fibUntil(n) script atLimit property ceiling : limit - on lambda(x) + on |λ|(x) (item 2 of x) > (atLimit's ceiling) - end lambda + end |λ| end script script nextPair property series : xs - on lambda([a, b]) + on |λ|([a, b]) set nextPair's series to nextPair's series & b [b, a + b] - end lambda + end |λ| end script |until|(atLimit, nextPair, {0, 1}) return nextPair's series end fibUntil - --- TEST +-- TEST ---------------------------------------------------------------------- on run intercalate(linefeed, ¬ - map(zeckendorf, range(0, 20))) + map(zeckendorf, enumFromTo(0, 20))) end run +-- GENERIC FUNCTIONS --------------------------------------------------------- --- GENERIC LIBRARY FUNCTIONS - --- 'The mapAccumL function behaves like a combination of map and foldl; --- it applies a function to each element of a list, passing an --- accumulating parameter from left to right, and returning a final --- value of this accumulator together with the new list.' (see Hoogle) - --- mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y]) -on mapAccumL(f, acc, xs) - script - on lambda(a, x) - tell mReturn(f) to set pair to lambda(item 1 of a, x) - [item 1 of pair, (item 2 of a) & item 2 of pair] - end lambda - end script - - foldl(result, [acc, []], xs) -end mapAccumL - --- until :: (a -> Bool) -> (a -> a) -> a -> a -on |until|(p, f, x) - set mp to mReturn(p) - set v to x - - tell mReturn(f) - repeat until mp's lambda(v) - set v to lambda(v) - end repeat - end tell - return v -end |until| - --- map :: (a -> b) -> [a] -> [b] -on map(f, xs) - tell mReturn(f) - set lng to length of xs - set lst to {} - repeat with i from 1 to lng - set end of lst to lambda(item i of xs, i, xs) - end repeat - return lst - end tell -end map - --- foldl :: (a -> b -> a) -> a -> [b] -> a -on foldl(f, startValue, xs) - tell mReturn(f) - set v to startValue - set lng to length of xs - repeat with i from 1 to lng - set v to lambda(v, item i of xs, i, xs) - end repeat - return v - end tell -end foldl - --- Lift 2nd class handler function into 1st class script wrapper --- mReturn :: Handler -> Script -on mReturn(f) - if class of f is script then - f - else - script - property lambda : f - end script - end if -end mReturn - --- range :: Int -> Int -> [Int] -on range(m, n) - if n < m then +-- enumFromTo :: Int -> Int -> [Int] +on enumFromTo(m, n) + if m > n then set d to -1 else set d to 1 @@ -132,7 +65,60 @@ on range(m, n) set end of lst to i end repeat return lst -end range +end enumFromTo + +-- foldl :: (a -> b -> a) -> a -> [b] -> a +on foldl(f, startValue, xs) + tell mReturn(f) + set v to startValue + set lng to length of xs + repeat with i from 1 to lng + set v to |λ|(v, item i of xs, i, xs) + end repeat + return v + end tell +end foldl + +-- 'The mapAccumL function behaves like a combination of map and foldl; +-- it applies a function to each element of a list, passing an +-- accumulating parameter from left to right, and returning a final +-- value of this accumulator together with the new list.' (see Hoogle) + +-- mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y]) +on mapAccumL(f, acc, xs) + script + on |λ|(a, x) + tell mReturn(f) to set pair to |λ|(item 1 of a, x) + [item 1 of pair, (item 2 of a) & item 2 of pair] + end |λ| + end script + + foldl(result, [acc, []], xs) +end mapAccumL + +-- map :: (a -> b) -> [a] -> [b] +on map(f, xs) + tell mReturn(f) + set lng to length of xs + set lst to {} + repeat with i from 1 to lng + set end of lst to |λ|(item i of xs, i, xs) + end repeat + return lst + end tell +end map + +-- Lift 2nd class handler function into 1st class script wrapper +-- mReturn :: Handler -> Script +on mReturn(f) + if class of f is script then + f + else + script + property |λ| : f + end script + end if +end mReturn -- intercalate :: Text -> [Text] -> Text on intercalate(strText, lstText) @@ -142,20 +128,33 @@ on intercalate(strText, lstText) return strJoined end intercalate --- _reverse :: [a] -> [a] -on _reverse(xs) +-- reverse :: [a] -> [a] +on |reverse|(xs) if class of xs is text then (reverse of characters of xs) as text else reverse of xs end if -end _reverse +end |reverse| --- tail :: [a] -> [a] -on tail(xs) +-- tailMay :: [a] -> Maybe [a] +on tailMay(xs) if length of xs > 1 then - items 2 thru -1 of xs + {nothing:false, just:items 2 thru -1 of xs} else - {} + {nothing:true} end if -end tail +end tailMay + +-- until :: (a -> Bool) -> (a -> a) -> a -> a +on |until|(p, f, x) + set mp to mReturn(p) + set v to x + + tell mReturn(f) + repeat until mp's |λ|(v) + set v to |λ|(v) + end repeat + end tell + return v +end |until| diff --git a/Task/Zeckendorf-number-representation/Lingo/zeckendorf-number-representation-1.lingo b/Task/Zeckendorf-number-representation/Lingo/zeckendorf-number-representation-1.lingo new file mode 100644 index 0000000000..ce81e2c56f --- /dev/null +++ b/Task/Zeckendorf-number-representation/Lingo/zeckendorf-number-representation-1.lingo @@ -0,0 +1,29 @@ +-- Return the distinct Fibonacci numbers not greater than 'n' +on fibsUpTo (n) + fibList = [] + last = 1 + current = 1 + repeat while current <= n + fibList.add(current) + nxt = last + current + last = current + current = nxt + end repeat + return fibList +end + +-- Return the Zeckendorf representation of 'n' +on zeckendorf (n) + fib = fibsUpTo(n) + zeck = "" + repeat with pos = fib.count down to 1 + if n >= fib[pos] then + zeck = zeck & "1" + n = n - fib[pos] + else + zeck = zeck & "0" + end if + end repeat + if zeck = "" then return "0" + return zeck +end diff --git a/Task/Zeckendorf-number-representation/Lingo/zeckendorf-number-representation-2.lingo b/Task/Zeckendorf-number-representation/Lingo/zeckendorf-number-representation-2.lingo new file mode 100644 index 0000000000..6d79557c2f --- /dev/null +++ b/Task/Zeckendorf-number-representation/Lingo/zeckendorf-number-representation-2.lingo @@ -0,0 +1,3 @@ +repeat with n = 0 to 20 + put n & ": " & zeckendorf(n) +end repeat diff --git a/Task/Zeckendorf-number-representation/Ring/zeckendorf-number-representation.ring b/Task/Zeckendorf-number-representation/Ring/zeckendorf-number-representation.ring new file mode 100644 index 0000000000..f6ddf4668c --- /dev/null +++ b/Task/Zeckendorf-number-representation/Ring/zeckendorf-number-representation.ring @@ -0,0 +1,30 @@ +# Project : Zeckendorf number representation +# Date : 2017/12/13 +# Author : Gal Zsolt (~ CalmoSoft ~) +# Email : + +see "0 0" + nl +for n = 1 to 20 + see "" + n + " " + zeckendorf(n) + nl +next + +func zeckendorf(n) + fib = list(45) + fib[1] = 1 + fib[2] = 1 + i = 2 + o = "" + while fib[i] <= n + i = i + 1 + fib[i] = fib[i-1] + fib[i-2] + end + while i != 2 + i = i - 1 + if n >= fib[i] + o = o + "1" + n = n - fib[i] + else + o = o + "0" + ok + end + return o diff --git a/Task/Zero-to-the-zero-power/Dc/zero-to-the-zero-power.dc b/Task/Zero-to-the-zero-power/Dc/zero-to-the-zero-power.dc new file mode 100644 index 0000000000..1aa8ef0f38 --- /dev/null +++ b/Task/Zero-to-the-zero-power/Dc/zero-to-the-zero-power.dc @@ -0,0 +1 @@ +0 0^p diff --git a/Task/Zero-to-the-zero-power/Falcon/zero-to-the-zero-power.falcon b/Task/Zero-to-the-zero-power/Falcon/zero-to-the-zero-power.falcon new file mode 100644 index 0000000000..4a45c93f0e --- /dev/null +++ b/Task/Zero-to-the-zero-power/Falcon/zero-to-the-zero-power.falcon @@ -0,0 +1,7 @@ +/* created by Aykayayciti Earl Lamont Montgomery +April 9th, 2018 */ + +x = 0 +y = 0 +z = x**y +> "z=", z diff --git a/Task/Zero-to-the-zero-power/HolyC/zero-to-the-zero-power.holyc b/Task/Zero-to-the-zero-power/HolyC/zero-to-the-zero-power.holyc new file mode 100644 index 0000000000..f7897bd3cf --- /dev/null +++ b/Task/Zero-to-the-zero-power/HolyC/zero-to-the-zero-power.holyc @@ -0,0 +1,2 @@ +F64 a = 0 ` 0; +Print("0 ` 0 = %5.3f\n", a); diff --git a/Task/Zero-to-the-zero-power/JavaScript/zero-to-the-zero-power.js b/Task/Zero-to-the-zero-power/JavaScript/zero-to-the-zero-power-1.js similarity index 100% rename from Task/Zero-to-the-zero-power/JavaScript/zero-to-the-zero-power.js rename to Task/Zero-to-the-zero-power/JavaScript/zero-to-the-zero-power-1.js diff --git a/Task/Zero-to-the-zero-power/JavaScript/zero-to-the-zero-power-2.js b/Task/Zero-to-the-zero-power/JavaScript/zero-to-the-zero-power-2.js new file mode 100644 index 0000000000..3307362208 --- /dev/null +++ b/Task/Zero-to-the-zero-power/JavaScript/zero-to-the-zero-power-2.js @@ -0,0 +1,2 @@ +> 0**0 +1 diff --git a/Task/Zero-to-the-zero-power/Julia/zero-to-the-zero-power.julia b/Task/Zero-to-the-zero-power/Julia/zero-to-the-zero-power.julia index c11150d34d..c6d0aef985 100644 --- a/Task/Zero-to-the-zero-power/Julia/zero-to-the-zero-power.julia +++ b/Task/Zero-to-the-zero-power/Julia/zero-to-the-zero-power.julia @@ -1,9 +1,7 @@ -zs = Any[zero(Complex), - zero(FloatingPoint), - zero(Rational), - zero(Integer), - zero(Bool)] +const types = (Complex, Float64, Rational, Int, Bool) -for i in zs, j in zs - println(i, "^", j, " = ", i^j, " (", typeof(i^j), ")") +for Tb in types, Te in types + zb, ze = zero(Tb), zero(Te) + r = zb ^ ze + @printf("%10s ^ %-10s = %7s ^ %-7s = %-12s (%s)\n", Tb, Te, zb, ze, r, typeof(r)) end diff --git a/Task/Zero-to-the-zero-power/Python/zero-to-the-zero-power-1.py b/Task/Zero-to-the-zero-power/Python/zero-to-the-zero-power-1.py new file mode 100644 index 0000000000..ee9771b965 --- /dev/null +++ b/Task/Zero-to-the-zero-power/Python/zero-to-the-zero-power-1.py @@ -0,0 +1,11 @@ +from decimal import Decimal +from fractions import Fraction +from itertools import product + +zeroes = [0, 0.0, 0j, Decimal(0), Fraction(0, 1), -0.0, -0.0j, Decimal(-0.0)] +for i, j in product(zeroes, repeat=2): + try: + ans = i**j + except: + ans = '' + print(f'{i!r:>15} ** {j!r:<15} = {ans!r}') diff --git a/Task/Zero-to-the-zero-power/Python/zero-to-the-zero-power.py b/Task/Zero-to-the-zero-power/Python/zero-to-the-zero-power-2.py similarity index 100% rename from Task/Zero-to-the-zero-power/Python/zero-to-the-zero-power.py rename to Task/Zero-to-the-zero-power/Python/zero-to-the-zero-power-2.py diff --git a/Task/Zhang-Suen-thinning-algorithm/C/zhang-suen-thinning-algorithm.c b/Task/Zhang-Suen-thinning-algorithm/C/zhang-suen-thinning-algorithm.c new file mode 100644 index 0000000000..c6ae5cd13c --- /dev/null +++ b/Task/Zhang-Suen-thinning-algorithm/C/zhang-suen-thinning-algorithm.c @@ -0,0 +1,162 @@ +/*Abhishek Ghosh, 24th September 2017*/ + +#include +#include + +char** imageMatrix; + +char blankPixel,imagePixel; + +typedef struct{ + int row,col; +}pixel; + +int getBlackNeighbours(int row,int col){ + + int i,j,sum = 0; + + for(i=-1;i<=1;i++){ + for(j=-1;j<=1;j++){ + if(i!=0 && j!=0) + sum+= (imageMatrix[row+i][col+i]==imagePixel); + } + } + + return sum; +} + +int getBWTransitions(int row,int col){ + return ((imageMatrix[row-1][col]==blankPixel && imageMatrix[row-1][col+1]==imagePixel) + +(imageMatrix[row-1][col+1]==blankPixel && imageMatrix[row][col+1]==imagePixel) + +(imageMatrix[row][col+1]==blankPixel && imageMatrix[row+1][col+1]==imagePixel) + +(imageMatrix[row+1][col+1]==blankPixel && imageMatrix[row+1][col]==imagePixel) + +(imageMatrix[row+1][col]==blankPixel && imageMatrix[row+1][col-1]==imagePixel) + +(imageMatrix[row+1][col-1]==blankPixel && imageMatrix[row][col-1]==imagePixel) + +(imageMatrix[row][col-1]==blankPixel && imageMatrix[row-1][col-1]==imagePixel) + +(imageMatrix[row-1][col-1]==blankPixel && imageMatrix[row-1][col]==imagePixel)); +} + +int zhangSuenTest1(int row,int col){ + int neighbours = getBlackNeighbours(row,col); + + return ((neighbours>=2 && neighbours<=6) + && (getBWTransitions(row,col)==1) + && (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel) + && (imageMatrix[row][col+1]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col-1]==blankPixel)); +} + +int zhangSuenTest2(int row,int col){ + int neighbours = getBlackNeighbours(row,col); + + return ((neighbours>=2 && neighbours<=6) + && (getBWTransitions(row,col)==1) + && (imageMatrix[row-1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel||imageMatrix[row][col-1]==blankPixel) + && (imageMatrix[row-1][col]==blankPixel||imageMatrix[row+1][col]==blankPixel||imageMatrix[row][col+1]==blankPixel)); +} + +void zhangSuen(char* inputFile, char* outputFile){ + + int startRow = 1,startCol = 1,endRow,endCol,i,j,count,rows,cols,processed; + + pixel* markers; + + FILE* inputP = fopen(inputFile,"r"); + + fscanf(inputP,"%d%d",&rows,&cols); + + fscanf(inputP,"%d%d",&blankPixel,&imagePixel); + + blankPixel<=9?blankPixel+='0':blankPixel; + imagePixel<=9?imagePixel+='0':imagePixel; + + printf("\nPrinting original image :\n"); + + imageMatrix = (char**)malloc(rows*sizeof(char*)); + + for(i=0;i0); + + for(i=0;i0); + + for(i=0;i 6 # criteria 1.both + return false + end + if sum([(s[i] == 0 && s[i+1] == 1) for i in 1:length(s)-1]) != 1 # criteria 2.both + return false + end + if step == 1 + rightwhite = s[1] == 0 || s[3] == 0 || s[5] == 0 # 1.3 + downwhite = s[3] == 0 || s[5] == 0 || s[7] == 0 # 1.4 + return rightwhite && downwhite + end + upwhite = s[1] == 0 || s[3] == 0 || s[7] == 0 # 2.3 + leftwhite = s[1] == 0 || s[5] == 0 || s[7] == 0 # 2.4 + return upwhite && leftwhite +end + + +function zsthinning(mat) + retmat = copy(mat) + testmat = zeros(Int, size(mat)) + isize, jsize = size(testmat) + needredo = true + loops = 0 + while(needredo) + loops += 1 + println("loop number $loops") + needredo = false + for n in 1:2 + for i in 1:isize, j in 1:jsize + testmat[i,j] = surroundtesting(retmat, i, j, n) ? 1 : 0 + end + for i in 1:isize, j in 1:jsize + if testmat[i,j] == 1 + retmat[i,j] = 0 + needredo = true + end + end + end + end + retmat +end + + +function asciiprint(mat) + for i in 1:size(mat)[1] + println(join(map(i -> i == 1 ? '#' : ' ', mat[i,:]))) + end +end + + +asciiprint(zsthinning(pixels)) diff --git a/Task/Zig-zag-matrix/Octave/zig-zag-matrix-1.octave b/Task/Zig-zag-matrix/Octave/zig-zag-matrix-1.octave new file mode 100644 index 0000000000..2e420cf216 --- /dev/null +++ b/Task/Zig-zag-matrix/Octave/zig-zag-matrix-1.octave @@ -0,0 +1,28 @@ +function a = zigzag1(n) + j = 1:n; + u = repmat([-1; 1], n, 1); + v = j.*(2*j-3); + v = reshape([v; v+1], 2*n, 1); + a = zeros(n, n); + for i = 1:n + a(:, i) = v(i+j); + v += u; + endfor +endfunction + +function a = zigzag2(n) + a = zigzag1(n); + v = (1:n-1)'.^2; + for i = 2:n + a(n+2-i:n, i) -= v(1:i-1); + endfor +endfunction + +>> zigzag2(5) +ans = + + 0 1 5 6 14 + 2 4 7 13 15 + 3 8 12 16 21 + 9 11 17 20 22 + 10 18 19 23 24 diff --git a/Task/Zig-zag-matrix/Octave/zig-zag-matrix-2.octave b/Task/Zig-zag-matrix/Octave/zig-zag-matrix-2.octave new file mode 100644 index 0000000000..ad69bd6dd1 --- /dev/null +++ b/Task/Zig-zag-matrix/Octave/zig-zag-matrix-2.octave @@ -0,0 +1,18 @@ +function a = zigzag3(n) + a = zeros(n, n); + for k=1:n + d = (2*(j = mod(k, 2))-1)*(n-1); + m = (n-1)*(k-1); + a(k+(1-j)*m:d:k+j*m) = k*(k-1)/2:k*(k+1)/2-1; + a(n*(n+1-k)+(1-j)*m:d:n*(n+1-k)+j*m) = n*n-k*(k+1)/2:n*n-k*(k-1)/2-1; + endfor +endfunction + +>> zigzag3(5) +ans = + + 0 1 5 6 14 + 2 4 7 13 15 + 3 8 12 16 21 + 9 11 17 20 22 + 10 18 19 23 24 diff --git a/Task/Zig-zag-matrix/Perl-6/zig-zag-matrix.pl6 b/Task/Zig-zag-matrix/Perl-6/zig-zag-matrix.pl6 index f70ed524a7..b340b9d204 100644 --- a/Task/Zig-zag-matrix/Perl-6/zig-zag-matrix.pl6 +++ b/Task/Zig-zag-matrix/Perl-6/zig-zag-matrix.pl6 @@ -1,4 +1,45 @@ -sub MAIN($size as Int) { +class Turtle { + my @dv = [0,-1], [1,-1], [1,0], [1,1], [0,1], [-1,1], [-1,0], [-1,-1]; + my $points = 8; # 'compass' points of neighbors on grid: north=0, northeast=1, east=2, etc. + + has @.loc = 0,0; + has $.dir = 0; + has %.world; + has $.maxegg; + has $.range-x; + has $.range-y; + + method turn-left ($angle = 90) { $!dir -= $angle / 45; $!dir %= $points; } + method turn-right($angle = 90) { $!dir += $angle / 45; $!dir %= $points; } + + method lay-egg($egg) { + %!world{~@!loc} = $egg; + $!maxegg max= $egg; + $!range-x minmax= @!loc[0]; + $!range-y minmax= @!loc[1]; + } + + method look($ahead = 1) { + my $there = @!loc »+« @dv[$!dir] »*» $ahead; + %!world{~$there}; + } + + method forward($ahead = 1) { + my $there = @!loc »+« @dv[$!dir] »*» $ahead; + @!loc = @($there); + } + + method showmap() { + my $form = "%{$!maxegg.chars}s"; + my $endx = $!range-x.max; + for $!range-y.list X $!range-x.list -> ($y, $x) { + print (%!world{"$x $y"} // '').fmt($form); + print $x == $endx ?? "\n" !! ' '; + } + } +} + +sub MAIN(Int $size = 5) { my $t = Turtle.new(dir => 1); my $counter = 0; for 1 ..^ $size -> $run { diff --git a/Task/Zig-zag-matrix/Ring/zig-zag-matrix.ring b/Task/Zig-zag-matrix/Ring/zig-zag-matrix.ring new file mode 100644 index 0000000000..920fdf76f1 --- /dev/null +++ b/Task/Zig-zag-matrix/Ring/zig-zag-matrix.ring @@ -0,0 +1,56 @@ +# Project : Zig-zag matrix +# Date : 2018/03/24 +# Author : Gal Zsolt [~ CalmoSoft ~] +# Email : + +load "stdlib.ring" +n = 5 +a = newlist(n,n) +for j = 1 to n + for i = 1 to n + a[j][i] = 0 + next +next +i = 1 +j = 1 +k = 1 +while k < n * n + a[j][i] = k + k = k + 1 + if i = n + j = j + 1 + a[j][i] = k + k = k + 1 + di = -1 + dj = 1 + ok + if j = 1 + i = i + 1 + a[j][i] = k + k = k + 1 + di = -1 + dj = 1 + ok + if j = n + i = i + 1 + a[j][i] = k + k = k + 1 + di = 1 + dj = -1 + ok + if i = 1 + j = j + 1 + a[j][i] = k + k = k + 1 + di = 1 + dj = -1 + ok + i = i + di + j = j + dj +end +for p = 1 to n + for m = 1 to n + see "" + a[p][m] + " " + next + see nl +next diff --git a/Task/Zig-zag-matrix/Scilab/zig-zag-matrix.scilab b/Task/Zig-zag-matrix/Scilab/zig-zag-matrix.scilab new file mode 100644 index 0000000000..455111458a --- /dev/null +++ b/Task/Zig-zag-matrix/Scilab/zig-zag-matrix.scilab @@ -0,0 +1,19 @@ +function a = zigzag3(n) + a = zeros(n, n) + for k=1:n + j = modulo(k, 2) + d = (2*j-1)*(n-1) + m = (n-1)*(k-1) + a(k+(1-j)*m:d:k+j*m) = k*(k-1)/2:k*(k+1)/2-1 + a(n*(n+1-k)+(1-j)*m:d:n*(n+1-k)+j*m) = n*n-k*(k+1)/2:n*n-k*(k-1)/2-1 + end +endfunction + +-->zigzag3(5) + ans = + + 0. 1. 5. 6. 14. + 2. 4. 7. 13. 15. + 3. 8. 12. 16. 21. + 9. 11. 17. 20. 22. + 10. 18. 19. 23. 24. diff --git a/Task/Zig-zag-matrix/Stata/zig-zag-matrix-1.stata b/Task/Zig-zag-matrix/Stata/zig-zag-matrix-1.stata new file mode 100644 index 0000000000..26ef572864 --- /dev/null +++ b/Task/Zig-zag-matrix/Stata/zig-zag-matrix-1.stata @@ -0,0 +1,22 @@ +function zigzag1(n) { + j = 0::n-1 + u = J(1, n, (-1, 1)) + v = (j:*(2:*j:+3)) + v = rowshape((v,v:+1), 1) + a = J(n, n, .) + for (i=1; i<=n; i++) { + a[i, .] = v[j:+i] + v = v+u + } + return(a) +} + +zigzag1(5) + 1 2 3 4 5 + +--------------------------+ + 1 | 0 1 5 6 14 | + 2 | 2 4 7 13 16 | + 3 | 3 8 12 17 25 | + 4 | 9 11 18 24 31 | + 5 | 10 19 23 32 40 | + +--------------------------+ diff --git a/Task/Zig-zag-matrix/Stata/zig-zag-matrix-2.stata b/Task/Zig-zag-matrix/Stata/zig-zag-matrix-2.stata new file mode 100644 index 0000000000..dacef6d51e --- /dev/null +++ b/Task/Zig-zag-matrix/Stata/zig-zag-matrix-2.stata @@ -0,0 +1,18 @@ +function zigzag2(n) { + a = zigzag1(n) + v = (1..n-1):^2 + for (i=1; i

XYZ
{}{}{}{}